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