Code

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