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