blob: ca79e033814006645b5e6afbf86a419ffea52670 [file] [log] [blame]
Adam Tkacb1585062009-11-22 03:43:55 +01001/*
2 * NTP client/server, based on OpenNTPD 3.9p1
3 *
4 * Author: Adam Tkac <vonsch@gmail.com>
5 *
6 * Licensed under GPLv2, see file LICENSE in this tarball for details.
7 */
Adam Tkacb1585062009-11-22 03:43:55 +01008#include "libbb.h"
9#include <netinet/ip.h> /* For IPTOS_LOWDELAY definition */
Denys Vlasenkob2e5fc32009-11-25 14:52:47 +010010#ifndef IPTOS_LOWDELAY
11# define IPTOS_LOWDELAY 0x10
12#endif
Adam Tkacb1585062009-11-22 03:43:55 +010013#ifndef IP_PKTINFO
14# error "Sorry, your kernel has to support IP_PKTINFO"
15#endif
16
Denys Vlasenko907647f2009-12-02 23:17:45 +010017
18/* Sync to peers every N secs */
19#define INTERVAL_QUERY_NORMAL 30
Denys Vlasenkob1278a32009-11-24 16:03:47 +010020#define INTERVAL_QUERY_PATHETIC 60
21#define INTERVAL_QUERY_AGRESSIVE 5
Adam Tkacb1585062009-11-22 03:43:55 +010022
Denys Vlasenko907647f2009-12-02 23:17:45 +010023/* Bad if *less than* TRUSTLEVEL_BADPEER */
24#define TRUSTLEVEL_BADPEER 6
Denys Vlasenkob1278a32009-11-24 16:03:47 +010025#define TRUSTLEVEL_PATHETIC 2
26#define TRUSTLEVEL_AGRESSIVE 8
27#define TRUSTLEVEL_MAX 10
Adam Tkacb1585062009-11-22 03:43:55 +010028
Denys Vlasenkob1278a32009-11-24 16:03:47 +010029#define QSCALE_OFF_MIN 0.05
30#define QSCALE_OFF_MAX 0.50
Adam Tkacb1585062009-11-22 03:43:55 +010031
Denys Vlasenko907647f2009-12-02 23:17:45 +010032/* Single query might take n secs max */
33#define QUERYTIME_MAX 15
34/* Min offset for settime at start. "man ntpd" says it's 128 ms */
35#define STEPTIME_MIN_OFFSET 0.128
Adam Tkacb1585062009-11-22 03:43:55 +010036
Adam Tkacb1585062009-11-22 03:43:55 +010037typedef struct {
38 uint32_t int_partl;
39 uint32_t fractionl;
40} l_fixedpt_t;
41
42typedef struct {
43 uint16_t int_parts;
44 uint16_t fractions;
45} s_fixedpt_t;
46
Denys Vlasenkoca6c7e42009-11-24 07:07:42 +010047enum {
48 NTP_DIGESTSIZE = 16,
49 NTP_MSGSIZE_NOAUTH = 48,
50 NTP_MSGSIZE = (NTP_MSGSIZE_NOAUTH + 4 + NTP_DIGESTSIZE),
51};
Adam Tkacb1585062009-11-22 03:43:55 +010052
53typedef struct {
Denys Vlasenko386960a2009-12-02 01:51:24 +010054 uint8_t m_status; /* status of local clock and leap info */
55 uint8_t m_stratum; /* stratum level */
56 uint8_t m_ppoll; /* poll value */
57 int8_t m_precision;
58 s_fixedpt_t m_rootdelay;
59 s_fixedpt_t m_dispersion;
60 uint32_t m_refid;
61 l_fixedpt_t m_reftime;
62 l_fixedpt_t m_orgtime;
63 l_fixedpt_t m_rectime;
64 l_fixedpt_t m_xmttime;
65 uint32_t m_keyid;
66 uint8_t m_digest[NTP_DIGESTSIZE];
Adam Tkacb1585062009-11-22 03:43:55 +010067} ntp_msg_t;
68
Adam Tkacb1585062009-11-22 03:43:55 +010069enum {
70 NTP_VERSION = 4,
71 NTP_MAXSTRATUM = 15,
Denys Vlasenko907647f2009-12-02 23:17:45 +010072 /* Leap Second Codes (high order two bits of m_status) */
Adam Tkacb1585062009-11-22 03:43:55 +010073 LI_NOWARNING = (0 << 6), /* no warning */
74 LI_PLUSSEC = (1 << 6), /* add a second (61 seconds) */
75 LI_MINUSSEC = (2 << 6), /* minus a second (59 seconds) */
76 LI_ALARM = (3 << 6), /* alarm condition */
77
78 /* Status Masks */
79 MODE_MASK = (7 << 0),
80 VERSION_MASK = (7 << 3),
Denys Vlasenkoca6c7e42009-11-24 07:07:42 +010081 VERSION_SHIFT = 3,
Adam Tkacb1585062009-11-22 03:43:55 +010082 LI_MASK = (3 << 6),
83
84 /* Mode values */
85 MODE_RES0 = 0, /* reserved */
86 MODE_SYM_ACT = 1, /* symmetric active */
87 MODE_SYM_PAS = 2, /* symmetric passive */
88 MODE_CLIENT = 3, /* client */
89 MODE_SERVER = 4, /* server */
90 MODE_BROADCAST = 5, /* broadcast */
91 MODE_RES1 = 6, /* reserved for NTP control message */
Denys Vlasenkoca6c7e42009-11-24 07:07:42 +010092 MODE_RES2 = 7, /* reserved for private use */
Adam Tkacb1585062009-11-22 03:43:55 +010093};
94
Denys Vlasenkob1278a32009-11-24 16:03:47 +010095#define OFFSET_1900_1970 2208988800UL /* 1970 - 1900 in seconds */
Adam Tkacb1585062009-11-22 03:43:55 +010096
Denys Vlasenko386960a2009-12-02 01:51:24 +010097typedef struct {
98 double o_offset;
99 double o_delay;
Denys Vlasenko4bd51892009-12-02 13:43:06 +0100100 //UNUSED: double o_error;
Denys Vlasenko386960a2009-12-02 01:51:24 +0100101 time_t o_rcvd;
102 uint32_t o_refid4;
103 uint8_t o_leap;
104 uint8_t o_stratum;
105 uint8_t o_good;
106} ntp_offset_t;
107
Denys Vlasenko907647f2009-12-02 23:17:45 +0100108#define OFFSET_ARRAY_SIZE 8
Denys Vlasenko386960a2009-12-02 01:51:24 +0100109typedef struct {
Denys Vlasenko386960a2009-12-02 01:51:24 +0100110 len_and_sockaddr *lsa;
111 char *dotted;
Denys Vlasenko907647f2009-12-02 23:17:45 +0100112 /* When to send new query (if fd == -1)
113 * or when receive times out (if fd >= 0): */
114 time_t next_action_time;
Denys Vlasenko386960a2009-12-02 01:51:24 +0100115 int fd;
Denys Vlasenko386960a2009-12-02 01:51:24 +0100116 uint8_t shift;
117 uint8_t trustlevel;
118 ntp_msg_t msg;
Denys Vlasenko907647f2009-12-02 23:17:45 +0100119 double xmttime;
Denys Vlasenko386960a2009-12-02 01:51:24 +0100120 ntp_offset_t update;
121 ntp_offset_t reply[OFFSET_ARRAY_SIZE];
122} ntp_peer_t;
Adam Tkacb1585062009-11-22 03:43:55 +0100123
Denys Vlasenko8d580c72009-11-23 16:27:16 +0100124enum {
125 OPT_n = (1 << 0),
Denys Vlasenko907647f2009-12-02 23:17:45 +0100126 OPT_q = (1 << 1),
127 OPT_N = (1 << 2),
128 OPT_x = (1 << 3),
Denys Vlasenko8d580c72009-11-23 16:27:16 +0100129 /* Insert new options above this line. */
130 /* Non-compat options: */
Denys Vlasenkob2e5fc32009-11-25 14:52:47 +0100131 OPT_p = (1 << 4),
132 OPT_l = (1 << 5) * ENABLE_FEATURE_NTPD_SERVER,
Denys Vlasenko8d580c72009-11-23 16:27:16 +0100133};
134
Adam Tkacb1585062009-11-22 03:43:55 +0100135
136struct globals {
Denys Vlasenko386960a2009-12-02 01:51:24 +0100137 double rootdelay;
138 double reftime;
139 llist_t *ntp_peers;
Adam Tkacb1585062009-11-22 03:43:55 +0100140#if ENABLE_FEATURE_NTPD_SERVER
141 int listen_fd;
142#endif
Denys Vlasenko386960a2009-12-02 01:51:24 +0100143 unsigned verbose;
Denys Vlasenkob1278a32009-11-24 16:03:47 +0100144 unsigned peer_cnt;
Denys Vlasenko907647f2009-12-02 23:17:45 +0100145 unsigned scale;
Denys Vlasenko386960a2009-12-02 01:51:24 +0100146 uint32_t refid;
147 uint32_t refid4;
Denys Vlasenko386960a2009-12-02 01:51:24 +0100148 uint8_t synced;
149 uint8_t leap;
Denys Vlasenko907647f2009-12-02 23:17:45 +0100150#define G_precision -6
151// int8_t precision;
Denys Vlasenko386960a2009-12-02 01:51:24 +0100152 uint8_t stratum;
Denys Vlasenkof91e63c2009-12-02 02:30:31 +0100153 uint8_t time_is_stepped;
Denys Vlasenkofae9f492009-12-01 02:32:01 +0100154 uint8_t first_adj_done;
Adam Tkacb1585062009-11-22 03:43:55 +0100155};
156#define G (*ptr_to_globals)
157
158
159static const int const_IPTOS_LOWDELAY = IPTOS_LOWDELAY;
160
161
162static void
Denys Vlasenko386960a2009-12-02 01:51:24 +0100163set_next(ntp_peer_t *p, unsigned t)
Adam Tkacb1585062009-11-22 03:43:55 +0100164{
Denys Vlasenko907647f2009-12-02 23:17:45 +0100165 p->next_action_time = time(NULL) + t;
Adam Tkacb1585062009-11-22 03:43:55 +0100166}
167
168static void
Denys Vlasenko907647f2009-12-02 23:17:45 +0100169add_peers(char *s)
Adam Tkacb1585062009-11-22 03:43:55 +0100170{
171 ntp_peer_t *p;
172
173 p = xzalloc(sizeof(*p));
Denys Vlasenko6a110c92009-12-03 00:20:58 +0100174 p->lsa = xhost2sockaddr(s, 123);
175 p->dotted = xmalloc_sockaddr2dotted_noport(&p->lsa->u.sa);
Denys Vlasenko386960a2009-12-02 01:51:24 +0100176 p->fd = -1;
177 p->msg.m_status = MODE_CLIENT | (NTP_VERSION << 3);
Adam Tkacb1585062009-11-22 03:43:55 +0100178 p->trustlevel = TRUSTLEVEL_PATHETIC;
Denys Vlasenko907647f2009-12-02 23:17:45 +0100179 p->next_action_time = time(NULL); /* = set_next(p, 0); */
Adam Tkacb1585062009-11-22 03:43:55 +0100180
181 llist_add_to(&G.ntp_peers, p);
182 G.peer_cnt++;
183}
184
185static double
Denys Vlasenko907647f2009-12-02 23:17:45 +0100186gettime1900d(void)
Adam Tkacb1585062009-11-22 03:43:55 +0100187{
Denys Vlasenkoca6c7e42009-11-24 07:07:42 +0100188 struct timeval tv;
Adam Tkacb1585062009-11-22 03:43:55 +0100189 gettimeofday(&tv, NULL); /* never fails */
Denys Vlasenkob1278a32009-11-24 16:03:47 +0100190 return (tv.tv_sec + 1.0e-6 * tv.tv_usec + OFFSET_1900_1970);
Adam Tkacb1585062009-11-22 03:43:55 +0100191}
192
Adam Tkacb1585062009-11-22 03:43:55 +0100193static void
194d_to_tv(double d, struct timeval *tv)
195{
196 tv->tv_sec = (long)d;
197 tv->tv_usec = (d - tv->tv_sec) * 1000000;
198}
199
200static double
201lfp_to_d(l_fixedpt_t lfp)
202{
Denys Vlasenkoca6c7e42009-11-24 07:07:42 +0100203 double ret;
Adam Tkacb1585062009-11-22 03:43:55 +0100204 lfp.int_partl = ntohl(lfp.int_partl);
205 lfp.fractionl = ntohl(lfp.fractionl);
Denys Vlasenkoca6c7e42009-11-24 07:07:42 +0100206 ret = (double)lfp.int_partl + ((double)lfp.fractionl / UINT_MAX);
207 return ret;
208}
209
Denys Vlasenko386960a2009-12-02 01:51:24 +0100210#if 0 //UNUSED
Denys Vlasenkoca6c7e42009-11-24 07:07:42 +0100211static double
212sfp_to_d(s_fixedpt_t sfp)
213{
214 double ret;
215 sfp.int_parts = ntohs(sfp.int_parts);
216 sfp.fractions = ntohs(sfp.fractions);
217 ret = (double)sfp.int_parts + ((double)sfp.fractions / USHRT_MAX);
Adam Tkacb1585062009-11-22 03:43:55 +0100218 return ret;
219}
Denys Vlasenko386960a2009-12-02 01:51:24 +0100220#endif
Adam Tkacb1585062009-11-22 03:43:55 +0100221
222#if ENABLE_FEATURE_NTPD_SERVER
223static l_fixedpt_t
224d_to_lfp(double d)
225{
Denys Vlasenkoca6c7e42009-11-24 07:07:42 +0100226 l_fixedpt_t lfp;
227 lfp.int_partl = (uint32_t)d;
228 lfp.fractionl = (uint32_t)((d - lfp.int_partl) * UINT_MAX);
229 lfp.int_partl = htonl(lfp.int_partl);
230 lfp.fractionl = htonl(lfp.fractionl);
Adam Tkacb1585062009-11-22 03:43:55 +0100231 return lfp;
232}
Adam Tkacb1585062009-11-22 03:43:55 +0100233
Adam Tkacb1585062009-11-22 03:43:55 +0100234static s_fixedpt_t
235d_to_sfp(double d)
236{
Denys Vlasenkoca6c7e42009-11-24 07:07:42 +0100237 s_fixedpt_t sfp;
238 sfp.int_parts = (uint16_t)d;
239 sfp.fractions = (uint16_t)((d - sfp.int_parts) * USHRT_MAX);
240 sfp.int_parts = htons(sfp.int_parts);
241 sfp.fractions = htons(sfp.fractions);
Adam Tkacb1585062009-11-22 03:43:55 +0100242 return sfp;
243}
244#endif
245
Denys Vlasenko386960a2009-12-02 01:51:24 +0100246static unsigned
Adam Tkacb1585062009-11-22 03:43:55 +0100247error_interval(void)
248{
Denys Vlasenko386960a2009-12-02 01:51:24 +0100249 unsigned interval, r;
Adam Tkacb1585062009-11-22 03:43:55 +0100250 interval = INTERVAL_QUERY_PATHETIC * QSCALE_OFF_MAX / QSCALE_OFF_MIN;
Denys Vlasenko386960a2009-12-02 01:51:24 +0100251 r = (unsigned)random() % (unsigned)(interval / 10);
Adam Tkacb1585062009-11-22 03:43:55 +0100252 return (interval + r);
253}
254
255static int
Denys Vlasenko386960a2009-12-02 01:51:24 +0100256do_sendto(int fd,
Adam Tkacb1585062009-11-22 03:43:55 +0100257 const struct sockaddr *from, const struct sockaddr *to, socklen_t addrlen,
258 ntp_msg_t *msg, ssize_t len)
259{
260 ssize_t ret;
261
262 errno = 0;
263 if (!from) {
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100264 ret = sendto(fd, msg, len, MSG_DONTWAIT, to, addrlen);
Adam Tkacb1585062009-11-22 03:43:55 +0100265 } else {
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100266 ret = send_to_from(fd, msg, len, MSG_DONTWAIT, to, from, addrlen);
Adam Tkacb1585062009-11-22 03:43:55 +0100267 }
268 if (ret != len) {
269 bb_perror_msg("send failed");
270 return -1;
271 }
272 return 0;
273}
274
275static int
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100276send_query_to_peer(ntp_peer_t *p)
Adam Tkacb1585062009-11-22 03:43:55 +0100277{
Denys Vlasenkob1278a32009-11-24 16:03:47 +0100278 // Why do we need to bind()?
279 // See what happens when we don't bind:
280 //
281 // socket(PF_INET, SOCK_DGRAM, IPPROTO_IP) = 3
282 // setsockopt(3, SOL_IP, IP_TOS, [16], 4) = 0
283 // gettimeofday({1259071266, 327885}, NULL) = 0
284 // sendto(3, "xxx", 48, MSG_DONTWAIT, {sa_family=AF_INET, sin_port=htons(123), sin_addr=inet_addr("10.34.32.125")}, 16) = 48
285 // ^^^ we sent it from some source port picked by kernel.
286 // time(NULL) = 1259071266
287 // write(2, "ntpd: entering poll 15 secs\n", 28) = 28
288 // poll([{fd=3, events=POLLIN}], 1, 15000) = 1 ([{fd=3, revents=POLLIN}])
289 // recv(3, "yyy", 68, MSG_DONTWAIT) = 48
290 // ^^^ this recv will receive packets to any local port!
291 //
292 // Uncomment this and use strace to see it in action:
293#define PROBE_LOCAL_ADDR // { len_and_sockaddr lsa; lsa.len = LSA_SIZEOF_SA; getsockname(p->query.fd, &lsa.u.sa, &lsa.len); }
294
Denys Vlasenko386960a2009-12-02 01:51:24 +0100295 if (p->fd == -1) {
Denys Vlasenkob1278a32009-11-24 16:03:47 +0100296 int fd, family;
297 len_and_sockaddr *local_lsa;
298
299 family = p->lsa->u.sa.sa_family;
Denys Vlasenko386960a2009-12-02 01:51:24 +0100300 p->fd = fd = xsocket_type(&local_lsa, family, SOCK_DGRAM);
Denys Vlasenkob1278a32009-11-24 16:03:47 +0100301 /* local_lsa has "null" address and port 0 now.
302 * bind() ensures we have a *particular port* selected by kernel
Denys Vlasenko386960a2009-12-02 01:51:24 +0100303 * and remembered in p->fd, thus later recv(p->fd)
Denys Vlasenkob1278a32009-11-24 16:03:47 +0100304 * receives only packets sent to this port.
305 */
306 PROBE_LOCAL_ADDR
307 xbind(fd, &local_lsa->u.sa, local_lsa->len);
308 PROBE_LOCAL_ADDR
Adam Tkacb1585062009-11-22 03:43:55 +0100309#if ENABLE_FEATURE_IPV6
Denys Vlasenkob1278a32009-11-24 16:03:47 +0100310 if (family == AF_INET)
Adam Tkacb1585062009-11-22 03:43:55 +0100311#endif
Denys Vlasenkob1278a32009-11-24 16:03:47 +0100312 setsockopt(fd, IPPROTO_IP, IP_TOS, &const_IPTOS_LOWDELAY, sizeof(const_IPTOS_LOWDELAY));
313 free(local_lsa);
Adam Tkacb1585062009-11-22 03:43:55 +0100314 }
315
316 /*
317 * Send out a random 64-bit number as our transmit time. The NTP
318 * server will copy said number into the originate field on the
319 * response that it sends us. This is totally legal per the SNTP spec.
320 *
321 * The impact of this is two fold: we no longer send out the current
322 * system time for the world to see (which may aid an attacker), and
323 * it gives us a (not very secure) way of knowing that we're not
324 * getting spoofed by an attacker that can't capture our traffic
325 * but can spoof packets from the NTP server we're communicating with.
326 *
327 * Save the real transmit timestamp locally.
328 */
329
Denys Vlasenko386960a2009-12-02 01:51:24 +0100330 p->msg.m_xmttime.int_partl = random();
331 p->msg.m_xmttime.fractionl = random();
Denys Vlasenko907647f2009-12-02 23:17:45 +0100332 p->xmttime = gettime1900d();
Adam Tkacb1585062009-11-22 03:43:55 +0100333
Denys Vlasenko386960a2009-12-02 01:51:24 +0100334 if (do_sendto(p->fd, /*from:*/ NULL, /*to:*/ &p->lsa->u.sa, /*addrlen:*/ p->lsa->len,
335 &p->msg, NTP_MSGSIZE_NOAUTH) == -1
336 ) {
Denys Vlasenko907647f2009-12-02 23:17:45 +0100337 close(p->fd);
338 p->fd = -1;
Adam Tkacb1585062009-11-22 03:43:55 +0100339 set_next(p, INTERVAL_QUERY_PATHETIC);
340 return -1;
341 }
342
Denys Vlasenko386960a2009-12-02 01:51:24 +0100343 if (G.verbose)
Denys Vlasenkof91e63c2009-12-02 02:30:31 +0100344 bb_error_msg("sent query to %s", p->dotted);
Denys Vlasenko907647f2009-12-02 23:17:45 +0100345 set_next(p, QUERYTIME_MAX);
Adam Tkacb1585062009-11-22 03:43:55 +0100346
347 return 0;
348}
349
Denys Vlasenko907647f2009-12-02 23:17:45 +0100350
351/* Time is stepped only once, when the first packet from a peer is received.
352 */
353static void
354step_time_once(double offset)
355{
356 llist_t *item;
357 struct timeval tv;
358 char buf[80];
359 time_t tval;
360
361 if (G.time_is_stepped)
362 goto bail;
363 G.time_is_stepped = 1;
364
365 /* if the offset is small, don't step, slew (later) */
366 if (offset < STEPTIME_MIN_OFFSET && offset > -STEPTIME_MIN_OFFSET)
367 goto bail;
368
369 gettimeofday(&tv, NULL); /* never fails */
370 offset += tv.tv_sec;
371 offset += 1.0e-6 * tv.tv_usec;
372 d_to_tv(offset, &tv);
373
374 if (settimeofday(&tv, NULL) == -1)
375 bb_perror_msg_and_die("settimeofday");
376
377 tval = tv.tv_sec;
378 strftime(buf, sizeof(buf), "%a %b %e %H:%M:%S %Z %Y", localtime(&tval));
379
380 bb_error_msg("setting clock to %s (offset %fs)", buf, offset);
381
382 for (item = G.ntp_peers; item != NULL; item = item->link) {
383 ntp_peer_t *p = (ntp_peer_t *) item->data;
384 p->next_action_time -= offset;
385 }
386
387 bail:
388 if (option_mask32 & OPT_q)
389 exit(0);
390}
391
392
393/* Time is periodically slewed when we collect enough
394 * good data points.
395 */
Adam Tkacb1585062009-11-22 03:43:55 +0100396static int
Denys Vlasenko386960a2009-12-02 01:51:24 +0100397compare_offsets(const void *aa, const void *bb)
Adam Tkacb1585062009-11-22 03:43:55 +0100398{
Denys Vlasenkoca6c7e42009-11-24 07:07:42 +0100399 const ntp_peer_t *const *a = aa;
400 const ntp_peer_t *const *b = bb;
Denys Vlasenko386960a2009-12-02 01:51:24 +0100401 if ((*a)->update.o_offset < (*b)->update.o_offset)
Adam Tkacb1585062009-11-22 03:43:55 +0100402 return -1;
Denys Vlasenko386960a2009-12-02 01:51:24 +0100403 return ((*a)->update.o_offset > (*b)->update.o_offset);
Adam Tkacb1585062009-11-22 03:43:55 +0100404}
Denys Vlasenko907647f2009-12-02 23:17:45 +0100405static unsigned
Adam Tkacb1585062009-11-22 03:43:55 +0100406updated_scale(double offset)
407{
408 if (offset < 0)
409 offset = -offset;
Adam Tkacb1585062009-11-22 03:43:55 +0100410 if (offset > QSCALE_OFF_MAX)
411 return 1;
412 if (offset < QSCALE_OFF_MIN)
413 return QSCALE_OFF_MAX / QSCALE_OFF_MIN;
414 return QSCALE_OFF_MAX / offset;
415}
Adam Tkacb1585062009-11-22 03:43:55 +0100416static void
Denys Vlasenko386960a2009-12-02 01:51:24 +0100417slew_time(void)
Adam Tkacb1585062009-11-22 03:43:55 +0100418{
Denys Vlasenko4bd51892009-12-02 13:43:06 +0100419 llist_t *item;
420 double offset_median;
421 struct timeval tv;
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100422
Denys Vlasenko386960a2009-12-02 01:51:24 +0100423 {
Denys Vlasenko4bd51892009-12-02 13:43:06 +0100424 ntp_peer_t **peers = xzalloc(sizeof(peers[0]) * G.peer_cnt);
425 unsigned goodpeer_cnt = 0;
Denys Vlasenko386960a2009-12-02 01:51:24 +0100426 unsigned middle;
Denys Vlasenko386960a2009-12-02 01:51:24 +0100427
428 for (item = G.ntp_peers; item != NULL; item = item->link) {
Denys Vlasenko4bd51892009-12-02 13:43:06 +0100429 ntp_peer_t *p = (ntp_peer_t *) item->data;
Denys Vlasenko386960a2009-12-02 01:51:24 +0100430 if (p->trustlevel < TRUSTLEVEL_BADPEER)
431 continue;
Denys Vlasenko907647f2009-12-02 23:17:45 +0100432 if (!p->update.o_good) {
433 free(peers);
Denys Vlasenko4bd51892009-12-02 13:43:06 +0100434 return;
Denys Vlasenko907647f2009-12-02 23:17:45 +0100435 }
Denys Vlasenko4bd51892009-12-02 13:43:06 +0100436 peers[goodpeer_cnt++] = p;
Denys Vlasenko386960a2009-12-02 01:51:24 +0100437 }
438
Denys Vlasenko4bd51892009-12-02 13:43:06 +0100439 if (goodpeer_cnt == 0) {
440 free(peers);
441 goto clear_good;
442 }
Denys Vlasenko386960a2009-12-02 01:51:24 +0100443
Denys Vlasenko4bd51892009-12-02 13:43:06 +0100444 qsort(peers, goodpeer_cnt, sizeof(peers[0]), compare_offsets);
445
446 middle = goodpeer_cnt / 2;
447 if (middle != 0 && (goodpeer_cnt & 1) == 0) {
Denys Vlasenko386960a2009-12-02 01:51:24 +0100448 offset_median = (peers[middle-1]->update.o_offset + peers[middle]->update.o_offset) / 2;
449 G.rootdelay = (peers[middle-1]->update.o_delay + peers[middle]->update.o_delay) / 2;
450 G.stratum = 1 + MAX(peers[middle-1]->update.o_stratum, peers[middle]->update.o_stratum);
451 } else {
452 offset_median = peers[middle]->update.o_offset;
453 G.rootdelay = peers[middle]->update.o_delay;
454 G.stratum = 1 + peers[middle]->update.o_stratum;
455 }
456 G.leap = peers[middle]->update.o_leap;
457 G.refid4 = peers[middle]->update.o_refid4;
Denys Vlasenko386960a2009-12-02 01:51:24 +0100458 G.refid =
459#if ENABLE_FEATURE_IPV6
Denys Vlasenko907647f2009-12-02 23:17:45 +0100460 peers[middle]->lsa->u.sa.sa_family != AF_INET ?
Denys Vlasenko386960a2009-12-02 01:51:24 +0100461 G.refid4 :
462#endif
Denys Vlasenko907647f2009-12-02 23:17:45 +0100463 peers[middle]->lsa->u.sin.sin_addr.s_addr;
Denys Vlasenko386960a2009-12-02 01:51:24 +0100464 free(peers);
Adam Tkacb1585062009-11-22 03:43:55 +0100465 }
Denys Vlasenko907647f2009-12-02 23:17:45 +0100466//TODO: if (offset_median > BIG) step_time(offset_median)?
Adam Tkacb1585062009-11-22 03:43:55 +0100467
Denys Vlasenko907647f2009-12-02 23:17:45 +0100468 G.scale = updated_scale(offset_median);
469
470 bb_error_msg("adjusting clock by %fs, our stratum is %u, time scale %u",
471 offset_median, G.stratum, G.scale);
Adam Tkacb1585062009-11-22 03:43:55 +0100472
Denys Vlasenkofae9f492009-12-01 02:32:01 +0100473 errno = 0;
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100474 d_to_tv(offset_median, &tv);
Denys Vlasenko907647f2009-12-02 23:17:45 +0100475 if (adjtime(&tv, &tv) == -1)
476 bb_perror_msg_and_die("adjtime failed");
477 if (G.verbose >= 2)
478 bb_error_msg("old adjust: %d.%06u", (int)tv.tv_sec, (unsigned)tv.tv_usec);
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100479
Denys Vlasenko907647f2009-12-02 23:17:45 +0100480 if (G.first_adj_done) {
481 uint8_t synced = (tv.tv_sec == 0 && tv.tv_usec == 0);
482 if (synced != G.synced) {
483 G.synced = synced;
484 bb_error_msg("clock is %ssynced", synced ? "" : "un");
485 }
486 }
487 G.first_adj_done = 1;
488
489 G.reftime = gettime1900d();
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100490
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100491 clear_good:
Adam Tkacb1585062009-11-22 03:43:55 +0100492 for (item = G.ntp_peers; item != NULL; item = item->link) {
Denys Vlasenko4bd51892009-12-02 13:43:06 +0100493 ntp_peer_t *p = (ntp_peer_t *) item->data;
Denys Vlasenko386960a2009-12-02 01:51:24 +0100494 p->update.o_good = 0;
Adam Tkacb1585062009-11-22 03:43:55 +0100495 }
496}
497
498static void
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100499update_peer_data(ntp_peer_t *p)
Adam Tkacb1585062009-11-22 03:43:55 +0100500{
Denys Vlasenko386960a2009-12-02 01:51:24 +0100501 /* Clock filter.
502 * Find the offset which arrived with the lowest delay.
503 * Use that as the peer update.
504 * Invalidate it and all older ones.
Adam Tkacb1585062009-11-22 03:43:55 +0100505 */
Denys Vlasenko386960a2009-12-02 01:51:24 +0100506 int i;
Denys Vlasenko4bd51892009-12-02 13:43:06 +0100507 int best = -1;
508 int good = 0;
Adam Tkacb1585062009-11-22 03:43:55 +0100509
Denys Vlasenko386960a2009-12-02 01:51:24 +0100510 for (i = 0; i < OFFSET_ARRAY_SIZE; i++) {
511 if (p->reply[i].o_good) {
Adam Tkacb1585062009-11-22 03:43:55 +0100512 good++;
Denys Vlasenko4bd51892009-12-02 13:43:06 +0100513 if (best < 0 || p->reply[i].o_delay < p->reply[best].o_delay)
Adam Tkacb1585062009-11-22 03:43:55 +0100514 best = i;
515 }
516 }
517
Denys Vlasenko386960a2009-12-02 01:51:24 +0100518 if (good < 8) //FIXME: was it meant to be OFFSET_ARRAY_SIZE, not 8?
Adam Tkacb1585062009-11-22 03:43:55 +0100519 return;
520
521 memcpy(&p->update, &p->reply[best], sizeof(p->update));
Denys Vlasenko386960a2009-12-02 01:51:24 +0100522 slew_time();
Adam Tkacb1585062009-11-22 03:43:55 +0100523
524 for (i = 0; i < OFFSET_ARRAY_SIZE; i++)
Denys Vlasenko386960a2009-12-02 01:51:24 +0100525 if (p->reply[i].o_rcvd <= p->reply[best].o_rcvd)
526 p->reply[i].o_good = 0;
Adam Tkacb1585062009-11-22 03:43:55 +0100527}
528
Denys Vlasenko386960a2009-12-02 01:51:24 +0100529static unsigned
530scale_interval(unsigned requested)
Adam Tkacb1585062009-11-22 03:43:55 +0100531{
Denys Vlasenko386960a2009-12-02 01:51:24 +0100532 unsigned interval, r;
Adam Tkacb1585062009-11-22 03:43:55 +0100533 interval = requested * G.scale;
Denys Vlasenko386960a2009-12-02 01:51:24 +0100534 r = (unsigned)random() % (unsigned)(MAX(5, interval / 10));
Adam Tkacb1585062009-11-22 03:43:55 +0100535 return (interval + r);
536}
Adam Tkacb1585062009-11-22 03:43:55 +0100537static void
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100538recv_and_process_peer_pkt(ntp_peer_t *p)
Adam Tkacb1585062009-11-22 03:43:55 +0100539{
Adam Tkacb1585062009-11-22 03:43:55 +0100540 ssize_t size;
541 ntp_msg_t msg;
542 double T1, T2, T3, T4;
Denys Vlasenko386960a2009-12-02 01:51:24 +0100543 unsigned interval;
Adam Tkacb1585062009-11-22 03:43:55 +0100544 ntp_offset_t *offset;
545
Denys Vlasenkob1278a32009-11-24 16:03:47 +0100546 /* We can recvfrom here and check from.IP, but some multihomed
547 * ntp servers reply from their *other IP*.
548 * TODO: maybe we should check at least what we can: from.port == 123?
549 */
Denys Vlasenko386960a2009-12-02 01:51:24 +0100550 size = recv(p->fd, &msg, sizeof(msg), MSG_DONTWAIT);
Adam Tkacb1585062009-11-22 03:43:55 +0100551 if (size == -1) {
Denys Vlasenko386960a2009-12-02 01:51:24 +0100552 bb_perror_msg("recv(%s) error", p->dotted);
Adam Tkacb1585062009-11-22 03:43:55 +0100553 if (errno == EHOSTUNREACH || errno == EHOSTDOWN
554 || errno == ENETUNREACH || errno == ENETDOWN
555 || errno == ECONNREFUSED || errno == EADDRNOTAVAIL
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100556 || errno == EAGAIN
Adam Tkacb1585062009-11-22 03:43:55 +0100557 ) {
558//TODO: always do this?
559 set_next(p, error_interval());
Denys Vlasenko386960a2009-12-02 01:51:24 +0100560 goto close_sock;
Adam Tkacb1585062009-11-22 03:43:55 +0100561 }
562 xfunc_die();
563 }
564
Adam Tkacb1585062009-11-22 03:43:55 +0100565 if (size != NTP_MSGSIZE_NOAUTH && size != NTP_MSGSIZE) {
Denys Vlasenko386960a2009-12-02 01:51:24 +0100566 bb_error_msg("malformed packet received from %s", p->dotted);
Adam Tkacb1585062009-11-22 03:43:55 +0100567 goto bail;
568 }
569
Denys Vlasenko386960a2009-12-02 01:51:24 +0100570 if (msg.m_orgtime.int_partl != p->msg.m_xmttime.int_partl
571 || msg.m_orgtime.fractionl != p->msg.m_xmttime.fractionl
Adam Tkacb1585062009-11-22 03:43:55 +0100572 ) {
573 goto bail;
574 }
575
Denys Vlasenko386960a2009-12-02 01:51:24 +0100576 if ((msg.m_status & LI_ALARM) == LI_ALARM
577 || msg.m_stratum == 0
578 || msg.m_stratum > NTP_MAXSTRATUM
Adam Tkacb1585062009-11-22 03:43:55 +0100579 ) {
580 interval = error_interval();
Denys Vlasenkof91e63c2009-12-02 02:30:31 +0100581 bb_error_msg("reply from %s: not synced, next query in %us", p->dotted, interval);
Denys Vlasenko386960a2009-12-02 01:51:24 +0100582 goto close_sock;
Adam Tkacb1585062009-11-22 03:43:55 +0100583 }
584
585 /*
586 * From RFC 2030 (with a correction to the delay math):
587 *
588 * Timestamp Name ID When Generated
589 * ------------------------------------------------------------
590 * Originate Timestamp T1 time request sent by client
591 * Receive Timestamp T2 time request received by server
592 * Transmit Timestamp T3 time reply sent by server
593 * Destination Timestamp T4 time reply received by client
594 *
595 * The roundtrip delay d and local clock offset t are defined as
596 *
597 * d = (T4 - T1) - (T3 - T2) t = ((T2 - T1) + (T3 - T4)) / 2.
598 */
599
Denys Vlasenko907647f2009-12-02 23:17:45 +0100600 T4 = gettime1900d();
Denys Vlasenko386960a2009-12-02 01:51:24 +0100601 T1 = p->xmttime;
602 T2 = lfp_to_d(msg.m_rectime);
603 T3 = lfp_to_d(msg.m_xmttime);
Adam Tkacb1585062009-11-22 03:43:55 +0100604
605 offset = &p->reply[p->shift];
606
Denys Vlasenko386960a2009-12-02 01:51:24 +0100607 offset->o_offset = ((T2 - T1) + (T3 - T4)) / 2;
608 offset->o_delay = (T4 - T1) - (T3 - T2);
609 if (offset->o_delay < 0) {
Denys Vlasenko4bd51892009-12-02 13:43:06 +0100610 bb_error_msg("reply from %s: negative delay %f", p->dotted, offset->o_delay);
Adam Tkacb1585062009-11-22 03:43:55 +0100611 interval = error_interval();
612 set_next(p, interval);
Denys Vlasenko386960a2009-12-02 01:51:24 +0100613 goto close_sock;
Adam Tkacb1585062009-11-22 03:43:55 +0100614 }
Denys Vlasenko386960a2009-12-02 01:51:24 +0100615 //UNUSED: offset->o_error = (T2 - T1) - (T3 - T4);
Denys Vlasenko4bd51892009-12-02 13:43:06 +0100616 offset->o_rcvd = time(NULL); /* can use (time_t)(T4 - OFFSET_1900_1970) too */
Denys Vlasenko386960a2009-12-02 01:51:24 +0100617 offset->o_good = 1;
Adam Tkacb1585062009-11-22 03:43:55 +0100618
Denys Vlasenko386960a2009-12-02 01:51:24 +0100619 offset->o_leap = (msg.m_status & LI_MASK);
620 //UNUSED: offset->o_precision = msg.m_precision;
621 //UNUSED: offset->o_rootdelay = sfp_to_d(msg.m_rootdelay);
622 //UNUSED: offset->o_rootdispersion = sfp_to_d(msg.m_dispersion);
623 //UNUSED: offset->o_refid = ntohl(msg.m_refid);
624 offset->o_refid4 = msg.m_xmttime.fractionl;
625 //UNUSED: offset->o_reftime = lfp_to_d(msg.m_reftime);
626 //UNUSED: offset->o_poll = msg.m_ppoll;
627 offset->o_stratum = msg.m_stratum;
Adam Tkacb1585062009-11-22 03:43:55 +0100628
629 if (p->trustlevel < TRUSTLEVEL_PATHETIC)
630 interval = scale_interval(INTERVAL_QUERY_PATHETIC);
631 else if (p->trustlevel < TRUSTLEVEL_AGRESSIVE)
632 interval = scale_interval(INTERVAL_QUERY_AGRESSIVE);
633 else
634 interval = scale_interval(INTERVAL_QUERY_NORMAL);
635
636 set_next(p, interval);
Adam Tkacb1585062009-11-22 03:43:55 +0100637
638 /* every received reply which we do not discard increases trust */
639 if (p->trustlevel < TRUSTLEVEL_MAX) {
Adam Tkacb1585062009-11-22 03:43:55 +0100640 p->trustlevel++;
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100641 if (p->trustlevel == TRUSTLEVEL_BADPEER)
Denys Vlasenko386960a2009-12-02 01:51:24 +0100642 bb_error_msg("peer %s now valid", p->dotted);
Adam Tkacb1585062009-11-22 03:43:55 +0100643 }
644
Denys Vlasenko386960a2009-12-02 01:51:24 +0100645 if (G.verbose)
Denys Vlasenkof91e63c2009-12-02 02:30:31 +0100646 bb_error_msg("reply from %s: offset %f delay %f, next query in %us", p->dotted,
Denys Vlasenko386960a2009-12-02 01:51:24 +0100647 offset->o_offset, offset->o_delay, interval);
Adam Tkacb1585062009-11-22 03:43:55 +0100648
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100649 update_peer_data(p);
Denys Vlasenkof91e63c2009-12-02 02:30:31 +0100650//TODO: do it after all peers had a chance to return at least one reply?
Denys Vlasenko386960a2009-12-02 01:51:24 +0100651 step_time_once(offset->o_offset);
Adam Tkacb1585062009-11-22 03:43:55 +0100652
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100653 p->shift++;
654 if (p->shift >= OFFSET_ARRAY_SIZE)
Adam Tkacb1585062009-11-22 03:43:55 +0100655 p->shift = 0;
656
Denys Vlasenko386960a2009-12-02 01:51:24 +0100657 close_sock:
Denys Vlasenko907647f2009-12-02 23:17:45 +0100658 /* We do not expect any more packets from this peer for now.
Denys Vlasenko386960a2009-12-02 01:51:24 +0100659 * Closing the socket informs kernel about it.
660 * We open a new socket when we send a new query.
661 */
662 close(p->fd);
663 p->fd = -1;
Adam Tkacb1585062009-11-22 03:43:55 +0100664 bail:
Denys Vlasenko386960a2009-12-02 01:51:24 +0100665 return;
Adam Tkacb1585062009-11-22 03:43:55 +0100666}
667
668#if ENABLE_FEATURE_NTPD_SERVER
669static void
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100670recv_and_process_client_pkt(void /*int fd*/)
Adam Tkacb1585062009-11-22 03:43:55 +0100671{
Denys Vlasenkoca6c7e42009-11-24 07:07:42 +0100672 ssize_t size;
673 uint8_t version;
674 double rectime;
675 len_and_sockaddr *to;
676 struct sockaddr *from;
677 ntp_msg_t msg;
678 uint8_t query_status;
679 uint8_t query_ppoll;
680 l_fixedpt_t query_xmttime;
Adam Tkacb1585062009-11-22 03:43:55 +0100681
682 to = get_sock_lsa(G.listen_fd);
683 from = xzalloc(to->len);
684
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100685 size = recv_from_to(G.listen_fd, &msg, sizeof(msg), MSG_DONTWAIT, from, &to->u.sa, to->len);
Adam Tkacb1585062009-11-22 03:43:55 +0100686 if (size != NTP_MSGSIZE_NOAUTH && size != NTP_MSGSIZE) {
Denys Vlasenkoca6c7e42009-11-24 07:07:42 +0100687 char *addr;
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100688 if (size < 0) {
689 if (errno == EAGAIN)
690 goto bail;
Denys Vlasenko907647f2009-12-02 23:17:45 +0100691 bb_perror_msg_and_die("recv");
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100692 }
Denys Vlasenkoca6c7e42009-11-24 07:07:42 +0100693 addr = xmalloc_sockaddr2dotted_noport(from);
Denys Vlasenko907647f2009-12-02 23:17:45 +0100694 bb_error_msg("malformed packet received from %s: size %u", addr, (int)size);
Adam Tkacb1585062009-11-22 03:43:55 +0100695 free(addr);
696 goto bail;
697 }
698
Denys Vlasenko386960a2009-12-02 01:51:24 +0100699 query_status = msg.m_status;
700 query_ppoll = msg.m_ppoll;
701 query_xmttime = msg.m_xmttime;
Adam Tkacb1585062009-11-22 03:43:55 +0100702
Denys Vlasenkoca6c7e42009-11-24 07:07:42 +0100703 /* Build a reply packet */
704 memset(&msg, 0, sizeof(msg));
Denys Vlasenko386960a2009-12-02 01:51:24 +0100705 msg.m_status = G.synced ? G.leap : LI_ALARM;
706 msg.m_status |= (query_status & VERSION_MASK);
707 msg.m_status |= ((query_status & MODE_MASK) == MODE_CLIENT) ?
Adam Tkacb1585062009-11-22 03:43:55 +0100708 MODE_SERVER : MODE_SYM_PAS;
Denys Vlasenko386960a2009-12-02 01:51:24 +0100709 msg.m_stratum = G.stratum;
710 msg.m_ppoll = query_ppoll;
Denys Vlasenko907647f2009-12-02 23:17:45 +0100711 msg.m_precision = G_precision;
712 rectime = gettime1900d();
Denys Vlasenko386960a2009-12-02 01:51:24 +0100713 msg.m_xmttime = msg.m_rectime = d_to_lfp(rectime);
714 msg.m_reftime = d_to_lfp(G.reftime);
Denys Vlasenko907647f2009-12-02 23:17:45 +0100715 //msg.m_xmttime = d_to_lfp(gettime1900d()); // = msg.m_rectime
Denys Vlasenko386960a2009-12-02 01:51:24 +0100716 msg.m_orgtime = query_xmttime;
717 msg.m_rootdelay = d_to_sfp(G.rootdelay);
Denys Vlasenkoca6c7e42009-11-24 07:07:42 +0100718 version = (query_status & VERSION_MASK); /* ... >> VERSION_SHIFT - done below instead */
Denys Vlasenko386960a2009-12-02 01:51:24 +0100719 msg.m_refid = (version > (3 << VERSION_SHIFT)) ? G.refid4 : G.refid;
Adam Tkacb1585062009-11-22 03:43:55 +0100720
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100721 /* We reply from the local address packet was sent to,
Adam Tkacb1585062009-11-22 03:43:55 +0100722 * this makes to/from look swapped here: */
Denys Vlasenko386960a2009-12-02 01:51:24 +0100723 do_sendto(G.listen_fd,
Denys Vlasenkoca6c7e42009-11-24 07:07:42 +0100724 /*from:*/ &to->u.sa, /*to:*/ from, /*addrlen:*/ to->len,
725 &msg, size);
Adam Tkacb1585062009-11-22 03:43:55 +0100726
727 bail:
728 free(to);
729 free(from);
730}
731#endif
732
733/* Upstream ntpd's options:
734 *
735 * -4 Force DNS resolution of host names to the IPv4 namespace.
736 * -6 Force DNS resolution of host names to the IPv6 namespace.
737 * -a Require cryptographic authentication for broadcast client,
738 * multicast client and symmetric passive associations.
739 * This is the default.
740 * -A Do not require cryptographic authentication for broadcast client,
741 * multicast client and symmetric passive associations.
742 * This is almost never a good idea.
743 * -b Enable the client to synchronize to broadcast servers.
744 * -c conffile
745 * Specify the name and path of the configuration file,
746 * default /etc/ntp.conf
747 * -d Specify debugging mode. This option may occur more than once,
748 * with each occurrence indicating greater detail of display.
749 * -D level
750 * Specify debugging level directly.
751 * -f driftfile
752 * Specify the name and path of the frequency file.
753 * This is the same operation as the "driftfile FILE"
754 * configuration command.
755 * -g Normally, ntpd exits with a message to the system log
756 * if the offset exceeds the panic threshold, which is 1000 s
757 * by default. This option allows the time to be set to any value
758 * without restriction; however, this can happen only once.
759 * If the threshold is exceeded after that, ntpd will exit
760 * with a message to the system log. This option can be used
761 * with the -q and -x options. See the tinker command for other options.
762 * -i jaildir
763 * Chroot the server to the directory jaildir. This option also implies
764 * that the server attempts to drop root privileges at startup
765 * (otherwise, chroot gives very little additional security).
766 * You may need to also specify a -u option.
767 * -k keyfile
768 * Specify the name and path of the symmetric key file,
769 * default /etc/ntp/keys. This is the same operation
770 * as the "keys FILE" configuration command.
771 * -l logfile
772 * Specify the name and path of the log file. The default
773 * is the system log file. This is the same operation as
774 * the "logfile FILE" configuration command.
775 * -L Do not listen to virtual IPs. The default is to listen.
776 * -n Don't fork.
777 * -N To the extent permitted by the operating system,
778 * run the ntpd at the highest priority.
779 * -p pidfile
780 * Specify the name and path of the file used to record the ntpd
781 * process ID. This is the same operation as the "pidfile FILE"
782 * configuration command.
783 * -P priority
784 * To the extent permitted by the operating system,
785 * run the ntpd at the specified priority.
786 * -q Exit the ntpd just after the first time the clock is set.
787 * This behavior mimics that of the ntpdate program, which is
788 * to be retired. The -g and -x options can be used with this option.
789 * Note: The kernel time discipline is disabled with this option.
790 * -r broadcastdelay
791 * Specify the default propagation delay from the broadcast/multicast
792 * server to this client. This is necessary only if the delay
793 * cannot be computed automatically by the protocol.
794 * -s statsdir
795 * Specify the directory path for files created by the statistics
796 * facility. This is the same operation as the "statsdir DIR"
797 * configuration command.
798 * -t key
799 * Add a key number to the trusted key list. This option can occur
800 * more than once.
801 * -u user[:group]
802 * Specify a user, and optionally a group, to switch to.
803 * -v variable
804 * -V variable
805 * Add a system variable listed by default.
806 * -x Normally, the time is slewed if the offset is less than the step
807 * threshold, which is 128 ms by default, and stepped if above
808 * the threshold. This option sets the threshold to 600 s, which is
809 * well within the accuracy window to set the clock manually.
810 * Note: since the slew rate of typical Unix kernels is limited
811 * to 0.5 ms/s, each second of adjustment requires an amortization
812 * interval of 2000 s. Thus, an adjustment as much as 600 s
813 * will take almost 14 days to complete. This option can be used
814 * with the -g and -q options. See the tinker command for other options.
815 * Note: The kernel time discipline is disabled with this option.
816 */
817
Adam Tkacb1585062009-11-22 03:43:55 +0100818/* By doing init in a separate function we decrease stack usage
819 * in main loop.
820 */
821static NOINLINE void ntp_init(char **argv)
822{
823 unsigned opts;
824 llist_t *peers;
825
Denys Vlasenkoca6c7e42009-11-24 07:07:42 +0100826 srandom(getpid());
Adam Tkacb1585062009-11-22 03:43:55 +0100827
828 if (getuid())
Denys Vlasenkob2e5fc32009-11-25 14:52:47 +0100829 bb_error_msg_and_die(bb_msg_you_must_be_root);
Adam Tkacb1585062009-11-22 03:43:55 +0100830
831 peers = NULL;
832 opt_complementary = "dd:p::"; /* d: counter, p: list */
833 opts = getopt32(argv,
Denys Vlasenko907647f2009-12-02 23:17:45 +0100834 "nqNx" /* compat */
Adam Tkacb1585062009-11-22 03:43:55 +0100835 "p:"IF_FEATURE_NTPD_SERVER("l") /* NOT compat */
836 "d" /* compat */
Denys Vlasenko907647f2009-12-02 23:17:45 +0100837 "46aAbgL", /* compat, ignored */
Adam Tkacb1585062009-11-22 03:43:55 +0100838 &peers, &G.verbose);
Denys Vlasenkob2e5fc32009-11-25 14:52:47 +0100839 if (!(opts & (OPT_p|OPT_l)))
840 bb_show_usage();
Denys Vlasenko907647f2009-12-02 23:17:45 +0100841 if (opts & OPT_x) /* disable stepping, only slew is allowed */
842 G.time_is_stepped = 1;
Denys Vlasenko160b9ca2009-11-27 02:35:15 +0100843 while (peers)
844 add_peers(llist_pop(&peers));
845 if (!(opts & OPT_n)) {
846 bb_daemonize_or_rexec(DAEMON_DEVNULL_STDIO, argv);
847 logmode = LOGMODE_NONE;
848 }
Adam Tkacb1585062009-11-22 03:43:55 +0100849#if ENABLE_FEATURE_NTPD_SERVER
850 G.listen_fd = -1;
851 if (opts & OPT_l) {
852 G.listen_fd = create_and_bind_dgram_or_die(NULL, 123);
853 socket_want_pktinfo(G.listen_fd);
854 setsockopt(G.listen_fd, IPPROTO_IP, IP_TOS, &const_IPTOS_LOWDELAY, sizeof(const_IPTOS_LOWDELAY));
855 }
856#endif
Denys Vlasenkob2e5fc32009-11-25 14:52:47 +0100857 /* I hesitate to set -20 prio. -15 should be high enough for timekeeping */
858 if (opts & OPT_N)
859 setpriority(PRIO_PROCESS, 0, -15);
Adam Tkacb1585062009-11-22 03:43:55 +0100860
861 /* Set some globals */
Denys Vlasenko907647f2009-12-02 23:17:45 +0100862#if 0
863 /* With constant b = 100, G.precision is also constant -6.
864 * Uncomment this and you'll see */
Adam Tkacb1585062009-11-22 03:43:55 +0100865 {
866 int prec = 0;
867 int b;
Denys Vlasenko907647f2009-12-02 23:17:45 +0100868# if 0
Adam Tkacb1585062009-11-22 03:43:55 +0100869 struct timespec tp;
870 /* We can use sys_clock_getres but assuming 10ms tick should be fine */
871 clock_getres(CLOCK_REALTIME, &tp);
872 tp.tv_sec = 0;
873 tp.tv_nsec = 10000000;
874 b = 1000000000 / tp.tv_nsec; /* convert to Hz */
Denys Vlasenko907647f2009-12-02 23:17:45 +0100875# else
Adam Tkacb1585062009-11-22 03:43:55 +0100876 b = 100; /* b = 1000000000/10000000 = 100 */
Denys Vlasenko907647f2009-12-02 23:17:45 +0100877# endif
Adam Tkacb1585062009-11-22 03:43:55 +0100878 while (b > 1)
879 prec--, b >>= 1;
Denys Vlasenko907647f2009-12-02 23:17:45 +0100880 //G.precision = prec;
881 bb_error_msg("G.precision:%d", prec); /* -6 */
Adam Tkacb1585062009-11-22 03:43:55 +0100882 }
Denys Vlasenko907647f2009-12-02 23:17:45 +0100883#endif
Adam Tkacb1585062009-11-22 03:43:55 +0100884 G.scale = 1;
Adam Tkacb1585062009-11-22 03:43:55 +0100885
886 bb_signals((1 << SIGTERM) | (1 << SIGINT), record_signo);
887 bb_signals((1 << SIGPIPE) | (1 << SIGHUP), SIG_IGN);
888}
889
890int ntpd_main(int argc UNUSED_PARAM, char **argv) MAIN_EXTERNALLY_VISIBLE;
891int ntpd_main(int argc UNUSED_PARAM, char **argv)
892{
893 struct globals g;
Adam Tkacb1585062009-11-22 03:43:55 +0100894 struct pollfd *pfd;
895 ntp_peer_t **idx2peer;
896
897 memset(&g, 0, sizeof(g));
898 SET_PTR_TO_GLOBALS(&g);
899
900 ntp_init(argv);
901
Denys Vlasenko8d580c72009-11-23 16:27:16 +0100902 {
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100903 unsigned cnt = g.peer_cnt;
Denys Vlasenko8d580c72009-11-23 16:27:16 +0100904 /* if ENABLE_FEATURE_NTPD_SERVER, + 1 for listen_fd: */
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100905 idx2peer = xzalloc(sizeof(void *) * (cnt + ENABLE_FEATURE_NTPD_SERVER));
906 pfd = xzalloc(sizeof(pfd[0]) * (cnt + ENABLE_FEATURE_NTPD_SERVER));
Denys Vlasenko8d580c72009-11-23 16:27:16 +0100907 }
Adam Tkacb1585062009-11-22 03:43:55 +0100908
909 while (!bb_got_signal) {
910 llist_t *item;
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100911 unsigned i, j;
Adam Tkacb1585062009-11-22 03:43:55 +0100912 unsigned sent_cnt, trial_cnt;
913 int nfds, timeout;
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100914 time_t cur_time, nextaction;
Adam Tkacb1585062009-11-22 03:43:55 +0100915
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100916 /* Nothing between here and poll() blocks for any significant time */
917
918 cur_time = time(NULL);
919 nextaction = cur_time + 3600;
Adam Tkacb1585062009-11-22 03:43:55 +0100920
921 i = 0;
922#if ENABLE_FEATURE_NTPD_SERVER
923 if (g.listen_fd != -1) {
924 pfd[0].fd = g.listen_fd;
925 pfd[0].events = POLLIN;
926 i++;
927 }
928#endif
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100929 /* Pass over peer list, send requests, time out on receives */
Adam Tkacb1585062009-11-22 03:43:55 +0100930 sent_cnt = trial_cnt = 0;
931 for (item = g.ntp_peers; item != NULL; item = item->link) {
932 ntp_peer_t *p = (ntp_peer_t *) item->data;
933
Denys Vlasenko907647f2009-12-02 23:17:45 +0100934 /* Overflow-safe "if (p->next_action_time <= cur_time) ..." */
935 if ((int)(cur_time - p->next_action_time) >= 0) {
936 if (p->fd == -1) {
937 /* Time to send new req */
938 trial_cnt++;
939 if (send_query_to_peer(p) == 0)
940 sent_cnt++;
941 } else {
942 /* Timed out waiting for reply */
943 close(p->fd);
944 p->fd = -1;
945 timeout = error_interval();
946 bb_error_msg("timed out waiting for %s, "
947 "next query in %us", p->dotted, timeout);
948 if (p->trustlevel >= TRUSTLEVEL_BADPEER) {
949 p->trustlevel /= 2;
950 if (p->trustlevel < TRUSTLEVEL_BADPEER)
951 bb_error_msg("peer %s now invalid", p->dotted);
952 }
953 set_next(p, timeout);
Adam Tkacb1585062009-11-22 03:43:55 +0100954 }
Adam Tkacb1585062009-11-22 03:43:55 +0100955 }
956
Denys Vlasenko907647f2009-12-02 23:17:45 +0100957 if (p->next_action_time < nextaction)
958 nextaction = p->next_action_time;
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100959
Denys Vlasenko907647f2009-12-02 23:17:45 +0100960 if (p->fd >= 0) {
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100961 /* Wait for reply from this peer */
Denys Vlasenko386960a2009-12-02 01:51:24 +0100962 pfd[i].fd = p->fd;
Adam Tkacb1585062009-11-22 03:43:55 +0100963 pfd[i].events = POLLIN;
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100964 idx2peer[i] = p;
Adam Tkacb1585062009-11-22 03:43:55 +0100965 i++;
966 }
967 }
968
Denys Vlasenko8d580c72009-11-23 16:27:16 +0100969 if ((trial_cnt > 0 && sent_cnt == 0) || g.peer_cnt == 0)
Denys Vlasenkofae9f492009-12-01 02:32:01 +0100970 step_time_once(0); /* no good peers, don't wait */
Adam Tkacb1585062009-11-22 03:43:55 +0100971
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100972 timeout = nextaction - cur_time;
Denys Vlasenko386960a2009-12-02 01:51:24 +0100973 if (timeout < 1)
974 timeout = 1;
Adam Tkacb1585062009-11-22 03:43:55 +0100975
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100976 /* Here we may block */
Denys Vlasenko386960a2009-12-02 01:51:24 +0100977 if (g.verbose >= 2)
Denys Vlasenko907647f2009-12-02 23:17:45 +0100978 bb_error_msg("poll %us, sockets:%u", timeout, i);
Adam Tkacb1585062009-11-22 03:43:55 +0100979 nfds = poll(pfd, i, timeout * 1000);
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100980 if (nfds <= 0)
981 continue;
Adam Tkacb1585062009-11-22 03:43:55 +0100982
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100983 /* Process any received packets */
Adam Tkacb1585062009-11-22 03:43:55 +0100984 j = 0;
985#if ENABLE_FEATURE_NTPD_SERVER
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100986 if (g.listen_fd != -1) {
987 if (pfd[0].revents /* & (POLLIN|POLLERR)*/) {
Adam Tkacb1585062009-11-22 03:43:55 +0100988 nfds--;
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100989 recv_and_process_client_pkt(/*g.listen_fd*/);
Adam Tkacb1585062009-11-22 03:43:55 +0100990 }
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100991 j = 1;
Adam Tkacb1585062009-11-22 03:43:55 +0100992 }
993#endif
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100994 for (; nfds != 0 && j < i; j++) {
995 if (pfd[j].revents /* & (POLLIN|POLLERR)*/) {
Adam Tkacb1585062009-11-22 03:43:55 +0100996 nfds--;
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100997 recv_and_process_peer_pkt(idx2peer[j]);
Adam Tkacb1585062009-11-22 03:43:55 +0100998 }
999 }
1000 } /* while (!bb_got_signal) */
1001
1002 kill_myself_with_sig(bb_got_signal);
1003}