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