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