Merge pull request #1821 from rubenk/memset
[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 = { 0 };
310   struct addrinfo *res = NULL, *ressave = NULL;
311   int n, sockfd;
312
313   hints.ai_family = p_family;
314   hints.ai_socktype = p_socktype;
315
316   n = getaddrinfo(p_hostname, p_service, &hints, &res);
317
318   if (n < 0)
319   {
320     ERROR(PLUGIN_NAME ": getaddrinfo error:: [%s]", gai_strerror(n));
321     return -1;
322   }
323
324   ressave = res;
325
326   sockfd = -1;
327   while (res)
328   {
329     sockfd = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
330
331     if (!(sockfd < 0))
332     {
333       if (connect(sockfd, res->ai_addr, res->ai_addrlen) == 0)
334       {
335         /* Success */
336         break;
337       }
338
339       close(sockfd);
340       sockfd = -1;
341     }
342     res = res->ai_next;
343   }
344
345   freeaddrinfo(ressave);
346   return sockfd;
347 }
348
349
350 /* niptoha code originally from: git://git.tuxfamily.org/gitroot/chrony/chrony.git:util.c */
351 /* Original code licensed as GPLv2, by Richard P. Purnow, Miroslav Lichvar */
352 /* Original name: char * UTI_IPToString(IPAddr *addr)*/
353 static char *
354 niptoha(const tChrony_IPAddr * addr, char *p_buf, size_t p_buf_size)
355 {
356   int rc = 1;
357   unsigned long a, b, c, d, ip;
358
359   switch (ntohs(addr->f_family))
360   {
361   case IPADDR_UNSPEC:
362     rc = snprintf(p_buf, p_buf_size, "[UNSPEC]");
363     break;
364   case IPADDR_INET4:
365     ip = ntohl(addr->addr.ip4);
366     a = (ip >> 24) & 0xff;
367     b = (ip >> 16) & 0xff;
368     c = (ip >> 8) & 0xff;
369     d = (ip >> 0) & 0xff;
370     rc = snprintf(p_buf, p_buf_size, "%ld.%ld.%ld.%ld", a, b, c, d);
371     break;
372   case IPADDR_INET6:
373   {
374     const char *rp = inet_ntop(AF_INET6, addr->addr.ip6, p_buf, p_buf_size);
375     if (rp == NULL)
376     {
377       ERROR(PLUGIN_NAME ": Error converting ipv6 address to string. Errno = %d", errno);
378       rc = snprintf(p_buf, p_buf_size, "[UNKNOWN]");
379     }
380     break;
381   }
382   default:
383     rc = snprintf(p_buf, p_buf_size, "[UNKNOWN]");
384   }
385   assert(rc > 0);
386   return p_buf;
387 }
388
389
390 static int
391 chrony_set_timeout(void)
392 {
393   /* Set the socket's  timeout to g_chrony_timeout; a value of 0 signals infinite timeout */
394   /* Returns 0 on success, !0 on error (check errno) */
395
396   struct timeval tv;
397   tv.tv_sec = g_chrony_timeout;
398   tv.tv_usec = 0;
399
400   assert(g_chrony_socket >= 0);
401   if (setsockopt(g_chrony_socket, SOL_SOCKET,
402       SO_RCVTIMEO, (char *) &tv, sizeof(struct timeval)) < 0)
403   {
404     return CHRONY_RC_FAIL;
405   }
406   return CHRONY_RC_OK;
407 }
408
409
410 static int
411 chrony_connect(void)
412 {
413   /* Connects to the chrony daemon */
414   /* Returns 0 on success, !0 on error (check errno) */
415   int socket;
416
417   if (g_chrony_host == NULL)
418   {
419     g_chrony_host = strdup(CHRONY_DEFAULT_HOST);
420     if (g_chrony_host == NULL)
421     {
422       ERROR(PLUGIN_NAME ": Error duplicating chrony host name");
423       return CHRONY_RC_FAIL;
424     }
425   }
426   if (g_chrony_port == NULL)
427   {
428     g_chrony_port = strdup(CHRONY_DEFAULT_PORT);
429     if (g_chrony_port == NULL)
430     {
431       ERROR(PLUGIN_NAME ": Error duplicating chrony port string");
432       return CHRONY_RC_FAIL;
433     }
434   }
435   if (g_chrony_timeout < 0)
436   {
437     g_chrony_timeout = CHRONY_DEFAULT_TIMEOUT;
438     assert(g_chrony_timeout >= 0);
439   }
440
441   DEBUG(PLUGIN_NAME ": Connecting to %s:%s", g_chrony_host, g_chrony_port);
442   socket = connect_client(g_chrony_host, g_chrony_port, AF_UNSPEC, SOCK_DGRAM);
443   if (socket < 0)
444   {
445     ERROR(PLUGIN_NAME ": Error connecting to daemon. Errno = %d", errno);
446     return CHRONY_RC_FAIL;
447   }
448   DEBUG(PLUGIN_NAME ": Connected");
449   g_chrony_socket = socket;
450
451   if (chrony_set_timeout())
452   {
453     ERROR(PLUGIN_NAME ": Error setting timeout to %lds. Errno = %d",
454           g_chrony_timeout, errno);
455     return CHRONY_RC_FAIL;
456   }
457   return CHRONY_RC_OK;
458 }
459
460
461 static int
462 chrony_send_request(const tChrony_Request * p_req, size_t p_req_size)
463 {
464   if (send(g_chrony_socket, p_req, p_req_size, 0) < 0)
465   {
466     ERROR(PLUGIN_NAME ": Error sending packet. Errno = %d", errno);
467     return CHRONY_RC_FAIL;
468   }
469   return CHRONY_RC_OK;
470 }
471
472
473 static int
474 chrony_recv_response(tChrony_Response * p_resp, size_t p_resp_max_size,
475                      size_t * p_resp_size)
476 {
477   ssize_t rc = recv(g_chrony_socket, p_resp, p_resp_max_size, 0);
478   if (rc <= 0)
479   {
480     ERROR(PLUGIN_NAME ": Error receiving packet: %s (%d)", strerror(errno),
481           errno);
482     return CHRONY_RC_FAIL;
483   }
484   else
485   {
486     *p_resp_size = rc;
487     return CHRONY_RC_OK;
488   }
489 }
490
491
492 static int
493 chrony_query(const int p_command, tChrony_Request * p_req,
494              tChrony_Response * p_resp, size_t * p_resp_size)
495 {
496   /* Check connection. We simply perform one try as collectd already handles retries */
497   assert(p_req);
498   assert(p_resp);
499   assert(p_resp_size);
500
501   if (g_chrony_is_connected == 0)
502   {
503     if (chrony_connect() == CHRONY_RC_OK)
504     {
505       g_chrony_is_connected = 1;
506     }
507     else
508     {
509       ERROR(PLUGIN_NAME ": Unable to connect. Errno = %d", errno);
510       return CHRONY_RC_FAIL;
511     }
512   }
513
514   do
515   {
516     int valid_command = 0;
517     size_t req_size  = sizeof(p_req->header) + sizeof(p_req->padding);
518     size_t resp_size = sizeof(p_resp->header);
519     uint16_t resp_code = RPY_NULL;
520     switch (p_command)
521     {
522     case REQ_TRACKING:
523       req_size  += sizeof(p_req->body.tracking);
524       resp_size += sizeof(p_resp->body.tracking);
525       resp_code = RPY_TRACKING;
526       valid_command = 1;
527       break;
528     case REQ_N_SOURCES:
529       req_size  += sizeof(p_req->body.n_sources);
530       resp_size += sizeof(p_resp->body.n_sources);
531       resp_code = RPY_N_SOURCES;
532       valid_command = 1;
533       break;
534     case REQ_SOURCE_DATA:
535       req_size  += sizeof(p_req->body.source_data);
536       resp_size += sizeof(p_resp->body.source_data);
537       resp_code = RPY_SOURCE_DATA;
538       valid_command = 1;
539       break;
540     case REQ_SOURCE_STATS:
541       req_size  += sizeof(p_req->body.source_stats);
542       resp_size += sizeof(p_resp->body.source_stats);
543       resp_code = RPY_SOURCE_STATS;
544       valid_command = 1;
545       break;
546     default:
547       ERROR(PLUGIN_NAME ": Unknown request command (Was: %d)", p_command);
548       break;
549     }
550
551     if (valid_command == 0)
552       break;
553
554     uint32_t seq_nr = rand_r(&g_chrony_rand);
555     p_req->header.f_cmd = htons(p_command);
556     p_req->header.f_cmd_try = 0;
557     p_req->header.f_seq = seq_nr;
558
559     DEBUG(PLUGIN_NAME ": Sending request (.cmd = %d, .seq = %d)", p_command,
560           seq_nr);
561     if (chrony_send_request(p_req, req_size) != 0)
562       break;
563
564     DEBUG(PLUGIN_NAME ": Waiting for response");
565     if (chrony_recv_response(p_resp, resp_size, p_resp_size) != 0)
566       break;
567
568     DEBUG(PLUGIN_NAME
569           ": Received response: .version = %u, .type = %u, .cmd = %u, .reply = %u, .status = %u, .seq = %u",
570           p_resp->header.f_version, p_resp->header.f_type,
571           ntohs(p_resp->header.f_cmd), ntohs(p_resp->header.f_reply),
572           ntohs(p_resp->header.f_status), p_resp->header.f_seq);
573
574     if (p_resp->header.f_version != p_req->header.f_version)
575     {
576       ERROR(PLUGIN_NAME ": Wrong protocol version (Was: %d, expected: %d)",
577             p_resp->header.f_version, p_req->header.f_version);
578       return CHRONY_RC_FAIL;
579     }
580     if (p_resp->header.f_type != PKT_TYPE_CMD_REPLY)
581     {
582       ERROR(PLUGIN_NAME ": Wrong packet type (Was: %d, expected: %d)",
583             p_resp->header.f_type, PKT_TYPE_CMD_REPLY);
584       return CHRONY_RC_FAIL;
585     }
586     if (p_resp->header.f_seq != seq_nr)
587     {
588       /* FIXME: Implement sequence number handling */
589       ERROR(PLUGIN_NAME
590             ": Unexpected sequence number (Was: %d, expected: %d)",
591             p_resp->header.f_seq, p_req->header.f_seq);
592       return CHRONY_RC_FAIL;
593     }
594     if (p_resp->header.f_cmd != p_req->header.f_cmd)
595     {
596       ERROR(PLUGIN_NAME ": Wrong reply command (Was: %d, expected: %d)",
597             p_resp->header.f_cmd, p_req->header.f_cmd);
598       return CHRONY_RC_FAIL;
599     }
600
601     if (ntohs(p_resp->header.f_reply) != resp_code)
602     {
603       ERROR(PLUGIN_NAME ": Wrong reply code (Was: %d, expected: %d)",
604             ntohs(p_resp->header.f_reply), resp_code);
605       return CHRONY_RC_FAIL;
606     }
607
608     switch (p_resp->header.f_status)
609     {
610     case STT_SUCCESS:
611       DEBUG(PLUGIN_NAME ": Reply packet status STT_SUCCESS");
612       break;
613     default:
614       ERROR(PLUGIN_NAME
615             ": Reply packet contains error status: %d (expected: %d)",
616             p_resp->header.f_status, STT_SUCCESS);
617       return CHRONY_RC_FAIL;
618     }
619
620     /* Good result */
621     return CHRONY_RC_OK;
622   }
623   while (0);
624
625   /* Some error occured */
626   return CHRONY_RC_FAIL;
627 }
628
629
630 static void
631 chrony_init_req(tChrony_Request * p_req)
632 {
633   memset(p_req, 0, sizeof(*p_req));
634   p_req->header.f_version = PROTO_VERSION_NUMBER;
635   p_req->header.f_type    = PKT_TYPE_CMD_REQUEST;
636   p_req->header.f_dummy0  = 0;
637   p_req->header.f_dummy1  = 0;
638   p_req->header.f_dummy2  = 0;
639   p_req->header.f_dummy3  = 0;
640 }
641
642
643 /* ntohf code originally from: git://git.tuxfamily.org/gitroot/chrony/chrony.git:util.c */
644 /* Original code licensed as GPLv2, by Richard P. Purnow, Miroslav Lichvar */
645 /* Original name: double UTI_tFloatNetworkToHost(tFloat f) */
646 static double
647 ntohf(tFloat p_float)
648 {
649   /* Convert tFloat in Network-bit-order to double in host-bit-order */
650
651 #define FLOAT_EXP_BITS 7
652 #define FLOAT_EXP_MIN (-(1 << (FLOAT_EXP_BITS - 1)))
653 #define FLOAT_EXP_MAX (-FLOAT_EXP_MIN - 1)
654 #define FLOAT_COEF_BITS ((int)sizeof (int32_t) * 8 - FLOAT_EXP_BITS)
655 #define FLOAT_COEF_MIN (-(1 << (FLOAT_COEF_BITS - 1)))
656 #define FLOAT_COEF_MAX (-FLOAT_COEF_MIN - 1)
657
658   int32_t exp, coef;
659   uint32_t uval;
660
661   uval = ntohl(p_float.value);
662   exp = (uval >> FLOAT_COEF_BITS) - FLOAT_COEF_BITS;
663   if (exp >= 1 << (FLOAT_EXP_BITS - 1))
664     exp -= 1 << FLOAT_EXP_BITS;
665
666   /* coef = (x << FLOAT_EXP_BITS) >> FLOAT_EXP_BITS; */
667   coef = uval % (1U << FLOAT_COEF_BITS);
668   if (coef >= 1 << (FLOAT_COEF_BITS - 1))
669     coef -= 1 << FLOAT_COEF_BITS;
670
671   return coef * pow(2.0, exp);
672 }
673
674
675 static void
676 chrony_push_data(const char *p_type, const char *p_type_inst, double p_value)
677 {
678   value_t values[1];
679   value_list_t vl = VALUE_LIST_INIT;
680
681   values[0].gauge = p_value;    /* TODO: Check type??? (counter, gauge, derive, absolute) */
682
683   vl.values = values;
684   vl.values_len = 1;
685
686   /* XXX: Shall g_chrony_host/g_chrony_port be reflected in the plugin's output? */
687   /* hostname_g is set in daemon/collectd.c (from config, via gethostname or by resolving localhost) */
688   /* defined as: char hostname_g[DATA_MAX_NAME_LEN]; (never NULL) */
689   sstrncpy(vl.host, hostname_g, sizeof(vl.host));
690   sstrncpy(vl.plugin, PLUGIN_NAME_SHORT, sizeof(vl.plugin));
691   if (g_chrony_plugin_instance != NULL)
692   {
693     sstrncpy(vl.plugin_instance, g_chrony_plugin_instance,
694              sizeof(vl.plugin_instance));
695   }
696   if (p_type != NULL)
697     sstrncpy(vl.type, p_type, sizeof(vl.type));
698
699   if (p_type_inst != NULL)
700     sstrncpy(vl.type_instance, p_type_inst, sizeof(vl.type_instance));
701
702   plugin_dispatch_values(&vl);
703 }
704
705
706 static void
707 chrony_push_data_valid(const char *p_type, const char *p_type_inst, const int p_is_valid,
708                        double p_value)
709 {
710   /* Push real value if p_is_valid is true, push NAN if p_is_valid is not true (idea from ntp plugin) */
711   if (p_is_valid == 0)
712     p_value = NAN;
713
714   chrony_push_data(p_type, p_type_inst, p_value);
715 }
716
717
718 static int
719 chrony_init_seq(void)
720 {
721   /* Initialize the sequence number generator from /dev/urandom */
722   /* Fallbacks: /dev/random and time(NULL) */
723
724   int fh;
725
726   /* Try urandom */
727   fh = open(URAND_DEVICE_PATH, O_RDONLY);
728   if (fh >= 0)
729   {
730     ssize_t rc = read(fh, &g_chrony_rand, sizeof(g_chrony_rand));
731     if (rc != sizeof(g_chrony_rand))
732     {
733       ERROR(PLUGIN_NAME ": Reading from random source \'%s\'failed: %s (%d)",
734             URAND_DEVICE_PATH, strerror(errno), errno);
735       close(fh);
736       return CHRONY_RC_FAIL;
737     }
738     close(fh);
739     DEBUG(PLUGIN_NAME ": Seeding RNG from " URAND_DEVICE_PATH);
740   }
741   else
742   {
743     if (errno == ENOENT)
744     {
745       /* URAND_DEVICE_PATH device not found. Try RAND_DEVICE_PATH as fall-back */
746       fh = open(RAND_DEVICE_PATH, O_RDONLY);
747       if (fh >= 0)
748       {
749         ssize_t rc = read(fh, &g_chrony_rand, sizeof(g_chrony_rand));
750         if (rc != sizeof(g_chrony_rand))
751         {
752           ERROR(PLUGIN_NAME
753                 ": Reading from random source \'%s\'failed: %s (%d)",
754                 RAND_DEVICE_PATH, strerror(errno), errno);
755           close(fh);
756           return CHRONY_RC_FAIL;
757         }
758         close(fh);
759         DEBUG(PLUGIN_NAME ": Seeding RNG from " RAND_DEVICE_PATH);
760       }
761       else
762       {
763         /* Error opening RAND_DEVICE_PATH. Try time(NULL) as fall-back */
764         DEBUG(PLUGIN_NAME ": Seeding RNG from time(NULL)");
765         g_chrony_rand = time(NULL) ^ getpid();
766       }
767     }
768     else
769     {
770       ERROR(PLUGIN_NAME ": Opening random source \'%s\' failed: %s (%d)",
771             URAND_DEVICE_PATH, strerror(errno), errno);
772       return CHRONY_RC_FAIL;
773     }
774   }
775
776   return CHRONY_RC_OK;
777 }
778
779
780 /*****************************************************************************/
781 /* Exported functions */
782 /*****************************************************************************/
783 static int
784 chrony_config(const char *p_key, const char *p_value)
785 {
786   assert(p_key);
787   assert(p_value);
788
789   /* Parse config variables */
790   if (strcasecmp(p_key, CONFIG_KEY_HOST) == 0)
791   {
792     if (g_chrony_host != NULL)
793       free(g_chrony_host);
794
795     if ((g_chrony_host = strdup(p_value)) == NULL)
796     {
797       ERROR(PLUGIN_NAME ": Error duplicating host name");
798       return CHRONY_RC_FAIL;
799     }
800   }
801   else
802   {
803     if (strcasecmp(p_key, CONFIG_KEY_PORT) == 0)
804     {
805       if (g_chrony_port != NULL)
806         free(g_chrony_port);
807
808       if ((g_chrony_port = strdup(p_value)) == NULL)
809       {
810         ERROR(PLUGIN_NAME ": Error duplicating port name");
811         return CHRONY_RC_FAIL;
812       }
813     }
814     else
815     {
816       if (strcasecmp(p_key, CONFIG_KEY_TIMEOUT) == 0)
817       {
818         time_t tosec = strtol(p_value, NULL, 0);
819         g_chrony_timeout = tosec;
820       }
821       else
822       {
823         WARNING(PLUGIN_NAME ": Unknown configuration variable: %s %s", p_key, p_value);
824         return CHRONY_RC_FAIL;
825       }
826     }
827   }
828   /* 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 */
829
830   return CHRONY_RC_OK;
831 }
832
833
834 static int
835 chrony_request_daemon_stats(void)
836 {
837   /* Perform Tracking request */
838   int rc;
839   size_t chrony_resp_size;
840   tChrony_Request chrony_req;
841   tChrony_Response chrony_resp;
842
843   chrony_init_req(&chrony_req);
844   rc =
845     chrony_query(REQ_TRACKING, &chrony_req, &chrony_resp, &chrony_resp_size);
846   if (rc != 0)
847   {
848     ERROR(PLUGIN_NAME ": chrony_query (REQ_TRACKING) failed with status %i",
849           rc);
850     return rc;
851   }
852 #if COLLECT_DEBUG
853   {
854     char src_addr[IPV6_STR_MAX_SIZE] = { 0 };
855     niptoha(&chrony_resp.body.tracking.addr, src_addr, sizeof(src_addr));
856     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),  
857           ntohs(chrony_resp.body.tracking.f_stratum),
858           ntohs(chrony_resp.body.tracking.f_leap_status),
859           ntohl(chrony_resp.body.tracking.f_ref_time.tv_sec_high),
860           ntohl(chrony_resp.body.tracking.f_ref_time.tv_sec_low),
861           ntohl(chrony_resp.body.tracking.f_ref_time.tv_nsec),
862           ntohf(chrony_resp.body.tracking.f_current_correction),
863           ntohf(chrony_resp.body.tracking.f_last_offset),
864           ntohf(chrony_resp.body.tracking.f_rms_offset),
865           ntohf(chrony_resp.body.tracking.f_freq_ppm),
866           ntohf(chrony_resp.body.tracking.f_skew_ppm),
867           ntohf(chrony_resp.body.tracking.f_root_delay),
868           ntohf(chrony_resp.body.tracking.f_root_dispersion),
869           ntohf(chrony_resp.body.tracking.f_last_update_interval));
870   }
871 #endif
872
873   double time_ref = ntohl(chrony_resp.body.tracking.f_ref_time.tv_nsec);
874   time_ref /= 1000000000.0;
875   time_ref += ntohl(chrony_resp.body.tracking.f_ref_time.tv_sec_low);
876   if (chrony_resp.body.tracking.f_ref_time.tv_sec_high)
877   {
878     double secs_high =
879       ntohl(chrony_resp.body.tracking.f_ref_time.tv_sec_high);
880     secs_high *= 4294967296.0;
881     time_ref += secs_high;
882   }
883
884   /* Forward results to collectd-daemon */
885   /* Type_instance is always 'chrony' to tag daemon-wide data */
886   /*                Type                Type_instan  Value */
887   chrony_push_data("clock_stratum",     DAEMON_NAME, ntohs(chrony_resp.body.tracking.f_stratum));
888   chrony_push_data("time_ref",          DAEMON_NAME, time_ref);  /* unit: s */
889   chrony_push_data("time_offset_ntp",   DAEMON_NAME, ntohf(chrony_resp.body.tracking.f_current_correction));      /* Offset between system time and NTP, unit: s */
890   chrony_push_data("time_offset",       DAEMON_NAME, ntohf(chrony_resp.body.tracking.f_last_offset)); /* Estimated Offset of the NTP time, unit: s */
891   chrony_push_data("time_offset_rms",   DAEMON_NAME, ntohf(chrony_resp.body.tracking.f_rms_offset));  /* averaged value of the above, unit: s */
892   chrony_push_data("frequency_error",   DAEMON_NAME, ntohf(chrony_resp.body.tracking.f_freq_ppm));    /* Frequency error of the local osc, unit: ppm */
893   chrony_push_data("clock_skew_ppm",    DAEMON_NAME, ntohf(chrony_resp.body.tracking.f_skew_ppm));
894   chrony_push_data("root_delay",        DAEMON_NAME, ntohf(chrony_resp.body.tracking.f_root_delay));  /* Network latency between local daemon and the current source */
895   chrony_push_data("root_dispersion",   DAEMON_NAME, ntohf(chrony_resp.body.tracking.f_root_dispersion));
896   chrony_push_data("clock_last_update", DAEMON_NAME, ntohf(chrony_resp.body.tracking.f_last_update_interval));
897
898   return CHRONY_RC_OK;
899 }
900
901
902 static int
903 chrony_request_sources_count(unsigned int *p_count)
904 {
905   /* Requests the number of time sources from the chrony daemon */
906   int rc;
907   size_t chrony_resp_size;
908   tChrony_Request chrony_req;
909   tChrony_Response chrony_resp;
910
911   DEBUG(PLUGIN_NAME ": Requesting data");
912   chrony_init_req(&chrony_req);
913   rc =
914     chrony_query(REQ_N_SOURCES, &chrony_req, &chrony_resp, &chrony_resp_size);
915   if (rc != 0)
916   {
917     ERROR(PLUGIN_NAME ": chrony_query (REQ_N_SOURCES) failed with status %i",
918           rc);
919     return rc;
920   }
921
922   *p_count = ntohl(chrony_resp.body.n_sources.f_n_sources);
923   DEBUG(PLUGIN_NAME ": Getting data of %d clock sources", *p_count);
924
925   return CHRONY_RC_OK;
926 }
927
928
929 static int
930 chrony_request_source_data(int p_src_idx, int *p_is_reachable)
931 {
932   /* Perform Source data request for source #p_src_idx */
933   int rc;
934   size_t chrony_resp_size;
935   tChrony_Request chrony_req;
936   tChrony_Response chrony_resp;
937
938   char src_addr[IPV6_STR_MAX_SIZE] = { 0 };
939
940   chrony_init_req(&chrony_req);
941   chrony_req.body.source_data.f_index = htonl(p_src_idx);
942   rc =
943     chrony_query(REQ_SOURCE_DATA, &chrony_req, &chrony_resp,
944                  &chrony_resp_size);
945   if (rc != 0)
946   {
947     ERROR(PLUGIN_NAME
948           ": chrony_query (REQ_SOURCE_DATA) failed with status %i", rc);
949     return rc;
950   }
951
952   niptoha(&chrony_resp.body.source_data.addr, src_addr, sizeof(src_addr));
953   DEBUG(PLUGIN_NAME
954         ": 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",
955         p_src_idx, src_addr, ntohs(chrony_resp.body.source_data.f_poll),
956         ntohs(chrony_resp.body.source_data.f_stratum),
957         ntohs(chrony_resp.body.source_data.f_state),
958         ntohs(chrony_resp.body.source_data.f_mode),
959         ntohs(chrony_resp.body.source_data.f_flags),
960         ntohs(chrony_resp.body.source_data.f_reachability),
961         ntohl(chrony_resp.body.source_data.f_since_sample),
962         ntohf(chrony_resp.body.source_data.f_origin_latest_meas),
963         ntohf(chrony_resp.body.source_data.f_latest_meas),
964         ntohf(chrony_resp.body.source_data.f_latest_meas_err));
965
966   /* Push NaN if source is currently not reachable */
967   int is_reachable =
968     ntohs(chrony_resp.body.source_data.f_reachability) & 0x01;
969   *p_is_reachable = is_reachable;
970
971   /* Forward results to collectd-daemon */
972   chrony_push_data_valid("clock_stratum", src_addr, is_reachable,
973                          ntohs(chrony_resp.body.source_data.f_stratum));
974   chrony_push_data_valid("clock_state", src_addr, is_reachable,
975                          ntohs(chrony_resp.body.source_data.f_state));
976   chrony_push_data_valid("clock_mode", src_addr, is_reachable,
977                          ntohs(chrony_resp.body.source_data.f_mode));
978   chrony_push_data_valid("clock_reachability", src_addr, is_reachable,
979                          ntohs(chrony_resp.body.source_data.f_reachability));
980   chrony_push_data_valid("clock_last_meas", src_addr, is_reachable,
981                          ntohs(chrony_resp.body.source_data.f_since_sample));
982
983   return CHRONY_RC_OK;
984 }
985
986
987 static int
988 chrony_request_source_stats(int p_src_idx, const int *p_is_reachable)
989 {
990   /* Perform Source stats request for source #p_src_idx */
991   int rc;
992   size_t chrony_resp_size;
993   tChrony_Request chrony_req;
994   tChrony_Response chrony_resp;
995   double skew_ppm, frequency_error, time_offset;
996
997   char src_addr[IPV6_STR_MAX_SIZE] = { 0 };
998
999   if (*p_is_reachable == 0)
1000   {
1001     skew_ppm = 0;
1002     frequency_error = 0;
1003     time_offset = 0;
1004   }
1005   else
1006   {
1007     chrony_init_req(&chrony_req);
1008     chrony_req.body.source_stats.f_index = htonl(p_src_idx);
1009     rc =
1010       chrony_query(REQ_SOURCE_STATS, &chrony_req, &chrony_resp,
1011                    &chrony_resp_size);
1012     if (rc != 0)
1013     {
1014       ERROR(PLUGIN_NAME
1015             ": chrony_query (REQ_SOURCE_STATS) failed with status %i", rc);
1016       return rc;
1017     }
1018
1019     skew_ppm = ntohf(chrony_resp.body.source_stats.f_skew_ppm);
1020     frequency_error =
1021       ntohf(chrony_resp.body.source_stats.f_rtc_gain_rate_ppm);
1022     time_offset = ntohf(chrony_resp.body.source_stats.f_est_offset);
1023
1024     niptoha(&chrony_resp.body.source_stats.addr, src_addr, sizeof(src_addr));
1025     DEBUG(PLUGIN_NAME
1026           ": Source[%d] stat: .addr = %s, .ref_id= %u, .n_samples = %u, "
1027           ".n_runs = %u, .span_seconds = %u, .rtc_seconds_fast = %f, "
1028           ".rtc_gain_rate_ppm = %f, .skew_ppm= %f, .est_offset = %f, .est_offset_err = %f",
1029           p_src_idx, src_addr,
1030           ntohl(chrony_resp.body.source_stats.f_ref_id),
1031           ntohl(chrony_resp.body.source_stats.f_n_samples),
1032           ntohl(chrony_resp.body.source_stats.f_n_runs),
1033           ntohl(chrony_resp.body.source_stats.f_span_seconds),
1034           ntohf(chrony_resp.body.source_stats.f_rtc_seconds_fast),
1035           frequency_error, skew_ppm, time_offset,
1036           ntohf(chrony_resp.body.source_stats.f_est_offset_err));
1037
1038   } /* if (*is_reachable) */
1039
1040   /* Forward results to collectd-daemon */
1041   chrony_push_data_valid("clock_skew_ppm", src_addr, *p_is_reachable, skew_ppm);
1042   chrony_push_data_valid("frequency_error", src_addr, *p_is_reachable, frequency_error); /* unit: ppm */
1043   chrony_push_data_valid("time_offset", src_addr, *p_is_reachable, time_offset);         /* unit: s */
1044
1045   return CHRONY_RC_OK;
1046 }
1047
1048
1049 static int
1050 chrony_read(void)
1051 {
1052   /* collectd read callback: Perform data acquisition */
1053   int rc;
1054   unsigned int now_src, n_sources;
1055
1056   if (g_chrony_seq_is_initialized == 0)
1057   {
1058     /* Seed RNG for sequence number generation */
1059     rc = chrony_init_seq();
1060     if (rc != CHRONY_RC_OK)
1061       return rc;
1062
1063     g_chrony_seq_is_initialized = 1;
1064   }
1065
1066   /* Get daemon stats */
1067   rc = chrony_request_daemon_stats();
1068   if (rc != CHRONY_RC_OK)
1069     return rc;
1070
1071   /* Get number of time sources, then check every source for status */
1072   rc = chrony_request_sources_count(&n_sources);
1073   if (rc != CHRONY_RC_OK)
1074     return rc;
1075
1076   for (now_src = 0; now_src < n_sources; ++now_src)
1077   {
1078     int is_reachable;
1079     rc = chrony_request_source_data(now_src, &is_reachable);
1080     if (rc != CHRONY_RC_OK)
1081       return rc;
1082
1083     rc = chrony_request_source_stats(now_src, &is_reachable);
1084     if (rc != CHRONY_RC_OK)
1085       return rc;
1086
1087   }
1088   return CHRONY_RC_OK;
1089 }
1090
1091
1092 static int
1093 chrony_shutdown(void)
1094 {
1095   /* Collectd shutdown callback: Free mem */
1096   if (g_chrony_is_connected != 0)
1097   {
1098     close(g_chrony_socket);
1099     g_chrony_is_connected = 0;
1100   }
1101   if (g_chrony_host != NULL)
1102     sfree(g_chrony_host);
1103
1104   if (g_chrony_port != NULL)
1105     sfree(g_chrony_port);
1106   
1107   if (g_chrony_plugin_instance != NULL)
1108     sfree(g_chrony_plugin_instance);
1109   
1110   return CHRONY_RC_OK;
1111 }
1112
1113
1114 void
1115 module_register(void)
1116 {
1117   plugin_register_config(PLUGIN_NAME_SHORT, chrony_config, g_config_keys,
1118                          g_config_keys_num);
1119   plugin_register_read(PLUGIN_NAME_SHORT, chrony_read);
1120   plugin_register_shutdown(PLUGIN_NAME_SHORT, chrony_shutdown);
1121 }