Code

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