Code

Bulk EOL cleanup
[nagiosplug.git] / plugins / check_ntp_peer.c
1 /*****************************************************************************
2
3 * Nagios check_ntp_peer plugin
4
5 * License: GPL
6 * Copyright (c) 2006 Sean Finney <seanius@seanius.net>
7 * Copyright (c) 2006-2008 Nagios Plugins Development Team
8
9 * Last Modified: $Date$
10
11 * Description:
12
13 * This file contains the check_ntp_peer plugin
14
15 * This plugin checks an NTP server independent of any commandline
16 * programs or external libraries.
17
18 * Use this plugin to check the health of an NTP server. It supports
19 * checking the offset with the sync peer, the jitter and stratum. This
20 * plugin will not check the clock offset between the local host and NTP
21 * server; please use check_ntp_time for that purpose.
22
23
24 * This program is free software: you can redistribute it and/or modify
25 * it under the terms of the GNU General Public License as published by
26 * the Free Software Foundation, either version 3 of the License, or
27 * (at your option) any later version.
28
29 * This program is distributed in the hope that it will be useful,
30 * but WITHOUT ANY WARRANTY; without even the implied warranty of
31 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
32 * GNU General Public License for more details.
33
34 * You should have received a copy of the GNU General Public License
35 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
36
37 * $Id$
38
39 *****************************************************************************/
41 const char *progname = "check_ntp_peer";
42 const char *revision = "$Revision$";
43 const char *copyright = "2006-2008";
44 const char *email = "nagiosplug-devel@lists.sourceforge.net";
46 #include "common.h"
47 #include "netutils.h"
48 #include "utils.h"
50 static char *server_address=NULL;
51 static int port=123;
52 static int verbose=0;
53 static int quiet=0;
54 static short do_offset=0;
55 static char *owarn="60";
56 static char *ocrit="120";
57 static short do_stratum=0;
58 static char *swarn="-1:16";
59 static char *scrit="-1:16";
60 static short do_jitter=0;
61 static char *jwarn="-1:5000";
62 static char *jcrit="-1:10000";
63 static int syncsource_found=0;
64 static int li_alarm=0;
66 int process_arguments (int, char **);
67 thresholds *offset_thresholds = NULL;
68 thresholds *jitter_thresholds = NULL;
69 thresholds *stratum_thresholds = NULL;
70 void print_help (void);
71 void print_usage (void);
73 /* max size of control message data */
74 #define MAX_CM_SIZE 468
76 /* this structure holds everything in an ntp control message as per rfc1305 */
77 typedef struct {
78         uint8_t flags;       /* byte with leapindicator,vers,mode. see macros */
79         uint8_t op;          /* R,E,M bits and Opcode */
80         uint16_t seq;        /* Packet sequence */
81         uint16_t status;     /* Clock status */
82         uint16_t assoc;      /* Association */
83         uint16_t offset;     /* Similar to TCP sequence # */
84         uint16_t count;      /* # bytes of data */
85         char data[MAX_CM_SIZE]; /* ASCII data of the request */
86                                 /* NB: not necessarily NULL terminated! */
87 } ntp_control_message;
89 /* this is an association/status-word pair found in control packet reponses */
90 typedef struct {
91         uint16_t assoc;
92         uint16_t status;
93 } ntp_assoc_status_pair;
95 /* bits 1,2 are the leap indicator */
96 #define LI_MASK 0xc0
97 #define LI(x) ((x&LI_MASK)>>6)
98 #define LI_SET(x,y) do{ x |= ((y<<6)&LI_MASK); }while(0)
99 /* and these are the values of the leap indicator */
100 #define LI_NOWARNING 0x00
101 #define LI_EXTRASEC 0x01
102 #define LI_MISSINGSEC 0x02
103 #define LI_ALARM 0x03
104 /* bits 3,4,5 are the ntp version */
105 #define VN_MASK 0x38
106 #define VN(x)   ((x&VN_MASK)>>3)
107 #define VN_SET(x,y)     do{ x |= ((y<<3)&VN_MASK); }while(0)
108 #define VN_RESERVED 0x02
109 /* bits 6,7,8 are the ntp mode */
110 #define MODE_MASK 0x07
111 #define MODE(x) (x&MODE_MASK)
112 #define MODE_SET(x,y)   do{ x |= (y&MODE_MASK); }while(0)
113 /* here are some values */
114 #define MODE_CLIENT 0x03
115 #define MODE_CONTROLMSG 0x06
116 /* In control message, bits 8-10 are R,E,M bits */
117 #define REM_MASK 0xe0
118 #define REM_RESP 0x80
119 #define REM_ERROR 0x40
120 #define REM_MORE 0x20
121 /* In control message, bits 11 - 15 are opcode */
122 #define OP_MASK 0x1f
123 #define OP_SET(x,y)   do{ x |= (y&OP_MASK); }while(0)
124 #define OP_READSTAT 0x01
125 #define OP_READVAR  0x02
126 /* In peer status bytes, bits 6,7,8 determine clock selection status */
127 #define PEER_SEL(x) ((ntohs(x)>>8)&0x07)
128 #define PEER_INCLUDED 0x04
129 #define PEER_SYNCSOURCE 0x06
131 /* NTP control message header is 12 bytes, plus any data in the data
132  * field, plus null padding to the nearest 32-bit boundary per rfc.
133  */
134 #define SIZEOF_NTPCM(m) (12+ntohs(m.count)+((ntohs(m.count)%4)?4-(ntohs(m.count)%4):0))
136 /* finally, a little helper or two for debugging: */
137 #define DBG(x) do{if(verbose>1){ x; }}while(0);
138 #define PRINTSOCKADDR(x) \
139         do{ \
140                 printf("%u.%u.%u.%u", (x>>24)&0xff, (x>>16)&0xff, (x>>8)&0xff, x&0xff);\
141         }while(0);
143 void print_ntp_control_message(const ntp_control_message *p){
144         int i=0, numpeers=0;
145         const ntp_assoc_status_pair *peer=NULL;
147         printf("control packet contents:\n");
148         printf("\tflags: 0x%.2x , 0x%.2x\n", p->flags, p->op);
149         printf("\t  li=%d (0x%.2x)\n", LI(p->flags), p->flags&LI_MASK);
150         printf("\t  vn=%d (0x%.2x)\n", VN(p->flags), p->flags&VN_MASK);
151         printf("\t  mode=%d (0x%.2x)\n", MODE(p->flags), p->flags&MODE_MASK);
152         printf("\t  response=%d (0x%.2x)\n", (p->op&REM_RESP)>0, p->op&REM_RESP);
153         printf("\t  more=%d (0x%.2x)\n", (p->op&REM_MORE)>0, p->op&REM_MORE);
154         printf("\t  error=%d (0x%.2x)\n", (p->op&REM_ERROR)>0, p->op&REM_ERROR);
155         printf("\t  op=%d (0x%.2x)\n", p->op&OP_MASK, p->op&OP_MASK);
156         printf("\tsequence: %d (0x%.2x)\n", ntohs(p->seq), ntohs(p->seq));
157         printf("\tstatus: %d (0x%.2x)\n", ntohs(p->status), ntohs(p->status));
158         printf("\tassoc: %d (0x%.2x)\n", ntohs(p->assoc), ntohs(p->assoc));
159         printf("\toffset: %d (0x%.2x)\n", ntohs(p->offset), ntohs(p->offset));
160         printf("\tcount: %d (0x%.2x)\n", ntohs(p->count), ntohs(p->count));
161         numpeers=ntohs(p->count)/(sizeof(ntp_assoc_status_pair));
162         if(p->op&REM_RESP && p->op&OP_READSTAT){
163                 peer=(ntp_assoc_status_pair*)p->data;
164                 for(i=0;i<numpeers;i++){
165                         printf("\tpeer id %.2x status %.2x",
166                                ntohs(peer[i].assoc), ntohs(peer[i].status));
167                         if (PEER_SEL(peer[i].status) >= PEER_INCLUDED){
168                                 if(PEER_SEL(peer[i].status) >= PEER_SYNCSOURCE){
169                                         printf(" <-- current sync source");
170                                 } else {
171                                         printf(" <-- current sync candidate");
172                                 }
173                         }
174                         printf("\n");
175                 }
176         }
179 /*
180  * Extract the value from NTP key/value pairs, or return NULL.
181  * The value returned can be free()ed.
182  */
183 char *extract_value(const char *varlist, const char *name){
184         char *tmp=NULL, *value=NULL;
185         int i;
187         while (1) {
188                 /* Strip any leading space */
189                 for (varlist; isspace(varlist[0]); varlist++);
191                 if (strncmp(name, varlist, strlen(name)) == 0) {
192                         varlist += strlen(name);
193                         /* strip trailing spaces */
194                         for (varlist; isspace(varlist[0]); varlist++);
196                         if (varlist[0] == '=') {
197                                 /* We matched the key, go past the = sign */
198                                 varlist++;
199                                 /* strip leading spaces */
200                                 for (varlist; isspace(varlist[0]); varlist++);
202                                 if (tmp = index(varlist, ',')) {
203                                         /* Value is delimited by a comma */
204                                         if (tmp-varlist == 0) continue;
205                                         value = (char *)malloc(tmp-varlist+1);
206                                         strncpy(value, varlist, tmp-varlist);
207                                         value[tmp-varlist] = '\0';
208                                 } else {
209                                         /* Value is delimited by a \0 */
210                                         if (strlen(varlist) == 0) continue;
211                                         value = (char *)malloc(strlen(varlist) + 1);
212                                         strncpy(value, varlist, strlen(varlist));
213                                         value[strlen(varlist)] = '\0';
214                                 }
215                                 break;
216                         }
217                 }
218                 if (tmp = index(varlist, ',')) {
219                         /* More keys, keep going... */
220                         varlist = tmp + 1;
221                 } else {
222                         /* We're done */
223                         break;
224                 }
225         }
227         /* Clean-up trailing spaces/newlines */
228         if (value) for (i=strlen(value)-1; isspace(value[i]); i--) value[i] = '\0';
230         return value;
233 void
234 setup_control_request(ntp_control_message *p, uint8_t opcode, uint16_t seq){
235         memset(p, 0, sizeof(ntp_control_message));
236         LI_SET(p->flags, LI_NOWARNING);
237         VN_SET(p->flags, VN_RESERVED);
238         MODE_SET(p->flags, MODE_CONTROLMSG);
239         OP_SET(p->op, opcode);
240         p->seq = htons(seq);
241         /* Remaining fields are zero for requests */
244 /* This function does all the actual work; roughly here's what it does
245  * beside setting the offest, jitter and stratum passed as argument:
246  *  - offset can be negative, so if it cannot get the offset, offset_result
247  *    is set to UNKNOWN, otherwise OK.
248  *  - jitter and stratum are set to -1 if they cannot be retrieved so any
249  *    positive value means a success retrieving the value.
250  *  - status is set to WARNING if there's no sync.peer (otherwise OK) and is
251  *    the return value of the function.
252  *  status is pretty much useless as syncsource_found is a global variable
253  *  used later in main to check is the server was synchronized. It works
254  *  so I left it alone */
255 int ntp_request(const char *host, double *offset, int *offset_result, double *jitter, int *stratum){
256         int conn=-1, i, npeers=0, num_candidates=0;
257         double tmp_offset = 0;
258         int min_peer_sel=PEER_INCLUDED;
259         int peers_size=0, peer_offset=0;
260         int status;
261         ntp_assoc_status_pair *peers=NULL;
262         ntp_control_message req;
263         const char *getvar = "stratum,offset,jitter";
264         char *data, *value, *nptr;
265         void *tmp;
267         status = STATE_OK;
268         *offset_result = STATE_UNKNOWN;
269         *jitter = *stratum = -1;
271         /* Long-winded explanation:
272          * Getting the sync peer offset, jitter and stratum requires a number of
273          * steps:
274          * 1) Send a READSTAT request.
275          * 2) Interpret the READSTAT reply
276          *  a) The data section contains a list of peer identifiers (16 bits)
277          *     and associated status words (16 bits)
278          *  b) We want the value of 0x06 in the SEL (peer selection) value,
279          *     which means "current synchronizatin source".  If that's missing,
280          *     we take anything better than 0x04 (see the rfc for details) but
281          *     set a minimum of warning.
282          * 3) Send a READVAR request for information on each peer identified
283          *    in 2b greater than the minimum selection value.
284          * 4) Extract the offset, jitter and stratum value from the data[]
285          *    (it's ASCII)
286          */
287         my_udp_connect(server_address, port, &conn);
289         /* keep sending requests until the server stops setting the
290          * REM_MORE bit, though usually this is only 1 packet. */
291         do{
292                 setup_control_request(&req, OP_READSTAT, 1);
293                 DBG(printf("sending READSTAT request"));
294                 write(conn, &req, SIZEOF_NTPCM(req));
295                 DBG(print_ntp_control_message(&req));
296                 /* Attempt to read the largest size packet possible */
297                 req.count=htons(MAX_CM_SIZE);
298                 DBG(printf("recieving READSTAT response"))
299                 if(read(conn, &req, SIZEOF_NTPCM(req)) == -1)
300                         die(STATE_CRITICAL, "NTP CRITICAL: No response from NTP server\n");
301                 DBG(print_ntp_control_message(&req));
302                 /* discard obviously invalid packets */
303                 if (ntohs(req.count) > MAX_CM_SIZE)
304                         die(STATE_CRITICAL, "NTP CRITICAL: Invalid packet received from NTP server\n");
305                 if (LI(req.flags) == LI_ALARM) li_alarm = 1;
306                 /* Each peer identifier is 4 bytes in the data section, which
307                  * we represent as a ntp_assoc_status_pair datatype.
308                  */
309                 peers_size+=ntohs(req.count);
310                 if((tmp=realloc(peers, peers_size)) == NULL)
311                         free(peers), die(STATE_UNKNOWN, "can not (re)allocate 'peers' buffer\n");
312                 peers=tmp;
313                 memcpy((void*)((ptrdiff_t)peers+peer_offset), (void*)req.data, ntohs(req.count));
314                 npeers=peers_size/sizeof(ntp_assoc_status_pair);
315                 peer_offset+=ntohs(req.count);
316         } while(req.op&REM_MORE);
318         /* first, let's find out if we have a sync source, or if there are
319          * at least some candidates. In the latter case we'll issue
320          * a warning but go ahead with the check on them. */
321         for (i = 0; i < npeers; i++){
322                 if (PEER_SEL(peers[i].status) >= PEER_INCLUDED){
323                         num_candidates++;
324                         if(PEER_SEL(peers[i].status) >= PEER_SYNCSOURCE){
325                                 syncsource_found=1;
326                                 min_peer_sel=PEER_SYNCSOURCE;
327                         }
328                 }
329         }
330         if(verbose) printf("%d candiate peers available\n", num_candidates);
331         if(verbose && syncsource_found) printf("synchronization source found\n");
332         if(! syncsource_found){
333                 status = STATE_WARNING;
334                 if(verbose) printf("warning: no synchronization source found\n");
335         }
336         if(li_alarm){
337                 status = STATE_WARNING;
338                 if(verbose) printf("warning: LI_ALARM bit is set\n");
339         }
342         for (i = 0; i < npeers; i++){
343                 /* Only query this server if it is the current sync source */
344                 /* If there's no sync.peer, query all candidates and use the best one */
345                 if (PEER_SEL(peers[i].status) >= min_peer_sel){
346                         if(verbose) printf("Getting offset, jitter and stratum for peer %.2x\n", ntohs(peers[i].assoc));
347                         asprintf(&data, "");
348                         do{
349                                 setup_control_request(&req, OP_READVAR, 2);
350                                 req.assoc = peers[i].assoc;
351                                 /* Putting the wanted variable names in the request
352                                  * cause the server to provide _only_ the requested values.
353                                  * thus reducing net traffic, guaranteeing us only a single
354                                  * datagram in reply, and making intepretation much simpler
355                                  */
356                                 /* Older servers doesn't know what jitter is, so if we get an
357                                  * error on the first pass we redo it with "dispersion" */
358                                 strncpy(req.data, getvar, MAX_CM_SIZE-1);
359                                 req.count = htons(strlen(getvar));
360                                 DBG(printf("sending READVAR request...\n"));
361                                 write(conn, &req, SIZEOF_NTPCM(req));
362                                 DBG(print_ntp_control_message(&req));
364                                 req.count = htons(MAX_CM_SIZE);
365                                 DBG(printf("receiving READVAR response...\n"));
366                                 read(conn, &req, SIZEOF_NTPCM(req));
367                                 DBG(print_ntp_control_message(&req));
369                                 if(!(req.op&REM_ERROR))
370                                         asprintf(&data, "%s%s", data, req.data);
371                         } while(req.op&REM_MORE);
373                         if(req.op&REM_ERROR) {
374                                 if(strstr(getvar, "jitter")) {
375                                         if(verbose) printf("The command failed. This is usually caused by servers refusing the 'jitter'\nvariable. Restarting with 'dispersion'...\n");
376                                         getvar = "stratum,offset,dispersion";
377                                         i--;
378                                         continue;
379                                 } else if(strlen(getvar)) {
380                                         if(verbose) printf("Server didn't like dispersion either; will retrieve everything\n");
381                                         getvar = "";
382                                         i--;
383                                         continue;
384                                 }
385                         }
387                         if(verbose > 1)
388                                 printf("Server responded: >>>%s<<<\n", data);
390                         /* get the offset */
391                         if(verbose)
392                                 printf("parsing offset from peer %.2x: ", ntohs(peers[i].assoc));
394                         value = extract_value(data, "offset");
395                         nptr=NULL;
396                         /* Convert the value if we have one */
397                         if(value != NULL)
398                                 tmp_offset = strtod(value, &nptr) / 1000;
399                         /* If value is null or no conversion was performed */
400                         if(value == NULL || value==nptr) {
401                                 if(verbose) printf("error: unable to read server offset response.\n");
402                         } else {
403                                 if(verbose) printf("%.10g\n", tmp_offset);
404                                 if(*offset_result == STATE_UNKNOWN || fabs(tmp_offset) < fabs(*offset)) {
405                                         *offset = tmp_offset;
406                                         *offset_result = STATE_OK;
407                                 } else {
408                                         /* Skip this one; move to the next */
409                                         continue;
410                                 }
411                         }
413                         if(do_jitter) {
414                                 /* get the jitter */
415                                 if(verbose) {
416                                         printf("parsing %s from peer %.2x: ", strstr(getvar, "dispersion") != NULL ? "dispersion" : "jitter", ntohs(peers[i].assoc));
417                                 }
418                                 value = extract_value(data, strstr(getvar, "dispersion") != NULL ? "dispersion" : "jitter");
419                                 nptr=NULL;
420                                 /* Convert the value if we have one */
421                                 if(value != NULL)
422                                         *jitter = strtod(value, &nptr);
423                                 /* If value is null or no conversion was performed */
424                                 if(value == NULL || value==nptr) {
425                                         if(verbose) printf("error: unable to read server jitter/dispersion response.\n");
426                                         *jitter = -1;
427                                 } else if(verbose) {
428                                         printf("%.10g\n", *jitter);
429                                 }
430                         }
432                         if(do_stratum) {
433                                 /* get the stratum */
434                                 if(verbose) {
435                                         printf("parsing stratum from peer %.2x: ", ntohs(peers[i].assoc));
436                                 }
437                                 value = extract_value(data, "stratum");
438                                 nptr=NULL;
439                                 /* Convert the value if we have one */
440                                 if(value != NULL)
441                                         *stratum = strtol(value, &nptr, 10);
442                                 if(value == NULL || value==nptr) {
443                                         if(verbose) printf("error: unable to read server stratum response.\n");
444                                         *stratum = -1;
445                                 } else {
446                                         if(verbose) printf("%i\n", *stratum);
447                                 }
448                         }
449                 } /* if (PEER_SEL(peers[i].status) >= min_peer_sel) */
450         } /* for (i = 0; i < npeers; i++) */
452         close(conn);
453         if(peers!=NULL) free(peers);
455         return status;
458 int process_arguments(int argc, char **argv){
459         int c;
460         int option=0;
461         static struct option longopts[] = {
462                 {"version", no_argument, 0, 'V'},
463                 {"help", no_argument, 0, 'h'},
464                 {"verbose", no_argument, 0, 'v'},
465                 {"use-ipv4", no_argument, 0, '4'},
466                 {"use-ipv6", no_argument, 0, '6'},
467                 {"quiet", no_argument, 0, 'q'},
468                 {"warning", required_argument, 0, 'w'},
469                 {"critical", required_argument, 0, 'c'},
470                 {"swarn", required_argument, 0, 'W'},
471                 {"scrit", required_argument, 0, 'C'},
472                 {"jwarn", required_argument, 0, 'j'},
473                 {"jcrit", required_argument, 0, 'k'},
474                 {"timeout", required_argument, 0, 't'},
475                 {"hostname", required_argument, 0, 'H'},
476                 {"port", required_argument, 0, 'p'},
477                 {0, 0, 0, 0}
478         };
481         if (argc < 2)
482                 usage ("\n");
484         while (1) {
485                 c = getopt_long (argc, argv, "Vhv46qw:c:W:C:j:k:t:H:p:", longopts, &option);
486                 if (c == -1 || c == EOF || c == 1)
487                         break;
489                 switch (c) {
490                 case 'h':
491                         print_help();
492                         exit(STATE_OK);
493                         break;
494                 case 'V':
495                         print_revision(progname, revision);
496                         exit(STATE_OK);
497                         break;
498                 case 'v':
499                         verbose++;
500                         break;
501                 case 'q':
502                         quiet = 1;
503                         break;
504                 case 'w':
505                         do_offset=1;
506                         owarn = optarg;
507                         break;
508                 case 'c':
509                         do_offset=1;
510                         ocrit = optarg;
511                         break;
512                 case 'W':
513                         do_stratum=1;
514                         swarn = optarg;
515                         break;
516                 case 'C':
517                         do_stratum=1;
518                         scrit = optarg;
519                         break;
520                 case 'j':
521                         do_jitter=1;
522                         jwarn = optarg;
523                         break;
524                 case 'k':
525                         do_jitter=1;
526                         jcrit = optarg;
527                         break;
528                 case 'H':
529                         if(is_host(optarg) == FALSE)
530                                 usage2(_("Invalid hostname/address"), optarg);
531                         server_address = strdup(optarg);
532                         break;
533                 case 'p':
534                         port=atoi(optarg);
535                         break;
536                 case 't':
537                         socket_timeout=atoi(optarg);
538                         break;
539                 case '4':
540                         address_family = AF_INET;
541                         break;
542                 case '6':
543 #ifdef USE_IPV6
544                         address_family = AF_INET6;
545 #else
546                         usage4 (_("IPv6 support not available"));
547 #endif
548                         break;
549                 case '?':
550                         /* print short usage statement if args not parsable */
551                         usage5 ();
552                         break;
553                 }
554         }
556         if(server_address == NULL){
557                 usage4(_("Hostname was not supplied"));
558         }
560         return 0;
563 char *perfd_offset (double offset)
565         return fperfdata ("offset", offset, "s",
566                 TRUE, offset_thresholds->warning->end,
567                 TRUE, offset_thresholds->critical->end,
568                 FALSE, 0, FALSE, 0);
571 char *perfd_jitter (double jitter)
573         return fperfdata ("jitter", jitter, "",
574                 do_jitter, jitter_thresholds->warning->end,
575                 do_jitter, jitter_thresholds->critical->end,
576                 TRUE, 0, FALSE, 0);
579 char *perfd_stratum (int stratum)
581         return perfdata ("stratum", stratum, "",
582                 do_stratum, (int)stratum_thresholds->warning->end,
583                 do_stratum, (int)stratum_thresholds->critical->end,
584                 TRUE, 0, TRUE, 16);
587 int main(int argc, char *argv[]){
588         int result, offset_result, stratum;
589         double offset=0, jitter=0;
590         char *result_line, *perfdata_line;
592         setlocale (LC_ALL, "");
593         bindtextdomain (PACKAGE, LOCALEDIR);
594         textdomain (PACKAGE);
596         /* Parse extra opts if any */
597         argv=np_extra_opts (&argc, argv, progname);
599         if (process_arguments (argc, argv) == ERROR)
600                 usage4 (_("Could not parse arguments"));
602         set_thresholds(&offset_thresholds, owarn, ocrit);
603         set_thresholds(&jitter_thresholds, jwarn, jcrit);
604         set_thresholds(&stratum_thresholds, swarn, scrit);
606         /* initialize alarm signal handling */
607         signal (SIGALRM, socket_timeout_alarm_handler);
609         /* set socket timeout */
610         alarm (socket_timeout);
612         /* This returns either OK or WARNING (See comment preceeding ntp_request) */
613         result = ntp_request(server_address, &offset, &offset_result, &jitter, &stratum);
615         if(offset_result == STATE_UNKNOWN) {
616                 /* if there's no sync peer (this overrides ntp_request output): */
617                 result = (quiet == 1 ? STATE_UNKNOWN : STATE_CRITICAL);
618         } else {
619                 /* Be quiet if there's no candidates either */
620                 if (quiet == 1 && result == STATE_WARNING)
621                         result = STATE_UNKNOWN;
622                 result = max_state_alt(result, get_status(fabs(offset), offset_thresholds));
623         }
625         if(do_stratum)
626                 result = max_state_alt(result, get_status(stratum, stratum_thresholds));
628         if(do_jitter)
629                 result = max_state_alt(result, get_status(jitter, jitter_thresholds));
631         switch (result) {
632                 case STATE_CRITICAL :
633                         asprintf(&result_line, _("NTP CRITICAL:"));
634                         break;
635                 case STATE_WARNING :
636                         asprintf(&result_line, _("NTP WARNING:"));
637                         break;
638                 case STATE_OK :
639                         asprintf(&result_line, _("NTP OK:"));
640                         break;
641                 default :
642                         asprintf(&result_line, _("NTP UNKNOWN:"));
643                         break;
644         }
645         if(!syncsource_found)
646                 asprintf(&result_line, "%s %s,", result_line, _("Server not synchronized"));
647         else if(li_alarm)
648                 asprintf(&result_line, "%s %s,", result_line, _("Server has the LI_ALARM bit set"));
650         if(offset_result == STATE_UNKNOWN){
651                 asprintf(&result_line, "%s %s", result_line, _("Offset unknown"));
652                 asprintf(&perfdata_line, "");
653         } else {
654                 asprintf(&result_line, "%s %s %.10g secs", result_line, _("Offset"), offset);
655                 asprintf(&perfdata_line, "%s", perfd_offset(offset));
656         }
657         if (do_jitter) {
658                 asprintf(&result_line, "%s, jitter=%f", result_line, jitter);
659                 asprintf(&perfdata_line, "%s %s", perfdata_line, perfd_jitter(jitter));
660         }
661         if (do_stratum) {
662                 asprintf(&result_line, "%s, stratum=%i", result_line, stratum);
663                 asprintf(&perfdata_line, "%s %s", perfdata_line, perfd_stratum(stratum));
664         }
665         printf("%s|%s\n", result_line, perfdata_line);
667         if(server_address!=NULL) free(server_address);
668         return result;
673 void print_help(void){
674         print_revision(progname, revision);
676         printf ("Copyright (c) 2006 Sean Finney\n");
677         printf (COPYRIGHT, copyright, email);
679         printf ("%s\n", _("This plugin checks the selected ntp server"));
681         printf ("\n\n");
683         print_usage();
684         printf (_(UT_HELP_VRSN));
685         printf (_(UT_EXTRA_OPTS));
686         printf (_(UT_HOST_PORT), 'p', "123");
687         printf (" %s\n", "-q, --quiet");
688         printf ("    %s\n", _("Returns UNKNOWN instead of CRITICAL or WARNING if server isn't synchronized"));
689         printf (" %s\n", "-w, --warning=THRESHOLD");
690         printf ("    %s\n", _("Offset to result in warning status (seconds)"));
691         printf (" %s\n", "-c, --critical=THRESHOLD");
692         printf ("    %s\n", _("Offset to result in critical status (seconds)"));
693         printf (" %s\n", "-W, --swarn=THRESHOLD");
694         printf ("    %s\n", _("Warning threshold for stratum"));
695         printf (" %s\n", "-C, --scrit=THRESHOLD");
696         printf ("    %s\n", _("Critical threshold for stratum"));
697         printf (" %s\n", "-j, --jwarn=THRESHOLD");
698         printf ("    %s\n", _("Warning threshold for jitter"));
699         printf (" %s\n", "-k, --jcrit=THRESHOLD");
700         printf ("    %s\n", _("Critical threshold for jitter"));
701         printf (_(UT_TIMEOUT), DEFAULT_SOCKET_TIMEOUT);
702         printf (_(UT_VERBOSE));
704         printf("\n");
705         printf("%s\n", _("This plugin checks an NTP server independent of any commandline"));
706         printf("%s\n\n", _("programs or external libraries."));
708         printf("%s\n", _("Notes:"));
709         printf(" %s\n", _("Use this plugin to check the health of an NTP server. It supports"));
710         printf(" %s\n", _("checking the offset with the sync peer, the jitter and stratum. This"));
711         printf(" %s\n", _("plugin will not check the clock offset between the local host and NTP"));
712         printf(" %s\n", _("server; please use check_ntp_time for that purpose."));
713         printf("\n");
714         printf(_(UT_THRESHOLDS_NOTES));
715 #ifdef NP_EXTRA_OPTS
716         printf("\n");
717         printf(_(UT_EXTRA_OPTS_NOTES));
718 #endif
720         printf("\n");
721         printf("%s\n", _("Examples:"));
722         printf(" %s\n", _("Simple NTP server check:"));
723         printf("  %s\n", ("./check_ntp_peer -H ntpserv -w 0.5 -c 1"));
724         printf("\n");
725         printf(" %s\n", _("Check jitter too, avoiding critical notifications if jitter isn't available"));
726         printf(" %s\n", _("(See Notes above for more details on thresholds formats):"));
727         printf("  %s\n", ("./check_ntp_peer -H ntpserv -w 0.5 -c 1 -j -1:100 -k -1:200"));
728         printf("\n");
729         printf(" %s\n", _("Check only stratum:"));
730         printf("  %s\n", ("./check_ntp_peer -H ntpserv -W 4 -C 6"));
732         printf (_(UT_SUPPORT));
735 void
736 print_usage(void)
738         printf (_("Usage:"));
739         printf(" %s -H <host> [-w <warn>] [-c <crit>] [-W <warn>] [-C <crit>]\n", progname);
740         printf("       [-j <warn>] [-k <crit>] [-v verbose]\n");