check_ntp_peer: do not use uninitialized results for max state
[monitoring-plugins.git] / plugins / check_ntp.c
blob09a923eb86b777d8888d3af8df1f0281579d13b0
1 /*****************************************************************************
2 *
3 * Monitoring check_ntp plugin
4 *
5 * License: GPL
6 * Copyright (c) 2006 Sean Finney <seanius@seanius.net>
7 * Copyright (c) 2006-2008 Monitoring 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 = "devel@monitoring-plugins.org";
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 #ifndef AVG_NUM
58 #define AVG_NUM 4
59 #endif
61 /* max size of control message data */
62 #define MAX_CM_SIZE 468
64 /* this structure holds everything in an ntp request/response as per rfc1305 */
65 typedef struct {
66 uint8_t flags; /* byte with leapindicator,vers,mode. see macros */
67 uint8_t stratum; /* clock stratum */
68 int8_t poll; /* polling interval */
69 int8_t precision; /* precision of the local clock */
70 int32_t rtdelay; /* total rt delay, as a fixed point num. see macros */
71 uint32_t rtdisp; /* like above, but for max err to primary src */
72 uint32_t refid; /* ref clock identifier */
73 uint64_t refts; /* reference timestamp. local time local clock */
74 uint64_t origts; /* time at which request departed client */
75 uint64_t rxts; /* time at which request arrived at server */
76 uint64_t txts; /* time at which request departed server */
77 } ntp_message;
79 /* this structure holds data about results from querying offset from a peer */
80 typedef struct {
81 time_t waiting; /* ts set when we started waiting for a response */
82 int num_responses; /* number of successfully recieved responses */
83 uint8_t stratum; /* copied verbatim from the ntp_message */
84 double rtdelay; /* converted from the ntp_message */
85 double rtdisp; /* converted from the ntp_message */
86 double offset[AVG_NUM]; /* offsets from each response */
87 uint8_t flags; /* byte with leapindicator,vers,mode. see macros */
88 } ntp_server_results;
90 /* this structure holds everything in an ntp control message as per rfc1305 */
91 typedef struct {
92 uint8_t flags; /* byte with leapindicator,vers,mode. see macros */
93 uint8_t op; /* R,E,M bits and Opcode */
94 uint16_t seq; /* Packet sequence */
95 uint16_t status; /* Clock status */
96 uint16_t assoc; /* Association */
97 uint16_t offset; /* Similar to TCP sequence # */
98 uint16_t count; /* # bytes of data */
99 char data[MAX_CM_SIZE]; /* ASCII data of the request */
100 /* NB: not necessarily NULL terminated! */
101 } ntp_control_message;
103 /* this is an association/status-word pair found in control packet reponses */
104 typedef struct {
105 uint16_t assoc;
106 uint16_t status;
107 } ntp_assoc_status_pair;
109 /* bits 1,2 are the leap indicator */
110 #define LI_MASK 0xc0
111 #define LI(x) ((x&LI_MASK)>>6)
112 #define LI_SET(x,y) do{ x |= ((y<<6)&LI_MASK); }while(0)
113 /* and these are the values of the leap indicator */
114 #define LI_NOWARNING 0x00
115 #define LI_EXTRASEC 0x01
116 #define LI_MISSINGSEC 0x02
117 #define LI_ALARM 0x03
118 /* bits 3,4,5 are the ntp version */
119 #define VN_MASK 0x38
120 #define VN(x) ((x&VN_MASK)>>3)
121 #define VN_SET(x,y) do{ x |= ((y<<3)&VN_MASK); }while(0)
122 #define VN_RESERVED 0x02
123 /* bits 6,7,8 are the ntp mode */
124 #define MODE_MASK 0x07
125 #define MODE(x) (x&MODE_MASK)
126 #define MODE_SET(x,y) do{ x |= (y&MODE_MASK); }while(0)
127 /* here are some values */
128 #define MODE_CLIENT 0x03
129 #define MODE_CONTROLMSG 0x06
130 /* In control message, bits 8-10 are R,E,M bits */
131 #define REM_MASK 0xe0
132 #define REM_RESP 0x80
133 #define REM_ERROR 0x40
134 #define REM_MORE 0x20
135 /* In control message, bits 11 - 15 are opcode */
136 #define OP_MASK 0x1f
137 #define OP_SET(x,y) do{ x |= (y&OP_MASK); }while(0)
138 #define OP_READSTAT 0x01
139 #define OP_READVAR 0x02
140 /* In peer status bytes, bits 6,7,8 determine clock selection status */
141 #define PEER_SEL(x) ((ntohs(x)>>8)&0x07)
142 #define PEER_INCLUDED 0x04
143 #define PEER_SYNCSOURCE 0x06
146 ** a note about the 32-bit "fixed point" numbers:
148 they are divided into halves, each being a 16-bit int in network byte order:
149 - the first 16 bits are an int on the left side of a decimal point.
150 - the second 16 bits represent a fraction n/(2^16)
151 likewise for the 64-bit "fixed point" numbers with everything doubled :)
154 /* macros to access the left/right 16 bits of a 32-bit ntp "fixed point"
155 number. note that these can be used as lvalues too */
156 #define L16(x) (((uint16_t*)&x)[0])
157 #define R16(x) (((uint16_t*)&x)[1])
158 /* macros to access the left/right 32 bits of a 64-bit ntp "fixed point"
159 number. these too can be used as lvalues */
160 #define L32(x) (((uint32_t*)&x)[0])
161 #define R32(x) (((uint32_t*)&x)[1])
163 /* ntp wants seconds since 1/1/00, epoch is 1/1/70. this is the difference */
164 #define EPOCHDIFF 0x83aa7e80UL
166 /* extract a 32-bit ntp fixed point number into a double */
167 #define NTP32asDOUBLE(x) (ntohs(L16(x)) + (double)ntohs(R16(x))/65536.0)
169 /* likewise for a 64-bit ntp fp number */
170 #define NTP64asDOUBLE(n) (double)(((uint64_t)n)?\
171 (ntohl(L32(n))-EPOCHDIFF) + \
172 (.00000001*(0.5+(double)(ntohl(R32(n))/42.94967296))):\
175 /* convert a struct timeval to a double */
176 #define TVasDOUBLE(x) (double)(x.tv_sec+(0.000001*x.tv_usec))
178 /* convert an ntp 64-bit fp number to a struct timeval */
179 #define NTP64toTV(n,t) \
180 do{ if(!n) t.tv_sec = t.tv_usec = 0; \
181 else { \
182 t.tv_sec=ntohl(L32(n))-EPOCHDIFF; \
183 t.tv_usec=(int)(0.5+(double)(ntohl(R32(n))/4294.967296)); \
185 }while(0)
187 /* convert a struct timeval to an ntp 64-bit fp number */
188 #define TVtoNTP64(t,n) \
189 do{ if(!t.tv_usec && !t.tv_sec) n=0x0UL; \
190 else { \
191 L32(n)=htonl(t.tv_sec + EPOCHDIFF); \
192 R32(n)=htonl((uint64_t)((4294.967296*t.tv_usec)+.5)); \
194 } while(0)
196 /* NTP control message header is 12 bytes, plus any data in the data
197 * field, plus null padding to the nearest 32-bit boundary per rfc.
199 #define SIZEOF_NTPCM(m) (12+ntohs(m.count)+((ntohs(m.count)%4)?4-(ntohs(m.count)%4):0))
201 /* finally, a little helper or two for debugging: */
202 #define DBG(x) do{if(verbose>1){ x; }}while(0);
203 #define PRINTSOCKADDR(x) \
204 do{ \
205 printf("%u.%u.%u.%u", (x>>24)&0xff, (x>>16)&0xff, (x>>8)&0xff, x&0xff);\
206 }while(0);
208 /* calculate the offset of the local clock */
209 static inline double calc_offset(const ntp_message *m, const struct timeval *t){
210 double client_tx, peer_rx, peer_tx, client_rx;
211 client_tx = NTP64asDOUBLE(m->origts);
212 peer_rx = NTP64asDOUBLE(m->rxts);
213 peer_tx = NTP64asDOUBLE(m->txts);
214 client_rx=TVasDOUBLE((*t));
215 return (.5*((peer_tx-client_rx)+(peer_rx-client_tx)));
218 /* print out a ntp packet in human readable/debuggable format */
219 void print_ntp_message(const ntp_message *p){
220 struct timeval ref, orig, rx, tx;
222 NTP64toTV(p->refts,ref);
223 NTP64toTV(p->origts,orig);
224 NTP64toTV(p->rxts,rx);
225 NTP64toTV(p->txts,tx);
227 printf("packet contents:\n");
228 printf("\tflags: 0x%.2x\n", p->flags);
229 printf("\t li=%d (0x%.2x)\n", LI(p->flags), p->flags&LI_MASK);
230 printf("\t vn=%d (0x%.2x)\n", VN(p->flags), p->flags&VN_MASK);
231 printf("\t mode=%d (0x%.2x)\n", MODE(p->flags), p->flags&MODE_MASK);
232 printf("\tstratum = %d\n", p->stratum);
233 printf("\tpoll = %g\n", pow(2, p->poll));
234 printf("\tprecision = %g\n", pow(2, p->precision));
235 printf("\trtdelay = %-.16g\n", NTP32asDOUBLE(p->rtdelay));
236 printf("\trtdisp = %-.16g\n", NTP32asDOUBLE(p->rtdisp));
237 printf("\trefid = %x\n", p->refid);
238 printf("\trefts = %-.16g\n", NTP64asDOUBLE(p->refts));
239 printf("\torigts = %-.16g\n", NTP64asDOUBLE(p->origts));
240 printf("\trxts = %-.16g\n", NTP64asDOUBLE(p->rxts));
241 printf("\ttxts = %-.16g\n", NTP64asDOUBLE(p->txts));
244 void print_ntp_control_message(const ntp_control_message *p){
245 int i=0, numpeers=0;
246 const ntp_assoc_status_pair *peer=NULL;
248 printf("control packet contents:\n");
249 printf("\tflags: 0x%.2x , 0x%.2x\n", p->flags, p->op);
250 printf("\t li=%d (0x%.2x)\n", LI(p->flags), p->flags&LI_MASK);
251 printf("\t vn=%d (0x%.2x)\n", VN(p->flags), p->flags&VN_MASK);
252 printf("\t mode=%d (0x%.2x)\n", MODE(p->flags), p->flags&MODE_MASK);
253 printf("\t response=%d (0x%.2x)\n", (p->op&REM_RESP)>0, p->op&REM_RESP);
254 printf("\t more=%d (0x%.2x)\n", (p->op&REM_MORE)>0, p->op&REM_MORE);
255 printf("\t error=%d (0x%.2x)\n", (p->op&REM_ERROR)>0, p->op&REM_ERROR);
256 printf("\t op=%d (0x%.2x)\n", p->op&OP_MASK, p->op&OP_MASK);
257 printf("\tsequence: %d (0x%.2x)\n", ntohs(p->seq), ntohs(p->seq));
258 printf("\tstatus: %d (0x%.2x)\n", ntohs(p->status), ntohs(p->status));
259 printf("\tassoc: %d (0x%.2x)\n", ntohs(p->assoc), ntohs(p->assoc));
260 printf("\toffset: %d (0x%.2x)\n", ntohs(p->offset), ntohs(p->offset));
261 printf("\tcount: %d (0x%.2x)\n", ntohs(p->count), ntohs(p->count));
262 numpeers=ntohs(p->count)/(sizeof(ntp_assoc_status_pair));
263 if(p->op&REM_RESP && p->op&OP_READSTAT){
264 peer=(ntp_assoc_status_pair*)p->data;
265 for(i=0;i<numpeers;i++){
266 printf("\tpeer id %.2x status %.2x",
267 ntohs(peer[i].assoc), ntohs(peer[i].status));
268 if (PEER_SEL(peer[i].status) >= PEER_INCLUDED){
269 if(PEER_SEL(peer[i].status) >= PEER_SYNCSOURCE){
270 printf(" <-- current sync source");
271 } else {
272 printf(" <-- current sync candidate");
275 printf("\n");
280 void setup_request(ntp_message *p){
281 struct timeval t;
283 memset(p, 0, sizeof(ntp_message));
284 LI_SET(p->flags, LI_ALARM);
285 VN_SET(p->flags, 4);
286 MODE_SET(p->flags, MODE_CLIENT);
287 p->poll=4;
288 p->precision=(int8_t)0xfa;
289 L16(p->rtdelay)=htons(1);
290 L16(p->rtdisp)=htons(1);
292 gettimeofday(&t, NULL);
293 TVtoNTP64(t,p->txts);
296 /* select the "best" server from a list of servers, and return its index.
297 * this is done by filtering servers based on stratum, dispersion, and
298 * finally round-trip delay. */
299 int best_offset_server(const ntp_server_results *slist, int nservers){
300 int i=0, cserver=0, best_server=-1;
302 /* for each server */
303 for(cserver=0; cserver<nservers; cserver++){
304 /* We don't want any servers that fails these tests */
305 /* Sort out servers that didn't respond or responede with a 0 stratum;
306 * stratum 0 is for reference clocks so no NTP server should ever report
307 * a stratum 0 */
308 if ( slist[cserver].stratum == 0){
309 if (verbose) printf("discarding peer %d: stratum=%d\n", cserver, slist[cserver].stratum);
310 continue;
312 /* Sort out servers with error flags */
313 if ( LI(slist[cserver].flags) == LI_ALARM ){
314 if (verbose) printf("discarding peer %d: flags=%d\n", cserver, LI(slist[cserver].flags));
315 continue;
318 /* If we don't have a server yet, use the first one */
319 if (best_server == -1) {
320 best_server = cserver;
321 DBG(printf("using peer %d as our first candidate\n", best_server));
322 continue;
325 /* compare the server to the best one we've seen so far */
326 /* does it have an equal or better stratum? */
327 DBG(printf("comparing peer %d with peer %d\n", cserver, best_server));
328 if(slist[cserver].stratum <= slist[best_server].stratum){
329 DBG(printf("stratum for peer %d <= peer %d\n", cserver, best_server));
330 /* does it have an equal or better dispersion? */
331 if(slist[cserver].rtdisp <= slist[best_server].rtdisp){
332 DBG(printf("dispersion for peer %d <= peer %d\n", cserver, best_server));
333 /* does it have a better rtdelay? */
334 if(slist[cserver].rtdelay < slist[best_server].rtdelay){
335 DBG(printf("rtdelay for peer %d < peer %d\n", cserver, best_server));
336 best_server = cserver;
337 DBG(printf("peer %d is now our best candidate\n", best_server));
343 if(best_server >= 0) {
344 DBG(printf("best server selected: peer %d\n", best_server));
345 return best_server;
346 } else {
347 DBG(printf("no peers meeting synchronization criteria :(\n"));
348 return -1;
352 /* do everything we need to get the total average offset
353 * - we use a certain amount of parallelization with poll() to ensure
354 * we don't waste time sitting around waiting for single packets.
355 * - we also "manually" handle resolving host names and connecting, because
356 * we have to do it in a way that our lazy macros don't handle currently :( */
357 double offset_request(const char *host, int *status){
358 int i=0, j=0, ga_result=0, num_hosts=0, *socklist=NULL, respnum=0;
359 int servers_completed=0, one_written=0, one_read=0, servers_readable=0, best_index=-1;
360 time_t now_time=0, start_ts=0;
361 ntp_message *req=NULL;
362 double avg_offset=0.;
363 struct timeval recv_time;
364 struct addrinfo *ai=NULL, *ai_tmp=NULL, hints;
365 struct pollfd *ufds=NULL;
366 ntp_server_results *servers=NULL;
368 /* setup hints to only return results from getaddrinfo that we'd like */
369 memset(&hints, 0, sizeof(struct addrinfo));
370 hints.ai_family = address_family;
371 hints.ai_protocol = IPPROTO_UDP;
372 hints.ai_socktype = SOCK_DGRAM;
374 /* fill in ai with the list of hosts resolved by the host name */
375 ga_result = getaddrinfo(host, "123", &hints, &ai);
376 if(ga_result!=0){
377 die(STATE_UNKNOWN, "error getting address for %s: %s\n",
378 host, gai_strerror(ga_result));
381 /* count the number of returned hosts, and allocate stuff accordingly */
382 for(ai_tmp=ai; ai_tmp!=NULL; ai_tmp=ai_tmp->ai_next){ num_hosts++; }
383 req=(ntp_message*)malloc(sizeof(ntp_message)*num_hosts);
384 if(req==NULL) die(STATE_UNKNOWN, "can not allocate ntp message array");
385 socklist=(int*)malloc(sizeof(int)*num_hosts);
386 if(socklist==NULL) die(STATE_UNKNOWN, "can not allocate socket array");
387 ufds=(struct pollfd*)malloc(sizeof(struct pollfd)*num_hosts);
388 if(ufds==NULL) die(STATE_UNKNOWN, "can not allocate socket array");
389 servers=(ntp_server_results*)malloc(sizeof(ntp_server_results)*num_hosts);
390 if(servers==NULL) die(STATE_UNKNOWN, "can not allocate server array");
391 memset(servers, 0, sizeof(ntp_server_results)*num_hosts);
392 DBG(printf("Found %d peers to check\n", num_hosts));
394 /* setup each socket for writing, and the corresponding struct pollfd */
395 ai_tmp=ai;
396 for(i=0;ai_tmp;i++){
397 socklist[i]=socket(ai_tmp->ai_family, SOCK_DGRAM, IPPROTO_UDP);
398 if(socklist[i] == -1) {
399 perror(NULL);
400 die(STATE_UNKNOWN, "can not create new socket");
402 if(connect(socklist[i], ai_tmp->ai_addr, ai_tmp->ai_addrlen)){
403 /* don't die here, because it is enough if there is one server
404 answering in time. This also would break for dual ipv4/6 stacked
405 ntp servers when the client only supports on of them.
407 DBG(printf("can't create socket connection on peer %i: %s\n", i, strerror(errno)));
408 } else {
409 ufds[i].fd=socklist[i];
410 ufds[i].events=POLLIN;
411 ufds[i].revents=0;
413 ai_tmp = ai_tmp->ai_next;
416 /* now do AVG_NUM checks to each host. we stop before timeout/2 seconds
417 * have passed in order to ensure post-processing and jitter time. */
418 now_time=start_ts=time(NULL);
419 while(servers_completed<num_hosts && now_time-start_ts <= socket_timeout/2){
420 /* loop through each server and find each one which hasn't
421 * been touched in the past second or so and is still lacking
422 * some responses. for each of these servers, send a new request,
423 * and update the "waiting" timestamp with the current time. */
424 one_written=0;
425 now_time=time(NULL);
427 for(i=0; i<num_hosts; i++){
428 if(servers[i].waiting<now_time && servers[i].num_responses<AVG_NUM){
429 if(verbose && servers[i].waiting != 0) printf("re-");
430 if(verbose) printf("sending request to peer %d\n", i);
431 setup_request(&req[i]);
432 write(socklist[i], &req[i], sizeof(ntp_message));
433 servers[i].waiting=now_time;
434 one_written=1;
435 break;
439 /* quickly poll for any sockets with pending data */
440 servers_readable=poll(ufds, num_hosts, 100);
441 if(servers_readable==-1){
442 perror("polling ntp sockets");
443 die(STATE_UNKNOWN, "communication errors");
446 /* read from any sockets with pending data */
447 for(i=0; servers_readable && i<num_hosts; i++){
448 if(ufds[i].revents&POLLIN && servers[i].num_responses < AVG_NUM){
449 if(verbose) {
450 printf("response from peer %d: ", i);
453 read(ufds[i].fd, &req[i], sizeof(ntp_message));
454 gettimeofday(&recv_time, NULL);
455 DBG(print_ntp_message(&req[i]));
456 respnum=servers[i].num_responses++;
457 servers[i].offset[respnum]=calc_offset(&req[i], &recv_time);
458 if(verbose) {
459 printf("offset %.10g\n", servers[i].offset[respnum]);
461 servers[i].stratum=req[i].stratum;
462 servers[i].rtdisp=NTP32asDOUBLE(req[i].rtdisp);
463 servers[i].rtdelay=NTP32asDOUBLE(req[i].rtdelay);
464 servers[i].waiting=0;
465 servers[i].flags=req[i].flags;
466 servers_readable--;
467 one_read = 1;
468 if(servers[i].num_responses==AVG_NUM) servers_completed++;
471 /* lather, rinse, repeat. */
474 if (one_read == 0) {
475 die(STATE_CRITICAL, "NTP CRITICAL: No response from NTP server\n");
478 /* now, pick the best server from the list */
479 best_index=best_offset_server(servers, num_hosts);
480 if(best_index < 0){
481 *status=STATE_UNKNOWN;
482 } else {
483 /* finally, calculate the average offset */
484 for(i=0; i<servers[best_index].num_responses;i++){
485 avg_offset+=servers[best_index].offset[i];
487 avg_offset/=servers[best_index].num_responses;
490 /* cleanup */
491 /* FIXME: Not closing the socket to avoid re-use of the local port
492 * which can cause old NTP packets to be read instead of NTP control
493 * pactets in jitter_request(). THERE MUST BE ANOTHER WAY...
494 * for(j=0; j<num_hosts; j++){ close(socklist[j]); } */
495 free(socklist);
496 free(ufds);
497 free(servers);
498 free(req);
499 freeaddrinfo(ai);
501 if(verbose) printf("overall average offset: %.10g\n", avg_offset);
502 return avg_offset;
505 void
506 setup_control_request(ntp_control_message *p, uint8_t opcode, uint16_t seq){
507 memset(p, 0, sizeof(ntp_control_message));
508 LI_SET(p->flags, LI_NOWARNING);
509 VN_SET(p->flags, VN_RESERVED);
510 MODE_SET(p->flags, MODE_CONTROLMSG);
511 OP_SET(p->op, opcode);
512 p->seq = htons(seq);
513 /* Remaining fields are zero for requests */
516 /* XXX handle responses with the error bit set */
517 double jitter_request(const char *host, int *status){
518 int conn=-1, i, npeers=0, num_candidates=0, syncsource_found=0;
519 int run=0, min_peer_sel=PEER_INCLUDED, num_selected=0, num_valid=0;
520 int peers_size=0, peer_offset=0, bytes_read=0;
521 ntp_assoc_status_pair *peers=NULL;
522 ntp_control_message req;
523 const char *getvar = "jitter";
524 double rval = 0.0, jitter = -1.0;
525 char *startofvalue=NULL, *nptr=NULL;
526 void *tmp;
527 int ntp_cm_ints = sizeof(uint16_t) * 5 + sizeof(uint8_t) * 2;
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)
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. */
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.
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;
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");
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
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"));
613 /* cov-66524 - req.data not null terminated before usage. Also covers verifying struct was returned correctly*/
614 if ((bytes_read = read(conn, &req, SIZEOF_NTPCM(req))) == -1)
615 die(STATE_UNKNOWN, _("Cannot read from socket: %s"), strerror(errno));
616 if (bytes_read != ntp_cm_ints + req.count)
617 die(STATE_UNKNOWN, _("Invalid NTP response: %d bytes read does not equal %d plus %d data segment"), bytes_read, ntp_cm_ints, req.count);
618 /* else null terminate */
619 strncpy(req.data[req.count], "\0", 1);
621 DBG(print_ntp_control_message(&req));
623 if(req.op&REM_ERROR && strstr(getvar, "jitter")) {
624 if(verbose) printf("The 'jitter' command failed (old ntp server?)\nRestarting with 'dispersion'...\n");
625 getvar = "dispersion";
626 num_selected--;
627 i--;
628 continue;
631 /* get to the float value */
632 if(verbose) {
633 printf("parsing jitter from peer %.2x: ", ntohs(peers[i].assoc));
635 startofvalue = strchr(req.data, '=');
636 if(startofvalue != NULL) {
637 startofvalue++;
638 jitter = strtod(startofvalue, &nptr);
640 if(startofvalue == NULL || startofvalue==nptr){
641 printf("warning: unable to read server jitter response.\n");
642 *status = STATE_UNKNOWN;
643 } else {
644 if(verbose) printf("%g\n", jitter);
645 num_valid++;
646 rval += jitter;
650 if(verbose){
651 printf("jitter parsed from %d/%d peers\n", num_valid, num_selected);
655 rval = num_valid ? rval / num_valid : -1.0;
657 close(conn);
658 if(peers!=NULL) free(peers);
659 /* If we return -1.0, it means no synchronization source was found */
660 return rval;
663 int process_arguments(int argc, char **argv){
664 int c;
665 int option=0;
666 static struct option longopts[] = {
667 {"version", no_argument, 0, 'V'},
668 {"help", no_argument, 0, 'h'},
669 {"verbose", no_argument, 0, 'v'},
670 {"use-ipv4", no_argument, 0, '4'},
671 {"use-ipv6", no_argument, 0, '6'},
672 {"warning", required_argument, 0, 'w'},
673 {"critical", required_argument, 0, 'c'},
674 {"jwarn", required_argument, 0, 'j'},
675 {"jcrit", required_argument, 0, 'k'},
676 {"timeout", required_argument, 0, 't'},
677 {"hostname", required_argument, 0, 'H'},
678 {0, 0, 0, 0}
682 if (argc < 2)
683 usage ("\n");
685 while (1) {
686 c = getopt_long (argc, argv, "Vhv46w:c:j:k:t:H:", longopts, &option);
687 if (c == -1 || c == EOF || c == 1)
688 break;
690 switch (c) {
691 case 'h':
692 print_help();
693 exit(STATE_OK);
694 break;
695 case 'V':
696 print_revision(progname, NP_VERSION);
697 exit(STATE_OK);
698 break;
699 case 'v':
700 verbose++;
701 break;
702 case 'w':
703 do_offset=1;
704 owarn = optarg;
705 break;
706 case 'c':
707 do_offset=1;
708 ocrit = optarg;
709 break;
710 case 'j':
711 do_jitter=1;
712 jwarn = optarg;
713 break;
714 case 'k':
715 do_jitter=1;
716 jcrit = optarg;
717 break;
718 case 'H':
719 if(is_host(optarg) == FALSE)
720 usage2(_("Invalid hostname/address"), optarg);
721 server_address = strdup(optarg);
722 break;
723 case 't':
724 socket_timeout=atoi(optarg);
725 break;
726 case '4':
727 address_family = AF_INET;
728 break;
729 case '6':
730 #ifdef USE_IPV6
731 address_family = AF_INET6;
732 #else
733 usage4 (_("IPv6 support not available"));
734 #endif
735 break;
736 case '?':
737 /* print short usage statement if args not parsable */
738 usage5 ();
739 break;
743 if(server_address == NULL){
744 usage4(_("Hostname was not supplied"));
747 return 0;
750 char *perfd_offset (double offset)
752 return fperfdata ("offset", offset, "s",
753 TRUE, offset_thresholds->warning->end,
754 TRUE, offset_thresholds->critical->end,
755 FALSE, 0, FALSE, 0);
758 char *perfd_jitter (double jitter)
760 return fperfdata ("jitter", jitter, "s",
761 do_jitter, jitter_thresholds->warning->end,
762 do_jitter, jitter_thresholds->critical->end,
763 TRUE, 0, FALSE, 0);
766 int main(int argc, char *argv[]){
767 int result, offset_result, jitter_result;
768 double offset=0, jitter=0;
769 char *result_line, *perfdata_line;
771 setlocale (LC_ALL, "");
772 bindtextdomain (PACKAGE, LOCALEDIR);
773 textdomain (PACKAGE);
775 result = offset_result = jitter_result = STATE_OK;
777 /* Parse extra opts if any */
778 argv=np_extra_opts (&argc, argv, progname);
780 if (process_arguments (argc, argv) == ERROR)
781 usage4 (_("Could not parse arguments"));
783 set_thresholds(&offset_thresholds, owarn, ocrit);
784 set_thresholds(&jitter_thresholds, jwarn, jcrit);
786 /* initialize alarm signal handling */
787 signal (SIGALRM, socket_timeout_alarm_handler);
789 /* set socket timeout */
790 alarm (socket_timeout);
792 offset = offset_request(server_address, &offset_result);
793 /* check_ntp used to always return CRITICAL if offset_result == STATE_UNKNOWN.
794 * Now we'll only do that is the offset thresholds were set */
795 if (do_offset && offset_result == STATE_UNKNOWN) {
796 result = STATE_CRITICAL;
797 } else {
798 result = get_status(fabs(offset), offset_thresholds);
801 /* If not told to check the jitter, we don't even send packets.
802 * jitter is checked using NTP control packets, which not all
803 * servers recognize. Trying to check the jitter on OpenNTPD
804 * (for example) will result in an error
806 if(do_jitter){
807 jitter=jitter_request(server_address, &jitter_result);
808 result = max_state_alt(result, get_status(jitter, jitter_thresholds));
809 /* -1 indicates that we couldn't calculate the jitter
810 * Only overrides STATE_OK from the offset */
811 if(jitter == -1.0 && result == STATE_OK)
812 result = STATE_UNKNOWN;
814 result = max_state_alt(result, jitter_result);
816 switch (result) {
817 case STATE_CRITICAL :
818 xasprintf(&result_line, _("NTP CRITICAL:"));
819 break;
820 case STATE_WARNING :
821 xasprintf(&result_line, _("NTP WARNING:"));
822 break;
823 case STATE_OK :
824 xasprintf(&result_line, _("NTP OK:"));
825 break;
826 default :
827 xasprintf(&result_line, _("NTP UNKNOWN:"));
828 break;
830 if(offset_result == STATE_UNKNOWN){
831 xasprintf(&result_line, "%s %s", result_line, _("Offset unknown"));
832 xasprintf(&perfdata_line, "");
833 } else {
834 xasprintf(&result_line, "%s %s %.10g secs", result_line, _("Offset"), offset);
835 xasprintf(&perfdata_line, "%s", perfd_offset(offset));
837 if (do_jitter) {
838 xasprintf(&result_line, "%s, jitter=%f", result_line, jitter);
839 xasprintf(&perfdata_line, "%s %s", perfdata_line, perfd_jitter(jitter));
841 printf("%s|%s\n", result_line, perfdata_line);
843 if(server_address!=NULL) free(server_address);
844 return result;
849 void print_help(void){
850 print_revision(progname, NP_VERSION);
852 printf ("Copyright (c) 2006 Sean Finney\n");
853 printf (COPYRIGHT, copyright, email);
855 printf ("%s\n", _("This plugin checks the selected ntp server"));
857 printf ("\n\n");
859 print_usage();
860 printf (UT_HELP_VRSN);
861 printf (UT_EXTRA_OPTS);
862 printf (UT_HOST_PORT, 'p', "123");
863 printf (UT_IPv46);
864 printf (" %s\n", "-w, --warning=THRESHOLD");
865 printf (" %s\n", _("Offset to result in warning status (seconds)"));
866 printf (" %s\n", "-c, --critical=THRESHOLD");
867 printf (" %s\n", _("Offset to result in critical status (seconds)"));
868 printf (" %s\n", "-j, --jwarn=THRESHOLD");
869 printf (" %s\n", _("Warning threshold for jitter"));
870 printf (" %s\n", "-k, --jcrit=THRESHOLD");
871 printf (" %s\n", _("Critical threshold for jitter"));
872 printf (UT_CONN_TIMEOUT, DEFAULT_SOCKET_TIMEOUT);
873 printf (UT_VERBOSE);
875 printf("\n");
876 printf("%s\n", _("Notes:"));
877 printf(UT_THRESHOLDS_NOTES);
879 printf("\n");
880 printf("%s\n", _("Examples:"));
881 printf(" %s\n", _("Normal offset check:"));
882 printf(" %s\n", ("./check_ntp -H ntpserv -w 0.5 -c 1"));
883 printf("\n");
884 printf(" %s\n", _("Check jitter too, avoiding critical notifications if jitter isn't available"));
885 printf(" %s\n", _("(See Notes above for more details on thresholds formats):"));
886 printf(" %s\n", ("./check_ntp -H ntpserv -w 0.5 -c 1 -j -1:100 -k -1:200"));
888 printf (UT_SUPPORT);
890 printf ("%s\n", _("WARNING: check_ntp is deprecated. Please use check_ntp_peer or"));
891 printf ("%s\n\n", _("check_ntp_time instead."));
894 void
895 print_usage(void)
897 printf ("%s\n", _("WARNING: check_ntp is deprecated. Please use check_ntp_peer or"));
898 printf ("%s\n\n", _("check_ntp_time instead."));
899 printf ("%s\n", _("Usage:"));
900 printf(" %s -H <host> [-w <warn>] [-c <crit>] [-j <warn>] [-k <crit>] [-4|-6] [-v verbose]\n", progname);