5037786a97d316b4ddfcd1c53f016c71b13d8b4b
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$
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=0;
37 static double ocrit=0;
38 static short do_jitter=0;
39 static double jwarn=0;
40 static double jcrit=0;
42 int process_arguments (int, char **);
43 void print_help (void);
44 void print_usage (void);
46 /* this structure holds everything in an ntp request/response as per rfc1305 */
47 typedef struct {
48 uint8_t flags; /* byte with leapindicator,vers,mode. see macros */
49 uint8_t stratum; /* clock stratum */
50 int8_t poll; /* polling interval */
51 int8_t precision; /* precision of the local clock */
52 int32_t rtdelay; /* total rt delay, as a fixed point num. see macros */
53 uint32_t rtdisp; /* like above, but for max err to primary src */
54 uint32_t refid; /* ref clock identifier */
55 uint64_t refts; /* reference timestamp. local time local clock */
56 uint64_t origts; /* time at which request departed client */
57 uint64_t rxts; /* time at which request arrived at server */
58 uint64_t txts; /* time at which request departed server */
59 } ntp_message;
61 /* bits 1,2 are the leap indicator */
62 #define LI_MASK 0xc0
63 #define LI(x) ((x&LI_MASK)>>6)
64 #define LI_SET(x,y) do{ x |= ((y<<6)&LI_MASK); }while(0)
65 /* and these are the values of the leap indicator */
66 #define LI_NOWARNING 0x00
67 #define LI_EXTRASEC 0x01
68 #define LI_MISSINGSEC 0x02
69 #define LI_ALARM 0x03
70 /* bits 3,4,5 are the ntp version */
71 #define VN_MASK 0x38
72 #define VN(x) ((x&VN_MASK)>>3)
73 #define VN_SET(x,y) do{ x |= ((y<<3)&VN_MASK); }while(0)
74 /* bits 6,7,8 are the ntp mode */
75 #define MODE_MASK 0x07
76 #define MODE(x) (x&MODE_MASK)
77 #define MODE_SET(x,y) do{ x |= (y&MODE_MASK); }while(0)
78 /* here are some values */
79 #define MODE_CLIENT 0x03
81 /**
82 ** a note about the 32-bit "fixed point" numbers:
83 **
84 they are divided into halves, each being a 16-bit int in network byte order:
85 - the first 16 bits are an int on the left side of a decimal point.
86 - the second 16 bits represent a fraction n/(2^16)
87 likewise for the 64-bit "fixed point" numbers with everything doubled :)
88 **/
90 /* macros to access the left/right 16 bits of a 32-bit ntp "fixed point"
91 number. note that these can be used as lvalues too */
92 #define L16(x) (((uint16_t*)&x)[0])
93 #define R16(x) (((uint16_t*)&x)[1])
94 /* macros to access the left/right 32 bits of a 64-bit ntp "fixed point"
95 number. these too can be used as lvalues */
96 #define L32(x) (((uint32_t*)&x)[0])
97 #define R32(x) (((uint32_t*)&x)[1])
99 /* ntp wants seconds since 1/1/00, epoch is 1/1/70. this is the difference */
100 #define EPOCHDIFF 0x83aa7e80UL
102 /* extract a 32-bit ntp fixed point number into a double */
103 #define NTP32asDOUBLE(x) (ntohs(L16(x)) + (double)ntohs(R16(x))/65536.0)
105 /* likewise for a 64-bit ntp fp number */
106 #define NTP64asDOUBLE(n) (double)(((uint64_t)n)?\
107 (ntohl(L32(n))-EPOCHDIFF) + \
108 (.00000001*(0.5+(double)(ntohl(R32(n))/42.94967296))):\
109 0)
111 /* convert a struct timeval to a double */
112 #define TVasDOUBLE(x) (double)(x.tv_sec+(0.000001*x.tv_usec))
114 /* convert an ntp 64-bit fp number to a struct timeval */
115 #define NTP64toTV(n,t) \
116 do{ if(!n) t.tv_sec = t.tv_usec = 0; \
117 else { \
118 t.tv_sec=ntohl(L32(n))-EPOCHDIFF; \
119 t.tv_usec=(int)(0.5+(double)(ntohl(R32(n))/4294.967296)); \
120 } \
121 }while(0)
123 /* convert a struct timeval to an ntp 64-bit fp number */
124 #define TVtoNTP64(t,n) \
125 do{ if(!t.tv_usec && !t.tv_sec) n=0x0UL; \
126 else { \
127 L32(n)=htonl(t.tv_sec + EPOCHDIFF); \
128 R32(n)=htonl((4294.967296*t.tv_usec)+.5); \
129 } \
130 } while(0)
133 /* calculate the offset of the local clock */
134 static inline double calc_offset(const ntp_message *m, const struct timeval *t){
135 double client_tx, peer_rx, peer_tx, client_rx, rtdelay;
136 client_tx = NTP64asDOUBLE(m->origts);
137 peer_rx = NTP64asDOUBLE(m->rxts);
138 peer_tx = NTP64asDOUBLE(m->txts);
139 client_rx=TVasDOUBLE((*t));
140 rtdelay=NTP32asDOUBLE(m->rtdelay);
141 return (.5*((peer_tx-client_rx)+(peer_rx-client_tx)))-rtdelay;
142 }
144 /* print out a ntp packet in human readable/debuggable format */
145 void print_packet(const ntp_message *p){
146 struct timeval ref, orig, rx, tx;
148 NTP64toTV(p->refts,ref);
149 NTP64toTV(p->origts,orig);
150 NTP64toTV(p->rxts,rx);
151 NTP64toTV(p->txts,tx);
153 printf("packet contents:\n");
154 printf("\tflags: 0x%.2x\n", p->flags);
155 printf("\t li=%d (0x%.2x)\n", LI(p->flags), p->flags&LI_MASK);
156 printf("\t vn=%d (0x%.2x)\n", VN(p->flags), p->flags&VN_MASK);
157 printf("\t mode=%d (0x%.2x)\n", MODE(p->flags), p->flags&MODE_MASK);
158 printf("\tstratum = %d\n", p->stratum);
159 printf("\tpoll = %g\n", pow(2, p->poll));
160 printf("\tprecision = %g\n", pow(2, p->precision));
161 printf("\trtdelay = %-.16g\n", NTP32asDOUBLE(p->rtdelay));
162 printf("\trtdisp = %-.16g\n", NTP32asDOUBLE(p->rtdisp));
163 printf("\trefid = %x\n", p->refid);
164 printf("\trefts = %-.16g\n", NTP64asDOUBLE(p->refts));
165 printf("\torigts = %-.16g\n", NTP64asDOUBLE(p->origts));
166 printf("\trxts = %-.16g\n", NTP64asDOUBLE(p->rxts));
167 printf("\ttxts = %-.16g\n", NTP64asDOUBLE(p->txts));
168 }
170 void setup_request(ntp_message *p){
171 struct timeval t;
173 memset(p, 0, sizeof(ntp_message));
174 LI_SET(p->flags, LI_ALARM);
175 VN_SET(p->flags, 4);
176 MODE_SET(p->flags, MODE_CLIENT);
177 p->poll=4;
178 p->precision=0xfa;
179 L16(p->rtdelay)=htons(1);
180 L16(p->rtdisp)=htons(1);
182 gettimeofday(&t, NULL);
183 TVtoNTP64(t,p->txts);
184 }
186 double offset_request(const char *host){
187 int i=0, conn=-1;
188 ntp_message req;
189 double next_offset=0., avg_offset=0.;
190 struct timeval recv_time;
192 for(i=0; i<4; i++){
193 setup_request(&req);
194 my_udp_connect(server_address, 123, &conn);
195 write(conn, &req, sizeof(ntp_message));
196 read(conn, &req, sizeof(ntp_message));
197 gettimeofday(&recv_time, NULL);
198 /* if(verbose) print_packet(&req); */
199 close(conn);
200 next_offset=calc_offset(&req, &recv_time);
201 if(verbose) printf("offset: %g\n", next_offset);
202 avg_offset+=next_offset;
203 }
204 return avg_offset/4.;
205 }
207 /* not yet implemented yet */
208 double jitter_request(const char *host){
209 return 0.;
210 }
212 int process_arguments(int argc, char **argv){
213 int c;
214 int option=0;
215 static struct option longopts[] = {
216 {"version", no_argument, 0, 'V'},
217 {"help", no_argument, 0, 'h'},
218 {"verbose", no_argument, 0, 'v'},
219 {"use-ipv4", no_argument, 0, '4'},
220 {"use-ipv6", no_argument, 0, '6'},
221 {"warning", required_argument, 0, 'w'},
222 {"critical", required_argument, 0, 'c'},
223 {"zero-offset", no_argument, 0, 'O'},
224 {"jwarn", required_argument, 0, 'j'},
225 {"jcrit", required_argument, 0, 'k'},
226 {"timeout", required_argument, 0, 't'},
227 {"hostname", required_argument, 0, 'H'},
228 {0, 0, 0, 0}
229 };
232 if (argc < 2)
233 usage ("\n");
235 while (1) {
236 c = getopt_long (argc, argv, "Vhv46w:c:Oj:k:t:H:", longopts, &option);
237 if (c == -1 || c == EOF || c == 1)
238 break;
240 switch (c) {
241 case 'h':
242 print_help();
243 exit(STATE_OK);
244 break;
245 case 'V':
246 print_revision(progname, revision);
247 exit(STATE_OK);
248 break;
249 case 'v':
250 verbose = 1;
251 break;
252 case 'w':
253 owarn = atof(optarg);
254 break;
255 case 'c':
256 ocrit = atof(optarg);
257 break;
258 case 'j':
259 do_jitter=1;
260 jwarn = atof(optarg);
261 break;
262 case 'k':
263 do_jitter=1;
264 jcrit = atof(optarg);
265 break;
266 case 'H':
267 if(is_host(optarg) == FALSE)
268 usage2(_("Invalid hostname/address"), optarg);
269 server_address = strdup(optarg);
270 break;
271 case 't':
272 socket_timeout=atoi(optarg);
273 break;
274 case 'O':
275 zero_offset_bad=1;
276 break;
277 case '4':
278 address_family = AF_INET;
279 break;
280 case '6':
281 #ifdef USE_IPV6
282 address_family = AF_INET6;
283 #else
284 usage4 (_("IPv6 support not available"));
285 #endif
286 break;
287 case '?':
288 /* print short usage statement if args not parsable */
289 usage2 (_("Unknown argument"), optarg);
290 break;
291 }
292 }
294 if (ocrit < owarn){
295 usage4(_("Critical offset should be larger than warning offset"));
296 }
298 if (ocrit < owarn){
299 usage4(_("Critical jitter should be larger than warning jitter"));
300 }
302 if(server_address == NULL){
303 usage4(_("Hostname was not supplied"));
304 }
306 return 0;
307 }
309 int main(int argc, char *argv[]){
310 int result = STATE_UNKNOWN;
311 double offset=0, jitter=0;
313 if (process_arguments (argc, argv) == ERROR)
314 usage4 (_("Could not parse arguments"));
316 /* initialize alarm signal handling */
317 signal (SIGALRM, socket_timeout_alarm_handler);
319 /* set socket timeout */
320 alarm (socket_timeout);
322 offset = offset_request(server_address);
323 if(offset > ocrit){
324 printf("NTP CRITICAL: ");
325 result = STATE_CRITICAL;
326 } else if(offset > owarn) {
327 printf("NTP WARNING: ");
328 result = STATE_WARNING;
329 } else {
330 printf("NTP OK: ");
331 result = STATE_OK;
332 }
334 /* not implemented yet: */
335 jitter=jitter_request(server_address);
337 /* not implemented yet:
338 if(do_jitter){
339 if(jitter > jcrit){
340 printf("NTP CRITICAL: ");
341 result = STATE_CRITICAL;
342 } else if(jitter > jwarn) {
343 printf("NTP WARNING: ");
344 result = STATE_WARNING;
345 } else {
346 printf("NTP OK: ");
347 result = STATE_OK;
348 }
349 }
350 */
352 printf("Offset %g secs|offset=%g\n", offset, offset);
354 if(server_address!=NULL) free(server_address);
355 return result;
356 }
359 void print_usage(void){
360 printf("\
361 Usage: %s -H <host> [-O] [-w <warn>] [-c <crit>] [-j <warn>] [-k <crit>] [-v verbose]\
362 \n", progname);
363 }
365 void print_help(void){
366 print_revision(progname, revision);
368 printf ("Copyright (c) 1999 Ethan Galstad\n");
369 printf (COPYRIGHT, copyright, email);
371 print_usage();
372 printf (_(UT_HELP_VRSN));
373 printf (_(UT_HOST_PORT), 'p', "123");
374 printf (_(UT_WARN_CRIT));
375 printf (_(UT_TIMEOUT), DEFAULT_SOCKET_TIMEOUT);
376 printf (_(UT_VERBOSE));
377 printf(_(UT_SUPPORT));
378 }