Not picking up solaris systems correctly for check_dhcp. Only
[monitoring-plugins.git] / plugins / check_ntp.c
blob68c82d1154655907b4b7e8df8221d8b1de1e2594
1 /*****************************************************************************
2 *
3 * Nagios check_ntp plugin
4 *
5 * License: GPL
6 * Copyright (c) 2006 Sean Finney <seanius@seanius.net>
7 * Copyright (c) 2006-2008 Nagios Plugins Development Team
8 *
9 * Last Modified: $Date$
11 * Description:
13 * This file contains the check_ntp plugin
15 * This plugin to check ntp servers independant of any commandline
16 * programs or external libraries.
19 * This program is free software: you can redistribute it and/or modify
20 * it under the terms of the GNU General Public License as published by
21 * the Free Software Foundation, either version 3 of the License, or
22 * (at your option) any later version.
24 * This program is distributed in the hope that it will be useful,
25 * but WITHOUT ANY WARRANTY; without even the implied warranty of
26 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
27 * GNU General Public License for more details.
29 * You should have received a copy of the GNU General Public License
30 * along with this program. If not, see <http://www.gnu.org/licenses/>.
32 * $Id$
34 *****************************************************************************/
36 const char *progname = "check_ntp";
37 const char *revision = "$Revision$";
38 const char *copyright = "2006-2008";
39 const char *email = "nagiosplug-devel@lists.sourceforge.net";
41 #include "common.h"
42 #include "netutils.h"
43 #include "utils.h"
45 static char *server_address=NULL;
46 static int verbose=0;
47 static short do_offset=0;
48 static char *owarn="60";
49 static char *ocrit="120";
50 static short do_jitter=0;
51 static char *jwarn="5000";
52 static char *jcrit="10000";
54 int process_arguments (int, char **);
55 thresholds *offset_thresholds = NULL;
56 thresholds *jitter_thresholds = NULL;
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 uint8_t flags; /* byte with leapindicator,vers,mode. see macros */
90 } ntp_server_results;
92 /* this structure holds everything in an ntp control message as per rfc1305 */
93 typedef struct {
94 uint8_t flags; /* byte with leapindicator,vers,mode. see macros */
95 uint8_t op; /* R,E,M bits and Opcode */
96 uint16_t seq; /* Packet sequence */
97 uint16_t status; /* Clock status */
98 uint16_t assoc; /* Association */
99 uint16_t offset; /* Similar to TCP sequence # */
100 uint16_t count; /* # bytes of data */
101 char data[MAX_CM_SIZE]; /* ASCII data of the request */
102 /* NB: not necessarily NULL terminated! */
103 } ntp_control_message;
105 /* this is an association/status-word pair found in control packet reponses */
106 typedef struct {
107 uint16_t assoc;
108 uint16_t status;
109 } ntp_assoc_status_pair;
111 /* bits 1,2 are the leap indicator */
112 #define LI_MASK 0xc0
113 #define LI(x) ((x&LI_MASK)>>6)
114 #define LI_SET(x,y) do{ x |= ((y<<6)&LI_MASK); }while(0)
115 /* and these are the values of the leap indicator */
116 #define LI_NOWARNING 0x00
117 #define LI_EXTRASEC 0x01
118 #define LI_MISSINGSEC 0x02
119 #define LI_ALARM 0x03
120 /* bits 3,4,5 are the ntp version */
121 #define VN_MASK 0x38
122 #define VN(x) ((x&VN_MASK)>>3)
123 #define VN_SET(x,y) do{ x |= ((y<<3)&VN_MASK); }while(0)
124 #define VN_RESERVED 0x02
125 /* bits 6,7,8 are the ntp mode */
126 #define MODE_MASK 0x07
127 #define MODE(x) (x&MODE_MASK)
128 #define MODE_SET(x,y) do{ x |= (y&MODE_MASK); }while(0)
129 /* here are some values */
130 #define MODE_CLIENT 0x03
131 #define MODE_CONTROLMSG 0x06
132 /* In control message, bits 8-10 are R,E,M bits */
133 #define REM_MASK 0xe0
134 #define REM_RESP 0x80
135 #define REM_ERROR 0x40
136 #define REM_MORE 0x20
137 /* In control message, bits 11 - 15 are opcode */
138 #define OP_MASK 0x1f
139 #define OP_SET(x,y) do{ x |= (y&OP_MASK); }while(0)
140 #define OP_READSTAT 0x01
141 #define OP_READVAR 0x02
142 /* In peer status bytes, bits 6,7,8 determine clock selection status */
143 #define PEER_SEL(x) ((ntohs(x)>>8)&0x07)
144 #define PEER_INCLUDED 0x04
145 #define PEER_SYNCSOURCE 0x06
148 ** a note about the 32-bit "fixed point" numbers:
150 they are divided into halves, each being a 16-bit int in network byte order:
151 - the first 16 bits are an int on the left side of a decimal point.
152 - the second 16 bits represent a fraction n/(2^16)
153 likewise for the 64-bit "fixed point" numbers with everything doubled :)
156 /* macros to access the left/right 16 bits of a 32-bit ntp "fixed point"
157 number. note that these can be used as lvalues too */
158 #define L16(x) (((uint16_t*)&x)[0])
159 #define R16(x) (((uint16_t*)&x)[1])
160 /* macros to access the left/right 32 bits of a 64-bit ntp "fixed point"
161 number. these too can be used as lvalues */
162 #define L32(x) (((uint32_t*)&x)[0])
163 #define R32(x) (((uint32_t*)&x)[1])
165 /* ntp wants seconds since 1/1/00, epoch is 1/1/70. this is the difference */
166 #define EPOCHDIFF 0x83aa7e80UL
168 /* extract a 32-bit ntp fixed point number into a double */
169 #define NTP32asDOUBLE(x) (ntohs(L16(x)) + (double)ntohs(R16(x))/65536.0)
171 /* likewise for a 64-bit ntp fp number */
172 #define NTP64asDOUBLE(n) (double)(((uint64_t)n)?\
173 (ntohl(L32(n))-EPOCHDIFF) + \
174 (.00000001*(0.5+(double)(ntohl(R32(n))/42.94967296))):\
177 /* convert a struct timeval to a double */
178 #define TVasDOUBLE(x) (double)(x.tv_sec+(0.000001*x.tv_usec))
180 /* convert an ntp 64-bit fp number to a struct timeval */
181 #define NTP64toTV(n,t) \
182 do{ if(!n) t.tv_sec = t.tv_usec = 0; \
183 else { \
184 t.tv_sec=ntohl(L32(n))-EPOCHDIFF; \
185 t.tv_usec=(int)(0.5+(double)(ntohl(R32(n))/4294.967296)); \
187 }while(0)
189 /* convert a struct timeval to an ntp 64-bit fp number */
190 #define TVtoNTP64(t,n) \
191 do{ if(!t.tv_usec && !t.tv_sec) n=0x0UL; \
192 else { \
193 L32(n)=htonl(t.tv_sec + EPOCHDIFF); \
194 R32(n)=htonl((uint64_t)((4294.967296*t.tv_usec)+.5)); \
196 } while(0)
198 /* NTP control message header is 12 bytes, plus any data in the data
199 * field, plus null padding to the nearest 32-bit boundary per rfc.
201 #define SIZEOF_NTPCM(m) (12+ntohs(m.count)+((m.count)?4-(ntohs(m.count)%4):0))
203 /* finally, a little helper or two for debugging: */
204 #define DBG(x) do{if(verbose>1){ x; }}while(0);
205 #define PRINTSOCKADDR(x) \
206 do{ \
207 printf("%u.%u.%u.%u", (x>>24)&0xff, (x>>16)&0xff, (x>>8)&0xff, x&0xff);\
208 }while(0);
210 /* calculate the offset of the local clock */
211 static inline double calc_offset(const ntp_message *m, const struct timeval *t){
212 double client_tx, peer_rx, peer_tx, client_rx;
213 client_tx = NTP64asDOUBLE(m->origts);
214 peer_rx = NTP64asDOUBLE(m->rxts);
215 peer_tx = NTP64asDOUBLE(m->txts);
216 client_rx=TVasDOUBLE((*t));
217 return (.5*((peer_tx-client_rx)+(peer_rx-client_tx)));
220 /* print out a ntp packet in human readable/debuggable format */
221 void print_ntp_message(const ntp_message *p){
222 struct timeval ref, orig, rx, tx;
224 NTP64toTV(p->refts,ref);
225 NTP64toTV(p->origts,orig);
226 NTP64toTV(p->rxts,rx);
227 NTP64toTV(p->txts,tx);
229 printf("packet contents:\n");
230 printf("\tflags: 0x%.2x\n", p->flags);
231 printf("\t li=%d (0x%.2x)\n", LI(p->flags), p->flags&LI_MASK);
232 printf("\t vn=%d (0x%.2x)\n", VN(p->flags), p->flags&VN_MASK);
233 printf("\t mode=%d (0x%.2x)\n", MODE(p->flags), p->flags&MODE_MASK);
234 printf("\tstratum = %d\n", p->stratum);
235 printf("\tpoll = %g\n", pow(2, p->poll));
236 printf("\tprecision = %g\n", pow(2, p->precision));
237 printf("\trtdelay = %-.16g\n", NTP32asDOUBLE(p->rtdelay));
238 printf("\trtdisp = %-.16g\n", NTP32asDOUBLE(p->rtdisp));
239 printf("\trefid = %x\n", p->refid);
240 printf("\trefts = %-.16g\n", NTP64asDOUBLE(p->refts));
241 printf("\torigts = %-.16g\n", NTP64asDOUBLE(p->origts));
242 printf("\trxts = %-.16g\n", NTP64asDOUBLE(p->rxts));
243 printf("\ttxts = %-.16g\n", NTP64asDOUBLE(p->txts));
246 void print_ntp_control_message(const ntp_control_message *p){
247 int i=0, numpeers=0;
248 const ntp_assoc_status_pair *peer=NULL;
250 printf("control packet contents:\n");
251 printf("\tflags: 0x%.2x , 0x%.2x\n", p->flags, p->op);
252 printf("\t li=%d (0x%.2x)\n", LI(p->flags), p->flags&LI_MASK);
253 printf("\t vn=%d (0x%.2x)\n", VN(p->flags), p->flags&VN_MASK);
254 printf("\t mode=%d (0x%.2x)\n", MODE(p->flags), p->flags&MODE_MASK);
255 printf("\t response=%d (0x%.2x)\n", (p->op&REM_RESP)>0, p->op&REM_RESP);
256 printf("\t more=%d (0x%.2x)\n", (p->op&REM_MORE)>0, p->op&REM_MORE);
257 printf("\t error=%d (0x%.2x)\n", (p->op&REM_ERROR)>0, p->op&REM_ERROR);
258 printf("\t op=%d (0x%.2x)\n", p->op&OP_MASK, p->op&OP_MASK);
259 printf("\tsequence: %d (0x%.2x)\n", ntohs(p->seq), ntohs(p->seq));
260 printf("\tstatus: %d (0x%.2x)\n", ntohs(p->status), ntohs(p->status));
261 printf("\tassoc: %d (0x%.2x)\n", ntohs(p->assoc), ntohs(p->assoc));
262 printf("\toffset: %d (0x%.2x)\n", ntohs(p->offset), ntohs(p->offset));
263 printf("\tcount: %d (0x%.2x)\n", ntohs(p->count), ntohs(p->count));
264 numpeers=ntohs(p->count)/(sizeof(ntp_assoc_status_pair));
265 if(p->op&REM_RESP && p->op&OP_READSTAT){
266 peer=(ntp_assoc_status_pair*)p->data;
267 for(i=0;i<numpeers;i++){
268 printf("\tpeer id %.2x status %.2x",
269 ntohs(peer[i].assoc), ntohs(peer[i].status));
270 if (PEER_SEL(peer[i].status) >= PEER_INCLUDED){
271 if(PEER_SEL(peer[i].status) >= PEER_SYNCSOURCE){
272 printf(" <-- current sync source");
273 } else {
274 printf(" <-- current sync candidate");
277 printf("\n");
282 void setup_request(ntp_message *p){
283 struct timeval t;
285 memset(p, 0, sizeof(ntp_message));
286 LI_SET(p->flags, LI_ALARM);
287 VN_SET(p->flags, 4);
288 MODE_SET(p->flags, MODE_CLIENT);
289 p->poll=4;
290 p->precision=(int8_t)0xfa;
291 L16(p->rtdelay)=htons(1);
292 L16(p->rtdisp)=htons(1);
294 gettimeofday(&t, NULL);
295 TVtoNTP64(t,p->txts);
298 /* select the "best" server from a list of servers, and return its index.
299 * this is done by filtering servers based on stratum, dispersion, and
300 * finally round-trip delay. */
301 int best_offset_server(const ntp_server_results *slist, int nservers){
302 int i=0, cserver=0, best_server=-1;
304 /* for each server */
305 for(cserver=0; cserver<nservers; cserver++){
306 /* We don't want any servers that fails these tests */
307 /* Sort out servers that didn't respond or responede with a 0 stratum;
308 * stratum 0 is for reference clocks so no NTP server should ever report
309 * a stratum 0 */
310 if ( slist[cserver].stratum == 0){
311 if (verbose) printf("discarding peer %d: stratum=%d\n", cserver, slist[cserver].stratum);
312 continue;
314 /* Sort out servers with error flags */
315 if ( LI(slist[cserver].flags) == LI_ALARM ){
316 if (verbose) printf("discarding peer %d: flags=%d\n", cserver, LI(slist[cserver].flags));
317 continue;
320 /* If we don't have a server yet, use the first one */
321 if (best_server == -1) {
322 best_server = cserver;
323 DBG(printf("using peer %d as our first candidate\n", best_server));
324 continue;
327 /* compare the server to the best one we've seen so far */
328 /* does it have an equal or better stratum? */
329 DBG(printf("comparing peer %d with peer %d\n", cserver, best_server));
330 if(slist[cserver].stratum <= slist[best_server].stratum){
331 DBG(printf("stratum for peer %d <= peer %d\n", cserver, best_server));
332 /* does it have an equal or better dispersion? */
333 if(slist[cserver].rtdisp <= slist[best_server].rtdisp){
334 DBG(printf("dispersion for peer %d <= peer %d\n", cserver, best_server));
335 /* does it have a better rtdelay? */
336 if(slist[cserver].rtdelay < slist[best_server].rtdelay){
337 DBG(printf("rtdelay for peer %d < peer %d\n", cserver, best_server));
338 best_server = cserver;
339 DBG(printf("peer %d is now our best candidate\n", best_server));
345 if(best_server >= 0) {
346 DBG(printf("best server selected: peer %d\n", best_server));
347 return best_server;
348 } else {
349 DBG(printf("no peers meeting synchronization criteria :(\n"));
350 return -1;
354 /* do everything we need to get the total average offset
355 * - we use a certain amount of parallelization with poll() to ensure
356 * we don't waste time sitting around waiting for single packets.
357 * - we also "manually" handle resolving host names and connecting, because
358 * we have to do it in a way that our lazy macros don't handle currently :( */
359 double offset_request(const char *host, int *status){
360 int i=0, j=0, ga_result=0, num_hosts=0, *socklist=NULL, respnum=0;
361 int servers_completed=0, one_written=0, one_read=0, servers_readable=0, best_index=-1;
362 time_t now_time=0, start_ts=0;
363 ntp_message *req=NULL;
364 double avg_offset=0.;
365 struct timeval recv_time;
366 struct addrinfo *ai=NULL, *ai_tmp=NULL, hints;
367 struct pollfd *ufds=NULL;
368 ntp_server_results *servers=NULL;
370 /* setup hints to only return results from getaddrinfo that we'd like */
371 memset(&hints, 0, sizeof(struct addrinfo));
372 hints.ai_family = address_family;
373 hints.ai_protocol = IPPROTO_UDP;
374 hints.ai_socktype = SOCK_DGRAM;
376 /* fill in ai with the list of hosts resolved by the host name */
377 ga_result = getaddrinfo(host, "123", &hints, &ai);
378 if(ga_result!=0){
379 die(STATE_UNKNOWN, "error getting address for %s: %s\n",
380 host, gai_strerror(ga_result));
383 /* count the number of returned hosts, and allocate stuff accordingly */
384 for(ai_tmp=ai; ai_tmp!=NULL; ai_tmp=ai_tmp->ai_next){ num_hosts++; }
385 req=(ntp_message*)malloc(sizeof(ntp_message)*num_hosts);
386 if(req==NULL) die(STATE_UNKNOWN, "can not allocate ntp message array");
387 socklist=(int*)malloc(sizeof(int)*num_hosts);
388 if(socklist==NULL) die(STATE_UNKNOWN, "can not allocate socket array");
389 ufds=(struct pollfd*)malloc(sizeof(struct pollfd)*num_hosts);
390 if(ufds==NULL) die(STATE_UNKNOWN, "can not allocate socket array");
391 servers=(ntp_server_results*)malloc(sizeof(ntp_server_results)*num_hosts);
392 if(servers==NULL) die(STATE_UNKNOWN, "can not allocate server array");
393 memset(servers, 0, sizeof(ntp_server_results)*num_hosts);
394 DBG(printf("Found %d peers to check\n", num_hosts));
396 /* setup each socket for writing, and the corresponding struct pollfd */
397 ai_tmp=ai;
398 for(i=0;ai_tmp;i++){
399 socklist[i]=socket(ai_tmp->ai_family, SOCK_DGRAM, IPPROTO_UDP);
400 if(socklist[i] == -1) {
401 perror(NULL);
402 die(STATE_UNKNOWN, "can not create new socket");
404 if(connect(socklist[i], ai_tmp->ai_addr, ai_tmp->ai_addrlen)){
405 die(STATE_UNKNOWN, "can't create socket connection");
406 } else {
407 ufds[i].fd=socklist[i];
408 ufds[i].events=POLLIN;
409 ufds[i].revents=0;
411 ai_tmp = ai_tmp->ai_next;
414 /* now do AVG_NUM checks to each host. we stop before timeout/2 seconds
415 * have passed in order to ensure post-processing and jitter time. */
416 now_time=start_ts=time(NULL);
417 while(servers_completed<num_hosts && now_time-start_ts <= socket_timeout/2){
418 /* loop through each server and find each one which hasn't
419 * been touched in the past second or so and is still lacking
420 * some responses. for each of these servers, send a new request,
421 * and update the "waiting" timestamp with the current time. */
422 one_written=0;
423 now_time=time(NULL);
425 for(i=0; i<num_hosts; i++){
426 if(servers[i].waiting<now_time && servers[i].num_responses<AVG_NUM){
427 if(verbose && servers[i].waiting != 0) printf("re-");
428 if(verbose) printf("sending request to peer %d\n", i);
429 setup_request(&req[i]);
430 write(socklist[i], &req[i], sizeof(ntp_message));
431 servers[i].waiting=now_time;
432 one_written=1;
433 break;
437 /* quickly poll for any sockets with pending data */
438 servers_readable=poll(ufds, num_hosts, 100);
439 if(servers_readable==-1){
440 perror("polling ntp sockets");
441 die(STATE_UNKNOWN, "communication errors");
444 /* read from any sockets with pending data */
445 for(i=0; servers_readable && i<num_hosts; i++){
446 if(ufds[i].revents&POLLIN && servers[i].num_responses < AVG_NUM){
447 if(verbose) {
448 printf("response from peer %d: ", i);
451 read(ufds[i].fd, &req[i], sizeof(ntp_message));
452 gettimeofday(&recv_time, NULL);
453 DBG(print_ntp_message(&req[i]));
454 respnum=servers[i].num_responses++;
455 servers[i].offset[respnum]=calc_offset(&req[i], &recv_time);
456 if(verbose) {
457 printf("offset %.10g\n", servers[i].offset[respnum]);
459 servers[i].stratum=req[i].stratum;
460 servers[i].rtdisp=NTP32asDOUBLE(req[i].rtdisp);
461 servers[i].rtdelay=NTP32asDOUBLE(req[i].rtdelay);
462 servers[i].waiting=0;
463 servers[i].flags=req[i].flags;
464 servers_readable--;
465 one_read = 1;
466 if(servers[i].num_responses==AVG_NUM) servers_completed++;
469 /* lather, rinse, repeat. */
472 if (one_read == 0) {
473 die(STATE_CRITICAL, "NTP CRITICAL: No response from NTP server\n");
476 /* now, pick the best server from the list */
477 best_index=best_offset_server(servers, num_hosts);
478 if(best_index < 0){
479 *status=STATE_UNKNOWN;
480 } else {
481 /* finally, calculate the average offset */
482 for(i=0; i<servers[best_index].num_responses;i++){
483 avg_offset+=servers[best_index].offset[j];
485 avg_offset/=servers[best_index].num_responses;
488 /* cleanup */
489 /* FIXME: Not closing the socket to avoid re-use of the local port
490 * which can cause old NTP packets to be read instead of NTP control
491 * pactets in jitter_request(). THERE MUST BE ANOTHER WAY...
492 * for(j=0; j<num_hosts; j++){ close(socklist[j]); } */
493 free(socklist);
494 free(ufds);
495 free(servers);
496 free(req);
497 freeaddrinfo(ai);
499 if(verbose) printf("overall average offset: %.10g\n", avg_offset);
500 return avg_offset;
503 void
504 setup_control_request(ntp_control_message *p, uint8_t opcode, uint16_t seq){
505 memset(p, 0, sizeof(ntp_control_message));
506 LI_SET(p->flags, LI_NOWARNING);
507 VN_SET(p->flags, VN_RESERVED);
508 MODE_SET(p->flags, MODE_CONTROLMSG);
509 OP_SET(p->op, opcode);
510 p->seq = htons(seq);
511 /* Remaining fields are zero for requests */
514 /* XXX handle responses with the error bit set */
515 double jitter_request(const char *host, int *status){
516 int conn=-1, i, npeers=0, num_candidates=0, syncsource_found=0;
517 int run=0, min_peer_sel=PEER_INCLUDED, num_selected=0, num_valid=0;
518 int peers_size=0, peer_offset=0;
519 ntp_assoc_status_pair *peers=NULL;
520 ntp_control_message req;
521 const char *getvar = "jitter";
522 double rval = 0.0, jitter = -1.0;
523 char *startofvalue=NULL, *nptr=NULL;
524 void *tmp;
526 /* Long-winded explanation:
527 * Getting the jitter requires a number of steps:
528 * 1) Send a READSTAT request.
529 * 2) Interpret the READSTAT reply
530 * a) The data section contains a list of peer identifiers (16 bits)
531 * and associated status words (16 bits)
532 * b) We want the value of 0x06 in the SEL (peer selection) value,
533 * which means "current synchronizatin source". If that's missing,
534 * we take anything better than 0x04 (see the rfc for details) but
535 * set a minimum of warning.
536 * 3) Send a READVAR request for information on each peer identified
537 * in 2b greater than the minimum selection value.
538 * 4) Extract the jitter value from the data[] (it's ASCII)
540 my_udp_connect(server_address, 123, &conn);
542 /* keep sending requests until the server stops setting the
543 * REM_MORE bit, though usually this is only 1 packet. */
545 setup_control_request(&req, OP_READSTAT, 1);
546 DBG(printf("sending READSTAT request"));
547 write(conn, &req, SIZEOF_NTPCM(req));
548 DBG(print_ntp_control_message(&req));
549 /* Attempt to read the largest size packet possible */
550 req.count=htons(MAX_CM_SIZE);
551 DBG(printf("recieving READSTAT response"))
552 read(conn, &req, SIZEOF_NTPCM(req));
553 DBG(print_ntp_control_message(&req));
554 /* Each peer identifier is 4 bytes in the data section, which
555 * we represent as a ntp_assoc_status_pair datatype.
557 peers_size+=ntohs(req.count);
558 if((tmp=realloc(peers, peers_size)) == NULL)
559 free(peers), die(STATE_UNKNOWN, "can not (re)allocate 'peers' buffer\n");
560 peers=tmp;
561 memcpy((void*)((ptrdiff_t)peers+peer_offset), (void*)req.data, ntohs(req.count));
562 npeers=peers_size/sizeof(ntp_assoc_status_pair);
563 peer_offset+=ntohs(req.count);
564 } while(req.op&REM_MORE);
566 /* first, let's find out if we have a sync source, or if there are
567 * at least some candidates. in the case of the latter we'll issue
568 * a warning but go ahead with the check on them. */
569 for (i = 0; i < npeers; i++){
570 if (PEER_SEL(peers[i].status) >= PEER_INCLUDED){
571 num_candidates++;
572 if(PEER_SEL(peers[i].status) >= PEER_SYNCSOURCE){
573 syncsource_found=1;
574 min_peer_sel=PEER_SYNCSOURCE;
578 if(verbose) printf("%d candiate peers available\n", num_candidates);
579 if(verbose && syncsource_found) printf("synchronization source found\n");
580 if(! syncsource_found){
581 *status = STATE_UNKNOWN;
582 if(verbose) printf("warning: no synchronization source found\n");
586 for (run=0; run<AVG_NUM; run++){
587 if(verbose) printf("jitter run %d of %d\n", run+1, AVG_NUM);
588 for (i = 0; i < npeers; i++){
589 /* Only query this server if it is the current sync source */
590 if (PEER_SEL(peers[i].status) >= min_peer_sel){
591 num_selected++;
592 setup_control_request(&req, OP_READVAR, 2);
593 req.assoc = peers[i].assoc;
594 /* By spec, putting the variable name "jitter" in the request
595 * should cause the server to provide _only_ the jitter value.
596 * thus reducing net traffic, guaranteeing us only a single
597 * datagram in reply, and making intepretation much simpler
599 /* Older servers doesn't know what jitter is, so if we get an
600 * error on the first pass we redo it with "dispersion" */
601 strncpy(req.data, getvar, MAX_CM_SIZE-1);
602 req.count = htons(strlen(getvar));
603 DBG(printf("sending READVAR request...\n"));
604 write(conn, &req, SIZEOF_NTPCM(req));
605 DBG(print_ntp_control_message(&req));
607 req.count = htons(MAX_CM_SIZE);
608 DBG(printf("recieving READVAR response...\n"));
609 read(conn, &req, SIZEOF_NTPCM(req));
610 DBG(print_ntp_control_message(&req));
612 if(req.op&REM_ERROR && strstr(getvar, "jitter")) {
613 if(verbose) printf("The 'jitter' command failed (old ntp server?)\nRestarting with 'dispersion'...\n");
614 getvar = "dispersion";
615 num_selected--;
616 i--;
617 continue;
620 /* get to the float value */
621 if(verbose) {
622 printf("parsing jitter from peer %.2x: ", ntohs(peers[i].assoc));
624 startofvalue = strchr(req.data, '=');
625 if(startofvalue != NULL) {
626 startofvalue++;
627 jitter = strtod(startofvalue, &nptr);
629 if(startofvalue == NULL || startofvalue==nptr){
630 printf("warning: unable to read server jitter response.\n");
631 *status = STATE_UNKNOWN;
632 } else {
633 if(verbose) printf("%g\n", jitter);
634 num_valid++;
635 rval += jitter;
639 if(verbose){
640 printf("jitter parsed from %d/%d peers\n", num_valid, num_selected);
644 rval = num_valid ? rval / num_valid : -1.0;
646 close(conn);
647 if(peers!=NULL) free(peers);
648 /* If we return -1.0, it means no synchronization source was found */
649 return rval;
652 int process_arguments(int argc, char **argv){
653 int c;
654 int option=0;
655 static struct option longopts[] = {
656 {"version", no_argument, 0, 'V'},
657 {"help", no_argument, 0, 'h'},
658 {"verbose", no_argument, 0, 'v'},
659 {"use-ipv4", no_argument, 0, '4'},
660 {"use-ipv6", no_argument, 0, '6'},
661 {"warning", required_argument, 0, 'w'},
662 {"critical", required_argument, 0, 'c'},
663 {"jwarn", required_argument, 0, 'j'},
664 {"jcrit", required_argument, 0, 'k'},
665 {"timeout", required_argument, 0, 't'},
666 {"hostname", required_argument, 0, 'H'},
667 {0, 0, 0, 0}
671 if (argc < 2)
672 usage ("\n");
674 while (1) {
675 c = getopt_long (argc, argv, "Vhv46w:c:j:k:t:H:", longopts, &option);
676 if (c == -1 || c == EOF || c == 1)
677 break;
679 switch (c) {
680 case 'h':
681 print_help();
682 exit(STATE_OK);
683 break;
684 case 'V':
685 print_revision(progname, revision);
686 exit(STATE_OK);
687 break;
688 case 'v':
689 verbose++;
690 break;
691 case 'w':
692 do_offset=1;
693 owarn = optarg;
694 break;
695 case 'c':
696 do_offset=1;
697 ocrit = optarg;
698 break;
699 case 'j':
700 do_jitter=1;
701 jwarn = optarg;
702 break;
703 case 'k':
704 do_jitter=1;
705 jcrit = optarg;
706 break;
707 case 'H':
708 if(is_host(optarg) == FALSE)
709 usage2(_("Invalid hostname/address"), optarg);
710 server_address = strdup(optarg);
711 break;
712 case 't':
713 socket_timeout=atoi(optarg);
714 break;
715 case '4':
716 address_family = AF_INET;
717 break;
718 case '6':
719 #ifdef USE_IPV6
720 address_family = AF_INET6;
721 #else
722 usage4 (_("IPv6 support not available"));
723 #endif
724 break;
725 case '?':
726 /* print short usage statement if args not parsable */
727 usage5 ();
728 break;
732 if(server_address == NULL){
733 usage4(_("Hostname was not supplied"));
736 return 0;
739 char *perfd_offset (double offset)
741 return fperfdata ("offset", offset, "s",
742 TRUE, offset_thresholds->warning->end,
743 TRUE, offset_thresholds->critical->end,
744 FALSE, 0, FALSE, 0);
747 char *perfd_jitter (double jitter)
749 return fperfdata ("jitter", jitter, "s",
750 do_jitter, jitter_thresholds->warning->end,
751 do_jitter, jitter_thresholds->critical->end,
752 TRUE, 0, FALSE, 0);
755 int main(int argc, char *argv[]){
756 int result, offset_result, jitter_result;
757 double offset=0, jitter=0;
758 char *result_line, *perfdata_line;
760 setlocale (LC_ALL, "");
761 bindtextdomain (PACKAGE, LOCALEDIR);
762 textdomain (PACKAGE);
764 result = offset_result = jitter_result = STATE_OK;
766 /* Parse extra opts if any */
767 argv=np_extra_opts (&argc, argv, progname);
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);
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
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;
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;
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));
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));
830 printf("%s|%s\n", result_line, perfdata_line);
832 if(server_address!=NULL) free(server_address);
833 return result;
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_EXTRA_OPTS));
851 printf (_(UT_HOST_PORT), 'p', "123");
852 printf (" %s\n", "-w, --warning=THRESHOLD");
853 printf (" %s\n", _("Offset to result in warning status (seconds)"));
854 printf (" %s\n", "-c, --critical=THRESHOLD");
855 printf (" %s\n", _("Offset to result in critical status (seconds)"));
856 printf (" %s\n", "-j, --jwarn=THRESHOLD");
857 printf (" %s\n", _("Warning threshold for jitter"));
858 printf (" %s\n", "-k, --jcrit=THRESHOLD");
859 printf (" %s\n", _("Critical threshold for jitter"));
860 printf (_(UT_TIMEOUT), DEFAULT_SOCKET_TIMEOUT);
861 printf (_(UT_VERBOSE));
863 printf("\n");
864 printf("%s\n", _("Notes:"));
865 printf(_(UT_THRESHOLDS_NOTES));
866 #ifdef NP_EXTRA_OPTS
867 printf("\n");
868 printf(_(UT_EXTRA_OPTS_NOTES));
869 #endif
871 printf("\n");
872 printf("%s\n", _("Examples:"));
873 printf(" %s\n", _("Normal offset check:"));
874 printf(" %s\n", ("./check_ntp -H ntpserv -w 0.5 -c 1"));
875 printf("\n");
876 printf(" %s\n", _("Check jitter too, avoiding critical notifications if jitter isn't available"));
877 printf(" %s\n", _("(See Notes above for more details on thresholds formats):"));
878 printf(" %s\n", ("./check_ntp -H ntpserv -w 0.5 -c 1 -j -1:100 -k -1:200"));
880 printf (_(UT_SUPPORT));
882 printf ("%s\n", _("WARNING: check_ntp is deprecated. Please use check_ntp_peer or"));
883 printf ("%s\n\n", _("check_ntp_time istead."));
886 void
887 print_usage(void)
889 printf ("%s\n", _("WARNING: check_ntp is deprecated. Please use check_ntp_peer or"));
890 printf ("%s\n\n", _("check_ntp_time istead."));
891 printf (_("Usage:"));
892 printf(" %s -H <host> [-w <warn>] [-c <crit>] [-j <warn>] [-k <crit>] [-v verbose]\n", progname);