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