1 /******************************************************************************
2 *
3 * Nagios check_ntp plugin
4 *
5 * License: GPL
6 * Copyright (c) 2006 sean finney <seanius@seanius.net>
7 * Copyright (c) 2007 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 = "2007";
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 short do_offset=0;
51 static char *owarn="60";
52 static char *ocrit="120";
53 static short do_jitter=0;
54 static char *jwarn="5000";
55 static char *jcrit="10000";
57 int process_arguments (int, char **);
58 thresholds *offset_thresholds = NULL;
59 thresholds *jitter_thresholds = NULL;
60 void print_help (void);
61 void print_usage (void);
63 /* number of times to perform each request to get a good average. */
64 #define AVG_NUM 4
66 /* max size of control message data */
67 #define MAX_CM_SIZE 468
69 /* this structure holds everything in an ntp request/response as per rfc1305 */
70 typedef struct {
71 uint8_t flags; /* byte with leapindicator,vers,mode. see macros */
72 uint8_t stratum; /* clock stratum */
73 int8_t poll; /* polling interval */
74 int8_t precision; /* precision of the local clock */
75 int32_t rtdelay; /* total rt delay, as a fixed point num. see macros */
76 uint32_t rtdisp; /* like above, but for max err to primary src */
77 uint32_t refid; /* ref clock identifier */
78 uint64_t refts; /* reference timestamp. local time local clock */
79 uint64_t origts; /* time at which request departed client */
80 uint64_t rxts; /* time at which request arrived at server */
81 uint64_t txts; /* time at which request departed server */
82 } ntp_message;
84 /* this structure holds data about results from querying offset from a peer */
85 typedef struct {
86 time_t waiting; /* ts set when we started waiting for a response */
87 int num_responses; /* number of successfully recieved responses */
88 uint8_t stratum; /* copied verbatim from the ntp_message */
89 double rtdelay; /* converted from the ntp_message */
90 double rtdisp; /* converted from the ntp_message */
91 double offset[AVG_NUM]; /* offsets from each response */
92 uint8_t flags; /* byte with leapindicator,vers,mode. see macros */
93 } ntp_server_results;
95 /* this structure holds everything in an ntp control message as per rfc1305 */
96 typedef struct {
97 uint8_t flags; /* byte with leapindicator,vers,mode. see macros */
98 uint8_t op; /* R,E,M bits and Opcode */
99 uint16_t seq; /* Packet sequence */
100 uint16_t status; /* Clock status */
101 uint16_t assoc; /* Association */
102 uint16_t offset; /* Similar to TCP sequence # */
103 uint16_t count; /* # bytes of data */
104 char data[MAX_CM_SIZE]; /* ASCII data of the request */
105 /* NB: not necessarily NULL terminated! */
106 } ntp_control_message;
108 /* this is an association/status-word pair found in control packet reponses */
109 typedef struct {
110 uint16_t assoc;
111 uint16_t status;
112 } ntp_assoc_status_pair;
114 /* bits 1,2 are the leap indicator */
115 #define LI_MASK 0xc0
116 #define LI(x) ((x&LI_MASK)>>6)
117 #define LI_SET(x,y) do{ x |= ((y<<6)&LI_MASK); }while(0)
118 /* and these are the values of the leap indicator */
119 #define LI_NOWARNING 0x00
120 #define LI_EXTRASEC 0x01
121 #define LI_MISSINGSEC 0x02
122 #define LI_ALARM 0x03
123 /* bits 3,4,5 are the ntp version */
124 #define VN_MASK 0x38
125 #define VN(x) ((x&VN_MASK)>>3)
126 #define VN_SET(x,y) do{ x |= ((y<<3)&VN_MASK); }while(0)
127 #define VN_RESERVED 0x02
128 /* bits 6,7,8 are the ntp mode */
129 #define MODE_MASK 0x07
130 #define MODE(x) (x&MODE_MASK)
131 #define MODE_SET(x,y) do{ x |= (y&MODE_MASK); }while(0)
132 /* here are some values */
133 #define MODE_CLIENT 0x03
134 #define MODE_CONTROLMSG 0x06
135 /* In control message, bits 8-10 are R,E,M bits */
136 #define REM_MASK 0xe0
137 #define REM_RESP 0x80
138 #define REM_ERROR 0x40
139 #define REM_MORE 0x20
140 /* In control message, bits 11 - 15 are opcode */
141 #define OP_MASK 0x1f
142 #define OP_SET(x,y) do{ x |= (y&OP_MASK); }while(0)
143 #define OP_READSTAT 0x01
144 #define OP_READVAR 0x02
145 /* In peer status bytes, bits 6,7,8 determine clock selection status */
146 #define PEER_SEL(x) ((ntohs(x)>>8)&0x07)
147 #define PEER_INCLUDED 0x04
148 #define PEER_SYNCSOURCE 0x06
150 /**
151 ** a note about the 32-bit "fixed point" numbers:
152 **
153 they are divided into halves, each being a 16-bit int in network byte order:
154 - the first 16 bits are an int on the left side of a decimal point.
155 - the second 16 bits represent a fraction n/(2^16)
156 likewise for the 64-bit "fixed point" numbers with everything doubled :)
157 **/
159 /* macros to access the left/right 16 bits of a 32-bit ntp "fixed point"
160 number. note that these can be used as lvalues too */
161 #define L16(x) (((uint16_t*)&x)[0])
162 #define R16(x) (((uint16_t*)&x)[1])
163 /* macros to access the left/right 32 bits of a 64-bit ntp "fixed point"
164 number. these too can be used as lvalues */
165 #define L32(x) (((uint32_t*)&x)[0])
166 #define R32(x) (((uint32_t*)&x)[1])
168 /* ntp wants seconds since 1/1/00, epoch is 1/1/70. this is the difference */
169 #define EPOCHDIFF 0x83aa7e80UL
171 /* extract a 32-bit ntp fixed point number into a double */
172 #define NTP32asDOUBLE(x) (ntohs(L16(x)) + (double)ntohs(R16(x))/65536.0)
174 /* likewise for a 64-bit ntp fp number */
175 #define NTP64asDOUBLE(n) (double)(((uint64_t)n)?\
176 (ntohl(L32(n))-EPOCHDIFF) + \
177 (.00000001*(0.5+(double)(ntohl(R32(n))/42.94967296))):\
178 0)
180 /* convert a struct timeval to a double */
181 #define TVasDOUBLE(x) (double)(x.tv_sec+(0.000001*x.tv_usec))
183 /* convert an ntp 64-bit fp number to a struct timeval */
184 #define NTP64toTV(n,t) \
185 do{ if(!n) t.tv_sec = t.tv_usec = 0; \
186 else { \
187 t.tv_sec=ntohl(L32(n))-EPOCHDIFF; \
188 t.tv_usec=(int)(0.5+(double)(ntohl(R32(n))/4294.967296)); \
189 } \
190 }while(0)
192 /* convert a struct timeval to an ntp 64-bit fp number */
193 #define TVtoNTP64(t,n) \
194 do{ if(!t.tv_usec && !t.tv_sec) n=0x0UL; \
195 else { \
196 L32(n)=htonl(t.tv_sec + EPOCHDIFF); \
197 R32(n)=htonl((uint64_t)((4294.967296*t.tv_usec)+.5)); \
198 } \
199 } while(0)
201 /* NTP control message header is 12 bytes, plus any data in the data
202 * field, plus null padding to the nearest 32-bit boundary per rfc.
203 */
204 #define SIZEOF_NTPCM(m) (12+ntohs(m.count)+((m.count)?4-(ntohs(m.count)%4):0))
206 /* finally, a little helper or two for debugging: */
207 #define DBG(x) do{if(verbose>1){ x; }}while(0);
208 #define PRINTSOCKADDR(x) \
209 do{ \
210 printf("%u.%u.%u.%u", (x>>24)&0xff, (x>>16)&0xff, (x>>8)&0xff, x&0xff);\
211 }while(0);
213 /* calculate the offset of the local clock */
214 static inline double calc_offset(const ntp_message *m, const struct timeval *t){
215 double client_tx, peer_rx, peer_tx, client_rx;
216 client_tx = NTP64asDOUBLE(m->origts);
217 peer_rx = NTP64asDOUBLE(m->rxts);
218 peer_tx = NTP64asDOUBLE(m->txts);
219 client_rx=TVasDOUBLE((*t));
220 return (.5*((peer_tx-client_rx)+(peer_rx-client_tx)));
221 }
223 /* print out a ntp packet in human readable/debuggable format */
224 void print_ntp_message(const ntp_message *p){
225 struct timeval ref, orig, rx, tx;
227 NTP64toTV(p->refts,ref);
228 NTP64toTV(p->origts,orig);
229 NTP64toTV(p->rxts,rx);
230 NTP64toTV(p->txts,tx);
232 printf("packet contents:\n");
233 printf("\tflags: 0x%.2x\n", p->flags);
234 printf("\t li=%d (0x%.2x)\n", LI(p->flags), p->flags&LI_MASK);
235 printf("\t vn=%d (0x%.2x)\n", VN(p->flags), p->flags&VN_MASK);
236 printf("\t mode=%d (0x%.2x)\n", MODE(p->flags), p->flags&MODE_MASK);
237 printf("\tstratum = %d\n", p->stratum);
238 printf("\tpoll = %g\n", pow(2, p->poll));
239 printf("\tprecision = %g\n", pow(2, p->precision));
240 printf("\trtdelay = %-.16g\n", NTP32asDOUBLE(p->rtdelay));
241 printf("\trtdisp = %-.16g\n", NTP32asDOUBLE(p->rtdisp));
242 printf("\trefid = %x\n", p->refid);
243 printf("\trefts = %-.16g\n", NTP64asDOUBLE(p->refts));
244 printf("\torigts = %-.16g\n", NTP64asDOUBLE(p->origts));
245 printf("\trxts = %-.16g\n", NTP64asDOUBLE(p->rxts));
246 printf("\ttxts = %-.16g\n", NTP64asDOUBLE(p->txts));
247 }
249 void print_ntp_control_message(const ntp_control_message *p){
250 int i=0, numpeers=0;
251 const ntp_assoc_status_pair *peer=NULL;
253 printf("control packet contents:\n");
254 printf("\tflags: 0x%.2x , 0x%.2x\n", p->flags, p->op);
255 printf("\t li=%d (0x%.2x)\n", LI(p->flags), p->flags&LI_MASK);
256 printf("\t vn=%d (0x%.2x)\n", VN(p->flags), p->flags&VN_MASK);
257 printf("\t mode=%d (0x%.2x)\n", MODE(p->flags), p->flags&MODE_MASK);
258 printf("\t response=%d (0x%.2x)\n", (p->op&REM_RESP)>0, p->op&REM_RESP);
259 printf("\t more=%d (0x%.2x)\n", (p->op&REM_MORE)>0, p->op&REM_MORE);
260 printf("\t error=%d (0x%.2x)\n", (p->op&REM_ERROR)>0, p->op&REM_ERROR);
261 printf("\t op=%d (0x%.2x)\n", p->op&OP_MASK, p->op&OP_MASK);
262 printf("\tsequence: %d (0x%.2x)\n", ntohs(p->seq), ntohs(p->seq));
263 printf("\tstatus: %d (0x%.2x)\n", ntohs(p->status), ntohs(p->status));
264 printf("\tassoc: %d (0x%.2x)\n", ntohs(p->assoc), ntohs(p->assoc));
265 printf("\toffset: %d (0x%.2x)\n", ntohs(p->offset), ntohs(p->offset));
266 printf("\tcount: %d (0x%.2x)\n", ntohs(p->count), ntohs(p->count));
267 numpeers=ntohs(p->count)/(sizeof(ntp_assoc_status_pair));
268 if(p->op&REM_RESP && p->op&OP_READSTAT){
269 peer=(ntp_assoc_status_pair*)p->data;
270 for(i=0;i<numpeers;i++){
271 printf("\tpeer id %.2x status %.2x",
272 ntohs(peer[i].assoc), ntohs(peer[i].status));
273 if (PEER_SEL(peer[i].status) >= PEER_INCLUDED){
274 if(PEER_SEL(peer[i].status) >= PEER_SYNCSOURCE){
275 printf(" <-- current sync source");
276 } else {
277 printf(" <-- current sync candidate");
278 }
279 }
280 printf("\n");
281 }
282 }
283 }
285 void setup_request(ntp_message *p){
286 struct timeval t;
288 memset(p, 0, sizeof(ntp_message));
289 LI_SET(p->flags, LI_ALARM);
290 VN_SET(p->flags, 4);
291 MODE_SET(p->flags, MODE_CLIENT);
292 p->poll=4;
293 p->precision=(int8_t)0xfa;
294 L16(p->rtdelay)=htons(1);
295 L16(p->rtdisp)=htons(1);
297 gettimeofday(&t, NULL);
298 TVtoNTP64(t,p->txts);
299 }
301 /* select the "best" server from a list of servers, and return its index.
302 * this is done by filtering servers based on stratum, dispersion, and
303 * finally round-trip delay. */
304 int best_offset_server(const ntp_server_results *slist, int nservers){
305 int i=0, cserver=0, best_server=-1;
307 /* for each server */
308 for(cserver=0; cserver<nservers; cserver++){
309 /* We don't want any servers that fails these tests */
310 /* Sort out servers that didn't respond or responede with a 0 stratum;
311 * stratum 0 is for reference clocks so no NTP server should ever report
312 * a stratum 0 */
313 if ( slist[cserver].stratum == 0){
314 if (verbose) printf("discarding peer %d: stratum=%d\n", cserver, slist[cserver].stratum);
315 continue;
316 }
317 /* Sort out servers with error flags */
318 if ( LI(slist[cserver].flags) == LI_ALARM ){
319 if (verbose) printf("discarding peer %d: flags=%d\n", cserver, LI(slist[cserver].flags));
320 continue;
321 }
323 /* If we don't have a server yet, use the first one */
324 if (best_server == -1) {
325 best_server = cserver;
326 DBG(printf("using peer %d as our first candidate\n", best_server));
327 continue;
328 }
330 /* compare the server to the best one we've seen so far */
331 /* does it have an equal or better stratum? */
332 DBG(printf("comparing peer %d with peer %d\n", cserver, best_server));
333 if(slist[cserver].stratum <= slist[best_server].stratum){
334 DBG(printf("stratum for peer %d <= peer %d\n", cserver, best_server));
335 /* does it have an equal or better dispersion? */
336 if(slist[cserver].rtdisp <= slist[best_server].rtdisp){
337 DBG(printf("dispersion for peer %d <= peer %d\n", cserver, best_server));
338 /* does it have a better rtdelay? */
339 if(slist[cserver].rtdelay < slist[best_server].rtdelay){
340 DBG(printf("rtdelay for peer %d < peer %d\n", cserver, best_server));
341 best_server = cserver;
342 DBG(printf("peer %d is now our best candidate\n", best_server));
343 }
344 }
345 }
346 }
348 if(best_server >= 0) {
349 DBG(printf("best server selected: peer %d\n", best_server));
350 return best_server;
351 } else {
352 DBG(printf("no peers meeting synchronization criteria :(\n"));
353 return -1;
354 }
355 }
357 /* do everything we need to get the total average offset
358 * - we use a certain amount of parallelization with poll() to ensure
359 * we don't waste time sitting around waiting for single packets.
360 * - we also "manually" handle resolving host names and connecting, because
361 * we have to do it in a way that our lazy macros don't handle currently :( */
362 double offset_request(const char *host, int *status){
363 int i=0, j=0, ga_result=0, num_hosts=0, *socklist=NULL, respnum=0;
364 int servers_completed=0, one_written=0, one_read=0, servers_readable=0, best_index=-1;
365 time_t now_time=0, start_ts=0;
366 ntp_message *req=NULL;
367 double avg_offset=0.;
368 struct timeval recv_time;
369 struct addrinfo *ai=NULL, *ai_tmp=NULL, hints;
370 struct pollfd *ufds=NULL;
371 ntp_server_results *servers=NULL;
373 /* setup hints to only return results from getaddrinfo that we'd like */
374 memset(&hints, 0, sizeof(struct addrinfo));
375 hints.ai_family = address_family;
376 hints.ai_protocol = IPPROTO_UDP;
377 hints.ai_socktype = SOCK_DGRAM;
379 /* fill in ai with the list of hosts resolved by the host name */
380 ga_result = getaddrinfo(host, "123", &hints, &ai);
381 if(ga_result!=0){
382 die(STATE_UNKNOWN, "error getting address for %s: %s\n",
383 host, gai_strerror(ga_result));
384 }
386 /* count the number of returned hosts, and allocate stuff accordingly */
387 for(ai_tmp=ai; ai_tmp!=NULL; ai_tmp=ai_tmp->ai_next){ num_hosts++; }
388 req=(ntp_message*)malloc(sizeof(ntp_message)*num_hosts);
389 if(req==NULL) die(STATE_UNKNOWN, "can not allocate ntp message array");
390 socklist=(int*)malloc(sizeof(int)*num_hosts);
391 if(socklist==NULL) die(STATE_UNKNOWN, "can not allocate socket array");
392 ufds=(struct pollfd*)malloc(sizeof(struct pollfd)*num_hosts);
393 if(ufds==NULL) die(STATE_UNKNOWN, "can not allocate socket array");
394 servers=(ntp_server_results*)malloc(sizeof(ntp_server_results)*num_hosts);
395 if(servers==NULL) die(STATE_UNKNOWN, "can not allocate server array");
396 memset(servers, 0, sizeof(ntp_server_results)*num_hosts);
397 DBG(printf("Found %d peers to check\n", num_hosts));
399 /* setup each socket for writing, and the corresponding struct pollfd */
400 ai_tmp=ai;
401 for(i=0;ai_tmp;i++){
402 socklist[i]=socket(ai_tmp->ai_family, SOCK_DGRAM, IPPROTO_UDP);
403 if(socklist[i] == -1) {
404 perror(NULL);
405 die(STATE_UNKNOWN, "can not create new socket");
406 }
407 if(connect(socklist[i], ai_tmp->ai_addr, ai_tmp->ai_addrlen)){
408 die(STATE_UNKNOWN, "can't create socket connection");
409 } else {
410 ufds[i].fd=socklist[i];
411 ufds[i].events=POLLIN;
412 ufds[i].revents=0;
413 }
414 ai_tmp = ai_tmp->ai_next;
415 }
417 /* now do AVG_NUM checks to each host. we stop before timeout/2 seconds
418 * have passed in order to ensure post-processing and jitter time. */
419 now_time=start_ts=time(NULL);
420 while(servers_completed<num_hosts && now_time-start_ts <= socket_timeout/2){
421 /* loop through each server and find each one which hasn't
422 * been touched in the past second or so and is still lacking
423 * some responses. for each of these servers, send a new request,
424 * and update the "waiting" timestamp with the current time. */
425 one_written=0;
426 now_time=time(NULL);
428 for(i=0; i<num_hosts; i++){
429 if(servers[i].waiting<now_time && servers[i].num_responses<AVG_NUM){
430 if(verbose && servers[i].waiting != 0) printf("re-");
431 if(verbose) printf("sending request to peer %d\n", i);
432 setup_request(&req[i]);
433 write(socklist[i], &req[i], sizeof(ntp_message));
434 servers[i].waiting=now_time;
435 one_written=1;
436 break;
437 }
438 }
440 /* quickly poll for any sockets with pending data */
441 servers_readable=poll(ufds, num_hosts, 100);
442 if(servers_readable==-1){
443 perror("polling ntp sockets");
444 die(STATE_UNKNOWN, "communication errors");
445 }
447 /* read from any sockets with pending data */
448 for(i=0; servers_readable && i<num_hosts; i++){
449 if(ufds[i].revents&POLLIN && servers[i].num_responses < AVG_NUM){
450 if(verbose) {
451 printf("response from peer %d: ", i);
452 }
454 read(ufds[i].fd, &req[i], sizeof(ntp_message));
455 gettimeofday(&recv_time, NULL);
456 DBG(print_ntp_message(&req[i]));
457 respnum=servers[i].num_responses++;
458 servers[i].offset[respnum]=calc_offset(&req[i], &recv_time);
459 if(verbose) {
460 printf("offset %.10g\n", servers[i].offset[respnum]);
461 }
462 servers[i].stratum=req[i].stratum;
463 servers[i].rtdisp=NTP32asDOUBLE(req[i].rtdisp);
464 servers[i].rtdelay=NTP32asDOUBLE(req[i].rtdelay);
465 servers[i].waiting=0;
466 servers[i].flags=req[i].flags;
467 servers_readable--;
468 one_read = 1;
469 if(servers[i].num_responses==AVG_NUM) servers_completed++;
470 }
471 }
472 /* lather, rinse, repeat. */
473 }
475 if (one_read == 0) {
476 die(STATE_CRITICAL, "NTP CRITICAL: No response from NTP server\n");
477 }
479 /* now, pick the best server from the list */
480 best_index=best_offset_server(servers, num_hosts);
481 if(best_index < 0){
482 *status=STATE_UNKNOWN;
483 } else {
484 /* finally, calculate the average offset */
485 for(i=0; i<servers[best_index].num_responses;i++){
486 avg_offset+=servers[best_index].offset[j];
487 }
488 avg_offset/=servers[best_index].num_responses;
489 }
491 /* cleanup */
492 /* FIXME: Not closing the socket to avoid re-use of the local port
493 * which can cause old NTP packets to be read instead of NTP control
494 * pactets in jitter_request(). THERE MUST BE ANOTHER WAY...
495 * for(j=0; j<num_hosts; j++){ close(socklist[j]); } */
496 free(socklist);
497 free(ufds);
498 free(servers);
499 free(req);
500 freeaddrinfo(ai);
502 if(verbose) printf("overall average offset: %.10g\n", avg_offset);
503 return avg_offset;
504 }
506 void
507 setup_control_request(ntp_control_message *p, uint8_t opcode, uint16_t seq){
508 memset(p, 0, sizeof(ntp_control_message));
509 LI_SET(p->flags, LI_NOWARNING);
510 VN_SET(p->flags, VN_RESERVED);
511 MODE_SET(p->flags, MODE_CONTROLMSG);
512 OP_SET(p->op, opcode);
513 p->seq = htons(seq);
514 /* Remaining fields are zero for requests */
515 }
517 /* XXX handle responses with the error bit set */
518 double jitter_request(const char *host, int *status){
519 int conn=-1, i, npeers=0, num_candidates=0, syncsource_found=0;
520 int run=0, min_peer_sel=PEER_INCLUDED, num_selected=0, num_valid=0;
521 int peers_size=0, peer_offset=0;
522 ntp_assoc_status_pair *peers=NULL;
523 ntp_control_message req;
524 const char *getvar = "jitter";
525 double rval = 0.0, jitter = -1.0;
526 char *startofvalue=NULL, *nptr=NULL;
527 void *tmp;
529 /* Long-winded explanation:
530 * Getting the jitter requires a number of steps:
531 * 1) Send a READSTAT request.
532 * 2) Interpret the READSTAT reply
533 * a) The data section contains a list of peer identifiers (16 bits)
534 * and associated status words (16 bits)
535 * b) We want the value of 0x06 in the SEL (peer selection) value,
536 * which means "current synchronizatin source". If that's missing,
537 * we take anything better than 0x04 (see the rfc for details) but
538 * set a minimum of warning.
539 * 3) Send a READVAR request for information on each peer identified
540 * in 2b greater than the minimum selection value.
541 * 4) Extract the jitter value from the data[] (it's ASCII)
542 */
543 my_udp_connect(server_address, 123, &conn);
545 /* keep sending requests until the server stops setting the
546 * REM_MORE bit, though usually this is only 1 packet. */
547 do{
548 setup_control_request(&req, OP_READSTAT, 1);
549 DBG(printf("sending READSTAT request"));
550 write(conn, &req, SIZEOF_NTPCM(req));
551 DBG(print_ntp_control_message(&req));
552 /* Attempt to read the largest size packet possible */
553 req.count=htons(MAX_CM_SIZE);
554 DBG(printf("recieving READSTAT response"))
555 read(conn, &req, SIZEOF_NTPCM(req));
556 DBG(print_ntp_control_message(&req));
557 /* Each peer identifier is 4 bytes in the data section, which
558 * we represent as a ntp_assoc_status_pair datatype.
559 */
560 peers_size+=ntohs(req.count);
561 if((tmp=realloc(peers, peers_size)) == NULL)
562 free(peers), die(STATE_UNKNOWN, "can not (re)allocate 'peers' buffer\n");
563 peers=tmp;
564 memcpy((void*)((ptrdiff_t)peers+peer_offset), (void*)req.data, ntohs(req.count));
565 npeers=peers_size/sizeof(ntp_assoc_status_pair);
566 peer_offset+=ntohs(req.count);
567 } while(req.op&REM_MORE);
569 /* first, let's find out if we have a sync source, or if there are
570 * at least some candidates. in the case of the latter we'll issue
571 * a warning but go ahead with the check on them. */
572 for (i = 0; i < npeers; i++){
573 if (PEER_SEL(peers[i].status) >= PEER_INCLUDED){
574 num_candidates++;
575 if(PEER_SEL(peers[i].status) >= PEER_SYNCSOURCE){
576 syncsource_found=1;
577 min_peer_sel=PEER_SYNCSOURCE;
578 }
579 }
580 }
581 if(verbose) printf("%d candiate peers available\n", num_candidates);
582 if(verbose && syncsource_found) printf("synchronization source found\n");
583 if(! syncsource_found){
584 *status = STATE_UNKNOWN;
585 if(verbose) printf("warning: no synchronization source found\n");
586 }
589 for (run=0; run<AVG_NUM; run++){
590 if(verbose) printf("jitter run %d of %d\n", run+1, AVG_NUM);
591 for (i = 0; i < npeers; i++){
592 /* Only query this server if it is the current sync source */
593 if (PEER_SEL(peers[i].status) >= min_peer_sel){
594 num_selected++;
595 setup_control_request(&req, OP_READVAR, 2);
596 req.assoc = peers[i].assoc;
597 /* By spec, putting the variable name "jitter" in the request
598 * should cause the server to provide _only_ the jitter value.
599 * thus reducing net traffic, guaranteeing us only a single
600 * datagram in reply, and making intepretation much simpler
601 */
602 /* Older servers doesn't know what jitter is, so if we get an
603 * error on the first pass we redo it with "dispersion" */
604 strncpy(req.data, getvar, MAX_CM_SIZE-1);
605 req.count = htons(strlen(getvar));
606 DBG(printf("sending READVAR request...\n"));
607 write(conn, &req, SIZEOF_NTPCM(req));
608 DBG(print_ntp_control_message(&req));
610 req.count = htons(MAX_CM_SIZE);
611 DBG(printf("recieving READVAR response...\n"));
612 read(conn, &req, SIZEOF_NTPCM(req));
613 DBG(print_ntp_control_message(&req));
615 if(req.op&REM_ERROR && strstr(getvar, "jitter")) {
616 if(verbose) printf("The 'jitter' command failed (old ntp server?)\nRestarting with 'dispersion'...\n");
617 getvar = "dispersion";
618 num_selected--;
619 i--;
620 continue;
621 }
623 /* get to the float value */
624 if(verbose) {
625 printf("parsing jitter from peer %.2x: ", ntohs(peers[i].assoc));
626 }
627 startofvalue = strchr(req.data, '=');
628 if(startofvalue != NULL) {
629 startofvalue++;
630 jitter = strtod(startofvalue, &nptr);
631 }
632 if(startofvalue == NULL || startofvalue==nptr){
633 printf("warning: unable to read server jitter response.\n");
634 *status = STATE_UNKNOWN;
635 } else {
636 if(verbose) printf("%g\n", jitter);
637 num_valid++;
638 rval += jitter;
639 }
640 }
641 }
642 if(verbose){
643 printf("jitter parsed from %d/%d peers\n", num_valid, num_selected);
644 }
645 }
647 rval = num_valid ? rval / num_valid : -1.0;
649 close(conn);
650 if(peers!=NULL) free(peers);
651 /* If we return -1.0, it means no synchronization source was found */
652 return rval;
653 }
655 int process_arguments(int argc, char **argv){
656 int c;
657 int option=0;
658 static struct option longopts[] = {
659 {"version", no_argument, 0, 'V'},
660 {"help", no_argument, 0, 'h'},
661 {"verbose", no_argument, 0, 'v'},
662 {"use-ipv4", no_argument, 0, '4'},
663 {"use-ipv6", no_argument, 0, '6'},
664 {"warning", required_argument, 0, 'w'},
665 {"critical", required_argument, 0, 'c'},
666 {"jwarn", required_argument, 0, 'j'},
667 {"jcrit", required_argument, 0, 'k'},
668 {"timeout", required_argument, 0, 't'},
669 {"hostname", required_argument, 0, 'H'},
670 {0, 0, 0, 0}
671 };
674 if (argc < 2)
675 usage ("\n");
677 while (1) {
678 c = getopt_long (argc, argv, "Vhv46w:c:j:k:t:H:", longopts, &option);
679 if (c == -1 || c == EOF || c == 1)
680 break;
682 switch (c) {
683 case 'h':
684 print_help();
685 exit(STATE_OK);
686 break;
687 case 'V':
688 print_revision(progname, revision);
689 exit(STATE_OK);
690 break;
691 case 'v':
692 verbose++;
693 break;
694 case 'w':
695 do_offset=1;
696 owarn = optarg;
697 break;
698 case 'c':
699 do_offset=1;
700 ocrit = optarg;
701 break;
702 case 'j':
703 do_jitter=1;
704 jwarn = optarg;
705 break;
706 case 'k':
707 do_jitter=1;
708 jcrit = optarg;
709 break;
710 case 'H':
711 if(is_host(optarg) == FALSE)
712 usage2(_("Invalid hostname/address"), optarg);
713 server_address = strdup(optarg);
714 break;
715 case 't':
716 socket_timeout=atoi(optarg);
717 break;
718 case '4':
719 address_family = AF_INET;
720 break;
721 case '6':
722 #ifdef USE_IPV6
723 address_family = AF_INET6;
724 #else
725 usage4 (_("IPv6 support not available"));
726 #endif
727 break;
728 case '?':
729 /* print short usage statement if args not parsable */
730 usage5 ();
731 break;
732 }
733 }
735 if(server_address == NULL){
736 usage4(_("Hostname was not supplied"));
737 }
739 return 0;
740 }
742 char *perfd_offset (double offset)
743 {
744 return fperfdata ("offset", offset, "s",
745 TRUE, offset_thresholds->warning->end,
746 TRUE, offset_thresholds->critical->end,
747 FALSE, 0, FALSE, 0);
748 }
750 char *perfd_jitter (double jitter)
751 {
752 return fperfdata ("jitter", jitter, "s",
753 do_jitter, jitter_thresholds->warning->end,
754 do_jitter, jitter_thresholds->critical->end,
755 TRUE, 0, FALSE, 0);
756 }
758 int main(int argc, char *argv[]){
759 int result, offset_result, jitter_result;
760 double offset=0, jitter=0;
761 char *result_line, *perfdata_line;
763 setlocale (LC_ALL, "");
764 bindtextdomain (PACKAGE, LOCALEDIR);
765 textdomain (PACKAGE);
767 result = offset_result = jitter_result = STATE_OK;
769 if (process_arguments (argc, argv) == ERROR)
770 usage4 (_("Could not parse arguments"));
772 set_thresholds(&offset_thresholds, owarn, ocrit);
773 set_thresholds(&jitter_thresholds, jwarn, jcrit);
775 /* initialize alarm signal handling */
776 signal (SIGALRM, socket_timeout_alarm_handler);
778 /* set socket timeout */
779 alarm (socket_timeout);
781 offset = offset_request(server_address, &offset_result);
782 /* check_ntp used to always return CRITICAL if offset_result == STATE_UNKNOWN.
783 * Now we'll only do that is the offset thresholds were set */
784 if (do_offset && offset_result == STATE_UNKNOWN) {
785 result = STATE_CRITICAL;
786 } else {
787 result = get_status(fabs(offset), offset_thresholds);
788 }
790 /* If not told to check the jitter, we don't even send packets.
791 * jitter is checked using NTP control packets, which not all
792 * servers recognize. Trying to check the jitter on OpenNTPD
793 * (for example) will result in an error
794 */
795 if(do_jitter){
796 jitter=jitter_request(server_address, &jitter_result);
797 result = max_state_alt(result, get_status(jitter, jitter_thresholds));
798 /* -1 indicates that we couldn't calculate the jitter
799 * Only overrides STATE_OK from the offset */
800 if(jitter == -1.0 && result == STATE_OK)
801 result = STATE_UNKNOWN;
802 }
803 result = max_state_alt(result, jitter_result);
805 switch (result) {
806 case STATE_CRITICAL :
807 asprintf(&result_line, _("NTP CRITICAL:"));
808 break;
809 case STATE_WARNING :
810 asprintf(&result_line, _("NTP WARNING:"));
811 break;
812 case STATE_OK :
813 asprintf(&result_line, _("NTP OK:"));
814 break;
815 default :
816 asprintf(&result_line, _("NTP UNKNOWN:"));
817 break;
818 }
819 if(offset_result == STATE_UNKNOWN){
820 asprintf(&result_line, "%s %s", result_line, _("Offset unknown"));
821 asprintf(&perfdata_line, "");
822 } else {
823 asprintf(&result_line, "%s %s %.10g secs", result_line, _("Offset"), offset);
824 asprintf(&perfdata_line, "%s", perfd_offset(offset));
825 }
826 if (do_jitter) {
827 asprintf(&result_line, "%s, jitter=%f", result_line, jitter);
828 asprintf(&perfdata_line, "%s %s", perfdata_line, perfd_jitter(jitter));
829 }
830 printf("%s|%s\n", result_line, perfdata_line);
832 if(server_address!=NULL) free(server_address);
833 return result;
834 }
838 void print_help(void){
839 print_revision(progname, revision);
841 printf ("Copyright (c) 2006 Sean Finney\n");
842 printf (COPYRIGHT, copyright, email);
844 printf ("%s\n", _("This plugin checks the selected ntp server"));
846 printf ("\n\n");
848 print_usage();
849 printf (_(UT_HELP_VRSN));
850 printf (_(UT_HOST_PORT), 'p', "123");
851 printf (" %s\n", "-w, --warning=THRESHOLD");
852 printf (" %s\n", _("Offset to result in warning status (seconds)"));
853 printf (" %s\n", "-c, --critical=THRESHOLD");
854 printf (" %s\n", _("Offset to result in critical status (seconds)"));
855 printf (" %s\n", "-j, --warning=THRESHOLD");
856 printf (" %s\n", _("Warning threshold for jitter"));
857 printf (" %s\n", "-k, --critical=THRESHOLD");
858 printf (" %s\n", _("Critical threshold for jitter"));
859 printf (_(UT_TIMEOUT), DEFAULT_SOCKET_TIMEOUT);
860 printf (_(UT_VERBOSE));
862 printf("\n");
863 printf("%s\n", _("Notes:"));
864 printf(" %s\n", _("See:"));
865 printf(" %s\n", ("http://nagiosplug.sourceforge.net/developer-guidelines.html#THRESHOLDFORMAT"));
866 printf(" %s\n", _("for THRESHOLD format and examples."));
868 printf("\n");
869 printf("%s\n", _("Examples:"));
870 printf(" %s\n", _("Normal offset check:"));
871 printf(" %s\n", ("./check_ntp -H ntpserv -w 0.5 -c 1"));
872 printf(" %s\n", _("Check jitter too, avoiding critical notifications if jitter isn't available"));
873 printf(" %s\n", _("(See Notes above for more details on thresholds formats):"));
874 printf(" %s\n", ("./check_ntp -H ntpserv -w 0.5 -c 1 -j -1:100 -k -1:200"));
876 printf (_(UT_SUPPORT));
878 printf("\n");
879 printf ("%s\n", _("WARNING: check_ntp is deprecated. Please use check_ntp_peer or"));
880 printf ("%s\n\n", _("check_ntp_time istead."));
881 }
883 void
884 print_usage(void)
885 {
886 printf ("%s\n", _("WARNING: check_ntp is deprecated. Please use check_ntp_peer or"));
887 printf ("%s\n\n", _("check_ntp_time istead."));
888 printf (_("Usage:"));
889 printf(" %s -H <host> [-w <warn>] [-c <crit>] [-j <warn>] [-k <crit>] [-v verbose]\n", progname);
890 }