Code

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