Merge pull request #3329 from efuss/fix-3311
[collectd.git] / src / chrony.c
1 /* chrony plugin for collectd (monitoring of chrony time server daemon)
2  **********************************************************************
3  * Copyright (C) Claudius M Zingerli, ZSeng, 2015-2016
4  *
5  * Internals roughly based on the ntpd plugin
6  * Some functions copied from chronyd/web (as marked)
7  *
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of version 2 of the GNU General Public License as
10  * published by the Free Software Foundation.
11  *
12  * This program is distributed in the hope that it will be useful, but
13  * WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License along
18  * with this program; if not, write to the Free Software Foundation, Inc.,
19  * 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
20  *
21  * TODO:
22  *      - More robust udp parsing (using offsets instead of structs?)
23  *        -> Currently chrony parses its data the same way as we do (using
24  *structs)
25  *      - Plausibility checks on values received
26  *        -> Done at higher levels
27  */
28
29 #include "collectd.h"
30
31 #include "plugin.h"              /* plugin_register_*, plugin_dispatch_values */
32 #include "utils/common/common.h" /* auxiliary functions */
33
34 #if HAVE_NETDB_H
35 #include <netdb.h> /* struct addrinfo */
36 #endif
37 #if HAVE_ARPA_INET_H
38 #include <arpa/inet.h> /* ntohs/ntohl */
39 #endif
40
41 /* AIX doesn't have MSG_DONTWAIT */
42 #ifndef MSG_DONTWAIT
43 #define MSG_DONTWAIT MSG_NONBLOCK
44 #endif
45
46 #define CONFIG_KEY_HOST "Host"
47 #define CONFIG_KEY_PORT "Port"
48 #define CONFIG_KEY_TIMEOUT "Timeout"
49
50 #define URAND_DEVICE_PATH                                                      \
51   "/dev/urandom" /* Used to initialize seq nr generator */
52 #define RAND_DEVICE_PATH                                                       \
53   "/dev/random" /* Used to initialize seq nr generator (fall back) */
54
55 static const char *g_config_keys[] = {CONFIG_KEY_HOST, CONFIG_KEY_PORT,
56                                       CONFIG_KEY_TIMEOUT};
57
58 static int g_config_keys_num = STATIC_ARRAY_SIZE(g_config_keys);
59 static int g_chrony_is_connected;
60 static int g_chrony_socket = -1;
61 static time_t g_chrony_timeout = -1;
62 static char *g_chrony_plugin_instance;
63 static char *g_chrony_host;
64 static char *g_chrony_port;
65 static uint32_t g_chrony_rand = 1;
66 static uint32_t g_chrony_seq_is_initialized;
67
68 #define PLUGIN_NAME_SHORT "chrony"
69 #define PLUGIN_NAME PLUGIN_NAME_SHORT " plugin"
70 #define DAEMON_NAME PLUGIN_NAME_SHORT
71 #define CHRONY_DEFAULT_HOST "localhost"
72 #define CHRONY_DEFAULT_PORT "323"
73 #define CHRONY_DEFAULT_TIMEOUT 2
74
75 /* Return codes (collectd expects non-zero on errors) */
76 #define CHRONY_RC_OK 0
77 #define CHRONY_RC_FAIL 1
78
79 /* Chronyd command packet variables adapted from chrony/candm.h (GPL2) */
80 #define PROTO_VERSION_NUMBER 6
81 #define IPADDR_UNSPEC 0
82 #define IPADDR_INET4 1
83 #define IPADDR_INET6 2
84 #define IPV6_STR_MAX_SIZE (8 * 4 + 7 + 1)
85 #define MODE_REFCLOCK 2
86
87 typedef enum { PKT_TYPE_CMD_REQUEST = 1, PKT_TYPE_CMD_REPLY = 2 } ePacketType;
88
89 typedef enum {
90   REQ_N_SOURCES = 14,
91   REQ_SOURCE_DATA = 15,
92   REQ_TRACKING = 33,
93   REQ_SOURCE_STATS = 34
94 } eDaemonRequests;
95
96 typedef enum {
97   RPY_NULL = 1,
98   RPY_N_SOURCES = 2,
99   RPY_SOURCE_DATA = 3,
100   RPY_MANUAL_TIMESTAMP = 4,
101   RPY_TRACKING = 5,
102   RPY_SOURCE_STATS = 6,
103   RPY_RTC = 7
104 } eDaemonReplies;
105
106 #if defined(__GNUC__) || defined(__SUNPRO_C) || defined(lint)
107 #/* extension to enforce struct packing. */
108 #define ATTRIB_PACKED __attribute__((packed))
109 #else
110 #error Not defining packed attribute (unknown compiler)
111 #define ATTRIB_PACKED
112 #endif
113
114 typedef struct ATTRIB_PACKED {
115   int32_t value;
116 } tFloat;
117
118 typedef struct ATTRIB_PACKED {
119   uint32_t tv_sec_high;
120   uint32_t tv_sec_low;
121   uint32_t tv_nsec;
122 } tTimeval;
123
124 typedef enum {
125   STT_SUCCESS = 0,
126   STT_FAILED = 1,
127   STT_UNAUTH = 2,
128   STT_INVALID = 3,
129   STT_NOSUCHSOURCE = 4,
130   STT_INVALIDTS = 5,
131   STT_NOTENABLED = 6,
132   STT_BADSUBNET = 7,
133   STT_ACCESSALLOWED = 8,
134   STT_ACCESSDENIED = 9,
135   STT_NOHOSTACCESS = 10,
136   STT_SOURCEALREADYKNOWN = 11,
137   STT_TOOMANYSOURCES = 12,
138   STT_NORTC = 13,
139   STT_BADRTCFILE = 14,
140   STT_INACTIVE = 15,
141   STT_BADSAMPLE = 16,
142   STT_INVALIDAF = 17,
143   STT_BADPKTVERSION = 18,
144   STT_BADPKTLENGTH = 19
145 } eChrony_Status;
146
147 /* Chrony client request packets */
148 typedef struct ATTRIB_PACKED {
149   uint8_t f_dummy0[80]; /* Chrony expects 80bytes dummy data (Avoiding UDP
150                            Amplification) */
151 } tChrony_Req_Tracking;
152
153 typedef struct ATTRIB_PACKED {
154   uint32_t f_n_sources;
155 } tChrony_Req_N_Sources;
156
157 typedef struct ATTRIB_PACKED {
158   int32_t f_index;
159   uint8_t f_dummy0[44];
160 } tChrony_Req_Source_data;
161
162 typedef struct ATTRIB_PACKED {
163   int32_t f_index;
164   uint8_t f_dummy0[56];
165 } tChrony_Req_Source_stats;
166
167 typedef struct ATTRIB_PACKED {
168   struct {
169     uint8_t f_version;
170     uint8_t f_type;
171     uint8_t f_dummy0;
172     uint8_t f_dummy1;
173     uint16_t f_cmd;
174     uint16_t f_cmd_try;
175     uint32_t f_seq;
176
177     uint32_t f_dummy2;
178     uint32_t f_dummy3;
179   } header; /* Packed: 20Bytes */
180   union {
181     tChrony_Req_N_Sources n_sources;
182     tChrony_Req_Source_data source_data;
183     tChrony_Req_Source_stats source_stats;
184     tChrony_Req_Tracking tracking;
185   } body;
186   uint8_t padding[4 + 16]; /* Padding to match minimal response size */
187 } tChrony_Request;
188
189 /* Chrony daemon response packets */
190 typedef struct ATTRIB_PACKED {
191   uint32_t f_n_sources;
192 } tChrony_Resp_N_Sources;
193
194 typedef struct ATTRIB_PACKED {
195   union {
196     uint32_t ip4;
197     uint8_t ip6[16];
198   } addr;
199   uint16_t f_family;
200   uint16_t padding;
201 } tChrony_IPAddr;
202
203 typedef struct ATTRIB_PACKED {
204   tChrony_IPAddr addr;
205   int16_t f_poll;     /* 2^f_poll = Time between polls (s) */
206   uint16_t f_stratum; /* Remote clock stratum */
207   uint16_t f_state;   /* 0 = RPY_SD_ST_SYNC,    1 = RPY_SD_ST_UNREACH,   2 =
208                          RPY_SD_ST_FALSETICKER */
209   /* 3 = RPY_SD_ST_JITTERY, 4 = RPY_SD_ST_CANDIDATE, 5 = RPY_SD_ST_OUTLIER */
210   uint16_t f_mode;  /* 0 = RPY_SD_MD_CLIENT,  1 = RPY_SD_MD_PEER,      2 =
211                        RPY_SD_MD_REF         */
212   uint16_t f_flags; /* unused */
213   uint16_t
214       f_reachability; /* Bit mask of successfull tries to reach the source */
215
216   uint32_t f_since_sample;     /* Time since last sample (s) */
217   tFloat f_origin_latest_meas; /*  */
218   tFloat f_latest_meas;        /*  */
219   tFloat f_latest_meas_err;    /*  */
220 } tChrony_Resp_Source_data;
221
222 typedef struct ATTRIB_PACKED {
223   uint32_t f_ref_id;
224   tChrony_IPAddr addr;
225   uint32_t f_n_samples;       /* Number of measurements done   */
226   uint32_t f_n_runs;          /* How many measurements to come */
227   uint32_t f_span_seconds;    /* For how long we're measuring  */
228   tFloat f_rtc_seconds_fast;  /* ??? */
229   tFloat f_rtc_gain_rate_ppm; /* Estimated relative frequency error */
230   tFloat f_skew_ppm;       /* Clock skew (ppm) (worst case freq est error (skew:
231                               peak2peak)) */
232   tFloat f_est_offset;     /* Estimated offset of source */
233   tFloat f_est_offset_err; /* Error of estimation        */
234 } tChrony_Resp_Source_stats;
235
236 typedef struct ATTRIB_PACKED {
237   uint32_t f_ref_id;
238   tChrony_IPAddr addr;
239   uint16_t f_stratum;
240   uint16_t f_leap_status;
241   tTimeval f_ref_time;
242   tFloat f_current_correction;
243   tFloat f_last_offset;
244   tFloat f_rms_offset;
245   tFloat f_freq_ppm;
246   tFloat f_resid_freq_ppm;
247   tFloat f_skew_ppm;
248   tFloat f_root_delay;
249   tFloat f_root_dispersion;
250   tFloat f_last_update_interval;
251 } tChrony_Resp_Tracking;
252
253 typedef struct ATTRIB_PACKED {
254   struct {
255     uint8_t f_version;
256     uint8_t f_type;
257     uint8_t f_dummy0;
258     uint8_t f_dummy1;
259     uint16_t f_cmd;
260     uint16_t f_reply;
261     uint16_t f_status;
262     uint16_t f_dummy2;
263     uint16_t f_dummy3;
264     uint16_t f_dummy4;
265     uint32_t f_seq;
266     uint32_t f_dummy5;
267     uint32_t f_dummy6;
268   } header; /* Packed: 28 Bytes */
269
270   union {
271     tChrony_Resp_N_Sources n_sources;
272     tChrony_Resp_Source_data source_data;
273     tChrony_Resp_Source_stats source_stats;
274     tChrony_Resp_Tracking tracking;
275   } body;
276
277   uint8_t padding[1024];
278 } tChrony_Response;
279
280 /*****************************************************************************/
281 /* Internal functions */
282 /*****************************************************************************/
283
284 /* connect_client code adapted from:
285  * http://long.ccaba.upc.edu/long/045Guidelines/eva/ipv6.html#daytimeClient6 */
286 /* License granted by Eva M Castro via e-mail on 2016-02-18 under the terms of
287  * GPLv3 */
288 static int connect_client(const char *p_hostname, const char *p_service,
289                           int p_family, int p_socktype) {
290   struct addrinfo *res, *ressave;
291   int n, sockfd;
292
293   struct addrinfo ai_hints = {.ai_family = p_family, .ai_socktype = p_socktype};
294
295   n = getaddrinfo(p_hostname, p_service, &ai_hints, &res);
296
297   if (n < 0) {
298     ERROR(PLUGIN_NAME ": getaddrinfo error:: [%s]", gai_strerror(n));
299     return -1;
300   }
301
302   ressave = res;
303
304   sockfd = -1;
305   while (res) {
306     sockfd = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
307
308     if (!(sockfd < 0)) {
309       if (connect(sockfd, res->ai_addr, res->ai_addrlen) == 0) {
310         /* Success */
311         break;
312       }
313
314       close(sockfd);
315       sockfd = -1;
316     }
317     res = res->ai_next;
318   }
319
320   freeaddrinfo(ressave);
321   return sockfd;
322 }
323
324 /* niptoha code originally from:
325  * git://git.tuxfamily.org/gitroot/chrony/chrony.git:util.c */
326 /* Original code licensed as GPLv2, by Richard P. Purnow, Miroslav Lichvar */
327 /* Original name: char * UTI_IPToString(IPAddr *addr)*/
328 static char *niptoha(const tChrony_IPAddr *addr, char *p_buf,
329                      size_t p_buf_size) {
330   int rc = 1;
331   unsigned long a, b, c, d, ip;
332
333   switch (ntohs(addr->f_family)) {
334   case IPADDR_UNSPEC:
335     rc = snprintf(p_buf, p_buf_size, "[UNSPEC]");
336     break;
337   case IPADDR_INET4:
338     ip = ntohl(addr->addr.ip4);
339     a = (ip >> 24) & 0xff;
340     b = (ip >> 16) & 0xff;
341     c = (ip >> 8) & 0xff;
342     d = (ip >> 0) & 0xff;
343     rc = snprintf(p_buf, p_buf_size, "%ld.%ld.%ld.%ld", a, b, c, d);
344     break;
345   case IPADDR_INET6: {
346     const char *rp = inet_ntop(AF_INET6, addr->addr.ip6, p_buf, p_buf_size);
347     if (rp == NULL) {
348       ERROR(PLUGIN_NAME ": Error converting ipv6 address to string. Errno = %d",
349             errno);
350       rc = snprintf(p_buf, p_buf_size, "[UNKNOWN]");
351     }
352     break;
353   }
354   default:
355     rc = snprintf(p_buf, p_buf_size, "[UNKNOWN]");
356   }
357   assert(rc > 0);
358   return p_buf;
359 }
360
361 static void nreftostr(uint32_t nrefid, char *p_buf, size_t p_buf_size) {
362   size_t j = 0;
363
364   for (int i = 0; i < 4; i++) {
365     int c = ntohl(nrefid) << i * 8 >> 24;
366     if (!isalnum(c) || j + 1 >= p_buf_size)
367       continue;
368     p_buf[j++] = c;
369   }
370   if (j < p_buf_size)
371     p_buf[j] = '\0';
372 }
373
374 static int chrony_set_timeout(void) {
375   /* Set the socket's  timeout to g_chrony_timeout; a value of 0 signals
376    * infinite timeout */
377   /* Returns 0 on success, !0 on error (check errno) */
378
379   struct timeval tv;
380   tv.tv_sec = g_chrony_timeout;
381   tv.tv_usec = 0;
382
383   assert(g_chrony_socket >= 0);
384   if (setsockopt(g_chrony_socket, SOL_SOCKET, SO_RCVTIMEO, (char *)&tv,
385                  sizeof(struct timeval)) < 0) {
386     return CHRONY_RC_FAIL;
387   }
388   return CHRONY_RC_OK;
389 }
390
391 static int chrony_connect(void) {
392   /* Connects to the chrony daemon */
393   /* Returns 0 on success, !0 on error (check errno) */
394   int socket;
395
396   if (g_chrony_host == NULL) {
397     g_chrony_host = strdup(CHRONY_DEFAULT_HOST);
398     if (g_chrony_host == NULL) {
399       ERROR(PLUGIN_NAME ": Error duplicating chrony host name");
400       return CHRONY_RC_FAIL;
401     }
402   }
403   if (g_chrony_port == NULL) {
404     g_chrony_port = strdup(CHRONY_DEFAULT_PORT);
405     if (g_chrony_port == NULL) {
406       ERROR(PLUGIN_NAME ": Error duplicating chrony port string");
407       return CHRONY_RC_FAIL;
408     }
409   }
410   if (g_chrony_timeout < 0) {
411     g_chrony_timeout = CHRONY_DEFAULT_TIMEOUT;
412     assert(g_chrony_timeout >= 0);
413   }
414
415   DEBUG(PLUGIN_NAME ": Connecting to %s:%s", g_chrony_host, g_chrony_port);
416   socket = connect_client(g_chrony_host, g_chrony_port, AF_UNSPEC, SOCK_DGRAM);
417   if (socket < 0) {
418     ERROR(PLUGIN_NAME ": Error connecting to daemon. Errno = %d", errno);
419     return CHRONY_RC_FAIL;
420   }
421   DEBUG(PLUGIN_NAME ": Connected");
422   g_chrony_socket = socket;
423
424   if (chrony_set_timeout()) {
425     ERROR(PLUGIN_NAME ": Error setting timeout to %llds. Errno = %d",
426           (long long)g_chrony_timeout, errno);
427     return CHRONY_RC_FAIL;
428   }
429   return CHRONY_RC_OK;
430 }
431
432 static int chrony_send_request(const tChrony_Request *p_req,
433                                size_t p_req_size) {
434   if (send(g_chrony_socket, p_req, p_req_size, 0) < 0) {
435     ERROR(PLUGIN_NAME ": Error sending packet. Errno = %d", errno);
436     return CHRONY_RC_FAIL;
437   }
438   return CHRONY_RC_OK;
439 }
440
441 static int chrony_recv_response(tChrony_Response *p_resp,
442                                 size_t p_resp_max_size, size_t *p_resp_size) {
443   ssize_t rc = recv(g_chrony_socket, p_resp, p_resp_max_size, 0);
444   if (rc <= 0) {
445     ERROR(PLUGIN_NAME ": Error receiving packet: %s (%d)", strerror(errno),
446           errno);
447     return CHRONY_RC_FAIL;
448   } else {
449     *p_resp_size = rc;
450     return CHRONY_RC_OK;
451   }
452 }
453
454 static void chrony_flush_recv_queue(void) {
455   char buf[1];
456
457   if (g_chrony_is_connected) {
458     while (recv(g_chrony_socket, buf, sizeof(buf), MSG_DONTWAIT) > 0)
459       ;
460   }
461 }
462
463 static int chrony_query(const int p_command, tChrony_Request *p_req,
464                         tChrony_Response *p_resp, size_t *p_resp_size) {
465   /* Check connection. We simply perform one try as collectd already handles
466    * retries */
467   assert(p_req);
468   assert(p_resp);
469   assert(p_resp_size);
470
471   if (g_chrony_is_connected == 0) {
472     if (chrony_connect() == CHRONY_RC_OK) {
473       g_chrony_is_connected = 1;
474     } else {
475       ERROR(PLUGIN_NAME ": Unable to connect. Errno = %d", errno);
476       return CHRONY_RC_FAIL;
477     }
478   }
479
480   do {
481     int valid_command = 0;
482     size_t req_size = sizeof(p_req->header) + sizeof(p_req->padding);
483     size_t resp_size = sizeof(p_resp->header);
484     uint16_t resp_code = RPY_NULL;
485     switch (p_command) {
486     case REQ_TRACKING:
487       req_size += sizeof(p_req->body.tracking);
488       resp_size += sizeof(p_resp->body.tracking);
489       resp_code = RPY_TRACKING;
490       valid_command = 1;
491       break;
492     case REQ_N_SOURCES:
493       req_size += sizeof(p_req->body.n_sources);
494       resp_size += sizeof(p_resp->body.n_sources);
495       resp_code = RPY_N_SOURCES;
496       valid_command = 1;
497       break;
498     case REQ_SOURCE_DATA:
499       req_size += sizeof(p_req->body.source_data);
500       resp_size += sizeof(p_resp->body.source_data);
501       resp_code = RPY_SOURCE_DATA;
502       valid_command = 1;
503       break;
504     case REQ_SOURCE_STATS:
505       req_size += sizeof(p_req->body.source_stats);
506       resp_size += sizeof(p_resp->body.source_stats);
507       resp_code = RPY_SOURCE_STATS;
508       valid_command = 1;
509       break;
510     default:
511       ERROR(PLUGIN_NAME ": Unknown request command (Was: %d)", p_command);
512       break;
513     }
514
515     if (valid_command == 0)
516       break;
517
518     uint32_t seq_nr = rand_r(&g_chrony_rand);
519     p_req->header.f_cmd = htons(p_command);
520     p_req->header.f_cmd_try = 0;
521     p_req->header.f_seq = seq_nr;
522
523     DEBUG(PLUGIN_NAME ": Sending request (.cmd = %d, .seq = %d)", p_command,
524           seq_nr);
525     if (chrony_send_request(p_req, req_size) != 0)
526       break;
527
528     DEBUG(PLUGIN_NAME ": Waiting for response");
529     if (chrony_recv_response(p_resp, resp_size, p_resp_size) != 0)
530       break;
531
532     DEBUG(PLUGIN_NAME ": Received response: .version = %u, .type = %u, .cmd = "
533                       "%u, .reply = %u, .status = %u, .seq = %u",
534           p_resp->header.f_version, p_resp->header.f_type,
535           ntohs(p_resp->header.f_cmd), ntohs(p_resp->header.f_reply),
536           ntohs(p_resp->header.f_status), p_resp->header.f_seq);
537
538     if (p_resp->header.f_version != p_req->header.f_version) {
539       ERROR(PLUGIN_NAME ": Wrong protocol version (Was: %d, expected: %d)",
540             p_resp->header.f_version, p_req->header.f_version);
541       return CHRONY_RC_FAIL;
542     }
543     if (p_resp->header.f_type != PKT_TYPE_CMD_REPLY) {
544       ERROR(PLUGIN_NAME ": Wrong packet type (Was: %d, expected: %d)",
545             p_resp->header.f_type, PKT_TYPE_CMD_REPLY);
546       return CHRONY_RC_FAIL;
547     }
548     if (p_resp->header.f_seq != seq_nr) {
549       /* FIXME: Implement sequence number handling */
550       ERROR(PLUGIN_NAME ": Unexpected sequence number (Was: %d, expected: %d)",
551             p_resp->header.f_seq, p_req->header.f_seq);
552       return CHRONY_RC_FAIL;
553     }
554     if (p_resp->header.f_cmd != p_req->header.f_cmd) {
555       ERROR(PLUGIN_NAME ": Wrong reply command (Was: %d, expected: %d)",
556             p_resp->header.f_cmd, p_req->header.f_cmd);
557       return CHRONY_RC_FAIL;
558     }
559
560     if (ntohs(p_resp->header.f_reply) != resp_code) {
561       ERROR(PLUGIN_NAME ": Wrong reply code (Was: %d, expected: %d)",
562             ntohs(p_resp->header.f_reply), resp_code);
563       return CHRONY_RC_FAIL;
564     }
565
566     switch (p_resp->header.f_status) {
567     case STT_SUCCESS:
568       DEBUG(PLUGIN_NAME ": Reply packet status STT_SUCCESS");
569       break;
570     default:
571       ERROR(PLUGIN_NAME
572             ": Reply packet contains error status: %d (expected: %d)",
573             p_resp->header.f_status, STT_SUCCESS);
574       return CHRONY_RC_FAIL;
575     }
576
577     /* Good result */
578     return CHRONY_RC_OK;
579   } while (0);
580
581   /* Some error occured */
582   return CHRONY_RC_FAIL;
583 }
584
585 static void chrony_init_req(tChrony_Request *p_req) {
586   memset(p_req, 0, sizeof(*p_req));
587   p_req->header.f_version = PROTO_VERSION_NUMBER;
588   p_req->header.f_type = PKT_TYPE_CMD_REQUEST;
589   p_req->header.f_dummy0 = 0;
590   p_req->header.f_dummy1 = 0;
591   p_req->header.f_dummy2 = 0;
592   p_req->header.f_dummy3 = 0;
593 }
594
595 /* ntohf code originally from:
596  * git://git.tuxfamily.org/gitroot/chrony/chrony.git:util.c */
597 /* Original code licensed as GPLv2, by Richard P. Purnow, Miroslav Lichvar */
598 /* Original name: double UTI_tFloatNetworkToHost(tFloat f) */
599 static double ntohf(tFloat p_float) {
600 /* Convert tFloat in Network-bit-order to double in host-bit-order */
601
602 #define FLOAT_EXP_BITS 7
603 #define FLOAT_EXP_MIN (-(1 << (FLOAT_EXP_BITS - 1)))
604 #define FLOAT_EXP_MAX (-FLOAT_EXP_MIN - 1)
605 #define FLOAT_COEF_BITS ((int)sizeof(int32_t) * 8 - FLOAT_EXP_BITS)
606 #define FLOAT_COEF_MIN (-(1 << (FLOAT_COEF_BITS - 1)))
607 #define FLOAT_COEF_MAX (-FLOAT_COEF_MIN - 1)
608
609   int32_t exp, coef;
610   uint32_t uval;
611
612   uval = ntohl(p_float.value);
613   exp = (uval >> FLOAT_COEF_BITS);
614   if (exp >= 1 << (FLOAT_EXP_BITS - 1))
615     exp -= 1 << FLOAT_EXP_BITS;
616   exp -= FLOAT_COEF_BITS;
617
618   /* coef = (x << FLOAT_EXP_BITS) >> FLOAT_EXP_BITS; */
619   coef = uval % (1U << FLOAT_COEF_BITS);
620   if (coef >= 1 << (FLOAT_COEF_BITS - 1))
621     coef -= 1 << FLOAT_COEF_BITS;
622
623   return coef * pow(2.0, exp);
624 }
625
626 static void chrony_push_data(const char *p_type, const char *p_type_inst,
627                              double p_value) {
628   value_list_t vl = VALUE_LIST_INIT;
629
630   vl.values = &(value_t){.gauge = p_value};
631   vl.values_len = 1;
632
633   /* XXX: Shall g_chrony_host/g_chrony_port be reflected in the plugin's output?
634    */
635   sstrncpy(vl.plugin, PLUGIN_NAME_SHORT, sizeof(vl.plugin));
636   if (g_chrony_plugin_instance != NULL) {
637     sstrncpy(vl.plugin_instance, g_chrony_plugin_instance,
638              sizeof(vl.plugin_instance));
639   }
640   if (p_type != NULL)
641     sstrncpy(vl.type, p_type, sizeof(vl.type));
642
643   if (p_type_inst != NULL)
644     sstrncpy(vl.type_instance, p_type_inst, sizeof(vl.type_instance));
645
646   plugin_dispatch_values(&vl);
647 }
648
649 static void chrony_push_data_valid(const char *p_type, const char *p_type_inst,
650                                    const int p_is_valid, double p_value) {
651   /* Push real value if p_is_valid is true, push NAN if p_is_valid is not true
652    * (idea from ntp plugin) */
653   if (p_is_valid == 0)
654     p_value = NAN;
655
656   chrony_push_data(p_type, p_type_inst, p_value);
657 }
658
659 static int chrony_init_seq(void) {
660   /* Initialize the sequence number generator from /dev/urandom */
661   /* Fallbacks: /dev/random and time(NULL) */
662
663   int fh;
664
665   /* Try urandom */
666   fh = open(URAND_DEVICE_PATH, O_RDONLY);
667   if (fh >= 0) {
668     ssize_t rc = read(fh, &g_chrony_rand, sizeof(g_chrony_rand));
669     if (rc != sizeof(g_chrony_rand)) {
670       ERROR(PLUGIN_NAME ": Reading from random source \'%s\'failed: %s (%d)",
671             URAND_DEVICE_PATH, strerror(errno), errno);
672       close(fh);
673       return CHRONY_RC_FAIL;
674     }
675     close(fh);
676     DEBUG(PLUGIN_NAME ": Seeding RNG from " URAND_DEVICE_PATH);
677   } else {
678     if (errno == ENOENT) {
679       /* URAND_DEVICE_PATH device not found. Try RAND_DEVICE_PATH as fall-back
680        */
681       fh = open(RAND_DEVICE_PATH, O_RDONLY);
682       if (fh >= 0) {
683         ssize_t rc = read(fh, &g_chrony_rand, sizeof(g_chrony_rand));
684         if (rc != sizeof(g_chrony_rand)) {
685           ERROR(PLUGIN_NAME
686                 ": Reading from random source \'%s\'failed: %s (%d)",
687                 RAND_DEVICE_PATH, strerror(errno), errno);
688           close(fh);
689           return CHRONY_RC_FAIL;
690         }
691         close(fh);
692         DEBUG(PLUGIN_NAME ": Seeding RNG from " RAND_DEVICE_PATH);
693       } else {
694         /* Error opening RAND_DEVICE_PATH. Try time(NULL) as fall-back */
695         DEBUG(PLUGIN_NAME ": Seeding RNG from time(NULL)");
696         g_chrony_rand = time(NULL) ^ getpid();
697       }
698     } else {
699       ERROR(PLUGIN_NAME ": Opening random source \'%s\' failed: %s (%d)",
700             URAND_DEVICE_PATH, strerror(errno), errno);
701       return CHRONY_RC_FAIL;
702     }
703   }
704
705   return CHRONY_RC_OK;
706 }
707
708 /*****************************************************************************/
709 /* Exported functions */
710 /*****************************************************************************/
711 static int chrony_config(const char *p_key, const char *p_value) {
712   assert(p_key);
713   assert(p_value);
714
715   /* Parse config variables */
716   if (strcasecmp(p_key, CONFIG_KEY_HOST) == 0) {
717     if (g_chrony_host != NULL)
718       free(g_chrony_host);
719
720     if ((g_chrony_host = strdup(p_value)) == NULL) {
721       ERROR(PLUGIN_NAME ": Error duplicating host name");
722       return CHRONY_RC_FAIL;
723     }
724   } else {
725     if (strcasecmp(p_key, CONFIG_KEY_PORT) == 0) {
726       if (g_chrony_port != NULL)
727         free(g_chrony_port);
728
729       if ((g_chrony_port = strdup(p_value)) == NULL) {
730         ERROR(PLUGIN_NAME ": Error duplicating port name");
731         return CHRONY_RC_FAIL;
732       }
733     } else {
734       if (strcasecmp(p_key, CONFIG_KEY_TIMEOUT) == 0) {
735         time_t tosec = strtol(p_value, NULL, 0);
736         g_chrony_timeout = tosec;
737       } else {
738         WARNING(PLUGIN_NAME ": Unknown configuration variable: %s %s", p_key,
739                 p_value);
740         return CHRONY_RC_FAIL;
741       }
742     }
743   }
744   /* XXX: We could set g_chrony_plugin_instance here to
745    * "g_chrony_host-g_chrony_port", but as multiple instances aren't yet
746    * supported, we skip this for now */
747
748   return CHRONY_RC_OK;
749 }
750
751 static int chrony_request_daemon_stats(void) {
752   /* Perform Tracking request */
753   int rc;
754   size_t chrony_resp_size;
755   tChrony_Request chrony_req;
756   tChrony_Response chrony_resp;
757
758   chrony_init_req(&chrony_req);
759   rc = chrony_query(REQ_TRACKING, &chrony_req, &chrony_resp, &chrony_resp_size);
760   if (rc != 0) {
761     ERROR(PLUGIN_NAME ": chrony_query (REQ_TRACKING) failed with status %i",
762           rc);
763     return rc;
764   }
765 #if COLLECT_DEBUG
766   {
767     char src_addr[IPV6_STR_MAX_SIZE] = {0};
768     niptoha(&chrony_resp.body.tracking.addr, src_addr, sizeof(src_addr));
769     DEBUG(PLUGIN_NAME
770           ": Daemon stat: .addr = %s, .ref_id= %u, .stratum = %u, .leap_status "
771           "= %u, .ref_time = %u:%u:%u, .current_correction = %f, .last_offset "
772           "= %f, .rms_offset = %f, .freq_ppm = %f, .skew_ppm = %f, .root_delay "
773           "= %f, .root_dispersion = %f, .last_update_interval = %f",
774           src_addr, ntohs(chrony_resp.body.tracking.f_ref_id),
775           ntohs(chrony_resp.body.tracking.f_stratum),
776           ntohs(chrony_resp.body.tracking.f_leap_status),
777           ntohl(chrony_resp.body.tracking.f_ref_time.tv_sec_high),
778           ntohl(chrony_resp.body.tracking.f_ref_time.tv_sec_low),
779           ntohl(chrony_resp.body.tracking.f_ref_time.tv_nsec),
780           ntohf(chrony_resp.body.tracking.f_current_correction),
781           ntohf(chrony_resp.body.tracking.f_last_offset),
782           ntohf(chrony_resp.body.tracking.f_rms_offset),
783           ntohf(chrony_resp.body.tracking.f_freq_ppm),
784           ntohf(chrony_resp.body.tracking.f_skew_ppm),
785           ntohf(chrony_resp.body.tracking.f_root_delay),
786           ntohf(chrony_resp.body.tracking.f_root_dispersion),
787           ntohf(chrony_resp.body.tracking.f_last_update_interval));
788   }
789 #endif
790
791   double time_ref = ntohl(chrony_resp.body.tracking.f_ref_time.tv_nsec);
792   time_ref /= 1000000000.0;
793   time_ref += ntohl(chrony_resp.body.tracking.f_ref_time.tv_sec_low);
794   if (chrony_resp.body.tracking.f_ref_time.tv_sec_high) {
795     double secs_high = ntohl(chrony_resp.body.tracking.f_ref_time.tv_sec_high);
796     secs_high *= 4294967296.0;
797     time_ref += secs_high;
798   }
799
800   /* Forward results to collectd-daemon */
801   /* Type_instance is always 'chrony' to tag daemon-wide data */
802   /*                Type                Type_instan  Value */
803   chrony_push_data("clock_stratum", DAEMON_NAME,
804                    ntohs(chrony_resp.body.tracking.f_stratum));
805   chrony_push_data("time_ref", DAEMON_NAME, time_ref); /* unit: s */
806   chrony_push_data(
807       "time_offset_ntp", DAEMON_NAME,
808       ntohf(chrony_resp.body.tracking.f_current_correction)); /* Offset between
809                                                                  system time and
810                                                                  NTP, unit: s */
811   chrony_push_data(
812       "time_offset", DAEMON_NAME,
813       ntohf(
814           chrony_resp.body.tracking
815               .f_last_offset)); /* Estimated Offset of the NTP time, unit: s */
816   chrony_push_data(
817       "time_offset_rms", DAEMON_NAME,
818       ntohf(chrony_resp.body.tracking
819                 .f_rms_offset)); /* averaged value of the above, unit: s */
820   chrony_push_data(
821       "frequency_error", DAEMON_NAME,
822       ntohf(chrony_resp.body.tracking
823                 .f_freq_ppm)); /* Frequency error of the local osc, unit: ppm */
824   chrony_push_data("clock_skew_ppm", DAEMON_NAME,
825                    ntohf(chrony_resp.body.tracking.f_skew_ppm));
826   chrony_push_data(
827       "root_delay", DAEMON_NAME,
828       ntohf(chrony_resp.body.tracking.f_root_delay)); /* Network latency between
829                                                          local daemon and the
830                                                          current source */
831   chrony_push_data("root_dispersion", DAEMON_NAME,
832                    ntohf(chrony_resp.body.tracking.f_root_dispersion));
833   chrony_push_data("clock_last_update", DAEMON_NAME,
834                    ntohf(chrony_resp.body.tracking.f_last_update_interval));
835
836   return CHRONY_RC_OK;
837 }
838
839 static int chrony_request_sources_count(unsigned int *p_count) {
840   /* Requests the number of time sources from the chrony daemon */
841   int rc;
842   size_t chrony_resp_size;
843   tChrony_Request chrony_req;
844   tChrony_Response chrony_resp;
845
846   DEBUG(PLUGIN_NAME ": Requesting data");
847   chrony_init_req(&chrony_req);
848   rc =
849       chrony_query(REQ_N_SOURCES, &chrony_req, &chrony_resp, &chrony_resp_size);
850   if (rc != 0) {
851     ERROR(PLUGIN_NAME ": chrony_query (REQ_N_SOURCES) failed with status %i",
852           rc);
853     return rc;
854   }
855
856   *p_count = ntohl(chrony_resp.body.n_sources.f_n_sources);
857   DEBUG(PLUGIN_NAME ": Getting data of %d clock sources", *p_count);
858
859   return CHRONY_RC_OK;
860 }
861
862 static int chrony_request_source_data(int p_src_idx, char *src_addr,
863                                       size_t addr_size, int *p_is_reachable) {
864   /* Perform Source data request for source #p_src_idx */
865   int rc;
866   size_t chrony_resp_size;
867   tChrony_Request chrony_req;
868   tChrony_Response chrony_resp;
869
870   chrony_init_req(&chrony_req);
871   chrony_req.body.source_data.f_index = htonl(p_src_idx);
872   rc = chrony_query(REQ_SOURCE_DATA, &chrony_req, &chrony_resp,
873                     &chrony_resp_size);
874   if (rc != 0) {
875     ERROR(PLUGIN_NAME ": chrony_query (REQ_SOURCE_DATA) failed with status %i",
876           rc);
877     return rc;
878   }
879
880   if (ntohs(chrony_resp.body.source_data.f_mode) == MODE_REFCLOCK)
881     nreftostr(chrony_resp.body.source_data.addr.addr.ip4, src_addr, addr_size);
882   else
883     niptoha(&chrony_resp.body.source_data.addr, src_addr, addr_size);
884
885   DEBUG(PLUGIN_NAME ": Source[%d] data: .addr = %s, .poll = %u, .stratum = %u, "
886                     ".state = %u, .mode = %u, .flags = %u, .reach = %u, "
887                     ".latest_meas_ago = %u, .orig_latest_meas = %f, "
888                     ".latest_meas = %f, .latest_meas_err = %f",
889         p_src_idx, src_addr, ntohs(chrony_resp.body.source_data.f_poll),
890         ntohs(chrony_resp.body.source_data.f_stratum),
891         ntohs(chrony_resp.body.source_data.f_state),
892         ntohs(chrony_resp.body.source_data.f_mode),
893         ntohs(chrony_resp.body.source_data.f_flags),
894         ntohs(chrony_resp.body.source_data.f_reachability),
895         ntohl(chrony_resp.body.source_data.f_since_sample),
896         ntohf(chrony_resp.body.source_data.f_origin_latest_meas),
897         ntohf(chrony_resp.body.source_data.f_latest_meas),
898         ntohf(chrony_resp.body.source_data.f_latest_meas_err));
899
900   /* Push NaN if source is currently not reachable */
901   int is_reachable = ntohs(chrony_resp.body.source_data.f_reachability) & 0x01;
902   *p_is_reachable = is_reachable;
903
904   /* Forward results to collectd-daemon */
905   chrony_push_data_valid("clock_stratum", src_addr, is_reachable,
906                          ntohs(chrony_resp.body.source_data.f_stratum));
907   chrony_push_data_valid("clock_state", src_addr, is_reachable,
908                          ntohs(chrony_resp.body.source_data.f_state));
909   chrony_push_data_valid("clock_mode", src_addr, is_reachable,
910                          ntohs(chrony_resp.body.source_data.f_mode));
911   chrony_push_data_valid("clock_reachability", src_addr, is_reachable,
912                          ntohs(chrony_resp.body.source_data.f_reachability));
913   chrony_push_data_valid("clock_last_meas", src_addr, is_reachable,
914                          ntohl(chrony_resp.body.source_data.f_since_sample));
915   chrony_push_data_valid(
916       "time_offset", src_addr, is_reachable,
917       ntohf(chrony_resp.body.source_data.f_origin_latest_meas));
918
919   return CHRONY_RC_OK;
920 }
921
922 static int chrony_request_source_stats(int p_src_idx, const char *src_addr,
923                                        const int *p_is_reachable) {
924   /* Perform Source stats request for source #p_src_idx */
925   int rc;
926   size_t chrony_resp_size;
927   tChrony_Request chrony_req;
928   tChrony_Response chrony_resp;
929   double skew_ppm, frequency_error;
930
931   if (*p_is_reachable == 0) {
932     skew_ppm = 0;
933     frequency_error = 0;
934   } else {
935     chrony_init_req(&chrony_req);
936     chrony_req.body.source_stats.f_index = htonl(p_src_idx);
937     rc = chrony_query(REQ_SOURCE_STATS, &chrony_req, &chrony_resp,
938                       &chrony_resp_size);
939     if (rc != 0) {
940       ERROR(PLUGIN_NAME
941             ": chrony_query (REQ_SOURCE_STATS) failed with status %i",
942             rc);
943       return rc;
944     }
945
946     skew_ppm = ntohf(chrony_resp.body.source_stats.f_skew_ppm);
947     frequency_error = ntohf(chrony_resp.body.source_stats.f_rtc_gain_rate_ppm);
948
949     DEBUG(PLUGIN_NAME
950           ": Source[%d] stat: .addr = %s, .ref_id= %u, .n_samples = %u, "
951           ".n_runs = %u, .span_seconds = %u, .rtc_seconds_fast = %f, "
952           ".rtc_gain_rate_ppm = %f, .skew_ppm= %f, .est_offset = %f, "
953           ".est_offset_err = %f",
954           p_src_idx, src_addr, ntohl(chrony_resp.body.source_stats.f_ref_id),
955           ntohl(chrony_resp.body.source_stats.f_n_samples),
956           ntohl(chrony_resp.body.source_stats.f_n_runs),
957           ntohl(chrony_resp.body.source_stats.f_span_seconds),
958           ntohf(chrony_resp.body.source_stats.f_rtc_seconds_fast),
959           frequency_error, skew_ppm,
960           ntohf(chrony_resp.body.source_stats.f_est_offset),
961           ntohf(chrony_resp.body.source_stats.f_est_offset_err));
962
963   } /* if (*is_reachable) */
964
965   /* Forward results to collectd-daemon */
966   chrony_push_data_valid("clock_skew_ppm", src_addr, *p_is_reachable, skew_ppm);
967   chrony_push_data_valid("frequency_error", src_addr, *p_is_reachable,
968                          frequency_error); /* unit: ppm */
969
970   return CHRONY_RC_OK;
971 }
972
973 static int chrony_read(void) {
974   /* collectd read callback: Perform data acquisition */
975   int rc;
976   unsigned int n_sources;
977
978   if (g_chrony_seq_is_initialized == 0) {
979     /* Seed RNG for sequence number generation */
980     rc = chrony_init_seq();
981     if (rc != CHRONY_RC_OK)
982       return rc;
983
984     g_chrony_seq_is_initialized = 1;
985   }
986
987   /* Ignore late responses that may have been received */
988   chrony_flush_recv_queue();
989
990   /* Get daemon stats */
991   rc = chrony_request_daemon_stats();
992   if (rc != CHRONY_RC_OK)
993     return rc;
994
995   /* Get number of time sources, then check every source for status */
996   rc = chrony_request_sources_count(&n_sources);
997   if (rc != CHRONY_RC_OK)
998     return rc;
999
1000   for (unsigned int now_src = 0; now_src < n_sources; ++now_src) {
1001     char src_addr[IPV6_STR_MAX_SIZE] = {0};
1002     int is_reachable;
1003     rc = chrony_request_source_data(now_src, src_addr, sizeof(src_addr),
1004                                     &is_reachable);
1005     if (rc != CHRONY_RC_OK)
1006       return rc;
1007
1008     rc = chrony_request_source_stats(now_src, src_addr, &is_reachable);
1009     if (rc != CHRONY_RC_OK)
1010       return rc;
1011   }
1012   return CHRONY_RC_OK;
1013 }
1014
1015 static int chrony_shutdown(void) {
1016   /* Collectd shutdown callback: Free mem */
1017   if (g_chrony_is_connected != 0) {
1018     close(g_chrony_socket);
1019     g_chrony_is_connected = 0;
1020   }
1021   if (g_chrony_host != NULL)
1022     sfree(g_chrony_host);
1023
1024   if (g_chrony_port != NULL)
1025     sfree(g_chrony_port);
1026
1027   if (g_chrony_plugin_instance != NULL)
1028     sfree(g_chrony_plugin_instance);
1029
1030   return CHRONY_RC_OK;
1031 }
1032
1033 void module_register(void) {
1034   plugin_register_config(PLUGIN_NAME_SHORT, chrony_config, g_config_keys,
1035                          g_config_keys_num);
1036   plugin_register_read(PLUGIN_NAME_SHORT, chrony_read);
1037   plugin_register_shutdown(PLUGIN_NAME_SHORT, chrony_shutdown);
1038 }