check_ntp.c 24 KB

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