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