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