summaryrefslogtreecommitdiffstats
path: root/plugins/check_ntp_time.c
diff options
context:
space:
mode:
Diffstat (limited to 'plugins/check_ntp_time.c')
-rw-r--r--plugins/check_ntp_time.c521
1 files changed, 307 insertions, 214 deletions
diff --git a/plugins/check_ntp_time.c b/plugins/check_ntp_time.c
index 703b69df..9e0beb9c 100644
--- a/plugins/check_ntp_time.c
+++ b/plugins/check_ntp_time.c
@@ -34,24 +34,29 @@
34 * 34 *
35 *****************************************************************************/ 35 *****************************************************************************/
36 36
37const char *progname = "check_ntp_time"; 37#include "output.h"
38const char *copyright = "2006-2024";
39const char *email = "devel@monitoring-plugins.org";
40
41#include "common.h" 38#include "common.h"
42#include "netutils.h" 39#include "netutils.h"
40#include "perfdata.h"
43#include "utils.h" 41#include "utils.h"
42#include "states.h"
43#include "thresholds.h"
44#include "check_ntp_time.d/config.h"
45#include <netinet/in.h>
46#include <sys/socket.h>
44 47
45static char *server_address = NULL;
46static char *port = "123";
47static int verbose = 0; 48static int verbose = 0;
48static bool quiet = false;
49static char *owarn = "60";
50static char *ocrit = "120";
51static int time_offset = 0;
52 49
53static int process_arguments(int, char **); 50const char *progname = "check_ntp_time";
54static thresholds *offset_thresholds = NULL; 51const char *copyright = "2006-2024";
52const char *email = "devel@monitoring-plugins.org";
53
54typedef struct {
55 int errorcode;
56 check_ntp_time_config config;
57} check_ntp_time_config_wrapper;
58static check_ntp_time_config_wrapper process_arguments(int /*argc*/, char ** /*argv*/);
59
55static void print_help(void); 60static void print_help(void);
56void print_usage(void); 61void print_usage(void);
57 62
@@ -60,9 +65,6 @@ void print_usage(void);
60# define AVG_NUM 4 65# define AVG_NUM 4
61#endif 66#endif
62 67
63/* max size of control message data */
64#define MAX_CM_SIZE 468
65
66/* this structure holds everything in an ntp request/response as per rfc1305 */ 68/* this structure holds everything in an ntp request/response as per rfc1305 */
67typedef struct { 69typedef struct {
68 uint8_t flags; /* byte with leapindicator,vers,mode. see macros */ 70 uint8_t flags; /* byte with leapindicator,vers,mode. see macros */
@@ -92,9 +94,9 @@ typedef struct {
92/* bits 1,2 are the leap indicator */ 94/* bits 1,2 are the leap indicator */
93#define LI_MASK 0xc0 95#define LI_MASK 0xc0
94#define LI(x) ((x & LI_MASK) >> 6) 96#define LI(x) ((x & LI_MASK) >> 6)
95#define LI_SET(x, y) \ 97#define LI_SET(x, y) \
96 do { \ 98 do { \
97 x |= ((y << 6) & LI_MASK); \ 99 x |= ((y << 6) & LI_MASK); \
98 } while (0) 100 } while (0)
99/* and these are the values of the leap indicator */ 101/* and these are the values of the leap indicator */
100#define LI_NOWARNING 0x00 102#define LI_NOWARNING 0x00
@@ -104,17 +106,17 @@ typedef struct {
104/* bits 3,4,5 are the ntp version */ 106/* bits 3,4,5 are the ntp version */
105#define VN_MASK 0x38 107#define VN_MASK 0x38
106#define VN(x) ((x & VN_MASK) >> 3) 108#define VN(x) ((x & VN_MASK) >> 3)
107#define VN_SET(x, y) \ 109#define VN_SET(x, y) \
108 do { \ 110 do { \
109 x |= ((y << 3) & VN_MASK); \ 111 x |= ((y << 3) & VN_MASK); \
110 } while (0) 112 } while (0)
111#define VN_RESERVED 0x02 113#define VN_RESERVED 0x02
112/* bits 6,7,8 are the ntp mode */ 114/* bits 6,7,8 are the ntp mode */
113#define MODE_MASK 0x07 115#define MODE_MASK 0x07
114#define MODE(x) (x & MODE_MASK) 116#define MODE(x) (x & MODE_MASK)
115#define MODE_SET(x, y) \ 117#define MODE_SET(x, y) \
116 do { \ 118 do { \
117 x |= (y & MODE_MASK); \ 119 x |= (y & MODE_MASK); \
118 } while (0) 120 } while (0)
119/* here are some values */ 121/* here are some values */
120#define MODE_CLIENT 0x03 122#define MODE_CLIENT 0x03
@@ -126,9 +128,9 @@ typedef struct {
126#define REM_MORE 0x20 128#define REM_MORE 0x20
127/* In control message, bits 11 - 15 are opcode */ 129/* In control message, bits 11 - 15 are opcode */
128#define OP_MASK 0x1f 130#define OP_MASK 0x1f
129#define OP_SET(x, y) \ 131#define OP_SET(x, y) \
130 do { \ 132 do { \
131 x |= (y & OP_MASK); \ 133 x |= (y & OP_MASK); \
132 } while (0) 134 } while (0)
133#define OP_READSTAT 0x01 135#define OP_READSTAT 0x01
134#define OP_READVAR 0x02 136#define OP_READVAR 0x02
@@ -159,35 +161,39 @@ typedef struct {
159#define EPOCHDIFF 0x83aa7e80UL 161#define EPOCHDIFF 0x83aa7e80UL
160 162
161/* extract a 32-bit ntp fixed point number into a double */ 163/* extract a 32-bit ntp fixed point number into a double */
162#define NTP32asDOUBLE(x) (ntohs(L16(x)) + (double)ntohs(R16(x)) / 65536.0) 164#define NTP32asDOUBLE(x) (ntohs(L16(x)) + ((double)ntohs(R16(x)) / 65536.0))
163 165
164/* likewise for a 64-bit ntp fp number */ 166/* likewise for a 64-bit ntp fp number */
165#define NTP64asDOUBLE(n) \ 167#define NTP64asDOUBLE(n) \
166 (double)(((uint64_t)n) ? (ntohl(L32(n)) - EPOCHDIFF) + (.00000001 * (0.5 + (double)(ntohl(R32(n)) / 42.94967296))) : 0) 168 (double)(((uint64_t)n) ? (ntohl(L32(n)) - EPOCHDIFF) + \
169 (.00000001 * (0.5 + (double)(ntohl(R32(n)) / 42.94967296))) \
170 : 0)
167 171
168/* convert a struct timeval to a double */ 172/* convert a struct timeval to a double */
169#define TVasDOUBLE(x) (double)(x.tv_sec + (0.000001 * x.tv_usec)) 173static double TVasDOUBLE(struct timeval time) {
174 return ((double)time.tv_sec + (0.000001 * (double)time.tv_usec));
175}
170 176
171/* convert an ntp 64-bit fp number to a struct timeval */ 177/* convert an ntp 64-bit fp number to a struct timeval */
172#define NTP64toTV(n, t) \ 178#define NTP64toTV(n, t) \
173 do { \ 179 do { \
174 if (!n) \ 180 if (!n) \
175 t.tv_sec = t.tv_usec = 0; \ 181 t.tv_sec = t.tv_usec = 0; \
176 else { \ 182 else { \
177 t.tv_sec = ntohl(L32(n)) - EPOCHDIFF; \ 183 t.tv_sec = ntohl(L32(n)) - EPOCHDIFF; \
178 t.tv_usec = (int)(0.5 + (double)(ntohl(R32(n)) / 4294.967296)); \ 184 t.tv_usec = (int)(0.5 + (double)(ntohl(R32(n)) / 4294.967296)); \
179 } \ 185 } \
180 } while (0) 186 } while (0)
181 187
182/* convert a struct timeval to an ntp 64-bit fp number */ 188/* convert a struct timeval to an ntp 64-bit fp number */
183#define TVtoNTP64(t, n) \ 189#define TVtoNTP64(t, n) \
184 do { \ 190 do { \
185 if (!t.tv_usec && !t.tv_sec) \ 191 if (!t.tv_usec && !t.tv_sec) \
186 n = 0x0UL; \ 192 n = 0x0UL; \
187 else { \ 193 else { \
188 L32(n) = htonl(t.tv_sec + EPOCHDIFF); \ 194 L32(n) = htonl(t.tv_sec + EPOCHDIFF); \
189 R32(n) = htonl((uint64_t)((4294.967296 * t.tv_usec) + .5)); \ 195 R32(n) = htonl((uint64_t)((4294.967296 * t.tv_usec) + .5)); \
190 } \ 196 } \
191 } while (0) 197 } while (0)
192 198
193/* NTP control message header is 12 bytes, plus any data in the data 199/* NTP control message header is 12 bytes, plus any data in the data
@@ -196,75 +202,71 @@ typedef struct {
196#define SIZEOF_NTPCM(m) (12 + ntohs(m.count) + ((m.count) ? 4 - (ntohs(m.count) % 4) : 0)) 202#define SIZEOF_NTPCM(m) (12 + ntohs(m.count) + ((m.count) ? 4 - (ntohs(m.count) % 4) : 0))
197 203
198/* finally, a little helper or two for debugging: */ 204/* finally, a little helper or two for debugging: */
199#define DBG(x) \ 205#define DBG(x) \
200 do { \ 206 do { \
201 if (verbose > 1) { \ 207 if (verbose > 1) { \
202 x; \ 208 x; \
203 } \ 209 } \
204 } while (0); 210 } while (0);
205#define PRINTSOCKADDR(x) \ 211#define PRINTSOCKADDR(x) \
206 do { \ 212 do { \
207 printf("%u.%u.%u.%u", (x >> 24) & 0xff, (x >> 16) & 0xff, (x >> 8) & 0xff, x & 0xff); \ 213 printf("%u.%u.%u.%u", (x >> 24) & 0xff, (x >> 16) & 0xff, (x >> 8) & 0xff, x & 0xff); \
208 } while (0); 214 } while (0);
209 215
210/* calculate the offset of the local clock */ 216/* calculate the offset of the local clock */
211static inline double calc_offset(const ntp_message *m, const struct timeval *t) { 217static inline double calc_offset(const ntp_message *message, const struct timeval *time_value) {
212 double client_tx = NTP64asDOUBLE(m->origts); 218 double client_tx = NTP64asDOUBLE(message->origts);
213 double peer_rx = NTP64asDOUBLE(m->rxts); 219 double peer_rx = NTP64asDOUBLE(message->rxts);
214 double peer_tx = NTP64asDOUBLE(m->txts); 220 double peer_tx = NTP64asDOUBLE(message->txts);
215 double client_rx = TVasDOUBLE((*t)); 221 double client_rx = TVasDOUBLE((*time_value));
216 return (.5 * ((peer_tx - client_rx) + (peer_rx - client_tx))); 222 return (((peer_tx - client_rx) + (peer_rx - client_tx)) / 2);
217} 223}
218 224
219/* print out a ntp packet in human readable/debuggable format */ 225/* print out a ntp packet in human readable/debuggable format */
220void print_ntp_message(const ntp_message *p) { 226void print_ntp_message(const ntp_message *message) {
221 struct timeval ref; 227 struct timeval ref;
222 struct timeval orig; 228 struct timeval orig;
223 struct timeval rx;
224 struct timeval tx;
225 229
226 NTP64toTV(p->refts, ref); 230 NTP64toTV(message->refts, ref);
227 NTP64toTV(p->origts, orig); 231 NTP64toTV(message->origts, orig);
228 NTP64toTV(p->rxts, rx);
229 NTP64toTV(p->txts, tx);
230 232
231 printf("packet contents:\n"); 233 printf("packet contents:\n");
232 printf("\tflags: 0x%.2x\n", p->flags); 234 printf("\tflags: 0x%.2x\n", message->flags);
233 printf("\t li=%d (0x%.2x)\n", LI(p->flags), p->flags & LI_MASK); 235 printf("\t li=%d (0x%.2x)\n", LI(message->flags), message->flags & LI_MASK);
234 printf("\t vn=%d (0x%.2x)\n", VN(p->flags), p->flags & VN_MASK); 236 printf("\t vn=%d (0x%.2x)\n", VN(message->flags), message->flags & VN_MASK);
235 printf("\t mode=%d (0x%.2x)\n", MODE(p->flags), p->flags & MODE_MASK); 237 printf("\t mode=%d (0x%.2x)\n", MODE(message->flags), message->flags & MODE_MASK);
236 printf("\tstratum = %d\n", p->stratum); 238 printf("\tstratum = %d\n", message->stratum);
237 printf("\tpoll = %g\n", pow(2, p->poll)); 239 printf("\tpoll = %g\n", pow(2, message->poll));
238 printf("\tprecision = %g\n", pow(2, p->precision)); 240 printf("\tprecision = %g\n", pow(2, message->precision));
239 printf("\trtdelay = %-.16g\n", NTP32asDOUBLE(p->rtdelay)); 241 printf("\trtdelay = %-.16g\n", NTP32asDOUBLE(message->rtdelay));
240 printf("\trtdisp = %-.16g\n", NTP32asDOUBLE(p->rtdisp)); 242 printf("\trtdisp = %-.16g\n", NTP32asDOUBLE(message->rtdisp));
241 printf("\trefid = %x\n", p->refid); 243 printf("\trefid = %x\n", message->refid);
242 printf("\trefts = %-.16g\n", NTP64asDOUBLE(p->refts)); 244 printf("\trefts = %-.16g\n", NTP64asDOUBLE(message->refts));
243 printf("\torigts = %-.16g\n", NTP64asDOUBLE(p->origts)); 245 printf("\torigts = %-.16g\n", NTP64asDOUBLE(message->origts));
244 printf("\trxts = %-.16g\n", NTP64asDOUBLE(p->rxts)); 246 printf("\trxts = %-.16g\n", NTP64asDOUBLE(message->rxts));
245 printf("\ttxts = %-.16g\n", NTP64asDOUBLE(p->txts)); 247 printf("\ttxts = %-.16g\n", NTP64asDOUBLE(message->txts));
246} 248}
247 249
248void setup_request(ntp_message *p) { 250void setup_request(ntp_message *message) {
249 memset(p, 0, sizeof(ntp_message)); 251 memset(message, 0, sizeof(ntp_message));
250 LI_SET(p->flags, LI_ALARM); 252 LI_SET(message->flags, LI_ALARM);
251 VN_SET(p->flags, 4); 253 VN_SET(message->flags, 4);
252 MODE_SET(p->flags, MODE_CLIENT); 254 MODE_SET(message->flags, MODE_CLIENT);
253 p->poll = 4; 255 message->poll = 4;
254 p->precision = (int8_t)0xfa; 256 message->precision = (int8_t)0xfa;
255 L16(p->rtdelay) = htons(1); 257 L16(message->rtdelay) = htons(1);
256 L16(p->rtdisp) = htons(1); 258 L16(message->rtdisp) = htons(1);
257 259
258 struct timeval t; 260 struct timeval t;
259 gettimeofday(&t, NULL); 261 gettimeofday(&t, NULL);
260 TVtoNTP64(t, p->txts); 262 TVtoNTP64(t, message->txts);
261} 263}
262 264
263/* select the "best" server from a list of servers, and return its index. 265/* select the "best" server from a list of servers, and return its index.
264 * this is done by filtering servers based on stratum, dispersion, and 266 * this is done by filtering servers based on stratum, dispersion, and
265 * finally round-trip delay. */ 267 * finally round-trip delay. */
266int best_offset_server(const ntp_server_results *slist, int nservers) { 268static int best_offset_server(const ntp_server_results *slist, int nservers) {
267 int best_server = -1; 269 int best_server_index = -1;
268 270
269 /* for each server */ 271 /* for each server */
270 for (int cserver = 0; cserver < nservers; cserver++) { 272 for (int cserver = 0; cserver < nservers; cserver++) {
@@ -273,45 +275,47 @@ int best_offset_server(const ntp_server_results *slist, int nservers) {
273 * stratum 0 is for reference clocks so no NTP server should ever report 275 * stratum 0 is for reference clocks so no NTP server should ever report
274 * a stratum 0 */ 276 * a stratum 0 */
275 if (slist[cserver].stratum == 0) { 277 if (slist[cserver].stratum == 0) {
276 if (verbose) 278 if (verbose) {
277 printf("discarding peer %d: stratum=%d\n", cserver, slist[cserver].stratum); 279 printf("discarding peer %d: stratum=%d\n", cserver, slist[cserver].stratum);
280 }
278 continue; 281 continue;
279 } 282 }
280 /* Sort out servers with error flags */ 283 /* Sort out servers with error flags */
281 if (LI(slist[cserver].flags) == LI_ALARM) { 284 if (LI(slist[cserver].flags) == LI_ALARM) {
282 if (verbose) 285 if (verbose) {
283 printf("discarding peer %d: flags=%d\n", cserver, LI(slist[cserver].flags)); 286 printf("discarding peer %d: flags=%d\n", cserver, LI(slist[cserver].flags));
287 }
284 continue; 288 continue;
285 } 289 }
286 290
287 /* If we don't have a server yet, use the first one */ 291 /* If we don't have a server yet, use the first one */
288 if (best_server == -1) { 292 if (best_server_index == -1) {
289 best_server = cserver; 293 best_server_index = cserver;
290 DBG(printf("using peer %d as our first candidate\n", best_server)); 294 DBG(printf("using peer %d as our first candidate\n", best_server_index));
291 continue; 295 continue;
292 } 296 }
293 297
294 /* compare the server to the best one we've seen so far */ 298 /* compare the server to the best one we've seen so far */
295 /* does it have an equal or better stratum? */ 299 /* does it have an equal or better stratum? */
296 DBG(printf("comparing peer %d with peer %d\n", cserver, best_server)); 300 DBG(printf("comparing peer %d with peer %d\n", cserver, best_server_index));
297 if (slist[cserver].stratum <= slist[best_server].stratum) { 301 if (slist[cserver].stratum <= slist[best_server_index].stratum) {
298 DBG(printf("stratum for peer %d <= peer %d\n", cserver, best_server)); 302 DBG(printf("stratum for peer %d <= peer %d\n", cserver, best_server_index));
299 /* does it have an equal or better dispersion? */ 303 /* does it have an equal or better dispersion? */
300 if (slist[cserver].rtdisp <= slist[best_server].rtdisp) { 304 if (slist[cserver].rtdisp <= slist[best_server_index].rtdisp) {
301 DBG(printf("dispersion for peer %d <= peer %d\n", cserver, best_server)); 305 DBG(printf("dispersion for peer %d <= peer %d\n", cserver, best_server_index));
302 /* does it have a better rtdelay? */ 306 /* does it have a better rtdelay? */
303 if (slist[cserver].rtdelay < slist[best_server].rtdelay) { 307 if (slist[cserver].rtdelay < slist[best_server_index].rtdelay) {
304 DBG(printf("rtdelay for peer %d < peer %d\n", cserver, best_server)); 308 DBG(printf("rtdelay for peer %d < peer %d\n", cserver, best_server_index));
305 best_server = cserver; 309 best_server_index = cserver;
306 DBG(printf("peer %d is now our best candidate\n", best_server)); 310 DBG(printf("peer %d is now our best candidate\n", best_server_index));
307 } 311 }
308 } 312 }
309 } 313 }
310 } 314 }
311 315
312 if (best_server >= 0) { 316 if (best_server_index >= 0) {
313 DBG(printf("best server selected: peer %d\n", best_server)); 317 DBG(printf("best server selected: peer %d\n", best_server_index));
314 return best_server; 318 return best_server_index;
315 } 319 }
316 DBG(printf("no peers meeting synchronization criteria :(\n")); 320 DBG(printf("no peers meeting synchronization criteria :(\n"));
317 return -1; 321 return -1;
@@ -322,7 +326,11 @@ int best_offset_server(const ntp_server_results *slist, int nservers) {
322 * we don't waste time sitting around waiting for single packets. 326 * we don't waste time sitting around waiting for single packets.
323 * - we also "manually" handle resolving host names and connecting, because 327 * - we also "manually" handle resolving host names and connecting, because
324 * we have to do it in a way that our lazy macros don't handle currently :( */ 328 * we have to do it in a way that our lazy macros don't handle currently :( */
325double offset_request(const char *host, int *status) { 329typedef struct {
330 mp_state_enum offset_result;
331 double offset;
332} offset_request_wrapper;
333static offset_request_wrapper offset_request(const char *host, const char *port, int time_offset) {
326 /* setup hints to only return results from getaddrinfo that we'd like */ 334 /* setup hints to only return results from getaddrinfo that we'd like */
327 struct addrinfo hints; 335 struct addrinfo hints;
328 memset(&hints, 0, sizeof(struct addrinfo)); 336 memset(&hints, 0, sizeof(struct addrinfo));
@@ -330,58 +338,97 @@ double offset_request(const char *host, int *status) {
330 hints.ai_protocol = IPPROTO_UDP; 338 hints.ai_protocol = IPPROTO_UDP;
331 hints.ai_socktype = SOCK_DGRAM; 339 hints.ai_socktype = SOCK_DGRAM;
332 340
333 /* fill in ai with the list of hosts resolved by the host name */ 341 bool is_socket;
334 struct addrinfo *ai = NULL; 342 struct addrinfo *addresses = NULL;
335 int ga_result = getaddrinfo(host, port, &hints, &ai); 343 size_t num_hosts = 0;
336 if (ga_result != 0) { 344 if (host[0] == '/') {
337 die(STATE_UNKNOWN, "error getting address for %s: %s\n", host, gai_strerror(ga_result)); 345 num_hosts = 1;
338 } 346 is_socket = true;
347 } else {
348 is_socket = false;
349
350 /* fill in ai with the list of hosts resolved by the host name */
351 int ga_result = getaddrinfo(host, port, &hints, &addresses);
352 if (ga_result != 0) {
353 die(STATE_UNKNOWN, "error getting address for %s: %s\n", host, gai_strerror(ga_result));
354 }
339 355
340 /* count the number of returned hosts, and allocate stuff accordingly */ 356 /* count the number of returned hosts, and allocate stuff accordingly */
341 int num_hosts = 0; 357 for (struct addrinfo *ai_tmp = addresses; ai_tmp != NULL; ai_tmp = ai_tmp->ai_next) {
342 for (struct addrinfo *ai_tmp = ai; ai_tmp != NULL; ai_tmp = ai_tmp->ai_next) { 358 num_hosts++;
343 num_hosts++; 359 }
344 } 360 }
345 361
346 ntp_message *req = (ntp_message *)malloc(sizeof(ntp_message) * num_hosts); 362 ntp_message *req = (ntp_message *)malloc(sizeof(ntp_message) * num_hosts);
347 363
348 if (req == NULL) 364 if (req == NULL) {
349 die(STATE_UNKNOWN, "can not allocate ntp message array"); 365 die(STATE_UNKNOWN, "can not allocate ntp message array");
366 }
350 int *socklist = (int *)malloc(sizeof(int) * num_hosts); 367 int *socklist = (int *)malloc(sizeof(int) * num_hosts);
351 368
352 if (socklist == NULL) 369 if (socklist == NULL) {
353 die(STATE_UNKNOWN, "can not allocate socket array"); 370 die(STATE_UNKNOWN, "can not allocate socket array");
371 }
354 372
355 struct pollfd *ufds = (struct pollfd *)malloc(sizeof(struct pollfd) * num_hosts); 373 struct pollfd *ufds = (struct pollfd *)malloc(sizeof(struct pollfd) * num_hosts);
356 if (ufds == NULL) 374 if (ufds == NULL) {
357 die(STATE_UNKNOWN, "can not allocate socket array"); 375 die(STATE_UNKNOWN, "can not allocate socket array");
376 }
358 377
359 ntp_server_results *servers = (ntp_server_results *)malloc(sizeof(ntp_server_results) * num_hosts); 378 ntp_server_results *servers =
360 if (servers == NULL) 379 (ntp_server_results *)malloc(sizeof(ntp_server_results) * num_hosts);
380 if (servers == NULL) {
361 die(STATE_UNKNOWN, "can not allocate server array"); 381 die(STATE_UNKNOWN, "can not allocate server array");
382 }
362 memset(servers, 0, sizeof(ntp_server_results) * num_hosts); 383 memset(servers, 0, sizeof(ntp_server_results) * num_hosts);
363 DBG(printf("Found %d peers to check\n", num_hosts)); 384 DBG(printf("Found %zu peers to check\n", num_hosts));
364 385
365 /* setup each socket for writing, and the corresponding struct pollfd */ 386 /* setup each socket for writing, and the corresponding struct pollfd */
366 struct addrinfo *ai_tmp = ai; 387 if (is_socket) {
367 for (int i = 0; ai_tmp; i++) { 388 socklist[0] = socket(AF_UNIX, SOCK_STREAM, 0);
368 socklist[i] = socket(ai_tmp->ai_family, SOCK_DGRAM, IPPROTO_UDP); 389 if (socklist[0] == -1) {
369 if (socklist[i] == -1) { 390 DBG(printf("can't create socket: %s\n", strerror(errno)));
370 perror(NULL); 391 die(STATE_UNKNOWN, "can not create new socket\n");
371 die(STATE_UNKNOWN, "can not create new socket");
372 } 392 }
373 if (connect(socklist[i], ai_tmp->ai_addr, ai_tmp->ai_addrlen)) { 393
394 struct sockaddr_un unix_socket = {
395 .sun_family = AF_UNIX,
396 };
397
398 strncpy(unix_socket.sun_path, host, strlen(host));
399
400 if (connect(socklist[0], &unix_socket, sizeof(unix_socket))) {
374 /* don't die here, because it is enough if there is one server 401 /* don't die here, because it is enough if there is one server
375 answering in time. This also would break for dual ipv4/6 stacked 402 answering in time. This also would break for dual ipv4/6 stacked
376 ntp servers when the client only supports on of them. 403 ntp servers when the client only supports on of them.
377 */ 404 */
378 DBG(printf("can't create socket connection on peer %i: %s\n", i, strerror(errno))); 405 DBG(printf("can't create socket connection on peer %i: %s\n", 0, strerror(errno)));
379 } else { 406 } else {
380 ufds[i].fd = socklist[i]; 407 ufds[0].fd = socklist[0];
381 ufds[i].events = POLLIN; 408 ufds[0].events = POLLIN;
382 ufds[i].revents = 0; 409 ufds[0].revents = 0;
410 }
411 } else {
412 struct addrinfo *ai_tmp = addresses;
413 for (int i = 0; ai_tmp; i++) {
414 socklist[i] = socket(ai_tmp->ai_family, SOCK_DGRAM, IPPROTO_UDP);
415 if (socklist[i] == -1) {
416 perror(NULL);
417 die(STATE_UNKNOWN, "can not create new socket");
418 }
419 if (connect(socklist[i], ai_tmp->ai_addr, ai_tmp->ai_addrlen)) {
420 /* don't die here, because it is enough if there is one server
421 answering in time. This also would break for dual ipv4/6 stacked
422 ntp servers when the client only supports on of them.
423 */
424 DBG(printf("can't create socket connection on peer %i: %s\n", i, strerror(errno)));
425 } else {
426 ufds[i].fd = socklist[i];
427 ufds[i].events = POLLIN;
428 ufds[i].revents = 0;
429 }
430 ai_tmp = ai_tmp->ai_next;
383 } 431 }
384 ai_tmp = ai_tmp->ai_next;
385 } 432 }
386 433
387 /* now do AVG_NUM checks to each host. We stop before timeout/2 seconds 434 /* now do AVG_NUM checks to each host. We stop before timeout/2 seconds
@@ -389,7 +436,7 @@ double offset_request(const char *host, int *status) {
389 time_t start_ts = 0; 436 time_t start_ts = 0;
390 time_t now_time = 0; 437 time_t now_time = 0;
391 now_time = start_ts = time(NULL); 438 now_time = start_ts = time(NULL);
392 int servers_completed = 0; 439 size_t servers_completed = 0;
393 bool one_read = false; 440 bool one_read = false;
394 while (servers_completed < num_hosts && now_time - start_ts <= socket_timeout / 2) { 441 while (servers_completed < num_hosts && now_time - start_ts <= socket_timeout / 2) {
395 /* loop through each server and find each one which hasn't 442 /* loop through each server and find each one which hasn't
@@ -398,12 +445,14 @@ double offset_request(const char *host, int *status) {
398 * and update the "waiting" timestamp with the current time. */ 445 * and update the "waiting" timestamp with the current time. */
399 now_time = time(NULL); 446 now_time = time(NULL);
400 447
401 for (int i = 0; i < num_hosts; i++) { 448 for (size_t i = 0; i < num_hosts; i++) {
402 if (servers[i].waiting < now_time && servers[i].num_responses < AVG_NUM) { 449 if (servers[i].waiting < now_time && servers[i].num_responses < AVG_NUM) {
403 if (verbose && servers[i].waiting != 0) 450 if (verbose && servers[i].waiting != 0) {
404 printf("re-"); 451 printf("re-");
405 if (verbose) 452 }
406 printf("sending request to peer %d\n", i); 453 if (verbose) {
454 printf("sending request to peer %zu\n", i);
455 }
407 setup_request(&req[i]); 456 setup_request(&req[i]);
408 write(socklist[i], &req[i], sizeof(ntp_message)); 457 write(socklist[i], &req[i], sizeof(ntp_message));
409 servers[i].waiting = now_time; 458 servers[i].waiting = now_time;
@@ -419,10 +468,10 @@ double offset_request(const char *host, int *status) {
419 } 468 }
420 469
421 /* read from any sockets with pending data */ 470 /* read from any sockets with pending data */
422 for (int i = 0; servers_readable && i < num_hosts; i++) { 471 for (size_t i = 0; servers_readable && i < num_hosts; i++) {
423 if (ufds[i].revents & POLLIN && servers[i].num_responses < AVG_NUM) { 472 if (ufds[i].revents & POLLIN && servers[i].num_responses < AVG_NUM) {
424 if (verbose) { 473 if (verbose) {
425 printf("response from peer %d: ", i); 474 printf("response from peer %zu: ", i);
426 } 475 }
427 476
428 read(ufds[i].fd, &req[i], sizeof(ntp_message)); 477 read(ufds[i].fd, &req[i], sizeof(ntp_message));
@@ -442,23 +491,30 @@ double offset_request(const char *host, int *status) {
442 servers[i].flags = req[i].flags; 491 servers[i].flags = req[i].flags;
443 servers_readable--; 492 servers_readable--;
444 one_read = true; 493 one_read = true;
445 if (servers[i].num_responses == AVG_NUM) 494 if (servers[i].num_responses == AVG_NUM) {
446 servers_completed++; 495 servers_completed++;
496 }
447 } 497 }
448 } 498 }
449 /* lather, rinse, repeat. */ 499 /* lather, rinse, repeat. */
450 } 500 }
451 501
452 if (one_read == false) { 502 if (!one_read) {
453 die(STATE_CRITICAL, "NTP CRITICAL: No response from NTP server\n"); 503 die(STATE_CRITICAL, "NTP CRITICAL: No response from NTP server\n");
454 } 504 }
455 505
506 offset_request_wrapper result = {
507 .offset = 0,
508 .offset_result = STATE_UNKNOWN,
509 };
510
456 /* now, pick the best server from the list */ 511 /* now, pick the best server from the list */
457 double avg_offset = 0.; 512 double avg_offset = 0.;
458 int best_index = best_offset_server(servers, num_hosts); 513 int best_index = best_offset_server(servers, num_hosts);
459 if (best_index < 0) { 514 if (best_index < 0) {
460 *status = STATE_UNKNOWN; 515 result.offset_result = STATE_UNKNOWN;
461 } else { 516 } else {
517 result.offset_result = STATE_OK;
462 /* finally, calculate the average offset */ 518 /* finally, calculate the average offset */
463 for (int i = 0; i < servers[best_index].num_responses; i++) { 519 for (int i = 0; i < servers[best_index].num_responses; i++) {
464 avg_offset += servers[best_index].offset[i]; 520 avg_offset += servers[best_index].offset[i];
@@ -467,45 +523,72 @@ double offset_request(const char *host, int *status) {
467 } 523 }
468 524
469 /* cleanup */ 525 /* cleanup */
470 for (int j = 0; j < num_hosts; j++) { 526 for (size_t j = 0; j < num_hosts; j++) {
471 close(socklist[j]); 527 close(socklist[j]);
472 } 528 }
473 free(socklist); 529 free(socklist);
474 free(ufds); 530 free(ufds);
475 free(servers); 531 free(servers);
476 free(req); 532 free(req);
477 freeaddrinfo(ai); 533 freeaddrinfo(addresses);
478 534
479 if (verbose) 535 if (verbose) {
480 printf("overall average offset: %.10g\n", avg_offset); 536 printf("overall average offset: %.10g\n", avg_offset);
481 return avg_offset; 537 }
538
539 result.offset = avg_offset;
540 return result;
482} 541}
483 542
484int process_arguments(int argc, char **argv) { 543static check_ntp_time_config_wrapper process_arguments(int argc, char **argv) {
544
545 enum {
546 output_format_index = CHAR_MAX + 1,
547 };
548
485 static struct option longopts[] = {{"version", no_argument, 0, 'V'}, 549 static struct option longopts[] = {{"version", no_argument, 0, 'V'},
486 {"help", no_argument, 0, 'h'}, 550 {"help", no_argument, 0, 'h'},
487 {"verbose", no_argument, 0, 'v'}, 551 {"verbose", no_argument, 0, 'v'},
488 {"use-ipv4", no_argument, 0, '4'}, 552 {"use-ipv4", no_argument, 0, '4'},
489 {"use-ipv6", no_argument, 0, '6'}, 553 {"use-ipv6", no_argument, 0, '6'},
490 {"quiet", no_argument, 0, 'q'}, 554 {"quiet", no_argument, 0, 'q'},
491 {"time-offset", optional_argument, 0, 'o'}, 555 {"time-offset", required_argument, 0, 'o'},
492 {"warning", required_argument, 0, 'w'}, 556 {"warning", required_argument, 0, 'w'},
493 {"critical", required_argument, 0, 'c'}, 557 {"critical", required_argument, 0, 'c'},
494 {"timeout", required_argument, 0, 't'}, 558 {"timeout", required_argument, 0, 't'},
495 {"hostname", required_argument, 0, 'H'}, 559 {"hostname", required_argument, 0, 'H'},
496 {"port", required_argument, 0, 'p'}, 560 {"port", required_argument, 0, 'p'},
561 {"output-format", required_argument, 0, output_format_index},
497 {0, 0, 0, 0}}; 562 {0, 0, 0, 0}};
498 563
499 if (argc < 2) 564 if (argc < 2) {
500 usage("\n"); 565 usage("\n");
566 }
567
568 check_ntp_time_config_wrapper result = {
569 .errorcode = OK,
570 .config = check_ntp_time_config_init(),
571 };
501 572
502 while (true) { 573 while (true) {
503 int option = 0; 574 int option = 0;
504 int option_char = getopt_long(argc, argv, "Vhv46qw:c:t:H:p:o:", longopts, &option); 575 int option_char = getopt_long(argc, argv, "Vhv46qw:c:t:H:p:o:", longopts, &option);
505 if (option_char == -1 || option_char == EOF || option_char == 1) 576 if (option_char == -1 || option_char == EOF || option_char == 1) {
506 break; 577 break;
578 }
507 579
508 switch (option_char) { 580 switch (option_char) {
581 case output_format_index: {
582 parsed_output_format parser = mp_parse_output_format(optarg);
583 if (!parser.parsing_success) {
584 printf("Invalid output format: %s\n", optarg);
585 exit(STATE_UNKNOWN);
586 }
587
588 result.config.output_format_is_set = true;
589 result.config.output_format = parser.output_format;
590 break;
591 }
509 case 'h': 592 case 'h':
510 print_help(); 593 print_help();
511 exit(STATE_UNKNOWN); 594 exit(STATE_UNKNOWN);
@@ -518,27 +601,40 @@ int process_arguments(int argc, char **argv) {
518 verbose++; 601 verbose++;
519 break; 602 break;
520 case 'q': 603 case 'q':
521 quiet = true; 604 result.config.quiet = true;
522 break;
523 case 'w':
524 owarn = optarg;
525 break;
526 case 'c':
527 ocrit = optarg;
528 break; 605 break;
606 case 'w': {
607 mp_range_parsed tmp = mp_parse_range_string(optarg);
608 if (tmp.error != MP_PARSING_SUCCES) {
609 die(STATE_UNKNOWN, "failed to parse warning threshold");
610 }
611
612 result.config.offset_thresholds =
613 mp_thresholds_set_warn(result.config.offset_thresholds, tmp.range);
614 } break;
615 case 'c': {
616 mp_range_parsed tmp = mp_parse_range_string(optarg);
617 if (tmp.error != MP_PARSING_SUCCES) {
618 die(STATE_UNKNOWN, "failed to parse crit threshold");
619 }
620
621 result.config.offset_thresholds =
622 mp_thresholds_set_crit(result.config.offset_thresholds, tmp.range);
623 } break;
529 case 'H': 624 case 'H':
530 if (!is_host(optarg)) 625 if (!is_host(optarg) && (optarg[0] != '/')) {
531 usage2(_("Invalid hostname/address"), optarg); 626 usage2(_("Invalid hostname/address"), optarg);
532 server_address = strdup(optarg); 627 }
628 result.config.server_address = strdup(optarg);
533 break; 629 break;
534 case 'p': 630 case 'p':
535 port = strdup(optarg); 631 result.config.port = strdup(optarg);
536 break; 632 break;
537 case 't': 633 case 't':
538 socket_timeout = atoi(optarg); 634 socket_timeout = atoi(optarg);
539 break; 635 break;
540 case 'o': 636 case 'o':
541 time_offset = atoi(optarg); 637 result.config.time_offset = atoi(optarg);
542 break; 638 break;
543 case '4': 639 case '4':
544 address_family = AF_INET; 640 address_family = AF_INET;
@@ -557,16 +653,11 @@ int process_arguments(int argc, char **argv) {
557 } 653 }
558 } 654 }
559 655
560 if (server_address == NULL) { 656 if (result.config.server_address == NULL) {
561 usage4(_("Hostname was not supplied")); 657 usage4(_("Hostname was not supplied"));
562 } 658 }
563 659
564 return 0; 660 return result;
565}
566
567char *perfd_offset(double offset) {
568 return fperfdata("offset", offset, "s", true, offset_thresholds->warning->end, true, offset_thresholds->critical->end, false, 0, false,
569 0);
570} 661}
571 662
572int main(int argc, char *argv[]) { 663int main(int argc, char *argv[]) {
@@ -577,10 +668,17 @@ int main(int argc, char *argv[]) {
577 /* Parse extra opts if any */ 668 /* Parse extra opts if any */
578 argv = np_extra_opts(&argc, argv, progname); 669 argv = np_extra_opts(&argc, argv, progname);
579 670
580 if (process_arguments(argc, argv) == ERROR) 671 check_ntp_time_config_wrapper tmp_config = process_arguments(argc, argv);
672
673 if (tmp_config.errorcode == ERROR) {
581 usage4(_("Could not parse arguments")); 674 usage4(_("Could not parse arguments"));
675 }
676
677 const check_ntp_time_config config = tmp_config.config;
582 678
583 set_thresholds(&offset_thresholds, owarn, ocrit); 679 if (config.output_format_is_set) {
680 mp_set_format(config.output_format);
681 }
584 682
585 /* initialize alarm signal handling */ 683 /* initialize alarm signal handling */
586 signal(SIGALRM, socket_timeout_alarm_handler); 684 signal(SIGALRM, socket_timeout_alarm_handler);
@@ -588,44 +686,37 @@ int main(int argc, char *argv[]) {
588 /* set socket timeout */ 686 /* set socket timeout */
589 alarm(socket_timeout); 687 alarm(socket_timeout);
590 688
591 int offset_result = STATE_OK; 689 mp_check overall = mp_check_init();
592 int result = STATE_OK;
593 double offset = offset_request(server_address, &offset_result);
594 if (offset_result == STATE_UNKNOWN) {
595 result = ((!quiet) ? STATE_UNKNOWN : STATE_CRITICAL);
596 } else {
597 result = get_status(fabs(offset), offset_thresholds);
598 }
599 690
600 char *result_line; 691 mp_subcheck sc_offset = mp_subcheck_init();
601 switch (result) { 692 offset_request_wrapper offset_result =
602 case STATE_CRITICAL: 693 offset_request(config.server_address, config.port, config.time_offset);
603 xasprintf(&result_line, _("NTP CRITICAL:"));
604 break;
605 case STATE_WARNING:
606 xasprintf(&result_line, _("NTP WARNING:"));
607 break;
608 case STATE_OK:
609 xasprintf(&result_line, _("NTP OK:"));
610 break;
611 default:
612 xasprintf(&result_line, _("NTP UNKNOWN:"));
613 break;
614 }
615 694
616 char *perfdata_line; 695 if (offset_result.offset_result == STATE_UNKNOWN) {
617 if (offset_result == STATE_UNKNOWN) { 696 sc_offset =
618 xasprintf(&result_line, "%s %s", result_line, _("Offset unknown")); 697 mp_set_subcheck_state(sc_offset, (!config.quiet) ? STATE_UNKNOWN : STATE_CRITICAL);
619 xasprintf(&perfdata_line, ""); 698 xasprintf(&sc_offset.output, "Offset unknown");
620 } else { 699 mp_add_subcheck_to_check(&overall, sc_offset);
621 xasprintf(&result_line, "%s %s %.10g secs", result_line, _("Offset"), offset); 700 mp_exit(overall);
622 xasprintf(&perfdata_line, "%s", perfd_offset(offset));
623 } 701 }
624 printf("%s|%s\n", result_line, perfdata_line);
625 702
626 if (server_address != NULL) 703 xasprintf(&sc_offset.output, "Offset: %.6fs", offset_result.offset);
627 free(server_address); 704
628 return result; 705 mp_perfdata pd_offset = perfdata_init();
706 pd_offset = mp_set_pd_value(pd_offset, fabs(offset_result.offset));
707 pd_offset.label = "offset";
708 pd_offset.uom = "s";
709 pd_offset = mp_pd_set_thresholds(pd_offset, config.offset_thresholds);
710
711 sc_offset = mp_set_subcheck_state(sc_offset, mp_get_pd_status(pd_offset));
712
713 mp_add_perfdata_to_subcheck(&sc_offset, pd_offset);
714 mp_add_subcheck_to_check(&overall, sc_offset);
715
716 if (config.server_address != NULL) {
717 free(config.server_address);
718 }
719 mp_exit(overall);
629} 720}
630 721
631void print_help(void) { 722void print_help(void) {
@@ -649,10 +740,11 @@ void print_help(void) {
649 printf(" %s\n", _("Offset to result in warning status (seconds)")); 740 printf(" %s\n", _("Offset to result in warning status (seconds)"));
650 printf(" %s\n", "-c, --critical=THRESHOLD"); 741 printf(" %s\n", "-c, --critical=THRESHOLD");
651 printf(" %s\n", _("Offset to result in critical status (seconds)")); 742 printf(" %s\n", _("Offset to result in critical status (seconds)"));
652 printf(" %s\n", "-o, --time_offset=INTEGER"); 743 printf(" %s\n", "-o, --time-offset=INTEGER");
653 printf(" %s\n", _("Expected offset of the ntp server relative to local server (seconds)")); 744 printf(" %s\n", _("Expected offset of the ntp server relative to local server (seconds)"));
654 printf(UT_CONN_TIMEOUT, DEFAULT_SOCKET_TIMEOUT); 745 printf(UT_CONN_TIMEOUT, DEFAULT_SOCKET_TIMEOUT);
655 printf(UT_VERBOSE); 746 printf(UT_VERBOSE);
747 printf(UT_OUTPUT_FORMAT);
656 748
657 printf("\n"); 749 printf("\n");
658 printf("%s\n", _("This plugin checks the clock offset between the local host and a")); 750 printf("%s\n", _("This plugin checks the clock offset between the local host and a"));
@@ -677,5 +769,6 @@ void print_help(void) {
677 769
678void print_usage(void) { 770void print_usage(void) {
679 printf("%s\n", _("Usage:")); 771 printf("%s\n", _("Usage:"));
680 printf(" %s -H <host> [-4|-6] [-w <warn>] [-c <crit>] [-v verbose] [-o <time offset>]\n", progname); 772 printf(" %s -H <host> [-4|-6] [-w <warn>] [-c <crit>] [-v verbose] [-o <time offset>]\n",
773 progname);
681} 774}