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