Code

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