Merge branch 'collectd-5.5'
[collectd.git] / src / ntpd.c
1 /**
2  * collectd - src/ntpd.c
3  * Copyright (C) 2006-2012  Florian octo Forster
4  *
5  * Permission is hereby granted, free of charge, to any person obtaining a
6  * copy of this software and associated documentation files (the "Software"),
7  * to deal in the Software without restriction, including without limitation
8  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
9  * and/or sell copies of the Software, and to permit persons to whom the
10  * Software is furnished to do so, subject to the following conditions:
11  *
12  * The above copyright notice and this permission notice shall be included in
13  * all copies or substantial portions of the Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
21  * DEALINGS IN THE SOFTWARE.
22  *
23  * Authors:
24  *   Florian octo Forster <octo at collectd.org>
25  **/
26
27 #define _DEFAULT_SOURCE
28 #define _BSD_SOURCE /* For NI_MAXHOST */
29
30 #include "collectd.h"
31 #include "common.h"
32 #include "plugin.h"
33 #include "configfile.h"
34
35 #if HAVE_STDINT_H
36 # include <stdint.h>
37 #endif
38 #if HAVE_NETDB_H
39 # include <netdb.h>
40 #endif
41 #if HAVE_NETINET_IN_H
42 # include <netinet/in.h>
43 #endif
44 #if HAVE_ARPA_INET_H
45 # include <arpa/inet.h> /* inet_ntoa */
46 #endif
47 #if HAVE_NETINET_TCP_H
48 # include <netinet/tcp.h>
49 #endif
50 #if HAVE_POLL_H
51 # include <poll.h>
52 #endif
53
54 #ifndef STA_NANO
55 # define STA_NANO 0x2000
56 #endif
57
58 static const char *config_keys[] =
59 {
60         "Host",
61         "Port",
62         "ReverseLookups",
63         "IncludeUnitID"
64 };
65 static int config_keys_num = STATIC_ARRAY_SIZE (config_keys);
66
67 static _Bool do_reverse_lookups = 1;
68
69 /* This option only exists for backward compatibility. If it is false and two
70  * ntpd peers use the same refclock driver, the plugin will try to write
71  * simultaneous measurements from both to the same type instance. */
72 static _Bool include_unit_id = 0;
73
74 # define NTPD_DEFAULT_HOST "localhost"
75 # define NTPD_DEFAULT_PORT "123"
76 static int   sock_descr = -1;
77 static char *ntpd_host = NULL;
78 static char  ntpd_port[16];
79
80 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
81  * The following definitions were copied from the NTPd distribution  *
82  * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
83 #define MAXFILENAME 128
84 #define MAXSEQ  127
85 #define MODE_PRIVATE 7
86 #define NTP_OLDVERSION ((uint8_t) 1) /* oldest credible version */
87 #define IMPL_XNTPD 3
88 #define FP_FRAC 65536.0
89
90 #define REFCLOCK_ADDR 0x7f7f0000 /* 127.127.0.0 */
91 #define REFCLOCK_MASK 0xffff0000 /* 255.255.0.0 */
92
93 /* This structure is missing the message authentication code, since collectd
94  * doesn't use it. */
95 struct req_pkt
96 {
97         uint8_t  rm_vn_mode;
98         uint8_t  auth_seq;
99         uint8_t  implementation;                /* implementation number */
100         uint8_t  request;                       /* request number */
101         uint16_t err_nitems;            /* error code/number of data items */
102         uint16_t mbz_itemsize;          /* item size */
103         char     data[MAXFILENAME + 48];        /* data area [32 prev](176 byte max) */
104                                         /* struct conf_peer must fit */
105 };
106 #define REQ_LEN_NOMAC (sizeof(struct req_pkt))
107
108 /*
109  * A response packet.  The length here is variable, this is a
110  * maximally sized one.  Note that this implementation doesn't
111  * authenticate responses.
112  */
113 #define RESP_HEADER_SIZE        (8)
114 #define RESP_DATA_SIZE          (500)
115
116 struct resp_pkt
117 {
118         uint8_t  rm_vn_mode;           /* response, more, version, mode */
119         uint8_t  auth_seq;             /* key, sequence number */
120         uint8_t  implementation;       /* implementation number */
121         uint8_t  request;              /* request number */
122         uint16_t err_nitems;           /* error code/number of data items */
123         uint16_t mbz_itemsize;         /* item size */
124         char     data[RESP_DATA_SIZE]; /* data area */
125 };
126
127 /*
128  * Bit setting macros for multifield items.
129  */
130 #define RESP_BIT        0x80
131 #define MORE_BIT        0x40
132
133 #define ISRESPONSE(rm_vn_mode)  (((rm_vn_mode)&RESP_BIT)!=0)
134 #define ISMORE(rm_vn_mode)      (((rm_vn_mode)&MORE_BIT)!=0)
135 #define INFO_VERSION(rm_vn_mode) ((uint8_t)(((rm_vn_mode)>>3)&0x7))
136 #define INFO_MODE(rm_vn_mode)   ((rm_vn_mode)&0x7)
137
138 #define RM_VN_MODE(resp, more, version)         \
139                                 ((uint8_t)(((resp)?RESP_BIT:0)\
140                                 |((more)?MORE_BIT:0)\
141                                 |((version?version:(NTP_OLDVERSION+1))<<3)\
142                                 |(MODE_PRIVATE)))
143
144 #define INFO_IS_AUTH(auth_seq)  (((auth_seq) & 0x80) != 0)
145 #define INFO_SEQ(auth_seq)      ((auth_seq)&0x7f)
146 #define AUTH_SEQ(auth, seq)     ((uint8_t)((((auth)!=0)?0x80:0)|((seq)&0x7f)))
147
148 #define INFO_ERR(err_nitems)    ((uint16_t)((ntohs(err_nitems)>>12)&0xf))
149 #define INFO_NITEMS(err_nitems) ((uint16_t)(ntohs(err_nitems)&0xfff))
150 #define ERR_NITEMS(err, nitems) (htons((uint16_t)((((uint16_t)(err)<<12)&0xf000)\
151                                 |((uint16_t)(nitems)&0xfff))))
152
153 #define INFO_MBZ(mbz_itemsize)  ((ntohs(mbz_itemsize)>>12)&0xf)
154 #define INFO_ITEMSIZE(mbz_itemsize)     ((uint16_t)(ntohs(mbz_itemsize)&0xfff))
155 #define MBZ_ITEMSIZE(itemsize)  (htons((uint16_t)(itemsize)))
156
157 /* negate a long float type */
158 #define M_NEG(v_i, v_f) \
159         do { \
160                 if ((v_f) == 0) \
161                 (v_i) = -((uint32_t)(v_i)); \
162                 else { \
163                         (v_f) = -((uint32_t)(v_f)); \
164                         (v_i) = ~(v_i); \
165                 } \
166         } while(0)
167 /* l_fp to double */
168 #define M_LFPTOD(r_i, r_uf, d) \
169         do { \
170                 register int32_t  ri; \
171                 register uint32_t rf; \
172                 \
173                 ri = (r_i); \
174                 rf = (r_uf); \
175                 if (ri < 0) { \
176                         M_NEG(ri, rf); \
177                         (d) = -((double) ri + ((double) rf) / 4294967296.0); \
178                 } else { \
179                         (d) = (double) ri + ((double) rf) / 4294967296.0; \
180                 } \
181         } while (0)
182
183 #define REQ_PEER_LIST_SUM 1
184 struct info_peer_summary
185 {
186         uint32_t dstadr;         /* local address (zero for undetermined) */
187         uint32_t srcadr;         /* source address */
188         uint16_t srcport;        /* source port */
189         uint8_t stratum;         /* stratum of peer */
190         int8_t hpoll;            /* host polling interval */
191         int8_t ppoll;            /* peer polling interval */
192         uint8_t reach;           /* reachability register */
193         uint8_t flags;           /* flags, from above */
194         uint8_t hmode;           /* peer mode */
195         int32_t  delay;          /* peer.estdelay; s_fp */
196         int32_t  offset_int;     /* peer.estoffset; integral part */
197         int32_t  offset_frc;     /* peer.estoffset; fractional part */
198         uint32_t dispersion;     /* peer.estdisp; u_fp */
199         uint32_t v6_flag;        /* is this v6 or not */
200         uint32_t unused1;        /* (unused) padding for dstadr6 */
201         struct in6_addr dstadr6; /* local address (v6) */
202         struct in6_addr srcadr6; /* source address (v6) */
203 };
204
205 #define REQ_SYS_INFO 4
206 struct info_sys
207 {
208         uint32_t peer;           /* system peer address (v4) */
209         uint8_t  peer_mode;      /* mode we are syncing to peer in */
210         uint8_t  leap;           /* system leap bits */
211         uint8_t  stratum;        /* our stratum */
212         int8_t   precision;      /* local clock precision */
213         int32_t  rootdelay;      /* distance from sync source */
214         uint32_t rootdispersion; /* dispersion from sync source */
215         uint32_t refid;          /* reference ID of sync source */
216         uint64_t reftime;        /* system reference time */
217         uint32_t poll;           /* system poll interval */
218         uint8_t  flags;          /* system flags */
219         uint8_t  unused1;        /* unused */
220         uint8_t  unused2;        /* unused */
221         uint8_t  unused3;        /* unused */
222         int32_t  bdelay;         /* default broadcast offset */
223         int32_t  frequency;      /* frequency residual (scaled ppm)  */
224         uint64_t authdelay;      /* default authentication delay */
225         uint32_t stability;      /* clock stability (scaled ppm) */
226         int32_t  v6_flag;        /* is this v6 or not */
227         int32_t  unused4;        /* unused, padding for peer6 */
228         struct in6_addr peer6;   /* system peer address (v6) */
229 };
230
231 #define REQ_GET_KERNEL 38
232 struct info_kernel
233 {
234         int32_t  offset;
235         int32_t  freq;
236         int32_t  maxerror;
237         int32_t  esterror;
238         uint16_t status;
239         uint16_t shift;
240         int32_t  constant;
241         int32_t  precision;
242         int32_t  tolerance;
243         /* pps stuff */
244         int32_t  ppsfreq;
245         int32_t  jitter;
246         int32_t  stabil;
247         int32_t  jitcnt;
248         int32_t  calcnt;
249         int32_t  errcnt;
250         int32_t  stbcnt;
251 };
252
253 /* List of reference clock names */
254 static const char *refclock_names[] =
255 {
256         "UNKNOWN",    "LOCAL",        "GPS_TRAK",   "WWV_PST",     /*  0- 3 */
257         "SPECTRACOM", "TRUETIME",     "IRIG_AUDIO", "CHU_AUDIO",   /*  4- 7 */
258         "GENERIC",    "GPS_MX4200",   "GPS_AS2201", "GPS_ARBITER", /*  8-11 */
259         "IRIG_TPRO",  "ATOM_LEITCH",  "MSF_EES",    "GPSTM_TRUE",  /* 12-15 */
260         "GPS_BANC",   "GPS_DATUM",    "ACTS_NIST",  "WWV_HEATH",   /* 16-19 */
261         "GPS_NMEA",   "GPS_VME",      "PPS",        "ACTS_PTB",    /* 20-23 */
262         "ACTS_USNO",  "TRUETIME",     "GPS_HP",     "MSF_ARCRON",  /* 24-27 */
263         "SHM",        "GPS_PALISADE", "GPS_ONCORE", "GPS_JUPITER", /* 28-31 */
264         "CHRONOLOG",  "DUMBCLOCK",    "ULINK_M320", "PCF",         /* 32-35 */
265         "WWV_AUDIO",  "GPS_FG",       "HOPF_S",     "HOPF_P",      /* 36-39 */
266         "JJY",        "TT_IRIG",      "GPS_ZYFER",  "GPS_RIPENCC", /* 40-43 */
267         "NEOCLK4X"                                                 /* 44    */
268 };
269 static size_t refclock_names_num = STATIC_ARRAY_SIZE (refclock_names);
270 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
271  * End of the copied stuff..                                         *
272  * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
273
274 static int ntpd_config (const char *key, const char *value)
275 {
276         if (strcasecmp (key, "Host") == 0)
277         {
278                 if (ntpd_host != NULL)
279                         free (ntpd_host);
280                 if ((ntpd_host = strdup (value)) == NULL)
281                         return (1);
282         }
283         else if (strcasecmp (key, "Port") == 0)
284         {
285                 int port = (int) (atof (value));
286                 if ((port > 0) && (port <= 65535))
287                         ssnprintf (ntpd_port, sizeof (ntpd_port),
288                                         "%i", port);
289                 else
290                         sstrncpy (ntpd_port, value, sizeof (ntpd_port));
291         }
292         else if (strcasecmp (key, "ReverseLookups") == 0)
293         {
294                 if (IS_TRUE (value))
295                         do_reverse_lookups = 1;
296                 else
297                         do_reverse_lookups = 0;
298         }
299         else if (strcasecmp (key, "IncludeUnitID") == 0)
300         {
301                 if (IS_TRUE (value))
302                         include_unit_id = 1;
303                 else
304                         include_unit_id = 0;
305         }
306         else
307         {
308                 return (-1);
309         }
310
311         return (0);
312 }
313
314 static void ntpd_submit (const char *type, const char *type_inst, gauge_t value)
315 {
316         value_t values[1];
317         value_list_t vl = VALUE_LIST_INIT;
318
319         values[0].gauge = value;
320
321         vl.values = values;
322         vl.values_len = 1;
323         sstrncpy (vl.host, hostname_g, sizeof (vl.host));
324         sstrncpy (vl.plugin, "ntpd", sizeof (vl.plugin));
325         sstrncpy (vl.plugin_instance, "", sizeof (vl.plugin_instance));
326         sstrncpy (vl.type, type, sizeof (vl.type));
327         sstrncpy (vl.type_instance, type_inst, sizeof (vl.type_instance));
328
329         plugin_dispatch_values (&vl);
330 }
331
332 /* Each time a peer is polled, ntpd shifts the reach register to the left and
333  * sets the LSB based on whether the peer was reachable. If the LSB is zero,
334  * the values are out of date. */
335 static void ntpd_submit_reach (const char *type, const char *type_inst,
336                 uint8_t reach, gauge_t value)
337 {
338         if (!(reach & 1))
339                 value = NAN;
340
341         ntpd_submit (type, type_inst, value);
342 }
343
344 static int ntpd_connect (void)
345 {
346         const char *host;
347         const char *port;
348
349         struct addrinfo  ai_hints;
350         struct addrinfo *ai_list;
351         struct addrinfo *ai_ptr;
352         int              status;
353
354         if (sock_descr >= 0)
355                 return (sock_descr);
356
357         DEBUG ("Opening a new socket");
358
359         host = ntpd_host;
360         if (host == NULL)
361                 host = NTPD_DEFAULT_HOST;
362
363         port = ntpd_port;
364         if (strlen (port) == 0)
365                 port = NTPD_DEFAULT_PORT;
366
367         memset (&ai_hints, '\0', sizeof (ai_hints));
368         ai_hints.ai_flags    = 0;
369 #ifdef AI_ADDRCONFIG
370         ai_hints.ai_flags   |= AI_ADDRCONFIG;
371 #endif
372         ai_hints.ai_family   = PF_UNSPEC;
373         ai_hints.ai_socktype = SOCK_DGRAM;
374         ai_hints.ai_protocol = IPPROTO_UDP;
375
376         if ((status = getaddrinfo (host, port, &ai_hints, &ai_list)) != 0)
377         {
378                 char errbuf[1024];
379                 ERROR ("ntpd plugin: getaddrinfo (%s, %s): %s",
380                                 host, port,
381                                 (status == EAI_SYSTEM)
382                                 ? sstrerror (errno, errbuf, sizeof (errbuf))
383                                 : gai_strerror (status));
384                 return (-1);
385         }
386
387         for (ai_ptr = ai_list; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next)
388         {
389                 /* create our socket descriptor */
390                 if ((sock_descr = socket (ai_ptr->ai_family,
391                                                 ai_ptr->ai_socktype,
392                                                 ai_ptr->ai_protocol)) < 0)
393                         continue;
394
395                 /* connect to the ntpd */
396                 if (connect (sock_descr, ai_ptr->ai_addr, ai_ptr->ai_addrlen))
397                 {
398                         close (sock_descr);
399                         sock_descr = -1;
400                         continue;
401                 }
402
403                 break;
404         }
405
406         freeaddrinfo (ai_list);
407
408         if (sock_descr < 0)
409         {
410                 ERROR ("ntpd plugin: Unable to connect to server.");
411         }
412
413         return (sock_descr);
414 }
415
416 /* For a description of the arguments see `ntpd_do_query' below. */
417 static int ntpd_receive_response (int *res_items, int *res_size,
418                 char **res_data, int res_item_size)
419 {
420         int              sd;
421         struct pollfd    poll_s;
422         struct resp_pkt  res;
423         int              status;
424         int              done;
425         int              i;
426
427         char            *items;
428         size_t           items_num;
429
430         struct timeval   time_end;
431         struct timeval   time_now;
432         int              timeout;
433
434         int              pkt_item_num;        /* items in this packet */
435         int              pkt_item_len;        /* size of the items in this packet */
436         int              pkt_sequence;
437         char             pkt_recvd[MAXSEQ+1]; /* sequence numbers that have been received */
438         int              pkt_recvd_num;       /* number of packets that have been received */
439         int              pkt_lastseq;         /* the last sequence number */
440         ssize_t          pkt_padding;         /* Padding in this packet */
441
442         if ((sd = ntpd_connect ()) < 0)
443                 return (-1);
444
445         items = NULL;
446         items_num = 0;
447
448         memset (pkt_recvd, '\0', sizeof (pkt_recvd));
449         pkt_recvd_num = 0;
450         pkt_lastseq   = -1;
451
452         *res_items = 0;
453         *res_size  = 0;
454         *res_data  = NULL;
455
456         if (gettimeofday (&time_end, NULL) < 0)
457         {
458                 char errbuf[1024];
459                 ERROR ("ntpd plugin: gettimeofday failed: %s",
460                                 sstrerror (errno, errbuf, sizeof (errbuf)));
461                 return (-1);
462         }
463         time_end.tv_sec++; /* wait for a most one second */
464
465         done = 0;
466         while (done == 0)
467         {
468                 struct timeval time_left;
469
470                 if (gettimeofday (&time_now, NULL) < 0)
471                 {
472                         char errbuf[1024];
473                         ERROR ("ntpd plugin: gettimeofday failed: %s",
474                                         sstrerror (errno, errbuf, sizeof (errbuf)));
475                         return (-1);
476                 }
477
478                 if (timeval_cmp (time_end, time_now, &time_left) <= 0)
479                         timeout = 0;
480                 else
481                         timeout = 1000 * time_left.tv_sec
482                                 + ((time_left.tv_usec + 500) / 1000);
483
484                 /* timeout reached */
485                 if (timeout <= 0)
486                         break;
487
488                 poll_s.fd      = sd;
489                 poll_s.events  = POLLIN | POLLPRI;
490                 poll_s.revents = 0;
491
492                 DEBUG ("Polling for %ims", timeout);
493                 status = poll (&poll_s, 1, timeout);
494
495                 if ((status < 0) && ((errno == EAGAIN) || (errno == EINTR)))
496                         continue;
497
498                 if (status < 0)
499                 {
500                         char errbuf[1024];
501                         ERROR ("ntpd plugin: poll failed: %s",
502                                         sstrerror (errno, errbuf, sizeof (errbuf)));
503                         return (-1);
504                 }
505
506                 if (status == 0) /* timeout */
507                 {
508                         DEBUG ("timeout reached.");
509                         break;
510                 }
511
512                 memset (&res, '\0', sizeof (res));
513                 status = recv (sd, (void *) &res, sizeof (res), 0 /* no flags */);
514
515                 if ((status < 0) && ((errno == EAGAIN) || (errno == EINTR)))
516                         continue;
517
518                 if (status < 0)
519                 {
520                         char errbuf[1024];
521                         INFO ("recv(2) failed: %s",
522                                         sstrerror (errno, errbuf, sizeof (errbuf)));
523                         DEBUG ("Closing socket #%i", sd);
524                         close (sd);
525                         sock_descr = sd = -1;
526                         return (-1);
527                 }
528
529                 DEBUG ("recv'd %i bytes", status);
530
531                 /*
532                  * Do some sanity checks first
533                  */
534                 if (status < RESP_HEADER_SIZE)
535                 {
536                         WARNING ("ntpd plugin: Short (%i bytes) packet received",
537                                         (int) status);
538                         continue;
539                 }
540                 if (INFO_MODE (res.rm_vn_mode) != MODE_PRIVATE)
541                 {
542                         NOTICE ("ntpd plugin: Packet received with mode %i",
543                                         INFO_MODE (res.rm_vn_mode));
544                         continue;
545                 }
546                 if (INFO_IS_AUTH (res.auth_seq))
547                 {
548                         NOTICE ("ntpd plugin: Encrypted packet received");
549                         continue;
550                 }
551                 if (!ISRESPONSE (res.rm_vn_mode))
552                 {
553                         NOTICE ("ntpd plugin: Received request packet, "
554                                         "wanted response");
555                         continue;
556                 }
557                 if (INFO_MBZ (res.mbz_itemsize))
558                 {
559                         WARNING ("ntpd plugin: Received packet with nonzero "
560                                         "MBZ field!");
561                         continue;
562                 }
563                 if (res.implementation != IMPL_XNTPD)
564                 {
565                         WARNING ("ntpd plugin: Asked for request of type %i, "
566                                         "got %i", (int) IMPL_XNTPD, (int) res.implementation);
567                         continue;
568                 }
569
570                 /* Check for error code */
571                 if (INFO_ERR (res.err_nitems) != 0)
572                 {
573                         ERROR ("ntpd plugin: Received error code %i",
574                                         (int) INFO_ERR(res.err_nitems));
575                         return ((int) INFO_ERR (res.err_nitems));
576                 }
577
578                 /* extract number of items in this packet and the size of these items */
579                 pkt_item_num = INFO_NITEMS (res.err_nitems);
580                 pkt_item_len = INFO_ITEMSIZE (res.mbz_itemsize);
581                 DEBUG ("pkt_item_num = %i; pkt_item_len = %i;",
582                                 pkt_item_num, pkt_item_len);
583
584                 /* Check if the reported items fit in the packet */
585                 if ((pkt_item_num * pkt_item_len) > (status - RESP_HEADER_SIZE))
586                 {
587                         ERROR ("ntpd plugin: %i items * %i bytes > "
588                                         "%i bytes - %i bytes header",
589                                         (int) pkt_item_num, (int) pkt_item_len,
590                                         (int) status, (int) RESP_HEADER_SIZE);
591                         continue;
592                 }
593
594                 if (pkt_item_len > res_item_size)
595                 {
596                         ERROR ("ntpd plugin: (pkt_item_len = %i) "
597                                         ">= (res_item_size = %i)",
598                                         pkt_item_len, res_item_size);
599                         continue;
600                 }
601
602                 /* If this is the first packet (time wise, not sequence wise),
603                  * set `res_size'. If it's not the first packet check if the
604                  * items have the same size. Discard invalid packets. */
605                 if (items_num == 0) /* first packet */
606                 {
607                         DEBUG ("*res_size = %i", pkt_item_len);
608                         *res_size = pkt_item_len;
609                 }
610                 else if (*res_size != pkt_item_len)
611                 {
612                         DEBUG ("Error: *res_size = %i; pkt_item_len = %i;",
613                                         *res_size, pkt_item_len);
614                         ERROR ("Item sizes differ.");
615                         continue;
616                 }
617
618                 /*
619                  * Because the items in the packet may be smaller than the
620                  * items requested, the following holds true:
621                  */
622                 assert ((*res_size == pkt_item_len)
623                                 && (pkt_item_len <= res_item_size));
624
625                 /* Calculate the padding. No idea why there might be any padding.. */
626                 pkt_padding = 0;
627                 if (pkt_item_len < res_item_size)
628                         pkt_padding = res_item_size - pkt_item_len;
629                 DEBUG ("res_item_size = %i; pkt_padding = %zi;",
630                                 res_item_size, pkt_padding);
631
632                 /* Extract the sequence number */
633                 pkt_sequence = INFO_SEQ (res.auth_seq);
634                 if ((pkt_sequence < 0) || (pkt_sequence > MAXSEQ))
635                 {
636                         ERROR ("ntpd plugin: Received packet with sequence %i",
637                                         pkt_sequence);
638                         continue;
639                 }
640
641                 /* Check if this sequence has been received before. If so, discard it. */
642                 if (pkt_recvd[pkt_sequence] != '\0')
643                 {
644                         NOTICE ("ntpd plugin: Sequence %i received twice",
645                                         pkt_sequence);
646                         continue;
647                 }
648
649                 /* If `pkt_lastseq != -1' another packet without `more bit' has
650                  * been received. */
651                 if (!ISMORE (res.rm_vn_mode))
652                 {
653                         if (pkt_lastseq != -1)
654                         {
655                                 ERROR ("ntpd plugin: Two packets which both "
656                                                 "claim to be the last one in the "
657                                                 "sequence have been received.");
658                                 continue;
659                         }
660                         pkt_lastseq = pkt_sequence;
661                         DEBUG ("Last sequence = %i;", pkt_lastseq);
662                 }
663
664                 /*
665                  * Enough with the checks. Copy the data now.
666                  * We start by allocating some more memory.
667                  */
668                 DEBUG ("realloc (%p, %zu)", (void *) *res_data,
669                                 (items_num + pkt_item_num) * res_item_size);
670                 items = realloc (*res_data,
671                                 (items_num + pkt_item_num) * res_item_size);
672                 if (items == NULL)
673                 {
674                         ERROR ("ntpd plugin: realloc failed.");
675                         continue;
676                 }
677                 items_num += pkt_item_num;
678                 *res_data = items;
679
680                 for (i = 0; i < pkt_item_num; i++)
681                 {
682                         /* dst: There are already `*res_items' items with
683                          *      res_item_size bytes each in in `*res_data'. Set
684                          *      dst to the first byte after that. */
685                         void *dst = (void *) (*res_data + ((*res_items) * res_item_size));
686                         /* src: We use `pkt_item_len' to calculate the offset
687                          *      from the beginning of the packet, because the
688                          *      items in the packet may be smaller than the
689                          *      items that were requested. We skip `i' such
690                          *      items. */
691                         void *src = (void *) (((char *) res.data) + (i * pkt_item_len));
692
693                         /* Set the padding to zeros */
694                         if (pkt_padding != 0)
695                                 memset (dst, '\0', res_item_size);
696                         memcpy (dst, src, (size_t) pkt_item_len);
697
698                         /* Increment `*res_items' by one, so `dst' will end up
699                          * one further in the next round. */
700                         (*res_items)++;
701                 } /* for (pkt_item_num) */
702
703                 pkt_recvd[pkt_sequence] = (char) 1;
704                 pkt_recvd_num++;
705
706                 if ((pkt_recvd_num - 1) == pkt_lastseq)
707                         done = 1;
708         } /* while (done == 0) */
709
710         return (0);
711 } /* int ntpd_receive_response */
712
713 /* For a description of the arguments see `ntpd_do_query' below. */
714 static int ntpd_send_request (int req_code, int req_items, int req_size, char *req_data)
715 {
716         int             sd;
717         struct req_pkt  req;
718         size_t          req_data_len;
719         int             status;
720
721         assert (req_items >= 0);
722         assert (req_size  >= 0);
723
724         if ((sd = ntpd_connect ()) < 0)
725                 return (-1);
726
727         memset (&req, '\0', sizeof (req));
728         req.rm_vn_mode = RM_VN_MODE(0, 0, 0);
729         req.auth_seq   = AUTH_SEQ (0, 0);
730         req.implementation = IMPL_XNTPD;
731         req.request = (unsigned char) req_code;
732
733         req_data_len = (size_t) (req_items * req_size);
734
735         assert (((req_data != NULL) && (req_data_len > 0))
736                         || ((req_data == NULL) && (req_items == 0) && (req_size == 0)));
737
738         req.err_nitems   = ERR_NITEMS (0, req_items);
739         req.mbz_itemsize = MBZ_ITEMSIZE (req_size);
740
741         if (req_data != NULL)
742                 memcpy ((void *) req.data, (const void *) req_data, req_data_len);
743
744         DEBUG ("req_items = %i; req_size = %i; req_data = %p;",
745                         req_items, req_size, (void *) req_data);
746
747         status = swrite (sd, (const char *) &req, REQ_LEN_NOMAC);
748         if (status < 0)
749         {
750                 DEBUG ("`swrite' failed. Closing socket #%i", sd);
751                 close (sd);
752                 sock_descr = sd = -1;
753                 return (status);
754         }
755
756         return (0);
757 }
758
759 /*
760  * ntpd_do_query:
761  *
762  * req_code:      Type of request packet
763  * req_items:     Numver of items in the request
764  * req_size:      Size of one item in the request
765  * req_data:      Data of the request packet
766  * res_items:     Pointer to where the number returned items will be stored.
767  * res_size:      Pointer to where the size of one returned item will be stored.
768  * res_data:      This is where a pointer to the (allocated) data will be stored.
769  * res_item_size: Size of one returned item. (used to calculate padding)
770  *
771  * returns:       zero upon success, non-zero otherwise.
772  */
773 static int ntpd_do_query (int req_code, int req_items, int req_size, char *req_data,
774                 int *res_items, int *res_size, char **res_data, int res_item_size)
775 {
776         int status;
777
778         status = ntpd_send_request (req_code, req_items, req_size, req_data);
779         if (status != 0)
780                 return (status);
781
782         status = ntpd_receive_response (res_items, res_size, res_data,
783                         res_item_size);
784         return (status);
785 }
786
787 static double ntpd_read_fp (int32_t val_int)
788 {
789         double val_double;
790
791         val_int = ntohl (val_int);
792         val_double = ((double) val_int) / FP_FRAC;
793
794         return (val_double);
795 }
796
797 static uint32_t ntpd_get_refclock_id (struct info_peer_summary const *peer_info)
798 {
799         uint32_t addr = ntohl (peer_info->srcadr);
800         uint32_t refclock_id = (addr >> 8) & 0x00FF;
801
802         return (refclock_id);
803 }
804
805 static int ntpd_get_name_from_address (char *buffer, size_t buffer_size,
806                 struct info_peer_summary const *peer_info, _Bool do_reverse_lookup)
807 {
808         struct sockaddr_storage sa;
809         socklen_t sa_len;
810         int flags = 0;
811         int status;
812
813         memset (&sa, 0, sizeof (sa));
814
815         if (peer_info->v6_flag)
816         {
817                 struct sockaddr_in6 sa6;
818
819                 assert (sizeof (sa) >= sizeof (sa6));
820
821                 memset (&sa6, 0, sizeof (sa6));
822                 sa6.sin6_family = AF_INET6;
823                 sa6.sin6_port = htons (123);
824                 memcpy (&sa6.sin6_addr, &peer_info->srcadr6,
825                                 sizeof (struct in6_addr));
826                 sa_len = sizeof (sa6);
827
828                 memcpy (&sa, &sa6, sizeof (sa6));
829         }
830         else
831         {
832                 struct sockaddr_in sa4;
833
834                 assert (sizeof (sa) >= sizeof (sa4));
835
836                 memset (&sa4, 0, sizeof (sa4));
837                 sa4.sin_family = AF_INET;
838                 sa4.sin_port = htons (123);
839                 memcpy (&sa4.sin_addr, &peer_info->srcadr,
840                                 sizeof (struct in_addr));
841                 sa_len = sizeof (sa4);
842
843                 memcpy (&sa, &sa4, sizeof (sa4));
844         }
845
846         if (!do_reverse_lookup)
847                 flags |= NI_NUMERICHOST;
848
849         status = getnameinfo ((struct sockaddr const *) &sa, sa_len,
850                         buffer, buffer_size,
851                         NULL, 0, /* No port name */
852                         flags);
853         if (status != 0)
854         {
855                 char errbuf[1024];
856                 ERROR ("ntpd plugin: getnameinfo failed: %s",
857                                 (status == EAI_SYSTEM)
858                                 ? sstrerror (errno, errbuf, sizeof (errbuf))
859                                 : gai_strerror (status));
860                 return (-1);
861         }
862
863         return (0);
864 } /* ntpd_get_name_from_address */
865
866 static int ntpd_get_name_refclock (char *buffer, size_t buffer_size,
867                 struct info_peer_summary const *peer_info)
868 {
869         uint32_t refclock_id = ntpd_get_refclock_id (peer_info);
870         uint32_t unit_id = ntohl (peer_info->srcadr) & 0x00FF;
871
872         if (((size_t) refclock_id) >= refclock_names_num)
873                 return (ntpd_get_name_from_address (buffer, buffer_size,
874                                         peer_info,
875                                         /* do_reverse_lookup = */ 0));
876
877         if (include_unit_id)
878                 ssnprintf (buffer, buffer_size, "%s-%"PRIu32,
879                                 refclock_names[refclock_id], unit_id);
880         else
881                 sstrncpy (buffer, refclock_names[refclock_id], buffer_size);
882
883         return (0);
884 } /* int ntpd_get_name_refclock */
885
886 static int ntpd_get_name (char *buffer, size_t buffer_size,
887                 struct info_peer_summary const *peer_info)
888 {
889         uint32_t addr = ntohl (peer_info->srcadr);
890
891         if (!peer_info->v6_flag && ((addr & REFCLOCK_MASK) == REFCLOCK_ADDR))
892                 return (ntpd_get_name_refclock (buffer, buffer_size,
893                                         peer_info));
894         else
895                 return (ntpd_get_name_from_address (buffer, buffer_size,
896                                         peer_info, do_reverse_lookups));
897 } /* int ntpd_addr_to_name */
898
899 static int ntpd_read (void)
900 {
901         struct info_kernel *ik;
902         int                 ik_num;
903         int                 ik_size;
904
905         struct info_peer_summary *ps;
906         int                       ps_num;
907         int                       ps_size;
908
909         gauge_t offset_loop;
910         gauge_t freq_loop;
911         gauge_t offset_error;
912
913         int status;
914         int i;
915
916         /* On Linux, if the STA_NANO bit is set in ik->status, then ik->offset
917          * is is nanoseconds, otherwise it's microseconds. */
918         double scale_loop  = 1e-6;
919         double scale_error = 1e-6;
920
921         ik      = NULL;
922         ik_num  = 0;
923         ik_size = 0;
924
925         status = ntpd_do_query (REQ_GET_KERNEL,
926                         0, 0, NULL, /* request data */
927                         &ik_num, &ik_size, (char **) ((void *) &ik), /* response data */
928                         sizeof (struct info_kernel));
929         if (status != 0)
930         {
931                 ERROR ("ntpd plugin: ntpd_do_query (REQ_GET_KERNEL) failed with status %i", status);
932                 return (status);
933         }
934         else if ((ik == NULL) || (ik_num == 0) || (ik_size == 0))
935         {
936                 ERROR ("ntpd plugin: ntpd_do_query returned unexpected data. "
937                                 "(ik = %p; ik_num = %i; ik_size = %i)",
938                                 (void *) ik, ik_num, ik_size);
939                 return (-1);
940         }
941
942         if (ntohs(ik->status) & STA_NANO) {
943                 scale_loop  = 1e-9;
944                 scale_error = 1e-9;
945         }
946
947         /* kerninfo -> estimated error */
948         offset_loop  = scale_loop * ((gauge_t) ntohl (ik->offset));
949         freq_loop    = ntpd_read_fp (ik->freq);
950         offset_error = scale_error * ((gauge_t) ntohl (ik->esterror));
951
952         DEBUG ("info_kernel:\n"
953                         "  pll offset    = %.8g\n"
954                         "  pll frequency = %.8g\n" /* drift compensation */
955                         "  est error     = %.8g\n",
956                         offset_loop, freq_loop, offset_error);
957
958         ntpd_submit ("frequency_offset", "loop",  freq_loop);
959         ntpd_submit ("time_offset",      "loop",  offset_loop);
960         ntpd_submit ("time_offset",      "error", offset_error);
961
962         free (ik);
963         ik = NULL;
964
965         status = ntpd_do_query (REQ_PEER_LIST_SUM,
966                         0, 0, NULL, /* request data */
967                         &ps_num, &ps_size, (char **) ((void *) &ps), /* response data */
968                         sizeof (struct info_peer_summary));
969         if (status != 0)
970         {
971                 ERROR ("ntpd plugin: ntpd_do_query (REQ_PEER_LIST_SUM) failed with status %i", status);
972                 return (status);
973         }
974         else if ((ps == NULL) || (ps_num == 0) || (ps_size == 0))
975         {
976                 ERROR ("ntpd plugin: ntpd_do_query returned unexpected data. "
977                                 "(ps = %p; ps_num = %i; ps_size = %i)",
978                                 (void *) ps, ps_num, ps_size);
979                 return (-1);
980         }
981
982         for (i = 0; i < ps_num; i++)
983         {
984                 struct info_peer_summary *ptr;
985                 double offset;
986
987                 char peername[NI_MAXHOST];
988                 uint32_t refclock_id;
989
990                 ptr = ps + i;
991
992                 status = ntpd_get_name (peername, sizeof (peername), ptr);
993                 if (status != 0)
994                 {
995                         ERROR ("ntpd plugin: Determining name of peer failed.");
996                         continue;
997                 }
998
999                 refclock_id = ntpd_get_refclock_id (ptr);
1000
1001                 /* Convert the `long floating point' offset value to double */
1002                 M_LFPTOD (ntohl (ptr->offset_int), ntohl (ptr->offset_frc), offset);
1003
1004                 DEBUG ("peer %i:\n"
1005                                 "  peername   = %s\n"
1006                                 "  srcadr     = 0x%08x\n"
1007                                 "  reach      = 0%03o\n"
1008                                 "  delay      = %f\n"
1009                                 "  offset_int = %i\n"
1010                                 "  offset_frc = %i\n"
1011                                 "  offset     = %f\n"
1012                                 "  dispersion = %f\n",
1013                                 i,
1014                                 peername,
1015                                 ntohl (ptr->srcadr),
1016                                 ptr->reach,
1017                                 ntpd_read_fp (ptr->delay),
1018                                 ntohl (ptr->offset_int),
1019                                 ntohl (ptr->offset_frc),
1020                                 offset,
1021                                 ntpd_read_fp (ptr->dispersion));
1022
1023                 if (refclock_id != 1) /* not the system clock (offset will always be zero.. */
1024                         ntpd_submit_reach ("time_offset", peername, ptr->reach,
1025                                         offset);
1026                 ntpd_submit_reach ("time_dispersion", peername, ptr->reach,
1027                                 ntpd_read_fp (ptr->dispersion));
1028                 if (refclock_id == 0) /* not a reference clock */
1029                         ntpd_submit_reach ("delay", peername, ptr->reach,
1030                                         ntpd_read_fp (ptr->delay));
1031         }
1032
1033         free (ps);
1034         ps = NULL;
1035
1036         return (0);
1037 } /* int ntpd_read */
1038
1039 void module_register (void)
1040 {
1041         plugin_register_config ("ntpd", ntpd_config,
1042                         config_keys, config_keys_num);
1043         plugin_register_read ("ntpd", ntpd_read);
1044 } /* void module_register */