1 /*****************************************************************************
3 * Nagios check_ntp_time plugin
6 * Copyright (c) 2006 Sean Finney <seanius@seanius.net>
7 * Copyright (c) 2006-2008 Nagios Plugins Development Team
11 * This file contains the check_ntp_time plugin
13 * This plugin checks the clock offset between the local host and a
14 * remote NTP server. It is independent of any commandline programs or
17 * If you'd rather want to monitor an NTP server, please use
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 3 of the License, or
24 * (at your option) any later version.
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.
31 * You should have received a copy of the GNU General Public License
32 * along with this program. If not, see <http://www.gnu.org/licenses/>.
35 *****************************************************************************/
37 const char *progname
= "check_ntp_time";
38 const char *copyright
= "2006-2008";
39 const char *email
= "nagiosplug-devel@lists.sourceforge.net";
45 static char *server_address
=NULL
;
46 static char *port
="123";
49 static char *owarn
="60";
50 static char *ocrit
="120";
52 int process_arguments (int, char **);
53 thresholds
*offset_thresholds
= NULL
;
54 void print_help (void);
55 void print_usage (void);
57 /* number of times to perform each request to get a good average. */
60 /* max size of control message data */
61 #define MAX_CM_SIZE 468
63 /* this structure holds everything in an ntp request/response as per rfc1305 */
65 uint8_t flags
; /* byte with leapindicator,vers,mode. see macros */
66 uint8_t stratum
; /* clock stratum */
67 int8_t poll
; /* polling interval */
68 int8_t precision
; /* precision of the local clock */
69 int32_t rtdelay
; /* total rt delay, as a fixed point num. see macros */
70 uint32_t rtdisp
; /* like above, but for max err to primary src */
71 uint32_t refid
; /* ref clock identifier */
72 uint64_t refts
; /* reference timestamp. local time local clock */
73 uint64_t origts
; /* time at which request departed client */
74 uint64_t rxts
; /* time at which request arrived at server */
75 uint64_t txts
; /* time at which request departed server */
78 /* this structure holds data about results from querying offset from a peer */
80 time_t waiting
; /* ts set when we started waiting for a response */
81 int num_responses
; /* number of successfully recieved responses */
82 uint8_t stratum
; /* copied verbatim from the ntp_message */
83 double rtdelay
; /* converted from the ntp_message */
84 double rtdisp
; /* converted from the ntp_message */
85 double offset
[AVG_NUM
]; /* offsets from each response */
86 uint8_t flags
; /* byte with leapindicator,vers,mode. see macros */
89 /* bits 1,2 are the leap indicator */
91 #define LI(x) ((x&LI_MASK)>>6)
92 #define LI_SET(x,y) do{ x |= ((y<<6)&LI_MASK); }while(0)
93 /* and these are the values of the leap indicator */
94 #define LI_NOWARNING 0x00
95 #define LI_EXTRASEC 0x01
96 #define LI_MISSINGSEC 0x02
98 /* bits 3,4,5 are the ntp version */
100 #define VN(x) ((x&VN_MASK)>>3)
101 #define VN_SET(x,y) do{ x |= ((y<<3)&VN_MASK); }while(0)
102 #define VN_RESERVED 0x02
103 /* bits 6,7,8 are the ntp mode */
104 #define MODE_MASK 0x07
105 #define MODE(x) (x&MODE_MASK)
106 #define MODE_SET(x,y) do{ x |= (y&MODE_MASK); }while(0)
107 /* here are some values */
108 #define MODE_CLIENT 0x03
109 #define MODE_CONTROLMSG 0x06
110 /* In control message, bits 8-10 are R,E,M bits */
111 #define REM_MASK 0xe0
112 #define REM_RESP 0x80
113 #define REM_ERROR 0x40
114 #define REM_MORE 0x20
115 /* In control message, bits 11 - 15 are opcode */
117 #define OP_SET(x,y) do{ x |= (y&OP_MASK); }while(0)
118 #define OP_READSTAT 0x01
119 #define OP_READVAR 0x02
120 /* In peer status bytes, bits 6,7,8 determine clock selection status */
121 #define PEER_SEL(x) ((ntohs(x)>>8)&0x07)
122 #define PEER_INCLUDED 0x04
123 #define PEER_SYNCSOURCE 0x06
126 ** a note about the 32-bit "fixed point" numbers:
128 they are divided into halves, each being a 16-bit int in network byte order:
129 - the first 16 bits are an int on the left side of a decimal point.
130 - the second 16 bits represent a fraction n/(2^16)
131 likewise for the 64-bit "fixed point" numbers with everything doubled :)
134 /* macros to access the left/right 16 bits of a 32-bit ntp "fixed point"
135 number. note that these can be used as lvalues too */
136 #define L16(x) (((uint16_t*)&x)[0])
137 #define R16(x) (((uint16_t*)&x)[1])
138 /* macros to access the left/right 32 bits of a 64-bit ntp "fixed point"
139 number. these too can be used as lvalues */
140 #define L32(x) (((uint32_t*)&x)[0])
141 #define R32(x) (((uint32_t*)&x)[1])
143 /* ntp wants seconds since 1/1/00, epoch is 1/1/70. this is the difference */
144 #define EPOCHDIFF 0x83aa7e80UL
146 /* extract a 32-bit ntp fixed point number into a double */
147 #define NTP32asDOUBLE(x) (ntohs(L16(x)) + (double)ntohs(R16(x))/65536.0)
149 /* likewise for a 64-bit ntp fp number */
150 #define NTP64asDOUBLE(n) (double)(((uint64_t)n)?\
151 (ntohl(L32(n))-EPOCHDIFF) + \
152 (.00000001*(0.5+(double)(ntohl(R32(n))/42.94967296))):\
155 /* convert a struct timeval to a double */
156 #define TVasDOUBLE(x) (double)(x.tv_sec+(0.000001*x.tv_usec))
158 /* convert an ntp 64-bit fp number to a struct timeval */
159 #define NTP64toTV(n,t) \
160 do{ if(!n) t.tv_sec = t.tv_usec = 0; \
162 t.tv_sec=ntohl(L32(n))-EPOCHDIFF; \
163 t.tv_usec=(int)(0.5+(double)(ntohl(R32(n))/4294.967296)); \
167 /* convert a struct timeval to an ntp 64-bit fp number */
168 #define TVtoNTP64(t,n) \
169 do{ if(!t.tv_usec && !t.tv_sec) n=0x0UL; \
171 L32(n)=htonl(t.tv_sec + EPOCHDIFF); \
172 R32(n)=htonl((uint64_t)((4294.967296*t.tv_usec)+.5)); \
176 /* NTP control message header is 12 bytes, plus any data in the data
177 * field, plus null padding to the nearest 32-bit boundary per rfc.
179 #define SIZEOF_NTPCM(m) (12+ntohs(m.count)+((m.count)?4-(ntohs(m.count)%4):0))
181 /* finally, a little helper or two for debugging: */
182 #define DBG(x) do{if(verbose>1){ x; }}while(0);
183 #define PRINTSOCKADDR(x) \
185 printf("%u.%u.%u.%u", (x>>24)&0xff, (x>>16)&0xff, (x>>8)&0xff, x&0xff);\
188 /* calculate the offset of the local clock */
189 static inline double calc_offset(const ntp_message
*m
, const struct timeval
*t
){
190 double client_tx
, peer_rx
, peer_tx
, client_rx
;
191 client_tx
= NTP64asDOUBLE(m
->origts
);
192 peer_rx
= NTP64asDOUBLE(m
->rxts
);
193 peer_tx
= NTP64asDOUBLE(m
->txts
);
194 client_rx
=TVasDOUBLE((*t
));
195 return (.5*((peer_tx
-client_rx
)+(peer_rx
-client_tx
)));
198 /* print out a ntp packet in human readable/debuggable format */
199 void print_ntp_message(const ntp_message
*p
){
200 struct timeval ref
, orig
, rx
, tx
;
202 NTP64toTV(p
->refts
,ref
);
203 NTP64toTV(p
->origts
,orig
);
204 NTP64toTV(p
->rxts
,rx
);
205 NTP64toTV(p
->txts
,tx
);
207 printf("packet contents:\n");
208 printf("\tflags: 0x%.2x\n", p
->flags
);
209 printf("\t li=%d (0x%.2x)\n", LI(p
->flags
), p
->flags
&LI_MASK
);
210 printf("\t vn=%d (0x%.2x)\n", VN(p
->flags
), p
->flags
&VN_MASK
);
211 printf("\t mode=%d (0x%.2x)\n", MODE(p
->flags
), p
->flags
&MODE_MASK
);
212 printf("\tstratum = %d\n", p
->stratum
);
213 printf("\tpoll = %g\n", pow(2, p
->poll
));
214 printf("\tprecision = %g\n", pow(2, p
->precision
));
215 printf("\trtdelay = %-.16g\n", NTP32asDOUBLE(p
->rtdelay
));
216 printf("\trtdisp = %-.16g\n", NTP32asDOUBLE(p
->rtdisp
));
217 printf("\trefid = %x\n", p
->refid
);
218 printf("\trefts = %-.16g\n", NTP64asDOUBLE(p
->refts
));
219 printf("\torigts = %-.16g\n", NTP64asDOUBLE(p
->origts
));
220 printf("\trxts = %-.16g\n", NTP64asDOUBLE(p
->rxts
));
221 printf("\ttxts = %-.16g\n", NTP64asDOUBLE(p
->txts
));
224 void setup_request(ntp_message
*p
){
227 memset(p
, 0, sizeof(ntp_message
));
228 LI_SET(p
->flags
, LI_ALARM
);
230 MODE_SET(p
->flags
, MODE_CLIENT
);
232 p
->precision
=(int8_t)0xfa;
233 L16(p
->rtdelay
)=htons(1);
234 L16(p
->rtdisp
)=htons(1);
236 gettimeofday(&t
, NULL
);
237 TVtoNTP64(t
,p
->txts
);
240 /* select the "best" server from a list of servers, and return its index.
241 * this is done by filtering servers based on stratum, dispersion, and
242 * finally round-trip delay. */
243 int best_offset_server(const ntp_server_results
*slist
, int nservers
){
244 int i
=0, cserver
=0, best_server
=-1;
246 /* for each server */
247 for(cserver
=0; cserver
<nservers
; cserver
++){
248 /* We don't want any servers that fails these tests */
249 /* Sort out servers that didn't respond or responede with a 0 stratum;
250 * stratum 0 is for reference clocks so no NTP server should ever report
252 if ( slist
[cserver
].stratum
== 0){
253 if (verbose
) printf("discarding peer %d: stratum=%d\n", cserver
, slist
[cserver
].stratum
);
256 /* Sort out servers with error flags */
257 if ( LI(slist
[cserver
].flags
) == LI_ALARM
){
258 if (verbose
) printf("discarding peer %d: flags=%d\n", cserver
, LI(slist
[cserver
].flags
));
262 /* If we don't have a server yet, use the first one */
263 if (best_server
== -1) {
264 best_server
= cserver
;
265 DBG(printf("using peer %d as our first candidate\n", best_server
));
269 /* compare the server to the best one we've seen so far */
270 /* does it have an equal or better stratum? */
271 DBG(printf("comparing peer %d with peer %d\n", cserver
, best_server
));
272 if(slist
[cserver
].stratum
<= slist
[best_server
].stratum
){
273 DBG(printf("stratum for peer %d <= peer %d\n", cserver
, best_server
));
274 /* does it have an equal or better dispersion? */
275 if(slist
[cserver
].rtdisp
<= slist
[best_server
].rtdisp
){
276 DBG(printf("dispersion for peer %d <= peer %d\n", cserver
, best_server
));
277 /* does it have a better rtdelay? */
278 if(slist
[cserver
].rtdelay
< slist
[best_server
].rtdelay
){
279 DBG(printf("rtdelay for peer %d < peer %d\n", cserver
, best_server
));
280 best_server
= cserver
;
281 DBG(printf("peer %d is now our best candidate\n", best_server
));
287 if(best_server
>= 0) {
288 DBG(printf("best server selected: peer %d\n", best_server
));
291 DBG(printf("no peers meeting synchronization criteria :(\n"));
296 /* do everything we need to get the total average offset
297 * - we use a certain amount of parallelization with poll() to ensure
298 * we don't waste time sitting around waiting for single packets.
299 * - we also "manually" handle resolving host names and connecting, because
300 * we have to do it in a way that our lazy macros don't handle currently :( */
301 double offset_request(const char *host
, int *status
){
302 int i
=0, j
=0, ga_result
=0, num_hosts
=0, *socklist
=NULL
, respnum
=0;
303 int servers_completed
=0, one_written
=0, one_read
=0, servers_readable
=0, best_index
=-1;
304 time_t now_time
=0, start_ts
=0;
305 ntp_message
*req
=NULL
;
306 double avg_offset
=0.;
307 struct timeval recv_time
;
308 struct addrinfo
*ai
=NULL
, *ai_tmp
=NULL
, hints
;
309 struct pollfd
*ufds
=NULL
;
310 ntp_server_results
*servers
=NULL
;
312 /* setup hints to only return results from getaddrinfo that we'd like */
313 memset(&hints
, 0, sizeof(struct addrinfo
));
314 hints
.ai_family
= address_family
;
315 hints
.ai_protocol
= IPPROTO_UDP
;
316 hints
.ai_socktype
= SOCK_DGRAM
;
318 /* fill in ai with the list of hosts resolved by the host name */
319 ga_result
= getaddrinfo(host
, port
, &hints
, &ai
);
321 die(STATE_UNKNOWN
, "error getting address for %s: %s\n",
322 host
, gai_strerror(ga_result
));
325 /* count the number of returned hosts, and allocate stuff accordingly */
326 for(ai_tmp
=ai
; ai_tmp
!=NULL
; ai_tmp
=ai_tmp
->ai_next
){ num_hosts
++; }
327 req
=(ntp_message
*)malloc(sizeof(ntp_message
)*num_hosts
);
328 if(req
==NULL
) die(STATE_UNKNOWN
, "can not allocate ntp message array");
329 socklist
=(int*)malloc(sizeof(int)*num_hosts
);
330 if(socklist
==NULL
) die(STATE_UNKNOWN
, "can not allocate socket array");
331 ufds
=(struct pollfd
*)malloc(sizeof(struct pollfd
)*num_hosts
);
332 if(ufds
==NULL
) die(STATE_UNKNOWN
, "can not allocate socket array");
333 servers
=(ntp_server_results
*)malloc(sizeof(ntp_server_results
)*num_hosts
);
334 if(servers
==NULL
) die(STATE_UNKNOWN
, "can not allocate server array");
335 memset(servers
, 0, sizeof(ntp_server_results
)*num_hosts
);
336 DBG(printf("Found %d peers to check\n", num_hosts
));
338 /* setup each socket for writing, and the corresponding struct pollfd */
341 socklist
[i
]=socket(ai_tmp
->ai_family
, SOCK_DGRAM
, IPPROTO_UDP
);
342 if(socklist
[i
] == -1) {
344 die(STATE_UNKNOWN
, "can not create new socket");
346 if(connect(socklist
[i
], ai_tmp
->ai_addr
, ai_tmp
->ai_addrlen
)){
347 die(STATE_UNKNOWN
, "can't create socket connection");
349 ufds
[i
].fd
=socklist
[i
];
350 ufds
[i
].events
=POLLIN
;
353 ai_tmp
= ai_tmp
->ai_next
;
356 /* now do AVG_NUM checks to each host. We stop before timeout/2 seconds
357 * have passed in order to ensure post-processing and jitter time. */
358 now_time
=start_ts
=time(NULL
);
359 while(servers_completed
<num_hosts
&& now_time
-start_ts
<= socket_timeout
/2){
360 /* loop through each server and find each one which hasn't
361 * been touched in the past second or so and is still lacking
362 * some responses. For each of these servers, send a new request,
363 * and update the "waiting" timestamp with the current time. */
367 for(i
=0; i
<num_hosts
; i
++){
368 if(servers
[i
].waiting
<now_time
&& servers
[i
].num_responses
<AVG_NUM
){
369 if(verbose
&& servers
[i
].waiting
!= 0) printf("re-");
370 if(verbose
) printf("sending request to peer %d\n", i
);
371 setup_request(&req
[i
]);
372 write(socklist
[i
], &req
[i
], sizeof(ntp_message
));
373 servers
[i
].waiting
=now_time
;
379 /* quickly poll for any sockets with pending data */
380 servers_readable
=poll(ufds
, num_hosts
, 100);
381 if(servers_readable
==-1){
382 perror("polling ntp sockets");
383 die(STATE_UNKNOWN
, "communication errors");
386 /* read from any sockets with pending data */
387 for(i
=0; servers_readable
&& i
<num_hosts
; i
++){
388 if(ufds
[i
].revents
&POLLIN
&& servers
[i
].num_responses
< AVG_NUM
){
390 printf("response from peer %d: ", i
);
393 read(ufds
[i
].fd
, &req
[i
], sizeof(ntp_message
));
394 gettimeofday(&recv_time
, NULL
);
395 DBG(print_ntp_message(&req
[i
]));
396 respnum
=servers
[i
].num_responses
++;
397 servers
[i
].offset
[respnum
]=calc_offset(&req
[i
], &recv_time
);
399 printf("offset %.10g\n", servers
[i
].offset
[respnum
]);
401 servers
[i
].stratum
=req
[i
].stratum
;
402 servers
[i
].rtdisp
=NTP32asDOUBLE(req
[i
].rtdisp
);
403 servers
[i
].rtdelay
=NTP32asDOUBLE(req
[i
].rtdelay
);
404 servers
[i
].waiting
=0;
405 servers
[i
].flags
=req
[i
].flags
;
408 if(servers
[i
].num_responses
==AVG_NUM
) servers_completed
++;
411 /* lather, rinse, repeat. */
415 die(STATE_CRITICAL
, "NTP CRITICAL: No response from NTP server\n");
418 /* now, pick the best server from the list */
419 best_index
=best_offset_server(servers
, num_hosts
);
421 *status
=STATE_UNKNOWN
;
423 /* finally, calculate the average offset */
424 for(i
=0; i
<servers
[best_index
].num_responses
;i
++){
425 avg_offset
+=servers
[best_index
].offset
[j
];
427 avg_offset
/=servers
[best_index
].num_responses
;
431 for(j
=0; j
<num_hosts
; j
++){ close(socklist
[j
]); }
438 if(verbose
) printf("overall average offset: %.10g\n", avg_offset
);
442 int process_arguments(int argc
, char **argv
){
445 static struct option longopts
[] = {
446 {"version", no_argument
, 0, 'V'},
447 {"help", no_argument
, 0, 'h'},
448 {"verbose", no_argument
, 0, 'v'},
449 {"use-ipv4", no_argument
, 0, '4'},
450 {"use-ipv6", no_argument
, 0, '6'},
451 {"quiet", no_argument
, 0, 'q'},
452 {"warning", required_argument
, 0, 'w'},
453 {"critical", required_argument
, 0, 'c'},
454 {"timeout", required_argument
, 0, 't'},
455 {"hostname", required_argument
, 0, 'H'},
456 {"port", required_argument
, 0, 'p'},
465 c
= getopt_long (argc
, argv
, "Vhv46qw:c:t:H:p:", longopts
, &option
);
466 if (c
== -1 || c
== EOF
|| c
== 1)
475 print_revision(progname
, NP_VERSION
);
491 if(is_host(optarg
) == FALSE
)
492 usage2(_("Invalid hostname/address"), optarg
);
493 server_address
= strdup(optarg
);
496 port
= strdup(optarg
);
499 socket_timeout
=atoi(optarg
);
502 address_family
= AF_INET
;
506 address_family
= AF_INET6
;
508 usage4 (_("IPv6 support not available"));
512 /* print short usage statement if args not parsable */
518 if(server_address
== NULL
){
519 usage4(_("Hostname was not supplied"));
525 char *perfd_offset (double offset
)
527 return fperfdata ("offset", offset
, "s",
528 TRUE
, offset_thresholds
->warning
->end
,
529 TRUE
, offset_thresholds
->critical
->end
,
533 int main(int argc
, char *argv
[]){
534 int result
, offset_result
;
536 char *result_line
, *perfdata_line
;
538 setlocale (LC_ALL
, "");
539 bindtextdomain (PACKAGE
, LOCALEDIR
);
540 textdomain (PACKAGE
);
542 result
= offset_result
= STATE_OK
;
544 /* Parse extra opts if any */
545 argv
=np_extra_opts (&argc
, argv
, progname
);
547 if (process_arguments (argc
, argv
) == ERROR
)
548 usage4 (_("Could not parse arguments"));
550 set_thresholds(&offset_thresholds
, owarn
, ocrit
);
552 /* initialize alarm signal handling */
553 signal (SIGALRM
, socket_timeout_alarm_handler
);
555 /* set socket timeout */
556 alarm (socket_timeout
);
558 offset
= offset_request(server_address
, &offset_result
);
559 if (offset_result
== STATE_UNKNOWN
) {
560 result
= (quiet
== 1 ? STATE_UNKNOWN
: STATE_CRITICAL
);
562 result
= get_status(fabs(offset
), offset_thresholds
);
566 case STATE_CRITICAL
:
567 asprintf(&result_line
, _("NTP CRITICAL:"));
570 asprintf(&result_line
, _("NTP WARNING:"));
573 asprintf(&result_line
, _("NTP OK:"));
576 asprintf(&result_line
, _("NTP UNKNOWN:"));
579 if(offset_result
== STATE_UNKNOWN
){
580 asprintf(&result_line
, "%s %s", result_line
, _("Offset unknown"));
581 asprintf(&perfdata_line
, "");
583 asprintf(&result_line
, "%s %s %.10g secs", result_line
, _("Offset"), offset
);
584 asprintf(&perfdata_line
, "%s", perfd_offset(offset
));
586 printf("%s|%s\n", result_line
, perfdata_line
);
588 if(server_address
!=NULL
) free(server_address
);
592 void print_help(void){
593 print_revision(progname
, NP_VERSION
);
595 printf ("Copyright (c) 2006 Sean Finney\n");
596 printf (COPYRIGHT
, copyright
, email
);
598 printf ("%s\n", _("This plugin checks the clock offset with the ntp server"));
603 printf (_(UT_HELP_VRSN
));
604 printf (_(UT_EXTRA_OPTS
));
605 printf (_(UT_HOST_PORT
), 'p', "123");
606 printf (" %s\n", "-q, --quiet");
607 printf (" %s\n", _("Returns UNKNOWN instead of CRITICAL if offset cannot be found"));
608 printf (" %s\n", "-w, --warning=THRESHOLD");
609 printf (" %s\n", _("Offset to result in warning status (seconds)"));
610 printf (" %s\n", "-c, --critical=THRESHOLD");
611 printf (" %s\n", _("Offset to result in critical status (seconds)"));
612 printf (_(UT_TIMEOUT
), DEFAULT_SOCKET_TIMEOUT
);
613 printf (_(UT_VERBOSE
));
616 printf("%s\n", _("This plugin checks the clock offset between the local host and a"));
617 printf("%s\n", _("remote NTP server. It is independent of any commandline programs or"));
618 printf("%s\n", _("external libraries."));
621 printf("%s\n", _("Notes:"));
622 printf(" %s\n", _("If you'd rather want to monitor an NTP server, please use"));
623 printf(" %s\n", _("check_ntp_peer."));
625 printf(_(UT_THRESHOLDS_NOTES
));
628 printf(_(UT_EXTRA_OPTS_NOTES
));
632 printf("%s\n", _("Examples:"));
633 printf(" %s\n", ("./check_ntp_time -H ntpserv -w 0.5 -c 1"));
635 printf (_(UT_SUPPORT
));
641 printf (_("Usage:"));
642 printf(" %s -H <host> [-w <warn>] [-c <crit>] [-v verbose]\n", progname
);