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