Code

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