check_ntp_time.c 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713
  1. /*****************************************************************************
  2. *
  3. * Nagios check_ntp_time plugin
  4. *
  5. * License: GPL
  6. * Copyright (c) 2006 Sean Finney <seanius@seanius.net>
  7. * Copyright (c) 2006-2014 Nagios Plugins Development Team
  8. *
  9. * Description:
  10. *
  11. * This file contains the check_ntp_time plugin
  12. *
  13. * This plugin checks the clock offset between the local host and a
  14. * remote NTP server. It is independent of any commandline programs or
  15. * external libraries.
  16. *
  17. * If you'd rather want to monitor an NTP server, please use
  18. * check_ntp_peer.
  19. *
  20. *
  21. * This program is free software: you can redistribute it and/or modify
  22. * it under the terms of the GNU General Public License as published by
  23. * the Free Software Foundation, either version 3 of the License, or
  24. * (at your option) any later version.
  25. *
  26. * This program is distributed in the hope that it will be useful,
  27. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  28. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  29. * GNU General Public License for more details.
  30. *
  31. * You should have received a copy of the GNU General Public License
  32. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  33. *
  34. *
  35. *****************************************************************************/
  36. const char *progname = "check_ntp_time";
  37. const char *copyright = "2006-2014";
  38. const char *email = "devel@nagios-plugins.org";
  39. #include "common.h"
  40. #include "netutils.h"
  41. #include "utils.h"
  42. static char *server_address=NULL;
  43. static char *port="123";
  44. static int verbose=0;
  45. static int quiet=0;
  46. static char *owarn="60";
  47. static char *ocrit="120";
  48. static char *swarn="16";
  49. static char *scrit="16";
  50. int time_offset=0;
  51. int num_hosts;
  52. int process_arguments (int, char **);
  53. thresholds *offset_thresholds = NULL;
  54. void print_help (void);
  55. void print_usage (void);
  56. /* number of times to perform each request to get a good average. */
  57. #ifndef AVG_NUM
  58. #define AVG_NUM 4
  59. #endif
  60. /* max size of control message data */
  61. #define MAX_CM_SIZE 468
  62. /* this structure holds everything in an ntp request/response as per rfc1305 */
  63. typedef struct {
  64. uint8_t flags; /* byte with leapindicator,vers,mode. see macros */
  65. uint8_t stratum; /* clock stratum */
  66. int8_t poll; /* polling interval */
  67. int8_t precision; /* precision of the local clock */
  68. int32_t rtdelay; /* total rt delay, as a fixed point num. see macros */
  69. uint32_t rtdisp; /* like above, but for max err to primary src */
  70. uint32_t refid; /* ref clock identifier */
  71. uint64_t refts; /* reference timestamp. local time local clock */
  72. uint64_t origts; /* time at which request departed client */
  73. uint64_t rxts; /* time at which request arrived at server */
  74. uint64_t txts; /* time at which request departed server */
  75. } ntp_message;
  76. /* this structure holds data about results from querying offset from a peer */
  77. typedef struct {
  78. time_t waiting; /* ts set when we started waiting for a response */
  79. int connected; /* don't try to "write()" if "connect()" fails */
  80. int num_responses; /* number of successfully received responses */
  81. uint8_t stratum; /* copied verbatim from the ntp_message */
  82. double rtdelay; /* converted from the ntp_message */
  83. double rtdisp; /* converted from the ntp_message */
  84. double offset[AVG_NUM]; /* offsets from each response */
  85. uint8_t flags; /* byte with leapindicator,vers,mode. see macros */
  86. } ntp_server_results;
  87. /* define this globally to be able to do other checks */
  88. ntp_server_results *servers=NULL;
  89. /* bits 1,2 are the leap indicator */
  90. #define LI_MASK 0xc0
  91. #define LI(x) ((x&LI_MASK)>>6)
  92. #define LI_SET(x,y) do{ x |= ((y<<6)&LI_MASK); }while(0)
  93. /* and these are the values of the leap indicator */
  94. #define LI_NOWARNING 0x00
  95. #define LI_EXTRASEC 0x01
  96. #define LI_MISSINGSEC 0x02
  97. #define LI_ALARM 0x03
  98. /* bits 3,4,5 are the ntp version */
  99. #define VN_MASK 0x38
  100. #define VN(x) ((x&VN_MASK)>>3)
  101. #define VN_SET(x,y) do{ x |= ((y<<3)&VN_MASK); }while(0)
  102. #define VN_RESERVED 0x02
  103. /* bits 6,7,8 are the ntp mode */
  104. #define MODE_MASK 0x07
  105. #define MODE(x) (x&MODE_MASK)
  106. #define MODE_SET(x,y) do{ x |= (y&MODE_MASK); }while(0)
  107. /* here are some values */
  108. #define MODE_CLIENT 0x03
  109. #define MODE_CONTROLMSG 0x06
  110. /* In control message, bits 8-10 are R,E,M bits */
  111. #define REM_MASK 0xe0
  112. #define REM_RESP 0x80
  113. #define REM_ERROR 0x40
  114. #define REM_MORE 0x20
  115. /* In control message, bits 11 - 15 are opcode */
  116. #define OP_MASK 0x1f
  117. #define OP_SET(x,y) do{ x |= (y&OP_MASK); }while(0)
  118. #define OP_READSTAT 0x01
  119. #define OP_READVAR 0x02
  120. /* In peer status bytes, bits 6,7,8 determine clock selection status */
  121. #define PEER_SEL(x) ((ntohs(x)>>8)&0x07)
  122. #define PEER_INCLUDED 0x04
  123. #define PEER_SYNCSOURCE 0x06
  124. /**
  125. ** a note about the 32-bit "fixed point" numbers:
  126. **
  127. they are divided into halves, each being a 16-bit int in network byte order:
  128. - the first 16 bits are an int on the left side of a decimal point.
  129. - the second 16 bits represent a fraction n/(2^16)
  130. likewise for the 64-bit "fixed point" numbers with everything doubled :)
  131. **/
  132. /* macros to access the left/right 16 bits of a 32-bit ntp "fixed point"
  133. number. note that these can be used as lvalues too */
  134. #define L16(x) (((uint16_t*)&x)[0])
  135. #define R16(x) (((uint16_t*)&x)[1])
  136. /* macros to access the left/right 32 bits of a 64-bit ntp "fixed point"
  137. number. these too can be used as lvalues */
  138. #define L32(x) (((uint32_t*)&x)[0])
  139. #define R32(x) (((uint32_t*)&x)[1])
  140. /* ntp wants seconds since 1/1/00, epoch is 1/1/70. this is the difference */
  141. #define EPOCHDIFF 0x83aa7e80UL
  142. /* extract a 32-bit ntp fixed point number into a double */
  143. #define NTP32asDOUBLE(x) (ntohs(L16(x)) + (double)ntohs(R16(x))/65536.0)
  144. /* likewise for a 64-bit ntp fp number */
  145. #define NTP64asDOUBLE(n) (double)(((uint64_t)n)?\
  146. (ntohl(L32(n))-EPOCHDIFF) + \
  147. (.00000001*(0.5+(double)(ntohl(R32(n))/42.94967296))):\
  148. 0)
  149. /* convert a struct timeval to a double */
  150. #define TVasDOUBLE(x) (double)(x.tv_sec+(0.000001*x.tv_usec))
  151. /* convert an ntp 64-bit fp number to a struct timeval */
  152. #define NTP64toTV(n,t) \
  153. do{ if(!n) t.tv_sec = t.tv_usec = 0; \
  154. else { \
  155. t.tv_sec=ntohl(L32(n))-EPOCHDIFF; \
  156. t.tv_usec=(int)(0.5+(double)(ntohl(R32(n))/4294.967296)); \
  157. } \
  158. }while(0)
  159. /* convert a struct timeval to an ntp 64-bit fp number */
  160. #define TVtoNTP64(t,n) \
  161. do{ if(!t.tv_usec && !t.tv_sec) n=0x0UL; \
  162. else { \
  163. L32(n)=htonl(t.tv_sec + EPOCHDIFF); \
  164. R32(n)=htonl((uint64_t)((4294.967296*t.tv_usec)+.5)); \
  165. } \
  166. } while(0)
  167. /* NTP control message header is 12 bytes, plus any data in the data
  168. * field, plus null padding to the nearest 32-bit boundary per rfc.
  169. */
  170. #define SIZEOF_NTPCM(m) (12+ntohs(m.count)+((m.count)?4-(ntohs(m.count)%4):0))
  171. /* finally, a little helper or two for debugging: */
  172. #define DBG(x) do{if(verbose>1){ x; }}while(0);
  173. #define PRINTSOCKADDR(x) \
  174. do{ \
  175. printf("%u.%u.%u.%u", (x>>24)&0xff, (x>>16)&0xff, (x>>8)&0xff, x&0xff);\
  176. }while(0);
  177. /* calculate the offset of the local clock */
  178. static inline double calc_offset(const ntp_message *m, const struct timeval *t){
  179. double client_tx, peer_rx, peer_tx, client_rx;
  180. client_tx = NTP64asDOUBLE(m->origts);
  181. peer_rx = NTP64asDOUBLE(m->rxts);
  182. peer_tx = NTP64asDOUBLE(m->txts);
  183. client_rx=TVasDOUBLE((*t));
  184. return (.5*((peer_tx-client_rx)+(peer_rx-client_tx)));
  185. }
  186. /* print out a ntp packet in human readable/debuggable format */
  187. void print_ntp_message(const ntp_message *p){
  188. struct timeval ref, orig, rx, tx;
  189. NTP64toTV(p->refts,ref);
  190. NTP64toTV(p->origts,orig);
  191. NTP64toTV(p->rxts,rx);
  192. NTP64toTV(p->txts,tx);
  193. printf("packet contents:\n");
  194. printf("\tflags: 0x%.2x\n", p->flags);
  195. printf("\t li=%d (0x%.2x)\n", LI(p->flags), p->flags&LI_MASK);
  196. printf("\t vn=%d (0x%.2x)\n", VN(p->flags), p->flags&VN_MASK);
  197. printf("\t mode=%d (0x%.2x)\n", MODE(p->flags), p->flags&MODE_MASK);
  198. printf("\tstratum = %d\n", p->stratum);
  199. printf("\tpoll = %g\n", pow(2, p->poll));
  200. printf("\tprecision = %g\n", pow(2, p->precision));
  201. printf("\trtdelay = %-.16g\n", NTP32asDOUBLE(p->rtdelay));
  202. printf("\trtdisp = %-.16g\n", NTP32asDOUBLE(p->rtdisp));
  203. printf("\trefid = %x\n", p->refid);
  204. printf("\trefts = %-.16g\n", NTP64asDOUBLE(p->refts));
  205. printf("\torigts = %-.16g\n", NTP64asDOUBLE(p->origts));
  206. printf("\trxts = %-.16g\n", NTP64asDOUBLE(p->rxts));
  207. printf("\ttxts = %-.16g\n", NTP64asDOUBLE(p->txts));
  208. }
  209. void setup_request(ntp_message *p){
  210. struct timeval t;
  211. memset(p, 0, sizeof(ntp_message));
  212. LI_SET(p->flags, LI_ALARM);
  213. VN_SET(p->flags, 4);
  214. MODE_SET(p->flags, MODE_CLIENT);
  215. p->poll=4;
  216. p->precision=(int8_t)0xfa;
  217. L16(p->rtdelay)=htons(1);
  218. L16(p->rtdisp)=htons(1);
  219. gettimeofday(&t, NULL);
  220. TVtoNTP64(t,p->txts);
  221. }
  222. /* select the "best" server from a list of servers, and return its index.
  223. * this is done by filtering servers based on stratum, dispersion, and
  224. * finally round-trip delay. */
  225. int best_offset_server(const ntp_server_results *slist, int nservers){
  226. int i=0, cserver=0, best_server=-1;
  227. /* for each server */
  228. for(cserver=0; cserver<nservers; cserver++){
  229. /* We don't want any servers that fails these tests */
  230. /* Sort out servers that didn't respond or responede with a 0 stratum;
  231. * stratum 0 is for reference clocks so no NTP server should ever report
  232. * a stratum 0 */
  233. if ( slist[cserver].stratum == 0){
  234. if (verbose) printf("discarding peer %d: stratum=%d\n", cserver, slist[cserver].stratum);
  235. continue;
  236. }
  237. /* Sort out servers with error flags */
  238. if ( LI(slist[cserver].flags) == LI_ALARM ){
  239. if (verbose) printf("discarding peer %d: flags=%d\n", cserver, LI(slist[cserver].flags));
  240. continue;
  241. }
  242. /* If we don't have a server yet, use the first one */
  243. if (best_server == -1) {
  244. best_server = cserver;
  245. DBG(printf("using peer %d as our first candidate\n", best_server));
  246. continue;
  247. }
  248. /* compare the server to the best one we've seen so far */
  249. /* does it have an equal or better stratum? */
  250. DBG(printf("comparing peer %d with peer %d\n", cserver, best_server));
  251. if(slist[cserver].stratum <= slist[best_server].stratum){
  252. DBG(printf("stratum for peer %d <= peer %d\n", cserver, best_server));
  253. /* does it have an equal or better dispersion? */
  254. if(slist[cserver].rtdisp <= slist[best_server].rtdisp){
  255. DBG(printf("dispersion for peer %d <= peer %d\n", cserver, best_server));
  256. /* does it have a better rtdelay? */
  257. if(slist[cserver].rtdelay < slist[best_server].rtdelay){
  258. DBG(printf("rtdelay for peer %d < peer %d\n", cserver, best_server));
  259. best_server = cserver;
  260. DBG(printf("peer %d is now our best candidate\n", best_server));
  261. }
  262. }
  263. }
  264. }
  265. if(best_server >= 0) {
  266. DBG(printf("best server selected: peer %d\n", best_server));
  267. return best_server;
  268. } else {
  269. DBG(printf("no peers meeting synchronization criteria :(\n"));
  270. return -1;
  271. }
  272. }
  273. /* do everything we need to get the total average offset
  274. * - we use a certain amount of parallelization with poll() to ensure
  275. * we don't waste time sitting around waiting for single packets.
  276. * - we also "manually" handle resolving host names and connecting, because
  277. * we have to do it in a way that our lazy macros don't handle currently :( */
  278. double offset_request(const char *host, int *status){
  279. int i=0, j=0, ga_result=0, *socklist=NULL, respnum=0;
  280. int servers_completed=0, one_read=0, servers_readable=0, best_index=-1;
  281. time_t now_time=0, start_ts=0;
  282. ntp_message *req=NULL;
  283. double avg_offset=0.;
  284. num_hosts = 0;
  285. struct timeval recv_time;
  286. struct addrinfo *ai=NULL, *ai_tmp=NULL, hints;
  287. struct pollfd *ufds=NULL;
  288. /* setup hints to only return results from getaddrinfo that we'd like */
  289. memset(&hints, 0, sizeof(struct addrinfo));
  290. hints.ai_family = address_family;
  291. hints.ai_protocol = IPPROTO_UDP;
  292. hints.ai_socktype = SOCK_DGRAM;
  293. /* fill in ai with the list of hosts resolved by the host name */
  294. ga_result = getaddrinfo(host, port, &hints, &ai);
  295. if(ga_result!=0){
  296. die(STATE_UNKNOWN, "error getting address for %s: %s\n",
  297. host, gai_strerror(ga_result));
  298. }
  299. /* count the number of returned hosts, and allocate stuff accordingly */
  300. for(ai_tmp=ai; ai_tmp!=NULL; ai_tmp=ai_tmp->ai_next){ num_hosts++; }
  301. req=(ntp_message*)malloc(sizeof(ntp_message)*num_hosts);
  302. if(req==NULL) die(STATE_UNKNOWN, "can not allocate ntp message array");
  303. socklist=(int*)malloc(sizeof(int)*num_hosts);
  304. if(socklist==NULL) die(STATE_UNKNOWN, "can not allocate socket array");
  305. ufds=(struct pollfd*)malloc(sizeof(struct pollfd)*num_hosts);
  306. if(ufds==NULL) die(STATE_UNKNOWN, "can not allocate socket array");
  307. servers=(ntp_server_results*)malloc(sizeof(ntp_server_results)*num_hosts);
  308. if(servers==NULL) die(STATE_UNKNOWN, "can not allocate server array");
  309. memset(servers, 0, sizeof(ntp_server_results)*num_hosts);
  310. DBG(printf("Found %d peers to check\n", num_hosts));
  311. /* setup each socket for writing, and the corresponding struct pollfd */
  312. ai_tmp=ai;
  313. for(i=0;ai_tmp;i++){
  314. socklist[i]=socket(ai_tmp->ai_family, SOCK_DGRAM, IPPROTO_UDP);
  315. if(socklist[i] == -1) {
  316. perror(NULL);
  317. die(STATE_UNKNOWN, "can not create new socket");
  318. }
  319. if(connect(socklist[i], ai_tmp->ai_addr, ai_tmp->ai_addrlen)){
  320. /* don't die here, because it is enough if there is one server
  321. answering in time. This also would break for dual ipv4/6 stacked
  322. ntp servers when the client only supports on of them.
  323. */
  324. DBG(printf("can't create socket connection on peer %i: %s\n", i, strerror(errno)));
  325. } else {
  326. ufds[i].fd=socklist[i];
  327. ufds[i].events=POLLIN;
  328. ufds[i].revents=0;
  329. servers[i].connected=1;
  330. }
  331. ai_tmp = ai_tmp->ai_next;
  332. }
  333. /* now do AVG_NUM checks to each host. We stop before timeout/2 seconds
  334. * have passed in order to ensure post-processing and jitter time. */
  335. now_time=start_ts=time(NULL);
  336. while(servers_completed<num_hosts && now_time-start_ts <= timeout_interval - 1){
  337. /* loop through each server and find each one which hasn't
  338. * been touched in the past second or so and is still lacking
  339. * some responses. For each of these servers, send a new request,
  340. * and update the "waiting" timestamp with the current time. */
  341. now_time=time(NULL);
  342. for(i=0; i<num_hosts; i++){
  343. if(servers[i].connected == 0)
  344. continue;
  345. if(servers[i].waiting<now_time && servers[i].num_responses<AVG_NUM){
  346. if(verbose && servers[i].waiting != 0) printf("re-");
  347. if(verbose) printf("sending request to peer %d\n", i);
  348. setup_request(&req[i]);
  349. write(socklist[i], &req[i], sizeof(ntp_message));
  350. servers[i].waiting=now_time;
  351. break;
  352. }
  353. }
  354. /* quickly poll for any sockets with pending data */
  355. servers_readable=poll(ufds, num_hosts, 100);
  356. if(servers_readable==-1){
  357. perror("polling ntp sockets");
  358. die(STATE_UNKNOWN, "communication errors");
  359. }
  360. /* read from any sockets with pending data */
  361. for(i=0; servers_readable && i<num_hosts; i++){
  362. if(ufds[i].revents&POLLIN && servers[i].num_responses < AVG_NUM){
  363. if(verbose) {
  364. printf("response from peer %d: ", i);
  365. }
  366. read(ufds[i].fd, &req[i], sizeof(ntp_message));
  367. gettimeofday(&recv_time, NULL);
  368. DBG(print_ntp_message(&req[i]));
  369. respnum=servers[i].num_responses++;
  370. servers[i].offset[respnum]=calc_offset(&req[i], &recv_time)+time_offset;
  371. if(verbose) {
  372. printf("offset %.10g\n", servers[i].offset[respnum]);
  373. }
  374. servers[i].stratum=req[i].stratum;
  375. servers[i].rtdisp=NTP32asDOUBLE(req[i].rtdisp);
  376. servers[i].rtdelay=NTP32asDOUBLE(req[i].rtdelay);
  377. servers[i].waiting=0;
  378. servers[i].flags=req[i].flags;
  379. servers_readable--;
  380. one_read = 1;
  381. if(servers[i].num_responses==AVG_NUM) servers_completed++;
  382. }
  383. }
  384. /* lather, rinse, repeat. */
  385. /* break if we have one response but other ntp servers doesn't response */
  386. /* greater than timeout_interval/2 */
  387. if (servers_completed && now_time-start_ts > timeout_interval/2) break;
  388. }
  389. if (one_read == 0) {
  390. die(timeout_state, "%s: No response from NTP server\n", state_text(timeout_state));
  391. }
  392. /* now, pick the best server from the list */
  393. best_index=best_offset_server(servers, num_hosts);
  394. if(best_index < 0){
  395. *status=STATE_UNKNOWN;
  396. } else {
  397. /* finally, calculate the average offset */
  398. for(i=0; i<servers[best_index].num_responses;i++){
  399. avg_offset+=servers[best_index].offset[j];
  400. }
  401. avg_offset/=servers[best_index].num_responses;
  402. }
  403. /* cleanup */
  404. for(j=0; j<num_hosts; j++){ close(socklist[j]); }
  405. free(socklist);
  406. free(ufds);
  407. free(req);
  408. freeaddrinfo(ai);
  409. if(verbose) printf("overall average offset: %.10g\n", avg_offset);
  410. return avg_offset;
  411. }
  412. int process_arguments(int argc, char **argv){
  413. int c;
  414. int option=0;
  415. static struct option longopts[] = {
  416. {"version", no_argument, 0, 'V'},
  417. {"help", no_argument, 0, 'h'},
  418. {"verbose", no_argument, 0, 'v'},
  419. {"use-ipv4", no_argument, 0, '4'},
  420. {"use-ipv6", no_argument, 0, '6'},
  421. {"quiet", no_argument, 0, 'q'},
  422. {"time-offset", optional_argument, 0, 'o'},
  423. {"warning", required_argument, 0, 'w'},
  424. {"critical", required_argument, 0, 'c'},
  425. {"stratum-warn", required_argument, 0, 'W'},
  426. {"stratum-crit", required_argument, 0, 'C'},
  427. {"timeout", required_argument, 0, 't'},
  428. {"hostname", required_argument, 0, 'H'},
  429. {"port", required_argument, 0, 'p'},
  430. {0, 0, 0, 0}
  431. };
  432. if (argc < 2)
  433. usage ("\n");
  434. while (1) {
  435. c = getopt_long (argc, argv, "Vhv46qw:c:t:H:p:o:W:C:", longopts, &option);
  436. if (c == -1 || c == EOF || c == 1)
  437. break;
  438. switch (c) {
  439. case 'h':
  440. print_help();
  441. exit(STATE_OK);
  442. break;
  443. case 'V':
  444. print_revision(progname, NP_VERSION);
  445. exit(STATE_OK);
  446. break;
  447. case 'v':
  448. verbose++;
  449. break;
  450. case 'q':
  451. quiet = 1;
  452. break;
  453. case 'w':
  454. owarn = optarg;
  455. break;
  456. case 'c':
  457. ocrit = optarg;
  458. break;
  459. case 'W':
  460. swarn = optarg;
  461. break;
  462. case 'C':
  463. scrit = optarg;
  464. break;
  465. case 'H':
  466. if(is_host(optarg) == FALSE)
  467. usage2(_("Invalid hostname/address"), optarg);
  468. server_address = strdup(optarg);
  469. break;
  470. case 'p':
  471. port = strdup(optarg);
  472. break;
  473. case 't':
  474. timeout_interval = parse_timeout_string(optarg);
  475. break;
  476. case 'o':
  477. time_offset=atoi(optarg);
  478. break;
  479. case '4':
  480. address_family = AF_INET;
  481. break;
  482. case '6':
  483. #ifdef USE_IPV6
  484. address_family = AF_INET6;
  485. #else
  486. usage4 (_("IPv6 support not available"));
  487. #endif
  488. break;
  489. case '?':
  490. /* print short usage statement if args not parsable */
  491. usage5 ();
  492. break;
  493. }
  494. }
  495. if(server_address == NULL){
  496. usage4(_("Hostname was not supplied"));
  497. }
  498. return 0;
  499. }
  500. char *perfd_offset (double offset)
  501. {
  502. return fperfdata ("offset", offset, "s",
  503. TRUE, offset_thresholds->warning->end,
  504. TRUE, offset_thresholds->critical->end,
  505. FALSE, 0, FALSE, 0);
  506. }
  507. int main(int argc, char *argv[]){
  508. int result, offset_result;
  509. double offset=0;
  510. char *result_line, *perfdata_line;
  511. setlocale (LC_ALL, "");
  512. bindtextdomain (PACKAGE, LOCALEDIR);
  513. textdomain (PACKAGE);
  514. offset_result = STATE_OK;
  515. /* Parse extra opts if any */
  516. argv=np_extra_opts (&argc, argv, progname);
  517. if (process_arguments (argc, argv) == ERROR)
  518. usage4 (_("Could not parse arguments"));
  519. set_thresholds(&offset_thresholds, owarn, ocrit);
  520. /* initialize alarm signal handling */
  521. signal (SIGALRM, socket_timeout_alarm_handler);
  522. /* set socket timeout */
  523. alarm (timeout_interval);
  524. offset = offset_request(server_address, &offset_result);
  525. if (offset_result == STATE_UNKNOWN) {
  526. result = (quiet == 1 ? STATE_UNKNOWN : STATE_CRITICAL);
  527. } else {
  528. result = get_status(fabs(offset), offset_thresholds);
  529. }
  530. int i;
  531. int servers_warn_stratum=0;
  532. int servers_crit_stratum=0;
  533. int servers_worst_stratum=0;
  534. int servers_best_stratum=16;
  535. for (i=0; i<num_hosts; i++) {
  536. // set best stratum
  537. if (servers[i].stratum < servers_best_stratum)
  538. servers_best_stratum = servers[i].stratum;
  539. // set worst stratum
  540. if (servers[i].stratum > servers_worst_stratum)
  541. servers_worst_stratum = servers[i].stratum;
  542. if (servers[i].stratum >= atoi(scrit))
  543. servers_crit_stratum++;
  544. if (servers[i].stratum >= atoi(swarn))
  545. servers_warn_stratum++;
  546. }
  547. // adjust result for stratum check
  548. if ((result == STATE_WARNING || result == STATE_OK) && servers_crit_stratum > 0)
  549. result = STATE_CRITICAL;
  550. if (result == STATE_OK && servers_warn_stratum > 0)
  551. result = STATE_WARNING;
  552. switch (result) {
  553. case STATE_CRITICAL :
  554. xasprintf(&result_line, _("NTP CRITICAL:"));
  555. break;
  556. case STATE_WARNING :
  557. xasprintf(&result_line, _("NTP WARNING:"));
  558. break;
  559. case STATE_OK :
  560. xasprintf(&result_line, _("NTP OK:"));
  561. break;
  562. default :
  563. xasprintf(&result_line, _("NTP UNKNOWN:"));
  564. break;
  565. }
  566. if(offset_result == STATE_UNKNOWN){
  567. xasprintf(&result_line, "%s %s", result_line, _("Offset unknown"));
  568. xasprintf(&perfdata_line, "");
  569. } else {
  570. xasprintf(&result_line, "%s %s %.10g secs, stratum best:%d worst:%d", result_line, _("Offset"), offset, servers_best_stratum, servers_worst_stratum);
  571. xasprintf(&perfdata_line, "%s stratum_best=%d stratum_worst=%d num_warn_stratum=%d num_crit_stratum=%d", perfd_offset(offset), servers_best_stratum, servers_worst_stratum, servers_warn_stratum, servers_crit_stratum);
  572. }
  573. printf("%s|%s\n", result_line, perfdata_line);
  574. free(servers);
  575. if(server_address!=NULL) free(server_address);
  576. return result;
  577. }
  578. void print_help(void){
  579. print_revision(progname, NP_VERSION);
  580. printf ("Copyright (c) 2006 Sean Finney\n");
  581. printf (COPYRIGHT, copyright, email);
  582. printf ("%s\n", _("This plugin checks the clock offset with the ntp server"));
  583. printf ("\n\n");
  584. print_usage();
  585. printf (UT_HELP_VRSN);
  586. printf (UT_EXTRA_OPTS);
  587. printf (UT_IPv46);
  588. printf (UT_HOST_PORT, 'p', "123");
  589. printf (" %s\n", "-q, --quiet");
  590. printf (" %s\n", _("Returns UNKNOWN instead of CRITICAL if offset cannot be found"));
  591. printf (" %s\n", "-w, --warning=THRESHOLD");
  592. printf (" %s\n", _("Offset to result in warning status (seconds)"));
  593. printf (" %s\n", "-c, --critical=THRESHOLD");
  594. printf (" %s\n", _("Offset to result in critical status (seconds)"));
  595. printf (" %s\n", "-o, --time_offset=INTEGER");
  596. printf (" %s\n", _("Expected offset of the ntp server relative to local server (seconds)"));
  597. printf (" %s\n", "-W, --stratum-warn=INTEGER");
  598. printf (" %s\n", _("Alert warning if stratum is worse (less) than specfied value"));
  599. printf (" %s\n", "-C, --stratum-crit=INTEGER");
  600. printf (" %s\n", _("Alert critical if stratum is worse (less) than specfied value"));
  601. printf (UT_CONN_TIMEOUT, DEFAULT_SOCKET_TIMEOUT);
  602. printf (UT_VERBOSE);
  603. printf("\n");
  604. printf("%s\n", _("This plugin checks the clock offset between the local host and a"));
  605. printf("%s\n", _("remote NTP server. It is independent of any commandline programs or"));
  606. printf("%s\n", _("external libraries."));
  607. printf("\n");
  608. printf("%s\n", _("Notes:"));
  609. printf(" %s\n", _("If you'd rather want to monitor an NTP server, please use"));
  610. printf(" %s\n", _("check_ntp_peer."));
  611. printf(" %s\n", _("--time-offset is useful for compensating for servers with known"));
  612. printf(" %s\n", _("and expected clock skew."));
  613. printf("\n");
  614. printf(UT_THRESHOLDS_NOTES);
  615. printf("\n");
  616. printf("%s\n", _("Examples:"));
  617. printf(" %s\n", ("./check_ntp_time -H ntpserv -w 0.5 -c 1"));
  618. printf (UT_SUPPORT);
  619. }
  620. void
  621. print_usage(void)
  622. {
  623. printf ("%s\n", _("Usage:"));
  624. printf(" %s -H <host> [-4|-6] [-w <warn>] [-c <crit>] [-v verbose] [-o <time offset>]\n", progname);
  625. }