check_ntp_time.c 23 KB

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