check_ntp.c 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679
  1. /******************************************************************************
  2. check_ntp.c: utility to check ntp servers independant of any commandline
  3. programs or external libraries.
  4. original author: sean finney <seanius@seanius.net>
  5. ******************************************************************************
  6. This program is free software; you can redistribute it and/or modify
  7. it under the terms of the GNU General Public License as published by
  8. the Free Software Foundation; either version 2 of the License, or
  9. (at your option) any later version.
  10. This program is distributed in the hope that it will be useful,
  11. but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. GNU General Public License for more details.
  14. You should have received a copy of the GNU General Public License
  15. along with this program; if not, write to the Free Software
  16. Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  17. $Id$
  18. *****************************************************************************/
  19. const char *progname = "check_ntp";
  20. const char *revision = "$Revision$";
  21. const char *copyright = "2006";
  22. const char *email = "nagiosplug-devel@lists.sourceforge.net";
  23. #include "common.h"
  24. #include "netutils.h"
  25. #include "utils.h"
  26. static char *server_address=NULL;
  27. static int verbose=0;
  28. static int zero_offset_bad=0;
  29. static double owarn=0;
  30. static double ocrit=0;
  31. static short do_jitter=0;
  32. static double jwarn=0;
  33. static double jcrit=0;
  34. int process_arguments (int, char **);
  35. void print_help (void);
  36. void print_usage (void);
  37. /* number of times to perform each request to get a good average. */
  38. #define AVG_NUM 4
  39. /* max size of control message data */
  40. #define MAX_CM_SIZE 468
  41. /* this structure holds everything in an ntp request/response as per rfc1305 */
  42. typedef struct {
  43. uint8_t flags; /* byte with leapindicator,vers,mode. see macros */
  44. uint8_t stratum; /* clock stratum */
  45. int8_t poll; /* polling interval */
  46. int8_t precision; /* precision of the local clock */
  47. int32_t rtdelay; /* total rt delay, as a fixed point num. see macros */
  48. uint32_t rtdisp; /* like above, but for max err to primary src */
  49. uint32_t refid; /* ref clock identifier */
  50. uint64_t refts; /* reference timestamp. local time local clock */
  51. uint64_t origts; /* time at which request departed client */
  52. uint64_t rxts; /* time at which request arrived at server */
  53. uint64_t txts; /* time at which request departed server */
  54. } ntp_message;
  55. /* this structure holds everything in an ntp control message as per rfc1305 */
  56. typedef struct {
  57. uint8_t flags; /* byte with leapindicator,vers,mode. see macros */
  58. uint8_t op; /* R,E,M bits and Opcode */
  59. uint16_t seq; /* Packet sequence */
  60. uint16_t status; /* Clock status */
  61. uint16_t assoc; /* Association */
  62. uint16_t offset; /* Similar to TCP sequence # */
  63. uint16_t count; /* # bytes of data */
  64. char data[MAX_CM_SIZE]; /* ASCII data of the request */
  65. /* NB: not necessarily NULL terminated! */
  66. } ntp_control_message;
  67. /* this is an association/status-word pair found in control packet reponses */
  68. typedef struct {
  69. uint16_t assoc;
  70. uint16_t status;
  71. } ntp_assoc_status_pair;
  72. /* bits 1,2 are the leap indicator */
  73. #define LI_MASK 0xc0
  74. #define LI(x) ((x&LI_MASK)>>6)
  75. #define LI_SET(x,y) do{ x |= ((y<<6)&LI_MASK); }while(0)
  76. /* and these are the values of the leap indicator */
  77. #define LI_NOWARNING 0x00
  78. #define LI_EXTRASEC 0x01
  79. #define LI_MISSINGSEC 0x02
  80. #define LI_ALARM 0x03
  81. /* bits 3,4,5 are the ntp version */
  82. #define VN_MASK 0x38
  83. #define VN(x) ((x&VN_MASK)>>3)
  84. #define VN_SET(x,y) do{ x |= ((y<<3)&VN_MASK); }while(0)
  85. #define VN_RESERVED 0x02
  86. /* bits 6,7,8 are the ntp mode */
  87. #define MODE_MASK 0x07
  88. #define MODE(x) (x&MODE_MASK)
  89. #define MODE_SET(x,y) do{ x |= (y&MODE_MASK); }while(0)
  90. /* here are some values */
  91. #define MODE_CLIENT 0x03
  92. #define MODE_CONTROLMSG 0x06
  93. /* In control message, bits 8-10 are R,E,M bits */
  94. #define REM_MASK 0xe0
  95. #define REM_RESP 0x80
  96. #define REM_ERROR 0x40
  97. #define REM_MORE 0x20
  98. /* In control message, bits 11 - 15 are opcode */
  99. #define OP_MASK 0x1f
  100. #define OP_SET(x,y) do{ x |= (y&OP_MASK); }while(0)
  101. #define OP_READSTAT 0x01
  102. #define OP_READVAR 0x02
  103. /* In peer status bytes, bytes 6,7,8 determine clock selection status */
  104. #define PEER_SEL(x) (x&0x07)
  105. #define PEER_INCLUDED 0x04
  106. #define PEER_SYNCSOURCE 0x06
  107. /**
  108. ** a note about the 32-bit "fixed point" numbers:
  109. **
  110. they are divided into halves, each being a 16-bit int in network byte order:
  111. - the first 16 bits are an int on the left side of a decimal point.
  112. - the second 16 bits represent a fraction n/(2^16)
  113. likewise for the 64-bit "fixed point" numbers with everything doubled :)
  114. **/
  115. /* macros to access the left/right 16 bits of a 32-bit ntp "fixed point"
  116. number. note that these can be used as lvalues too */
  117. #define L16(x) (((uint16_t*)&x)[0])
  118. #define R16(x) (((uint16_t*)&x)[1])
  119. /* macros to access the left/right 32 bits of a 64-bit ntp "fixed point"
  120. number. these too can be used as lvalues */
  121. #define L32(x) (((uint32_t*)&x)[0])
  122. #define R32(x) (((uint32_t*)&x)[1])
  123. /* ntp wants seconds since 1/1/00, epoch is 1/1/70. this is the difference */
  124. #define EPOCHDIFF 0x83aa7e80UL
  125. /* extract a 32-bit ntp fixed point number into a double */
  126. #define NTP32asDOUBLE(x) (ntohs(L16(x)) + (double)ntohs(R16(x))/65536.0)
  127. /* likewise for a 64-bit ntp fp number */
  128. #define NTP64asDOUBLE(n) (double)(((uint64_t)n)?\
  129. (ntohl(L32(n))-EPOCHDIFF) + \
  130. (.00000001*(0.5+(double)(ntohl(R32(n))/42.94967296))):\
  131. 0)
  132. /* convert a struct timeval to a double */
  133. #define TVasDOUBLE(x) (double)(x.tv_sec+(0.000001*x.tv_usec))
  134. /* convert an ntp 64-bit fp number to a struct timeval */
  135. #define NTP64toTV(n,t) \
  136. do{ if(!n) t.tv_sec = t.tv_usec = 0; \
  137. else { \
  138. t.tv_sec=ntohl(L32(n))-EPOCHDIFF; \
  139. t.tv_usec=(int)(0.5+(double)(ntohl(R32(n))/4294.967296)); \
  140. } \
  141. }while(0)
  142. /* convert a struct timeval to an ntp 64-bit fp number */
  143. #define TVtoNTP64(t,n) \
  144. do{ if(!t.tv_usec && !t.tv_sec) n=0x0UL; \
  145. else { \
  146. L32(n)=htonl(t.tv_sec + EPOCHDIFF); \
  147. R32(n)=htonl((4294.967296*t.tv_usec)+.5); \
  148. } \
  149. } while(0)
  150. /* NTP control message header is 12 bytes, plus any data in the data
  151. * field, plus null padding to the nearest 32-bit boundary per rfc.
  152. */
  153. #define SIZEOF_NTPCM(m) (12+ntohs(m.count)+((m.count)?4-(ntohs(m.count)%4):0))
  154. /* finally, a little helper or two for debugging: */
  155. #define DBG(x) do{if(verbose>1){ x; }}while(0);
  156. #define PRINTSOCKADDR(x) \
  157. do{ \
  158. printf("%u.%u.%u.%u", (x>>24)&0xff, (x>>16)&0xff, (x>>8)&0xff, x&0xff);\
  159. }while(0);
  160. /* calculate the offset of the local clock */
  161. static inline double calc_offset(const ntp_message *m, const struct timeval *t){
  162. double client_tx, peer_rx, peer_tx, client_rx, rtdelay;
  163. client_tx = NTP64asDOUBLE(m->origts);
  164. peer_rx = NTP64asDOUBLE(m->rxts);
  165. peer_tx = NTP64asDOUBLE(m->txts);
  166. client_rx=TVasDOUBLE((*t));
  167. rtdelay=NTP32asDOUBLE(m->rtdelay);
  168. return (.5*((peer_tx-client_rx)+(peer_rx-client_tx)))-rtdelay;
  169. }
  170. /* print out a ntp packet in human readable/debuggable format */
  171. void print_ntp_message(const ntp_message *p){
  172. struct timeval ref, orig, rx, tx;
  173. NTP64toTV(p->refts,ref);
  174. NTP64toTV(p->origts,orig);
  175. NTP64toTV(p->rxts,rx);
  176. NTP64toTV(p->txts,tx);
  177. printf("packet contents:\n");
  178. printf("\tflags: 0x%.2x\n", p->flags);
  179. printf("\t li=%d (0x%.2x)\n", LI(p->flags), p->flags&LI_MASK);
  180. printf("\t vn=%d (0x%.2x)\n", VN(p->flags), p->flags&VN_MASK);
  181. printf("\t mode=%d (0x%.2x)\n", MODE(p->flags), p->flags&MODE_MASK);
  182. printf("\tstratum = %d\n", p->stratum);
  183. printf("\tpoll = %g\n", pow(2, p->poll));
  184. printf("\tprecision = %g\n", pow(2, p->precision));
  185. printf("\trtdelay = %-.16g\n", NTP32asDOUBLE(p->rtdelay));
  186. printf("\trtdisp = %-.16g\n", NTP32asDOUBLE(p->rtdisp));
  187. printf("\trefid = %x\n", p->refid);
  188. printf("\trefts = %-.16g\n", NTP64asDOUBLE(p->refts));
  189. printf("\torigts = %-.16g\n", NTP64asDOUBLE(p->origts));
  190. printf("\trxts = %-.16g\n", NTP64asDOUBLE(p->rxts));
  191. printf("\ttxts = %-.16g\n", NTP64asDOUBLE(p->txts));
  192. }
  193. void print_ntp_control_message(const ntp_control_message *p){
  194. int i=0, numpeers=0;
  195. const ntp_assoc_status_pair *peer=NULL;
  196. printf("control packet contents:\n");
  197. printf("\tflags: 0x%.2x , 0x%.2x\n", p->flags, p->op);
  198. printf("\t li=%d (0x%.2x)\n", LI(p->flags), p->flags&LI_MASK);
  199. printf("\t vn=%d (0x%.2x)\n", VN(p->flags), p->flags&VN_MASK);
  200. printf("\t mode=%d (0x%.2x)\n", MODE(p->flags), p->flags&MODE_MASK);
  201. printf("\t response=%d (0x%.2x)\n", (p->op&REM_RESP)>0, p->op&REM_RESP);
  202. printf("\t more=%d (0x%.2x)\n", (p->op&REM_MORE)>0, p->op&REM_MORE);
  203. printf("\t error=%d (0x%.2x)\n", (p->op&REM_ERROR)>0, p->op&REM_ERROR);
  204. printf("\t op=%d (0x%.2x)\n", p->op&OP_MASK, p->op&OP_MASK);
  205. printf("\tsequence: %d (0x%.2x)\n", ntohs(p->seq), ntohs(p->seq));
  206. printf("\tstatus: %d (0x%.2x)\n", ntohs(p->status), ntohs(p->status));
  207. printf("\tassoc: %d (0x%.2x)\n", ntohs(p->assoc), ntohs(p->assoc));
  208. printf("\toffset: %d (0x%.2x)\n", ntohs(p->offset), ntohs(p->offset));
  209. printf("\tcount: %d (0x%.2x)\n", ntohs(p->count), ntohs(p->count));
  210. numpeers=ntohs(p->count)/(sizeof(ntp_assoc_status_pair));
  211. if(p->op&REM_RESP && p->op&OP_READSTAT){
  212. peer=(ntp_assoc_status_pair*)p->data;
  213. for(i=0;i<numpeers;i++){
  214. printf("\tpeer id %.2x status %.2x",
  215. ntohs(peer[i].assoc), ntohs(peer[i].status));
  216. if (PEER_SEL(peer[i].status) >= PEER_INCLUDED){
  217. if(PEER_SEL(peer[i].status) >= PEER_SYNCSOURCE){
  218. printf(" <-- current sync source");
  219. } else {
  220. printf(" <-- current sync candidate");
  221. }
  222. }
  223. printf("\n");
  224. }
  225. }
  226. }
  227. void setup_request(ntp_message *p){
  228. struct timeval t;
  229. memset(p, 0, sizeof(ntp_message));
  230. LI_SET(p->flags, LI_ALARM);
  231. VN_SET(p->flags, 4);
  232. MODE_SET(p->flags, MODE_CLIENT);
  233. p->poll=4;
  234. p->precision=0xfa;
  235. L16(p->rtdelay)=htons(1);
  236. L16(p->rtdisp)=htons(1);
  237. gettimeofday(&t, NULL);
  238. TVtoNTP64(t,p->txts);
  239. }
  240. double offset_request(const char *host){
  241. int i=0, conn=-1;
  242. ntp_message req;
  243. double next_offset=0., avg_offset=0.;
  244. struct timeval recv_time;
  245. for(i=0; i<AVG_NUM; i++){
  246. if(verbose) printf("offset run: %d/%d\n", i+1, AVG_NUM);
  247. setup_request(&req);
  248. my_udp_connect(server_address, 123, &conn);
  249. write(conn, &req, sizeof(ntp_message));
  250. read(conn, &req, sizeof(ntp_message));
  251. gettimeofday(&recv_time, NULL);
  252. /* if(verbose) print_packet(&req); */
  253. close(conn);
  254. next_offset=calc_offset(&req, &recv_time);
  255. if(verbose) printf("offset: %g\n", next_offset);
  256. avg_offset+=next_offset;
  257. }
  258. avg_offset/=AVG_NUM;
  259. if(verbose) printf("average offset: %g\n", avg_offset);
  260. return avg_offset;
  261. }
  262. /* this should behave more like ntpdate, but needs optomisations... */
  263. double offset_request_ntpdate(const char *host){
  264. int i=0, j=0, ga_result=0, num_hosts=0, *socklist=NULL;
  265. ntp_message req;
  266. double offset=0., avg_offset=0.;
  267. struct timeval recv_time;
  268. struct addrinfo *ai=NULL, *ai_tmp=NULL, hints;
  269. /* setup hints to only return results from getaddrinfo that we'd like */
  270. memset(&hints, 0, sizeof(struct addrinfo));
  271. hints.ai_family = address_family;
  272. hints.ai_protocol = IPPROTO_UDP;
  273. hints.ai_socktype = SOCK_DGRAM;
  274. /* XXX better error handling here... */
  275. ga_result = getaddrinfo(host, "123", &hints, &ai);
  276. if(ga_result!=0){
  277. fprintf(stderr, "error getting address for %s: %s\n",
  278. host, gai_strerror(ga_result));
  279. return -1.0;
  280. }
  281. /* count te number of returned hosts, and allocate an array of sockets */
  282. ai_tmp=ai;
  283. while(ai_tmp){
  284. ai_tmp = ai_tmp->ai_next;
  285. num_hosts++;
  286. }
  287. socklist=(int*)malloc(sizeof(int)*num_hosts);
  288. if(socklist==NULL) die(STATE_UNKNOWN, "can not allocate socket array");
  289. /* setup each socket for writing */
  290. ai_tmp=ai;
  291. for(i=0;ai_tmp;i++){
  292. socklist[i]=socket(ai_tmp->ai_family, SOCK_DGRAM, IPPROTO_UDP);
  293. if(socklist[i] == -1) {
  294. perror(NULL);
  295. die(STATE_UNKNOWN, "can not create new socket");
  296. }
  297. if(connect(socklist[i], ai_tmp->ai_addr, ai_tmp->ai_addrlen)){
  298. die(STATE_UNKNOWN, "can't create socket connection");
  299. }
  300. ai_tmp = ai_tmp->ai_next;
  301. }
  302. /* now do AVG_NUM checks to each host. this needs to be optimized
  303. * two ways:
  304. * - use some parellization w/poll for much faster results. currently
  305. * we do send/recv, send/recv, etc, whereas we could use poll(), to
  306. * determine when to read and just do a bunch of writing when we
  307. * have free time.
  308. * - behave like ntpdate and only take the 5 best responses.
  309. */
  310. for(i=0; i<AVG_NUM; i++){
  311. if(verbose) printf("offset calculation run %d/%d\n", i+1, AVG_NUM);
  312. for(j=0; j<num_hosts; j++){
  313. if(verbose) printf("peer %d: ", j);
  314. setup_request(&req);
  315. write(socklist[j], &req, sizeof(ntp_message));
  316. read(socklist[j], &req, sizeof(ntp_message));
  317. gettimeofday(&recv_time, NULL);
  318. offset=calc_offset(&req, &recv_time);
  319. if(verbose) printf("offset: %g\n", offset);
  320. avg_offset+=offset;
  321. }
  322. avg_offset/=num_hosts;
  323. }
  324. avg_offset/=AVG_NUM;
  325. if(verbose) printf("overall average offset: %g\n", avg_offset);
  326. for(j=0; j<num_hosts; j++){ close(socklist[j]); }
  327. freeaddrinfo(ai);
  328. return avg_offset;
  329. }
  330. void
  331. setup_control_request(ntp_control_message *p, uint8_t opcode, uint16_t seq){
  332. memset(p, 0, sizeof(ntp_control_message));
  333. LI_SET(p->flags, LI_NOWARNING);
  334. VN_SET(p->flags, VN_RESERVED);
  335. MODE_SET(p->flags, MODE_CONTROLMSG);
  336. OP_SET(p->op, opcode);
  337. p->seq = htons(seq);
  338. /* Remaining fields are zero for requests */
  339. }
  340. /* XXX handle responses with the error bit set */
  341. double jitter_request(const char *host){
  342. int conn=-1, i, npeers=0, num_candidates=0, syncsource_found=0;
  343. int run=0, min_peer_sel=PEER_INCLUDED, num_selected=0, num_valid=0;
  344. ntp_assoc_status_pair *peers;
  345. ntp_control_message req;
  346. double rval = 0.0, jitter = -1.0;
  347. char *startofvalue=NULL, *nptr=NULL;
  348. /* Long-winded explanation:
  349. * Getting the jitter requires a number of steps:
  350. * 1) Send a READSTAT request.
  351. * 2) Interpret the READSTAT reply
  352. * a) The data section contains a list of peer identifiers (16 bits)
  353. * and associated status words (16 bits)
  354. * b) We want the value of 0x06 in the SEL (peer selection) value,
  355. * which means "current synchronizatin source". If that's missing,
  356. * we take anything better than 0x04 (see the rfc for details) but
  357. * set a minimum of warning.
  358. * 3) Send a READVAR request for information on each peer identified
  359. * in 2b greater than the minimum selection value.
  360. * 4) Extract the jitter value from the data[] (it's ASCII)
  361. */
  362. my_udp_connect(server_address, 123, &conn);
  363. setup_control_request(&req, OP_READSTAT, 1);
  364. DBG(printf("sending READSTAT request"));
  365. write(conn, &req, SIZEOF_NTPCM(req));
  366. DBG(print_ntp_control_message(&req));
  367. /* Attempt to read the largest size packet possible
  368. * Is it possible for an NTP server to have more than 117 synchronization
  369. * sources? If so, we will receive a second datagram with additional
  370. * peers listed, since 117 is the maximum number that can fit in a
  371. * single NTP control datagram. This code doesn't handle that case */
  372. /* XXX check the REM_MORE bit */
  373. req.count=htons(MAX_CM_SIZE);
  374. DBG(printf("recieving READSTAT response"))
  375. read(conn, &req, SIZEOF_NTPCM(req));
  376. DBG(print_ntp_control_message(&req));
  377. /* Each peer identifier is 4 bytes in the data section, which
  378. * we represent as a ntp_assoc_status_pair datatype.
  379. */
  380. npeers=ntohs(req.count)/sizeof(ntp_assoc_status_pair);
  381. peers=(ntp_assoc_status_pair*)malloc(sizeof(ntp_assoc_status_pair)*npeers);
  382. memcpy((void*)peers, (void*)req.data, sizeof(ntp_assoc_status_pair)*npeers);
  383. /* first, let's find out if we have a sync source, or if there are
  384. * at least some candidates. in the case of the latter we'll issue
  385. * a warning but go ahead with the check on them. */
  386. for (i = 0; i < npeers; i++){
  387. if (PEER_SEL(peers[i].status) >= PEER_INCLUDED){
  388. num_candidates++;
  389. if(PEER_SEL(peers[i].status) >= PEER_SYNCSOURCE){
  390. syncsource_found=1;
  391. min_peer_sel=PEER_SYNCSOURCE;
  392. }
  393. }
  394. }
  395. if(verbose) printf("%d candiate peers available\n", num_candidates);
  396. if(verbose && syncsource_found) printf("synchronization source found\n");
  397. /* XXX if ! syncsource_found set status to warning */
  398. for (run=0; run<AVG_NUM; run++){
  399. if(verbose) printf("jitter run %d of %d\n", run+1, AVG_NUM);
  400. for (i = 0; i < npeers; i++){
  401. /* Only query this server if it is the current sync source */
  402. if (PEER_SEL(peers[i].status) >= min_peer_sel){
  403. setup_control_request(&req, OP_READVAR, 2);
  404. req.assoc = peers[i].assoc;
  405. /* By spec, putting the variable name "jitter" in the request
  406. * should cause the server to provide _only_ the jitter value.
  407. * thus reducing net traffic, guaranteeing us only a single
  408. * datagram in reply, and making intepretation much simpler
  409. */
  410. strncpy(req.data, "jitter", 6);
  411. req.count = htons(6);
  412. DBG(printf("sending READVAR request...\n"));
  413. write(conn, &req, SIZEOF_NTPCM(req));
  414. DBG(print_ntp_control_message(&req));
  415. req.count = htons(MAX_CM_SIZE);
  416. DBG(printf("recieving READVAR response...\n"));
  417. read(conn, &req, SIZEOF_NTPCM(req));
  418. DBG(print_ntp_control_message(&req));
  419. /* get to the float value */
  420. if(verbose) {
  421. printf("parsing jitter from peer %.2x: ", peers[i].assoc);
  422. }
  423. startofvalue = strchr(req.data, '=') + 1;
  424. jitter = strtod(startofvalue, &nptr);
  425. num_selected++;
  426. if(jitter == 0 && startofvalue==nptr){
  427. printf("warning: unable to parse server response.\n");
  428. /* XXX errors value ... */
  429. } else {
  430. if(verbose) printf("%g\n", jitter);
  431. num_valid++;
  432. rval += jitter;
  433. }
  434. }
  435. }
  436. if(verbose){
  437. printf("jitter parsed from %d/%d peers\n", num_selected, num_valid);
  438. }
  439. }
  440. rval /= num_valid;
  441. close(conn);
  442. free(peers);
  443. /* If we return -1.0, it means no synchronization source was found */
  444. return rval;
  445. }
  446. int process_arguments(int argc, char **argv){
  447. int c;
  448. int option=0;
  449. static struct option longopts[] = {
  450. {"version", no_argument, 0, 'V'},
  451. {"help", no_argument, 0, 'h'},
  452. {"verbose", no_argument, 0, 'v'},
  453. {"use-ipv4", no_argument, 0, '4'},
  454. {"use-ipv6", no_argument, 0, '6'},
  455. {"warning", required_argument, 0, 'w'},
  456. {"critical", required_argument, 0, 'c'},
  457. {"zero-offset", no_argument, 0, 'O'},
  458. {"jwarn", required_argument, 0, 'j'},
  459. {"jcrit", required_argument, 0, 'k'},
  460. {"timeout", required_argument, 0, 't'},
  461. {"hostname", required_argument, 0, 'H'},
  462. {0, 0, 0, 0}
  463. };
  464. if (argc < 2)
  465. usage ("\n");
  466. while (1) {
  467. c = getopt_long (argc, argv, "Vhv46w:c:Oj:k:t:H:", longopts, &option);
  468. if (c == -1 || c == EOF || c == 1)
  469. break;
  470. switch (c) {
  471. case 'h':
  472. print_help();
  473. exit(STATE_OK);
  474. break;
  475. case 'V':
  476. print_revision(progname, revision);
  477. exit(STATE_OK);
  478. break;
  479. case 'v':
  480. verbose++;
  481. break;
  482. case 'w':
  483. owarn = atof(optarg);
  484. break;
  485. case 'c':
  486. ocrit = atof(optarg);
  487. break;
  488. case 'j':
  489. do_jitter=1;
  490. jwarn = atof(optarg);
  491. break;
  492. case 'k':
  493. do_jitter=1;
  494. jcrit = atof(optarg);
  495. break;
  496. case 'H':
  497. if(is_host(optarg) == FALSE)
  498. usage2(_("Invalid hostname/address"), optarg);
  499. server_address = strdup(optarg);
  500. break;
  501. case 't':
  502. socket_timeout=atoi(optarg);
  503. break;
  504. case 'O':
  505. zero_offset_bad=1;
  506. break;
  507. case '4':
  508. address_family = AF_INET;
  509. break;
  510. case '6':
  511. #ifdef USE_IPV6
  512. address_family = AF_INET6;
  513. #else
  514. usage4 (_("IPv6 support not available"));
  515. #endif
  516. break;
  517. case '?':
  518. /* print short usage statement if args not parsable */
  519. usage2 (_("Unknown argument"), optarg);
  520. break;
  521. }
  522. }
  523. if (ocrit < owarn){
  524. usage4(_("Critical offset should be larger than warning offset"));
  525. }
  526. if (ocrit < owarn){
  527. usage4(_("Critical jitter should be larger than warning jitter"));
  528. }
  529. if(server_address == NULL){
  530. usage4(_("Hostname was not supplied"));
  531. }
  532. return 0;
  533. }
  534. int main(int argc, char *argv[]){
  535. int result = STATE_UNKNOWN;
  536. double offset=0, jitter=0;
  537. if (process_arguments (argc, argv) == ERROR)
  538. usage4 (_("Could not parse arguments"));
  539. /* initialize alarm signal handling */
  540. signal (SIGALRM, socket_timeout_alarm_handler);
  541. /* set socket timeout */
  542. alarm (socket_timeout);
  543. offset = offset_request(server_address);
  544. if(offset > ocrit){
  545. result = STATE_CRITICAL;
  546. } else if(offset > owarn) {
  547. result = STATE_WARNING;
  548. } else {
  549. result = STATE_OK;
  550. }
  551. /* If not told to check the jitter, we don't even send packets.
  552. * jitter is checked using NTP control packets, which not all
  553. * servers recognize. Trying to check the jitter on OpenNTPD
  554. * (for example) will result in an error
  555. */
  556. if(do_jitter){
  557. jitter=jitter_request(server_address);
  558. if(jitter > jcrit){
  559. result = max_state(result, STATE_CRITICAL);
  560. } else if(jitter > jwarn) {
  561. result = max_state(result, STATE_WARNING);
  562. } else if(jitter == -1.0 && result == STATE_OK){
  563. /* -1 indicates that we couldn't calculate the jitter
  564. * Only overrides STATE_OK from the offset */
  565. result = STATE_UNKNOWN;
  566. }
  567. }
  568. switch (result) {
  569. case STATE_CRITICAL :
  570. printf("NTP CRITICAL: ");
  571. break;
  572. case STATE_WARNING :
  573. printf("NTP WARNING: ");
  574. break;
  575. case STATE_OK :
  576. printf("NTP OK: ");
  577. break;
  578. default :
  579. printf("NTP UNKNOWN: ");
  580. break;
  581. }
  582. printf("Offset %g secs|offset=%g", offset, offset);
  583. if (do_jitter) printf("|jitter=%f", jitter);
  584. printf("\n");
  585. if(server_address!=NULL) free(server_address);
  586. return result;
  587. }
  588. void print_usage(void){
  589. printf("\
  590. Usage: %s -H <host> [-O] [-w <warn>] [-c <crit>] [-j <warn>] [-k <crit>] [-v verbose]\
  591. \n", progname);
  592. }
  593. void print_help(void){
  594. print_revision(progname, revision);
  595. printf ("Copyright (c) 1999 Ethan Galstad\n");
  596. printf (COPYRIGHT, copyright, email);
  597. print_usage();
  598. printf (_(UT_HELP_VRSN));
  599. printf (_(UT_HOST_PORT), 'p', "123");
  600. printf (_(UT_WARN_CRIT));
  601. printf (_(UT_TIMEOUT), DEFAULT_SOCKET_TIMEOUT);
  602. printf (_(UT_VERBOSE));
  603. printf(_(UT_SUPPORT));
  604. }