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