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