1 /******************************************************************************
2 *
3 * Nagios check_ntp plugin
4 *
5 * License: GPL
6 * Copyright (c) 2006 sean finney <seanius@seanius.net>
7 * Copyright (c) 2006 nagios-plugins team
8 *
9 * Last Modified: $Date$
10 *
11 * Description:
12 *
13 * This file contains the check_ntp plugin
14 *
15 * This plugin to check ntp servers independant of any commandline
16 * programs or external libraries.
17 *
18 *
19 * License Information:
20 *
21 * This program is free software; you can redistribute it and/or modify
22 * it under the terms of the GNU General Public License as published by
23 * the Free Software Foundation; either version 2 of the License, or
24 * (at your option) any later version.
25 *
26 * This program is distributed in the hope that it will be useful,
27 * but WITHOUT ANY WARRANTY; without even the implied warranty of
28 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
29 * GNU General Public License for more details.
30 *
31 * You should have received a copy of the GNU General Public License
32 * along with this program; if not, write to the Free Software
33 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
35 $Id$
37 *****************************************************************************/
39 const char *progname = "check_ntp";
40 const char *revision = "$Revision$";
41 const char *copyright = "2006";
42 const char *email = "nagiosplug-devel@lists.sourceforge.net";
44 #include "common.h"
45 #include "netutils.h"
46 #include "utils.h"
48 static char *server_address=NULL;
49 static int verbose=0;
50 static double owarn=60;
51 static double ocrit=120;
52 static short do_jitter=0;
53 static double jwarn=5000;
54 static double jcrit=10000;
56 int process_arguments (int, char **);
57 void print_help (void);
58 void print_usage (void);
60 /* number of times to perform each request to get a good average. */
61 #define AVG_NUM 4
63 /* max size of control message data */
64 #define MAX_CM_SIZE 468
66 /* this structure holds everything in an ntp request/response as per rfc1305 */
67 typedef struct {
68 uint8_t flags; /* byte with leapindicator,vers,mode. see macros */
69 uint8_t stratum; /* clock stratum */
70 int8_t poll; /* polling interval */
71 int8_t precision; /* precision of the local clock */
72 int32_t rtdelay; /* total rt delay, as a fixed point num. see macros */
73 uint32_t rtdisp; /* like above, but for max err to primary src */
74 uint32_t refid; /* ref clock identifier */
75 uint64_t refts; /* reference timestamp. local time local clock */
76 uint64_t origts; /* time at which request departed client */
77 uint64_t rxts; /* time at which request arrived at server */
78 uint64_t txts; /* time at which request departed server */
79 } ntp_message;
81 /* this structure holds data about results from querying offset from a peer */
82 typedef struct {
83 time_t waiting; /* ts set when we started waiting for a response */
84 int num_responses; /* number of successfully recieved responses */
85 uint8_t stratum; /* copied verbatim from the ntp_message */
86 double rtdelay; /* converted from the ntp_message */
87 double rtdisp; /* converted from the ntp_message */
88 double offset[AVG_NUM]; /* offsets from each response */
89 } ntp_server_results;
91 /* this structure holds everything in an ntp control message as per rfc1305 */
92 typedef struct {
93 uint8_t flags; /* byte with leapindicator,vers,mode. see macros */
94 uint8_t op; /* R,E,M bits and Opcode */
95 uint16_t seq; /* Packet sequence */
96 uint16_t status; /* Clock status */
97 uint16_t assoc; /* Association */
98 uint16_t offset; /* Similar to TCP sequence # */
99 uint16_t count; /* # bytes of data */
100 char data[MAX_CM_SIZE]; /* ASCII data of the request */
101 /* NB: not necessarily NULL terminated! */
102 } ntp_control_message;
104 /* this is an association/status-word pair found in control packet reponses */
105 typedef struct {
106 uint16_t assoc;
107 uint16_t status;
108 } ntp_assoc_status_pair;
110 /* bits 1,2 are the leap indicator */
111 #define LI_MASK 0xc0
112 #define LI(x) ((x&LI_MASK)>>6)
113 #define LI_SET(x,y) do{ x |= ((y<<6)&LI_MASK); }while(0)
114 /* and these are the values of the leap indicator */
115 #define LI_NOWARNING 0x00
116 #define LI_EXTRASEC 0x01
117 #define LI_MISSINGSEC 0x02
118 #define LI_ALARM 0x03
119 /* bits 3,4,5 are the ntp version */
120 #define VN_MASK 0x38
121 #define VN(x) ((x&VN_MASK)>>3)
122 #define VN_SET(x,y) do{ x |= ((y<<3)&VN_MASK); }while(0)
123 #define VN_RESERVED 0x02
124 /* bits 6,7,8 are the ntp mode */
125 #define MODE_MASK 0x07
126 #define MODE(x) (x&MODE_MASK)
127 #define MODE_SET(x,y) do{ x |= (y&MODE_MASK); }while(0)
128 /* here are some values */
129 #define MODE_CLIENT 0x03
130 #define MODE_CONTROLMSG 0x06
131 /* In control message, bits 8-10 are R,E,M bits */
132 #define REM_MASK 0xe0
133 #define REM_RESP 0x80
134 #define REM_ERROR 0x40
135 #define REM_MORE 0x20
136 /* In control message, bits 11 - 15 are opcode */
137 #define OP_MASK 0x1f
138 #define OP_SET(x,y) do{ x |= (y&OP_MASK); }while(0)
139 #define OP_READSTAT 0x01
140 #define OP_READVAR 0x02
141 /* In peer status bytes, bytes 6,7,8 determine clock selection status */
142 #define PEER_SEL(x) (x&0x07)
143 #define PEER_INCLUDED 0x04
144 #define PEER_SYNCSOURCE 0x06
146 /**
147 ** a note about the 32-bit "fixed point" numbers:
148 **
149 they are divided into halves, each being a 16-bit int in network byte order:
150 - the first 16 bits are an int on the left side of a decimal point.
151 - the second 16 bits represent a fraction n/(2^16)
152 likewise for the 64-bit "fixed point" numbers with everything doubled :)
153 **/
155 /* macros to access the left/right 16 bits of a 32-bit ntp "fixed point"
156 number. note that these can be used as lvalues too */
157 #define L16(x) (((uint16_t*)&x)[0])
158 #define R16(x) (((uint16_t*)&x)[1])
159 /* macros to access the left/right 32 bits of a 64-bit ntp "fixed point"
160 number. these too can be used as lvalues */
161 #define L32(x) (((uint32_t*)&x)[0])
162 #define R32(x) (((uint32_t*)&x)[1])
164 /* ntp wants seconds since 1/1/00, epoch is 1/1/70. this is the difference */
165 #define EPOCHDIFF 0x83aa7e80UL
167 /* extract a 32-bit ntp fixed point number into a double */
168 #define NTP32asDOUBLE(x) (ntohs(L16(x)) + (double)ntohs(R16(x))/65536.0)
170 /* likewise for a 64-bit ntp fp number */
171 #define NTP64asDOUBLE(n) (double)(((uint64_t)n)?\
172 (ntohl(L32(n))-EPOCHDIFF) + \
173 (.00000001*(0.5+(double)(ntohl(R32(n))/42.94967296))):\
174 0)
176 /* convert a struct timeval to a double */
177 #define TVasDOUBLE(x) (double)(x.tv_sec+(0.000001*x.tv_usec))
179 /* convert an ntp 64-bit fp number to a struct timeval */
180 #define NTP64toTV(n,t) \
181 do{ if(!n) t.tv_sec = t.tv_usec = 0; \
182 else { \
183 t.tv_sec=ntohl(L32(n))-EPOCHDIFF; \
184 t.tv_usec=(int)(0.5+(double)(ntohl(R32(n))/4294.967296)); \
185 } \
186 }while(0)
188 /* convert a struct timeval to an ntp 64-bit fp number */
189 #define TVtoNTP64(t,n) \
190 do{ if(!t.tv_usec && !t.tv_sec) n=0x0UL; \
191 else { \
192 L32(n)=htonl(t.tv_sec + EPOCHDIFF); \
193 R32(n)=htonl((uint64_t)((4294.967296*t.tv_usec)+.5)); \
194 } \
195 } while(0)
197 /* NTP control message header is 12 bytes, plus any data in the data
198 * field, plus null padding to the nearest 32-bit boundary per rfc.
199 */
200 #define SIZEOF_NTPCM(m) (12+ntohs(m.count)+((m.count)?4-(ntohs(m.count)%4):0))
202 /* finally, a little helper or two for debugging: */
203 #define DBG(x) do{if(verbose>1){ x; }}while(0);
204 #define PRINTSOCKADDR(x) \
205 do{ \
206 printf("%u.%u.%u.%u", (x>>24)&0xff, (x>>16)&0xff, (x>>8)&0xff, x&0xff);\
207 }while(0);
209 /* calculate the offset of the local clock */
210 static inline double calc_offset(const ntp_message *m, const struct timeval *t){
211 double client_tx, peer_rx, peer_tx, client_rx;
212 client_tx = NTP64asDOUBLE(m->origts);
213 peer_rx = NTP64asDOUBLE(m->rxts);
214 peer_tx = NTP64asDOUBLE(m->txts);
215 client_rx=TVasDOUBLE((*t));
216 return (.5*((peer_tx-client_rx)+(peer_rx-client_tx)));
217 }
219 /* print out a ntp packet in human readable/debuggable format */
220 void print_ntp_message(const ntp_message *p){
221 struct timeval ref, orig, rx, tx;
223 NTP64toTV(p->refts,ref);
224 NTP64toTV(p->origts,orig);
225 NTP64toTV(p->rxts,rx);
226 NTP64toTV(p->txts,tx);
228 printf("packet contents:\n");
229 printf("\tflags: 0x%.2x\n", p->flags);
230 printf("\t li=%d (0x%.2x)\n", LI(p->flags), p->flags&LI_MASK);
231 printf("\t vn=%d (0x%.2x)\n", VN(p->flags), p->flags&VN_MASK);
232 printf("\t mode=%d (0x%.2x)\n", MODE(p->flags), p->flags&MODE_MASK);
233 printf("\tstratum = %d\n", p->stratum);
234 printf("\tpoll = %g\n", pow(2, p->poll));
235 printf("\tprecision = %g\n", pow(2, p->precision));
236 printf("\trtdelay = %-.16g\n", NTP32asDOUBLE(p->rtdelay));
237 printf("\trtdisp = %-.16g\n", NTP32asDOUBLE(p->rtdisp));
238 printf("\trefid = %x\n", p->refid);
239 printf("\trefts = %-.16g\n", NTP64asDOUBLE(p->refts));
240 printf("\torigts = %-.16g\n", NTP64asDOUBLE(p->origts));
241 printf("\trxts = %-.16g\n", NTP64asDOUBLE(p->rxts));
242 printf("\ttxts = %-.16g\n", NTP64asDOUBLE(p->txts));
243 }
245 void print_ntp_control_message(const ntp_control_message *p){
246 int i=0, numpeers=0;
247 const ntp_assoc_status_pair *peer=NULL;
249 printf("control packet contents:\n");
250 printf("\tflags: 0x%.2x , 0x%.2x\n", p->flags, p->op);
251 printf("\t li=%d (0x%.2x)\n", LI(p->flags), p->flags&LI_MASK);
252 printf("\t vn=%d (0x%.2x)\n", VN(p->flags), p->flags&VN_MASK);
253 printf("\t mode=%d (0x%.2x)\n", MODE(p->flags), p->flags&MODE_MASK);
254 printf("\t response=%d (0x%.2x)\n", (p->op&REM_RESP)>0, p->op&REM_RESP);
255 printf("\t more=%d (0x%.2x)\n", (p->op&REM_MORE)>0, p->op&REM_MORE);
256 printf("\t error=%d (0x%.2x)\n", (p->op&REM_ERROR)>0, p->op&REM_ERROR);
257 printf("\t op=%d (0x%.2x)\n", p->op&OP_MASK, p->op&OP_MASK);
258 printf("\tsequence: %d (0x%.2x)\n", ntohs(p->seq), ntohs(p->seq));
259 printf("\tstatus: %d (0x%.2x)\n", ntohs(p->status), ntohs(p->status));
260 printf("\tassoc: %d (0x%.2x)\n", ntohs(p->assoc), ntohs(p->assoc));
261 printf("\toffset: %d (0x%.2x)\n", ntohs(p->offset), ntohs(p->offset));
262 printf("\tcount: %d (0x%.2x)\n", ntohs(p->count), ntohs(p->count));
263 numpeers=ntohs(p->count)/(sizeof(ntp_assoc_status_pair));
264 if(p->op&REM_RESP && p->op&OP_READSTAT){
265 peer=(ntp_assoc_status_pair*)p->data;
266 for(i=0;i<numpeers;i++){
267 printf("\tpeer id %.2x status %.2x",
268 ntohs(peer[i].assoc), ntohs(peer[i].status));
269 if (PEER_SEL(peer[i].status) >= PEER_INCLUDED){
270 if(PEER_SEL(peer[i].status) >= PEER_SYNCSOURCE){
271 printf(" <-- current sync source");
272 } else {
273 printf(" <-- current sync candidate");
274 }
275 }
276 printf("\n");
277 }
278 }
279 }
281 void setup_request(ntp_message *p){
282 struct timeval t;
284 memset(p, 0, sizeof(ntp_message));
285 LI_SET(p->flags, LI_ALARM);
286 VN_SET(p->flags, 4);
287 MODE_SET(p->flags, MODE_CLIENT);
288 p->poll=4;
289 p->precision=(int8_t)0xfa;
290 L16(p->rtdelay)=htons(1);
291 L16(p->rtdisp)=htons(1);
293 gettimeofday(&t, NULL);
294 TVtoNTP64(t,p->txts);
295 }
297 /* select the "best" server from a list of servers, and return its index.
298 * this is done by filtering servers based on stratum, dispersion, and
299 * finally round-trip delay. */
300 int best_offset_server(const ntp_server_results *slist, int nservers){
301 int i=0, j=0, cserver=0, candidates[5], csize=0;
303 /* for each server */
304 for(cserver=0; cserver<nservers; cserver++){
305 /* compare it to each of the servers already in the candidate list */
306 for(i=0; i<csize; i++){
307 /* does it have an equal or better stratum? */
308 if(slist[cserver].stratum <= slist[i].stratum){
309 /* does it have an equal or better dispersion? */
310 if(slist[cserver].rtdisp <= slist[i].rtdisp){
311 /* does it have a better rtdelay? */
312 if(slist[cserver].rtdelay < slist[i].rtdelay){
313 break;
314 }
315 }
316 }
317 }
319 /* if we haven't reached the current list's end, move everyone
320 * over one to the right, and insert the new candidate */
321 if(i<csize){
322 for(j=5; j>i; j--){
323 candidates[j]=candidates[j-1];
324 }
325 }
326 /* regardless, if they should be on the list... */
327 if(i<5) {
328 candidates[i]=cserver;
329 if(csize<5) csize++;
330 /* otherwise discard the server */
331 } else {
332 DBG(printf("discarding peer id %d\n", cserver));
333 }
334 }
336 if(csize>0) {
337 DBG(printf("best server selected: peer %d\n", candidates[0]));
338 return candidates[0];
339 } else {
340 DBG(printf("no peers meeting synchronization criteria :(\n"));
341 return -1;
342 }
343 }
345 /* do everything we need to get the total average offset
346 * - we use a certain amount of parallelization with poll() to ensure
347 * we don't waste time sitting around waiting for single packets.
348 * - we also "manually" handle resolving host names and connecting, because
349 * we have to do it in a way that our lazy macros don't handle currently :( */
350 double offset_request(const char *host, int *status){
351 int i=0, j=0, ga_result=0, num_hosts=0, *socklist=NULL, respnum=0;
352 int servers_completed=0, one_written=0, one_read=0, servers_readable=0, best_index=-1;
353 time_t now_time=0, start_ts=0;
354 ntp_message *req=NULL;
355 double avg_offset=0.;
356 struct timeval recv_time;
357 struct addrinfo *ai=NULL, *ai_tmp=NULL, hints;
358 struct pollfd *ufds=NULL;
359 ntp_server_results *servers=NULL;
361 /* setup hints to only return results from getaddrinfo that we'd like */
362 memset(&hints, 0, sizeof(struct addrinfo));
363 hints.ai_family = address_family;
364 hints.ai_protocol = IPPROTO_UDP;
365 hints.ai_socktype = SOCK_DGRAM;
367 /* fill in ai with the list of hosts resolved by the host name */
368 ga_result = getaddrinfo(host, "123", &hints, &ai);
369 if(ga_result!=0){
370 die(STATE_UNKNOWN, "error getting address for %s: %s\n",
371 host, gai_strerror(ga_result));
372 }
374 /* count the number of returned hosts, and allocate stuff accordingly */
375 for(ai_tmp=ai; ai_tmp!=NULL; ai_tmp=ai_tmp->ai_next){ num_hosts++; }
376 req=(ntp_message*)malloc(sizeof(ntp_message)*num_hosts);
377 if(req==NULL) die(STATE_UNKNOWN, "can not allocate ntp message array");
378 socklist=(int*)malloc(sizeof(int)*num_hosts);
379 if(socklist==NULL) die(STATE_UNKNOWN, "can not allocate socket array");
380 ufds=(struct pollfd*)malloc(sizeof(struct pollfd)*num_hosts);
381 if(ufds==NULL) die(STATE_UNKNOWN, "can not allocate socket array");
382 servers=(ntp_server_results*)malloc(sizeof(ntp_server_results)*num_hosts);
383 if(servers==NULL) die(STATE_UNKNOWN, "can not allocate server array");
384 memset(servers, 0, sizeof(ntp_server_results)*num_hosts);
386 /* setup each socket for writing, and the corresponding struct pollfd */
387 ai_tmp=ai;
388 for(i=0;ai_tmp;i++){
389 socklist[i]=socket(ai_tmp->ai_family, SOCK_DGRAM, IPPROTO_UDP);
390 if(socklist[i] == -1) {
391 perror(NULL);
392 die(STATE_UNKNOWN, "can not create new socket");
393 }
394 if(connect(socklist[i], ai_tmp->ai_addr, ai_tmp->ai_addrlen)){
395 die(STATE_UNKNOWN, "can't create socket connection");
396 } else {
397 ufds[i].fd=socklist[i];
398 ufds[i].events=POLLIN;
399 ufds[i].revents=0;
400 }
401 ai_tmp = ai_tmp->ai_next;
402 }
404 /* now do AVG_NUM checks to each host. we stop before timeout/2 seconds
405 * have passed in order to ensure post-processing and jitter time. */
406 now_time=start_ts=time(NULL);
407 while(servers_completed<num_hosts && now_time-start_ts <= socket_timeout/2){
408 /* loop through each server and find each one which hasn't
409 * been touched in the past second or so and is still lacking
410 * some responses. for each of these servers, send a new request,
411 * and update the "waiting" timestamp with the current time. */
412 one_written=0;
413 now_time=time(NULL);
415 for(i=0; i<num_hosts; i++){
416 if(servers[i].waiting<now_time && servers[i].num_responses<AVG_NUM){
417 if(verbose && servers[i].waiting != 0) printf("re-");
418 if(verbose) printf("sending request to peer %d\n", i);
419 setup_request(&req[i]);
420 write(socklist[i], &req[i], sizeof(ntp_message));
421 servers[i].waiting=now_time;
422 one_written=1;
423 break;
424 }
425 }
427 /* quickly poll for any sockets with pending data */
428 servers_readable=poll(ufds, num_hosts, 100);
429 if(servers_readable==-1){
430 perror("polling ntp sockets");
431 die(STATE_UNKNOWN, "communication errors");
432 }
434 /* read from any sockets with pending data */
435 for(i=0; servers_readable && i<num_hosts; i++){
436 if(ufds[i].revents&POLLIN && servers[i].num_responses < AVG_NUM){
437 if(verbose) {
438 printf("response from peer %d: ", i);
439 }
441 read(ufds[i].fd, &req[i], sizeof(ntp_message));
442 gettimeofday(&recv_time, NULL);
443 DBG(print_ntp_message(&req[i]));
444 respnum=servers[i].num_responses++;
445 servers[i].offset[respnum]=calc_offset(&req[i], &recv_time);
446 if(verbose) {
447 printf("offset %.10g\n", servers[i].offset[respnum]);
448 }
449 servers[i].stratum=req[i].stratum;
450 servers[i].rtdisp=NTP32asDOUBLE(req[i].rtdisp);
451 servers[i].rtdelay=NTP32asDOUBLE(req[i].rtdelay);
452 servers[i].waiting=0;
453 servers_readable--;
454 one_read = 1;
455 if(servers[i].num_responses==AVG_NUM) servers_completed++;
456 }
457 }
458 /* lather, rinse, repeat. */
459 }
461 if (one_read == 0) {
462 die(STATE_CRITICAL, "NTP CRITICAL: No response from NTP server\n");
463 }
465 /* now, pick the best server from the list */
466 best_index=best_offset_server(servers, num_hosts);
467 if(best_index < 0){
468 *status=STATE_CRITICAL;
469 } else {
470 /* finally, calculate the average offset */
471 for(i=0; i<servers[best_index].num_responses;i++){
472 avg_offset+=servers[best_index].offset[j];
473 }
474 avg_offset/=servers[best_index].num_responses;
475 }
477 /* cleanup */
478 for(j=0; j<num_hosts; j++){ close(socklist[j]); }
479 free(socklist);
480 free(ufds);
481 free(servers);
482 free(req);
483 freeaddrinfo(ai);
485 if(verbose) printf("overall average offset: %.10g\n", avg_offset);
486 return avg_offset;
487 }
489 void
490 setup_control_request(ntp_control_message *p, uint8_t opcode, uint16_t seq){
491 memset(p, 0, sizeof(ntp_control_message));
492 LI_SET(p->flags, LI_NOWARNING);
493 VN_SET(p->flags, VN_RESERVED);
494 MODE_SET(p->flags, MODE_CONTROLMSG);
495 OP_SET(p->op, opcode);
496 p->seq = htons(seq);
497 /* Remaining fields are zero for requests */
498 }
500 /* XXX handle responses with the error bit set */
501 double jitter_request(const char *host, int *status){
502 int conn=-1, i, npeers=0, num_candidates=0, syncsource_found=0;
503 int run=0, min_peer_sel=PEER_INCLUDED, num_selected=0, num_valid=0;
504 int peers_size=0, peer_offset=0;
505 ntp_assoc_status_pair *peers=NULL;
506 ntp_control_message req;
507 double rval = 0.0, jitter = -1.0;
508 char *startofvalue=NULL, *nptr=NULL;
509 void *tmp;
511 /* Long-winded explanation:
512 * Getting the jitter requires a number of steps:
513 * 1) Send a READSTAT request.
514 * 2) Interpret the READSTAT reply
515 * a) The data section contains a list of peer identifiers (16 bits)
516 * and associated status words (16 bits)
517 * b) We want the value of 0x06 in the SEL (peer selection) value,
518 * which means "current synchronizatin source". If that's missing,
519 * we take anything better than 0x04 (see the rfc for details) but
520 * set a minimum of warning.
521 * 3) Send a READVAR request for information on each peer identified
522 * in 2b greater than the minimum selection value.
523 * 4) Extract the jitter value from the data[] (it's ASCII)
524 */
525 my_udp_connect(server_address, 123, &conn);
527 /* keep sending requests until the server stops setting the
528 * REM_MORE bit, though usually this is only 1 packet. */
529 do{
530 setup_control_request(&req, OP_READSTAT, 1);
531 DBG(printf("sending READSTAT request"));
532 write(conn, &req, SIZEOF_NTPCM(req));
533 DBG(print_ntp_control_message(&req));
534 /* Attempt to read the largest size packet possible */
535 req.count=htons(MAX_CM_SIZE);
536 DBG(printf("recieving READSTAT response"))
537 read(conn, &req, SIZEOF_NTPCM(req));
538 DBG(print_ntp_control_message(&req));
539 /* Each peer identifier is 4 bytes in the data section, which
540 * we represent as a ntp_assoc_status_pair datatype.
541 */
542 peers_size+=ntohs(req.count);
543 if((tmp=realloc(peers, peers_size)) == NULL)
544 free(peers), die(STATE_UNKNOWN, "can not (re)allocate 'peers' buffer\n");
545 peers=tmp;
546 memcpy((void*)((ptrdiff_t)peers+peer_offset), (void*)req.data, ntohs(req.count));
547 npeers=peers_size/sizeof(ntp_assoc_status_pair);
548 peer_offset+=ntohs(req.count);
549 } while(req.op&REM_MORE);
551 /* first, let's find out if we have a sync source, or if there are
552 * at least some candidates. in the case of the latter we'll issue
553 * a warning but go ahead with the check on them. */
554 for (i = 0; i < npeers; i++){
555 if (PEER_SEL(peers[i].status) >= PEER_INCLUDED){
556 num_candidates++;
557 if(PEER_SEL(peers[i].status) >= PEER_SYNCSOURCE){
558 syncsource_found=1;
559 min_peer_sel=PEER_SYNCSOURCE;
560 }
561 }
562 }
563 if(verbose) printf("%d candiate peers available\n", num_candidates);
564 if(verbose && syncsource_found) printf("synchronization source found\n");
565 if(! syncsource_found){
566 *status = STATE_WARNING;
567 if(verbose) printf("warning: no synchronization source found\n");
568 }
571 for (run=0; run<AVG_NUM; run++){
572 if(verbose) printf("jitter run %d of %d\n", run+1, AVG_NUM);
573 for (i = 0; i < npeers; i++){
574 /* Only query this server if it is the current sync source */
575 if (PEER_SEL(peers[i].status) >= min_peer_sel){
576 num_selected++;
577 setup_control_request(&req, OP_READVAR, 2);
578 req.assoc = peers[i].assoc;
579 /* By spec, putting the variable name "jitter" in the request
580 * should cause the server to provide _only_ the jitter value.
581 * thus reducing net traffic, guaranteeing us only a single
582 * datagram in reply, and making intepretation much simpler
583 */
584 strncpy(req.data, "jitter", 6);
585 req.count = htons(6);
586 DBG(printf("sending READVAR request...\n"));
587 write(conn, &req, SIZEOF_NTPCM(req));
588 DBG(print_ntp_control_message(&req));
590 req.count = htons(MAX_CM_SIZE);
591 DBG(printf("recieving READVAR response...\n"));
592 read(conn, &req, SIZEOF_NTPCM(req));
593 DBG(print_ntp_control_message(&req));
595 /* get to the float value */
596 if(verbose) {
597 printf("parsing jitter from peer %.2x: ", ntohs(peers[i].assoc));
598 }
599 startofvalue = strchr(req.data, '=');
600 if(startofvalue != NULL) {
601 startofvalue++;
602 jitter = strtod(startofvalue, &nptr);
603 }
604 if(startofvalue == NULL || startofvalue==nptr){
605 printf("warning: unable to read server jitter response.\n");
606 *status = STATE_WARNING;
607 } else {
608 if(verbose) printf("%g\n", jitter);
609 num_valid++;
610 rval += jitter;
611 }
612 }
613 }
614 if(verbose){
615 printf("jitter parsed from %d/%d peers\n", num_valid, num_selected);
616 }
617 }
619 rval = num_valid ? rval / num_valid : -1.0;
621 close(conn);
622 if(peers!=NULL) free(peers);
623 /* If we return -1.0, it means no synchronization source was found */
624 return rval;
625 }
627 int process_arguments(int argc, char **argv){
628 int c;
629 int option=0;
630 static struct option longopts[] = {
631 {"version", no_argument, 0, 'V'},
632 {"help", no_argument, 0, 'h'},
633 {"verbose", no_argument, 0, 'v'},
634 {"use-ipv4", no_argument, 0, '4'},
635 {"use-ipv6", no_argument, 0, '6'},
636 {"warning", required_argument, 0, 'w'},
637 {"critical", required_argument, 0, 'c'},
638 {"jwarn", required_argument, 0, 'j'},
639 {"jcrit", required_argument, 0, 'k'},
640 {"timeout", required_argument, 0, 't'},
641 {"hostname", required_argument, 0, 'H'},
642 {0, 0, 0, 0}
643 };
646 if (argc < 2)
647 usage ("\n");
649 while (1) {
650 c = getopt_long (argc, argv, "Vhv46w:c:j:k:t:H:", longopts, &option);
651 if (c == -1 || c == EOF || c == 1)
652 break;
654 switch (c) {
655 case 'h':
656 print_help();
657 exit(STATE_OK);
658 break;
659 case 'V':
660 print_revision(progname, revision);
661 exit(STATE_OK);
662 break;
663 case 'v':
664 verbose++;
665 break;
666 case 'w':
667 owarn = atof(optarg);
668 break;
669 case 'c':
670 ocrit = atof(optarg);
671 break;
672 case 'j':
673 do_jitter=1;
674 jwarn = atof(optarg);
675 break;
676 case 'k':
677 do_jitter=1;
678 jcrit = atof(optarg);
679 break;
680 case 'H':
681 if(is_host(optarg) == FALSE)
682 usage2(_("Invalid hostname/address"), optarg);
683 server_address = strdup(optarg);
684 break;
685 case 't':
686 socket_timeout=atoi(optarg);
687 break;
688 case '4':
689 address_family = AF_INET;
690 break;
691 case '6':
692 #ifdef USE_IPV6
693 address_family = AF_INET6;
694 #else
695 usage4 (_("IPv6 support not available"));
696 #endif
697 break;
698 case '?':
699 /* print short usage statement if args not parsable */
700 usage5 ();
701 break;
702 }
703 }
705 if (ocrit < owarn){
706 usage4(_("Critical offset should be larger than warning offset"));
707 }
709 if (ocrit < owarn){
710 usage4(_("Critical jitter should be larger than warning jitter"));
711 }
713 if(server_address == NULL){
714 usage4(_("Hostname was not supplied"));
715 }
717 return 0;
718 }
720 int main(int argc, char *argv[]){
721 int result, offset_result, jitter_result;
722 double offset=0, jitter=0;
724 result=offset_result=jitter_result=STATE_UNKNOWN;
726 if (process_arguments (argc, argv) == ERROR)
727 usage4 (_("Could not parse arguments"));
729 /* initialize alarm signal handling */
730 signal (SIGALRM, socket_timeout_alarm_handler);
732 /* set socket timeout */
733 alarm (socket_timeout);
735 offset = offset_request(server_address, &offset_result);
736 if(fabs(offset) > ocrit){
737 result = STATE_CRITICAL;
738 } else if(fabs(offset) > owarn) {
739 result = STATE_WARNING;
740 } else {
741 result = STATE_OK;
742 }
743 result=max_state(result, offset_result);
745 /* If not told to check the jitter, we don't even send packets.
746 * jitter is checked using NTP control packets, which not all
747 * servers recognize. Trying to check the jitter on OpenNTPD
748 * (for example) will result in an error
749 */
750 if(do_jitter){
751 jitter=jitter_request(server_address, &jitter_result);
752 if(jitter > jcrit){
753 result = max_state(result, STATE_CRITICAL);
754 } else if(jitter > jwarn) {
755 result = max_state(result, STATE_WARNING);
756 } else if(jitter == -1.0 && result == STATE_OK){
757 /* -1 indicates that we couldn't calculate the jitter
758 * Only overrides STATE_OK from the offset */
759 result = STATE_UNKNOWN;
760 }
761 }
762 result=max_state(result, jitter_result);
764 switch (result) {
765 case STATE_CRITICAL :
766 printf("NTP CRITICAL: ");
767 break;
768 case STATE_WARNING :
769 printf("NTP WARNING: ");
770 break;
771 case STATE_OK :
772 printf("NTP OK: ");
773 break;
774 default :
775 printf("NTP UNKNOWN: ");
776 break;
777 }
778 if(offset_result==STATE_CRITICAL){
779 printf("Offset unknown|offset=unknown");
780 } else {
781 if(offset_result==STATE_WARNING){
782 printf("Unable to fully sample sync server. ");
783 }
784 printf("Offset %.10g secs|offset=%.10g", offset, offset);
785 }
786 if (do_jitter) printf(" jitter=%f", jitter);
787 printf("\n");
789 if(server_address!=NULL) free(server_address);
790 return result;
791 }
795 void print_help(void){
796 print_revision(progname, revision);
798 printf ("Copyright (c) 2006 Sean Finney\n");
799 printf (COPYRIGHT, copyright, email);
801 printf ("%s\n", _("This plugin checks the selected ntp server"));
803 printf ("\n\n");
805 print_usage();
806 printf (_(UT_HELP_VRSN));
807 printf (_(UT_HOST_PORT), 'p', "123");
808 printf (_(UT_WARN_CRIT));
809 printf (" %s\n", "-j, --warning=DOUBLE");
810 printf (" %s\n", _("warning value for jitter"));
811 printf (" %s\n", "-k, --critical=DOUBLE");
812 printf (" %s\n", _("critical value for jitter"));
813 printf (_(UT_TIMEOUT), DEFAULT_SOCKET_TIMEOUT);
814 printf (_(UT_VERBOSE));
815 printf (_(UT_SUPPORT));
816 }
818 void
819 print_usage(void)
820 {
821 printf (_("Usage:"));
822 printf("%s -H <host> [-w <warn>] [-c <crit>] [-j <warn>] [-k <crit>] [-v verbose]\n", progname);
823 }