blob: 3bca69a4c58797b7be107e1dc7f3335533cac15d [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;
Denys Vlasenko907647f2009-12-02 23:17:45 +0100111 char *hostname;
Denys Vlasenko386960a2009-12-02 01:51:24 +0100112 char *dotted;
Denys Vlasenko907647f2009-12-02 23:17:45 +0100113 /* When to send new query (if fd == -1)
114 * or when receive times out (if fd >= 0): */
115 time_t next_action_time;
Denys Vlasenko386960a2009-12-02 01:51:24 +0100116 int fd;
Denys Vlasenko386960a2009-12-02 01:51:24 +0100117 uint8_t shift;
118 uint8_t trustlevel;
119 ntp_msg_t msg;
Denys Vlasenko907647f2009-12-02 23:17:45 +0100120 double xmttime;
Denys Vlasenko386960a2009-12-02 01:51:24 +0100121 ntp_offset_t update;
122 ntp_offset_t reply[OFFSET_ARRAY_SIZE];
123} ntp_peer_t;
Adam Tkacb1585062009-11-22 03:43:55 +0100124
Denys Vlasenko8d580c72009-11-23 16:27:16 +0100125enum {
126 OPT_n = (1 << 0),
Denys Vlasenko907647f2009-12-02 23:17:45 +0100127 OPT_q = (1 << 1),
128 OPT_N = (1 << 2),
129 OPT_x = (1 << 3),
Denys Vlasenko8d580c72009-11-23 16:27:16 +0100130 /* Insert new options above this line. */
131 /* Non-compat options: */
Denys Vlasenkob2e5fc32009-11-25 14:52:47 +0100132 OPT_p = (1 << 4),
133 OPT_l = (1 << 5) * ENABLE_FEATURE_NTPD_SERVER,
Denys Vlasenko8d580c72009-11-23 16:27:16 +0100134};
135
Adam Tkacb1585062009-11-22 03:43:55 +0100136
137struct globals {
Denys Vlasenko386960a2009-12-02 01:51:24 +0100138 double rootdelay;
139 double reftime;
140 llist_t *ntp_peers;
Adam Tkacb1585062009-11-22 03:43:55 +0100141#if ENABLE_FEATURE_NTPD_SERVER
142 int listen_fd;
143#endif
Denys Vlasenko386960a2009-12-02 01:51:24 +0100144 unsigned verbose;
Denys Vlasenkob1278a32009-11-24 16:03:47 +0100145 unsigned peer_cnt;
Denys Vlasenko907647f2009-12-02 23:17:45 +0100146 unsigned scale;
Denys Vlasenko386960a2009-12-02 01:51:24 +0100147 uint32_t refid;
148 uint32_t refid4;
Denys Vlasenko386960a2009-12-02 01:51:24 +0100149 uint8_t synced;
150 uint8_t leap;
Denys Vlasenko907647f2009-12-02 23:17:45 +0100151#define G_precision -6
152// int8_t precision;
Denys Vlasenko386960a2009-12-02 01:51:24 +0100153 uint8_t stratum;
Denys Vlasenkof91e63c2009-12-02 02:30:31 +0100154 uint8_t time_is_stepped;
Denys Vlasenkofae9f492009-12-01 02:32:01 +0100155 uint8_t first_adj_done;
Adam Tkacb1585062009-11-22 03:43:55 +0100156};
157#define G (*ptr_to_globals)
158
159
160static const int const_IPTOS_LOWDELAY = IPTOS_LOWDELAY;
161
162
163static void
Denys Vlasenko386960a2009-12-02 01:51:24 +0100164set_next(ntp_peer_t *p, unsigned t)
Adam Tkacb1585062009-11-22 03:43:55 +0100165{
Denys Vlasenko907647f2009-12-02 23:17:45 +0100166 p->next_action_time = time(NULL) + t;
Adam Tkacb1585062009-11-22 03:43:55 +0100167}
168
169static void
Denys Vlasenko907647f2009-12-02 23:17:45 +0100170add_peers(char *s)
Adam Tkacb1585062009-11-22 03:43:55 +0100171{
172 ntp_peer_t *p;
173
174 p = xzalloc(sizeof(*p));
Denys Vlasenko907647f2009-12-02 23:17:45 +0100175 p->hostname = s;
176 p->dotted = s;
Denys Vlasenko386960a2009-12-02 01:51:24 +0100177 p->fd = -1;
178 p->msg.m_status = MODE_CLIENT | (NTP_VERSION << 3);
Adam Tkacb1585062009-11-22 03:43:55 +0100179 p->trustlevel = TRUSTLEVEL_PATHETIC;
Denys Vlasenko907647f2009-12-02 23:17:45 +0100180 p->next_action_time = time(NULL); /* = set_next(p, 0); */
Adam Tkacb1585062009-11-22 03:43:55 +0100181
182 llist_add_to(&G.ntp_peers, p);
183 G.peer_cnt++;
184}
185
186static double
Denys Vlasenko907647f2009-12-02 23:17:45 +0100187gettime1900d(void)
Adam Tkacb1585062009-11-22 03:43:55 +0100188{
Denys Vlasenkoca6c7e42009-11-24 07:07:42 +0100189 struct timeval tv;
Adam Tkacb1585062009-11-22 03:43:55 +0100190 gettimeofday(&tv, NULL); /* never fails */
Denys Vlasenkob1278a32009-11-24 16:03:47 +0100191 return (tv.tv_sec + 1.0e-6 * tv.tv_usec + OFFSET_1900_1970);
Adam Tkacb1585062009-11-22 03:43:55 +0100192}
193
Adam Tkacb1585062009-11-22 03:43:55 +0100194static void
195d_to_tv(double d, struct timeval *tv)
196{
197 tv->tv_sec = (long)d;
198 tv->tv_usec = (d - tv->tv_sec) * 1000000;
199}
200
201static double
202lfp_to_d(l_fixedpt_t lfp)
203{
Denys Vlasenkoca6c7e42009-11-24 07:07:42 +0100204 double ret;
Adam Tkacb1585062009-11-22 03:43:55 +0100205 lfp.int_partl = ntohl(lfp.int_partl);
206 lfp.fractionl = ntohl(lfp.fractionl);
Denys Vlasenkoca6c7e42009-11-24 07:07:42 +0100207 ret = (double)lfp.int_partl + ((double)lfp.fractionl / UINT_MAX);
208 return ret;
209}
210
Denys Vlasenko386960a2009-12-02 01:51:24 +0100211#if 0 //UNUSED
Denys Vlasenkoca6c7e42009-11-24 07:07:42 +0100212static double
213sfp_to_d(s_fixedpt_t sfp)
214{
215 double ret;
216 sfp.int_parts = ntohs(sfp.int_parts);
217 sfp.fractions = ntohs(sfp.fractions);
218 ret = (double)sfp.int_parts + ((double)sfp.fractions / USHRT_MAX);
Adam Tkacb1585062009-11-22 03:43:55 +0100219 return ret;
220}
Denys Vlasenko386960a2009-12-02 01:51:24 +0100221#endif
Adam Tkacb1585062009-11-22 03:43:55 +0100222
223#if ENABLE_FEATURE_NTPD_SERVER
224static l_fixedpt_t
225d_to_lfp(double d)
226{
Denys Vlasenkoca6c7e42009-11-24 07:07:42 +0100227 l_fixedpt_t lfp;
228 lfp.int_partl = (uint32_t)d;
229 lfp.fractionl = (uint32_t)((d - lfp.int_partl) * UINT_MAX);
230 lfp.int_partl = htonl(lfp.int_partl);
231 lfp.fractionl = htonl(lfp.fractionl);
Adam Tkacb1585062009-11-22 03:43:55 +0100232 return lfp;
233}
Adam Tkacb1585062009-11-22 03:43:55 +0100234
Adam Tkacb1585062009-11-22 03:43:55 +0100235static s_fixedpt_t
236d_to_sfp(double d)
237{
Denys Vlasenkoca6c7e42009-11-24 07:07:42 +0100238 s_fixedpt_t sfp;
239 sfp.int_parts = (uint16_t)d;
240 sfp.fractions = (uint16_t)((d - sfp.int_parts) * USHRT_MAX);
241 sfp.int_parts = htons(sfp.int_parts);
242 sfp.fractions = htons(sfp.fractions);
Adam Tkacb1585062009-11-22 03:43:55 +0100243 return sfp;
244}
245#endif
246
Denys Vlasenko386960a2009-12-02 01:51:24 +0100247static unsigned
Adam Tkacb1585062009-11-22 03:43:55 +0100248error_interval(void)
249{
Denys Vlasenko386960a2009-12-02 01:51:24 +0100250 unsigned interval, r;
Adam Tkacb1585062009-11-22 03:43:55 +0100251 interval = INTERVAL_QUERY_PATHETIC * QSCALE_OFF_MAX / QSCALE_OFF_MIN;
Denys Vlasenko386960a2009-12-02 01:51:24 +0100252 r = (unsigned)random() % (unsigned)(interval / 10);
Adam Tkacb1585062009-11-22 03:43:55 +0100253 return (interval + r);
254}
255
256static int
Denys Vlasenko386960a2009-12-02 01:51:24 +0100257do_sendto(int fd,
Adam Tkacb1585062009-11-22 03:43:55 +0100258 const struct sockaddr *from, const struct sockaddr *to, socklen_t addrlen,
259 ntp_msg_t *msg, ssize_t len)
260{
261 ssize_t ret;
262
263 errno = 0;
264 if (!from) {
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100265 ret = sendto(fd, msg, len, MSG_DONTWAIT, to, addrlen);
Adam Tkacb1585062009-11-22 03:43:55 +0100266 } else {
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100267 ret = send_to_from(fd, msg, len, MSG_DONTWAIT, to, from, addrlen);
Adam Tkacb1585062009-11-22 03:43:55 +0100268 }
269 if (ret != len) {
270 bb_perror_msg("send failed");
271 return -1;
272 }
273 return 0;
274}
275
276static int
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100277send_query_to_peer(ntp_peer_t *p)
Adam Tkacb1585062009-11-22 03:43:55 +0100278{
Denys Vlasenkob1278a32009-11-24 16:03:47 +0100279 // Why do we need to bind()?
280 // See what happens when we don't bind:
281 //
282 // socket(PF_INET, SOCK_DGRAM, IPPROTO_IP) = 3
283 // setsockopt(3, SOL_IP, IP_TOS, [16], 4) = 0
284 // gettimeofday({1259071266, 327885}, NULL) = 0
285 // sendto(3, "xxx", 48, MSG_DONTWAIT, {sa_family=AF_INET, sin_port=htons(123), sin_addr=inet_addr("10.34.32.125")}, 16) = 48
286 // ^^^ we sent it from some source port picked by kernel.
287 // time(NULL) = 1259071266
288 // write(2, "ntpd: entering poll 15 secs\n", 28) = 28
289 // poll([{fd=3, events=POLLIN}], 1, 15000) = 1 ([{fd=3, revents=POLLIN}])
290 // recv(3, "yyy", 68, MSG_DONTWAIT) = 48
291 // ^^^ this recv will receive packets to any local port!
292 //
293 // Uncomment this and use strace to see it in action:
294#define PROBE_LOCAL_ADDR // { len_and_sockaddr lsa; lsa.len = LSA_SIZEOF_SA; getsockname(p->query.fd, &lsa.u.sa, &lsa.len); }
295
Denys Vlasenko386960a2009-12-02 01:51:24 +0100296 if (p->fd == -1) {
Denys Vlasenkob1278a32009-11-24 16:03:47 +0100297 int fd, family;
298 len_and_sockaddr *local_lsa;
299
Denys Vlasenko907647f2009-12-02 23:17:45 +0100300//TODO: big ntpd uses all IPs, not just 1st, do we need to mimic that?
301//TODO: periodically re-resolve DNS names?
302 if (!p->lsa) {
303 p->lsa = host2sockaddr(p->hostname, 123);
304 if (!p->lsa) {
305 set_next(p, INTERVAL_QUERY_PATHETIC);
306 return -1;
307 }
308 p->dotted = xmalloc_sockaddr2dotted_noport(&p->lsa->u.sa);
309 }
310
Denys Vlasenkob1278a32009-11-24 16:03:47 +0100311 family = p->lsa->u.sa.sa_family;
Denys Vlasenko386960a2009-12-02 01:51:24 +0100312 p->fd = fd = xsocket_type(&local_lsa, family, SOCK_DGRAM);
Denys Vlasenkob1278a32009-11-24 16:03:47 +0100313 /* local_lsa has "null" address and port 0 now.
314 * bind() ensures we have a *particular port* selected by kernel
Denys Vlasenko386960a2009-12-02 01:51:24 +0100315 * and remembered in p->fd, thus later recv(p->fd)
Denys Vlasenkob1278a32009-11-24 16:03:47 +0100316 * receives only packets sent to this port.
317 */
318 PROBE_LOCAL_ADDR
319 xbind(fd, &local_lsa->u.sa, local_lsa->len);
320 PROBE_LOCAL_ADDR
Adam Tkacb1585062009-11-22 03:43:55 +0100321#if ENABLE_FEATURE_IPV6
Denys Vlasenkob1278a32009-11-24 16:03:47 +0100322 if (family == AF_INET)
Adam Tkacb1585062009-11-22 03:43:55 +0100323#endif
Denys Vlasenkob1278a32009-11-24 16:03:47 +0100324 setsockopt(fd, IPPROTO_IP, IP_TOS, &const_IPTOS_LOWDELAY, sizeof(const_IPTOS_LOWDELAY));
325 free(local_lsa);
Adam Tkacb1585062009-11-22 03:43:55 +0100326 }
327
328 /*
329 * Send out a random 64-bit number as our transmit time. The NTP
330 * server will copy said number into the originate field on the
331 * response that it sends us. This is totally legal per the SNTP spec.
332 *
333 * The impact of this is two fold: we no longer send out the current
334 * system time for the world to see (which may aid an attacker), and
335 * it gives us a (not very secure) way of knowing that we're not
336 * getting spoofed by an attacker that can't capture our traffic
337 * but can spoof packets from the NTP server we're communicating with.
338 *
339 * Save the real transmit timestamp locally.
340 */
341
Denys Vlasenko386960a2009-12-02 01:51:24 +0100342 p->msg.m_xmttime.int_partl = random();
343 p->msg.m_xmttime.fractionl = random();
Denys Vlasenko907647f2009-12-02 23:17:45 +0100344 p->xmttime = gettime1900d();
Adam Tkacb1585062009-11-22 03:43:55 +0100345
Denys Vlasenko386960a2009-12-02 01:51:24 +0100346 if (do_sendto(p->fd, /*from:*/ NULL, /*to:*/ &p->lsa->u.sa, /*addrlen:*/ p->lsa->len,
347 &p->msg, NTP_MSGSIZE_NOAUTH) == -1
348 ) {
Denys Vlasenko907647f2009-12-02 23:17:45 +0100349 close(p->fd);
350 p->fd = -1;
Adam Tkacb1585062009-11-22 03:43:55 +0100351 set_next(p, INTERVAL_QUERY_PATHETIC);
352 return -1;
353 }
354
Denys Vlasenko386960a2009-12-02 01:51:24 +0100355 if (G.verbose)
Denys Vlasenkof91e63c2009-12-02 02:30:31 +0100356 bb_error_msg("sent query to %s", p->dotted);
Denys Vlasenko907647f2009-12-02 23:17:45 +0100357 set_next(p, QUERYTIME_MAX);
Adam Tkacb1585062009-11-22 03:43:55 +0100358
359 return 0;
360}
361
Denys Vlasenko907647f2009-12-02 23:17:45 +0100362
363/* Time is stepped only once, when the first packet from a peer is received.
364 */
365static void
366step_time_once(double offset)
367{
368 llist_t *item;
369 struct timeval tv;
370 char buf[80];
371 time_t tval;
372
373 if (G.time_is_stepped)
374 goto bail;
375 G.time_is_stepped = 1;
376
377 /* if the offset is small, don't step, slew (later) */
378 if (offset < STEPTIME_MIN_OFFSET && offset > -STEPTIME_MIN_OFFSET)
379 goto bail;
380
381 gettimeofday(&tv, NULL); /* never fails */
382 offset += tv.tv_sec;
383 offset += 1.0e-6 * tv.tv_usec;
384 d_to_tv(offset, &tv);
385
386 if (settimeofday(&tv, NULL) == -1)
387 bb_perror_msg_and_die("settimeofday");
388
389 tval = tv.tv_sec;
390 strftime(buf, sizeof(buf), "%a %b %e %H:%M:%S %Z %Y", localtime(&tval));
391
392 bb_error_msg("setting clock to %s (offset %fs)", buf, offset);
393
394 for (item = G.ntp_peers; item != NULL; item = item->link) {
395 ntp_peer_t *p = (ntp_peer_t *) item->data;
396 p->next_action_time -= offset;
397 }
398
399 bail:
400 if (option_mask32 & OPT_q)
401 exit(0);
402}
403
404
405/* Time is periodically slewed when we collect enough
406 * good data points.
407 */
Adam Tkacb1585062009-11-22 03:43:55 +0100408static int
Denys Vlasenko386960a2009-12-02 01:51:24 +0100409compare_offsets(const void *aa, const void *bb)
Adam Tkacb1585062009-11-22 03:43:55 +0100410{
Denys Vlasenkoca6c7e42009-11-24 07:07:42 +0100411 const ntp_peer_t *const *a = aa;
412 const ntp_peer_t *const *b = bb;
Denys Vlasenko386960a2009-12-02 01:51:24 +0100413 if ((*a)->update.o_offset < (*b)->update.o_offset)
Adam Tkacb1585062009-11-22 03:43:55 +0100414 return -1;
Denys Vlasenko386960a2009-12-02 01:51:24 +0100415 return ((*a)->update.o_offset > (*b)->update.o_offset);
Adam Tkacb1585062009-11-22 03:43:55 +0100416}
Denys Vlasenko907647f2009-12-02 23:17:45 +0100417static unsigned
Adam Tkacb1585062009-11-22 03:43:55 +0100418updated_scale(double offset)
419{
420 if (offset < 0)
421 offset = -offset;
Adam Tkacb1585062009-11-22 03:43:55 +0100422 if (offset > QSCALE_OFF_MAX)
423 return 1;
424 if (offset < QSCALE_OFF_MIN)
425 return QSCALE_OFF_MAX / QSCALE_OFF_MIN;
426 return QSCALE_OFF_MAX / offset;
427}
Adam Tkacb1585062009-11-22 03:43:55 +0100428static void
Denys Vlasenko386960a2009-12-02 01:51:24 +0100429slew_time(void)
Adam Tkacb1585062009-11-22 03:43:55 +0100430{
Denys Vlasenko4bd51892009-12-02 13:43:06 +0100431 llist_t *item;
432 double offset_median;
433 struct timeval tv;
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100434
Denys Vlasenko386960a2009-12-02 01:51:24 +0100435 {
Denys Vlasenko4bd51892009-12-02 13:43:06 +0100436 ntp_peer_t **peers = xzalloc(sizeof(peers[0]) * G.peer_cnt);
437 unsigned goodpeer_cnt = 0;
Denys Vlasenko386960a2009-12-02 01:51:24 +0100438 unsigned middle;
Denys Vlasenko386960a2009-12-02 01:51:24 +0100439
440 for (item = G.ntp_peers; item != NULL; item = item->link) {
Denys Vlasenko4bd51892009-12-02 13:43:06 +0100441 ntp_peer_t *p = (ntp_peer_t *) item->data;
Denys Vlasenko386960a2009-12-02 01:51:24 +0100442 if (p->trustlevel < TRUSTLEVEL_BADPEER)
443 continue;
Denys Vlasenko907647f2009-12-02 23:17:45 +0100444 if (!p->update.o_good) {
445 free(peers);
Denys Vlasenko4bd51892009-12-02 13:43:06 +0100446 return;
Denys Vlasenko907647f2009-12-02 23:17:45 +0100447 }
Denys Vlasenko4bd51892009-12-02 13:43:06 +0100448 peers[goodpeer_cnt++] = p;
Denys Vlasenko386960a2009-12-02 01:51:24 +0100449 }
450
Denys Vlasenko4bd51892009-12-02 13:43:06 +0100451 if (goodpeer_cnt == 0) {
452 free(peers);
453 goto clear_good;
454 }
Denys Vlasenko386960a2009-12-02 01:51:24 +0100455
Denys Vlasenko4bd51892009-12-02 13:43:06 +0100456 qsort(peers, goodpeer_cnt, sizeof(peers[0]), compare_offsets);
457
458 middle = goodpeer_cnt / 2;
459 if (middle != 0 && (goodpeer_cnt & 1) == 0) {
Denys Vlasenko386960a2009-12-02 01:51:24 +0100460 offset_median = (peers[middle-1]->update.o_offset + peers[middle]->update.o_offset) / 2;
461 G.rootdelay = (peers[middle-1]->update.o_delay + peers[middle]->update.o_delay) / 2;
462 G.stratum = 1 + MAX(peers[middle-1]->update.o_stratum, peers[middle]->update.o_stratum);
463 } else {
464 offset_median = peers[middle]->update.o_offset;
465 G.rootdelay = peers[middle]->update.o_delay;
466 G.stratum = 1 + peers[middle]->update.o_stratum;
467 }
468 G.leap = peers[middle]->update.o_leap;
469 G.refid4 = peers[middle]->update.o_refid4;
Denys Vlasenko386960a2009-12-02 01:51:24 +0100470 G.refid =
471#if ENABLE_FEATURE_IPV6
Denys Vlasenko907647f2009-12-02 23:17:45 +0100472 peers[middle]->lsa->u.sa.sa_family != AF_INET ?
Denys Vlasenko386960a2009-12-02 01:51:24 +0100473 G.refid4 :
474#endif
Denys Vlasenko907647f2009-12-02 23:17:45 +0100475 peers[middle]->lsa->u.sin.sin_addr.s_addr;
Denys Vlasenko386960a2009-12-02 01:51:24 +0100476 free(peers);
Adam Tkacb1585062009-11-22 03:43:55 +0100477 }
Denys Vlasenko907647f2009-12-02 23:17:45 +0100478//TODO: if (offset_median > BIG) step_time(offset_median)?
Adam Tkacb1585062009-11-22 03:43:55 +0100479
Denys Vlasenko907647f2009-12-02 23:17:45 +0100480 G.scale = updated_scale(offset_median);
481
482 bb_error_msg("adjusting clock by %fs, our stratum is %u, time scale %u",
483 offset_median, G.stratum, G.scale);
Adam Tkacb1585062009-11-22 03:43:55 +0100484
Denys Vlasenkofae9f492009-12-01 02:32:01 +0100485 errno = 0;
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100486 d_to_tv(offset_median, &tv);
Denys Vlasenko907647f2009-12-02 23:17:45 +0100487 if (adjtime(&tv, &tv) == -1)
488 bb_perror_msg_and_die("adjtime failed");
489 if (G.verbose >= 2)
490 bb_error_msg("old adjust: %d.%06u", (int)tv.tv_sec, (unsigned)tv.tv_usec);
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100491
Denys Vlasenko907647f2009-12-02 23:17:45 +0100492 if (G.first_adj_done) {
493 uint8_t synced = (tv.tv_sec == 0 && tv.tv_usec == 0);
494 if (synced != G.synced) {
495 G.synced = synced;
496 bb_error_msg("clock is %ssynced", synced ? "" : "un");
497 }
498 }
499 G.first_adj_done = 1;
500
501 G.reftime = gettime1900d();
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100502
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100503 clear_good:
Adam Tkacb1585062009-11-22 03:43:55 +0100504 for (item = G.ntp_peers; item != NULL; item = item->link) {
Denys Vlasenko4bd51892009-12-02 13:43:06 +0100505 ntp_peer_t *p = (ntp_peer_t *) item->data;
Denys Vlasenko386960a2009-12-02 01:51:24 +0100506 p->update.o_good = 0;
Adam Tkacb1585062009-11-22 03:43:55 +0100507 }
508}
509
510static void
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100511update_peer_data(ntp_peer_t *p)
Adam Tkacb1585062009-11-22 03:43:55 +0100512{
Denys Vlasenko386960a2009-12-02 01:51:24 +0100513 /* Clock filter.
514 * Find the offset which arrived with the lowest delay.
515 * Use that as the peer update.
516 * Invalidate it and all older ones.
Adam Tkacb1585062009-11-22 03:43:55 +0100517 */
Denys Vlasenko386960a2009-12-02 01:51:24 +0100518 int i;
Denys Vlasenko4bd51892009-12-02 13:43:06 +0100519 int best = -1;
520 int good = 0;
Adam Tkacb1585062009-11-22 03:43:55 +0100521
Denys Vlasenko386960a2009-12-02 01:51:24 +0100522 for (i = 0; i < OFFSET_ARRAY_SIZE; i++) {
523 if (p->reply[i].o_good) {
Adam Tkacb1585062009-11-22 03:43:55 +0100524 good++;
Denys Vlasenko4bd51892009-12-02 13:43:06 +0100525 if (best < 0 || p->reply[i].o_delay < p->reply[best].o_delay)
Adam Tkacb1585062009-11-22 03:43:55 +0100526 best = i;
527 }
528 }
529
Denys Vlasenko386960a2009-12-02 01:51:24 +0100530 if (good < 8) //FIXME: was it meant to be OFFSET_ARRAY_SIZE, not 8?
Adam Tkacb1585062009-11-22 03:43:55 +0100531 return;
532
533 memcpy(&p->update, &p->reply[best], sizeof(p->update));
Denys Vlasenko386960a2009-12-02 01:51:24 +0100534 slew_time();
Adam Tkacb1585062009-11-22 03:43:55 +0100535
536 for (i = 0; i < OFFSET_ARRAY_SIZE; i++)
Denys Vlasenko386960a2009-12-02 01:51:24 +0100537 if (p->reply[i].o_rcvd <= p->reply[best].o_rcvd)
538 p->reply[i].o_good = 0;
Adam Tkacb1585062009-11-22 03:43:55 +0100539}
540
Denys Vlasenko386960a2009-12-02 01:51:24 +0100541static unsigned
542scale_interval(unsigned requested)
Adam Tkacb1585062009-11-22 03:43:55 +0100543{
Denys Vlasenko386960a2009-12-02 01:51:24 +0100544 unsigned interval, r;
Adam Tkacb1585062009-11-22 03:43:55 +0100545 interval = requested * G.scale;
Denys Vlasenko386960a2009-12-02 01:51:24 +0100546 r = (unsigned)random() % (unsigned)(MAX(5, interval / 10));
Adam Tkacb1585062009-11-22 03:43:55 +0100547 return (interval + r);
548}
Adam Tkacb1585062009-11-22 03:43:55 +0100549static void
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100550recv_and_process_peer_pkt(ntp_peer_t *p)
Adam Tkacb1585062009-11-22 03:43:55 +0100551{
Adam Tkacb1585062009-11-22 03:43:55 +0100552 ssize_t size;
553 ntp_msg_t msg;
554 double T1, T2, T3, T4;
Denys Vlasenko386960a2009-12-02 01:51:24 +0100555 unsigned interval;
Adam Tkacb1585062009-11-22 03:43:55 +0100556 ntp_offset_t *offset;
557
Denys Vlasenkob1278a32009-11-24 16:03:47 +0100558 /* We can recvfrom here and check from.IP, but some multihomed
559 * ntp servers reply from their *other IP*.
560 * TODO: maybe we should check at least what we can: from.port == 123?
561 */
Denys Vlasenko386960a2009-12-02 01:51:24 +0100562 size = recv(p->fd, &msg, sizeof(msg), MSG_DONTWAIT);
Adam Tkacb1585062009-11-22 03:43:55 +0100563 if (size == -1) {
Denys Vlasenko386960a2009-12-02 01:51:24 +0100564 bb_perror_msg("recv(%s) error", p->dotted);
Adam Tkacb1585062009-11-22 03:43:55 +0100565 if (errno == EHOSTUNREACH || errno == EHOSTDOWN
566 || errno == ENETUNREACH || errno == ENETDOWN
567 || errno == ECONNREFUSED || errno == EADDRNOTAVAIL
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100568 || errno == EAGAIN
Adam Tkacb1585062009-11-22 03:43:55 +0100569 ) {
570//TODO: always do this?
571 set_next(p, error_interval());
Denys Vlasenko386960a2009-12-02 01:51:24 +0100572 goto close_sock;
Adam Tkacb1585062009-11-22 03:43:55 +0100573 }
574 xfunc_die();
575 }
576
Adam Tkacb1585062009-11-22 03:43:55 +0100577 if (size != NTP_MSGSIZE_NOAUTH && size != NTP_MSGSIZE) {
Denys Vlasenko386960a2009-12-02 01:51:24 +0100578 bb_error_msg("malformed packet received from %s", p->dotted);
Adam Tkacb1585062009-11-22 03:43:55 +0100579 goto bail;
580 }
581
Denys Vlasenko386960a2009-12-02 01:51:24 +0100582 if (msg.m_orgtime.int_partl != p->msg.m_xmttime.int_partl
583 || msg.m_orgtime.fractionl != p->msg.m_xmttime.fractionl
Adam Tkacb1585062009-11-22 03:43:55 +0100584 ) {
585 goto bail;
586 }
587
Denys Vlasenko386960a2009-12-02 01:51:24 +0100588 if ((msg.m_status & LI_ALARM) == LI_ALARM
589 || msg.m_stratum == 0
590 || msg.m_stratum > NTP_MAXSTRATUM
Adam Tkacb1585062009-11-22 03:43:55 +0100591 ) {
592 interval = error_interval();
Denys Vlasenkof91e63c2009-12-02 02:30:31 +0100593 bb_error_msg("reply from %s: not synced, next query in %us", p->dotted, interval);
Denys Vlasenko386960a2009-12-02 01:51:24 +0100594 goto close_sock;
Adam Tkacb1585062009-11-22 03:43:55 +0100595 }
596
597 /*
598 * From RFC 2030 (with a correction to the delay math):
599 *
600 * Timestamp Name ID When Generated
601 * ------------------------------------------------------------
602 * Originate Timestamp T1 time request sent by client
603 * Receive Timestamp T2 time request received by server
604 * Transmit Timestamp T3 time reply sent by server
605 * Destination Timestamp T4 time reply received by client
606 *
607 * The roundtrip delay d and local clock offset t are defined as
608 *
609 * d = (T4 - T1) - (T3 - T2) t = ((T2 - T1) + (T3 - T4)) / 2.
610 */
611
Denys Vlasenko907647f2009-12-02 23:17:45 +0100612 T4 = gettime1900d();
Denys Vlasenko386960a2009-12-02 01:51:24 +0100613 T1 = p->xmttime;
614 T2 = lfp_to_d(msg.m_rectime);
615 T3 = lfp_to_d(msg.m_xmttime);
Adam Tkacb1585062009-11-22 03:43:55 +0100616
617 offset = &p->reply[p->shift];
618
Denys Vlasenko386960a2009-12-02 01:51:24 +0100619 offset->o_offset = ((T2 - T1) + (T3 - T4)) / 2;
620 offset->o_delay = (T4 - T1) - (T3 - T2);
621 if (offset->o_delay < 0) {
Denys Vlasenko4bd51892009-12-02 13:43:06 +0100622 bb_error_msg("reply from %s: negative delay %f", p->dotted, offset->o_delay);
Adam Tkacb1585062009-11-22 03:43:55 +0100623 interval = error_interval();
624 set_next(p, interval);
Denys Vlasenko386960a2009-12-02 01:51:24 +0100625 goto close_sock;
Adam Tkacb1585062009-11-22 03:43:55 +0100626 }
Denys Vlasenko386960a2009-12-02 01:51:24 +0100627 //UNUSED: offset->o_error = (T2 - T1) - (T3 - T4);
Denys Vlasenko4bd51892009-12-02 13:43:06 +0100628 offset->o_rcvd = time(NULL); /* can use (time_t)(T4 - OFFSET_1900_1970) too */
Denys Vlasenko386960a2009-12-02 01:51:24 +0100629 offset->o_good = 1;
Adam Tkacb1585062009-11-22 03:43:55 +0100630
Denys Vlasenko386960a2009-12-02 01:51:24 +0100631 offset->o_leap = (msg.m_status & LI_MASK);
632 //UNUSED: offset->o_precision = msg.m_precision;
633 //UNUSED: offset->o_rootdelay = sfp_to_d(msg.m_rootdelay);
634 //UNUSED: offset->o_rootdispersion = sfp_to_d(msg.m_dispersion);
635 //UNUSED: offset->o_refid = ntohl(msg.m_refid);
636 offset->o_refid4 = msg.m_xmttime.fractionl;
637 //UNUSED: offset->o_reftime = lfp_to_d(msg.m_reftime);
638 //UNUSED: offset->o_poll = msg.m_ppoll;
639 offset->o_stratum = msg.m_stratum;
Adam Tkacb1585062009-11-22 03:43:55 +0100640
641 if (p->trustlevel < TRUSTLEVEL_PATHETIC)
642 interval = scale_interval(INTERVAL_QUERY_PATHETIC);
643 else if (p->trustlevel < TRUSTLEVEL_AGRESSIVE)
644 interval = scale_interval(INTERVAL_QUERY_AGRESSIVE);
645 else
646 interval = scale_interval(INTERVAL_QUERY_NORMAL);
647
648 set_next(p, interval);
Adam Tkacb1585062009-11-22 03:43:55 +0100649
650 /* every received reply which we do not discard increases trust */
651 if (p->trustlevel < TRUSTLEVEL_MAX) {
Adam Tkacb1585062009-11-22 03:43:55 +0100652 p->trustlevel++;
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100653 if (p->trustlevel == TRUSTLEVEL_BADPEER)
Denys Vlasenko386960a2009-12-02 01:51:24 +0100654 bb_error_msg("peer %s now valid", p->dotted);
Adam Tkacb1585062009-11-22 03:43:55 +0100655 }
656
Denys Vlasenko386960a2009-12-02 01:51:24 +0100657 if (G.verbose)
Denys Vlasenkof91e63c2009-12-02 02:30:31 +0100658 bb_error_msg("reply from %s: offset %f delay %f, next query in %us", p->dotted,
Denys Vlasenko386960a2009-12-02 01:51:24 +0100659 offset->o_offset, offset->o_delay, interval);
Adam Tkacb1585062009-11-22 03:43:55 +0100660
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100661 update_peer_data(p);
Denys Vlasenkof91e63c2009-12-02 02:30:31 +0100662//TODO: do it after all peers had a chance to return at least one reply?
Denys Vlasenko386960a2009-12-02 01:51:24 +0100663 step_time_once(offset->o_offset);
Adam Tkacb1585062009-11-22 03:43:55 +0100664
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100665 p->shift++;
666 if (p->shift >= OFFSET_ARRAY_SIZE)
Adam Tkacb1585062009-11-22 03:43:55 +0100667 p->shift = 0;
668
Denys Vlasenko386960a2009-12-02 01:51:24 +0100669 close_sock:
Denys Vlasenko907647f2009-12-02 23:17:45 +0100670 /* We do not expect any more packets from this peer for now.
Denys Vlasenko386960a2009-12-02 01:51:24 +0100671 * Closing the socket informs kernel about it.
672 * We open a new socket when we send a new query.
673 */
674 close(p->fd);
675 p->fd = -1;
Adam Tkacb1585062009-11-22 03:43:55 +0100676 bail:
Denys Vlasenko386960a2009-12-02 01:51:24 +0100677 return;
Adam Tkacb1585062009-11-22 03:43:55 +0100678}
679
680#if ENABLE_FEATURE_NTPD_SERVER
681static void
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100682recv_and_process_client_pkt(void /*int fd*/)
Adam Tkacb1585062009-11-22 03:43:55 +0100683{
Denys Vlasenkoca6c7e42009-11-24 07:07:42 +0100684 ssize_t size;
685 uint8_t version;
686 double rectime;
687 len_and_sockaddr *to;
688 struct sockaddr *from;
689 ntp_msg_t msg;
690 uint8_t query_status;
691 uint8_t query_ppoll;
692 l_fixedpt_t query_xmttime;
Adam Tkacb1585062009-11-22 03:43:55 +0100693
694 to = get_sock_lsa(G.listen_fd);
695 from = xzalloc(to->len);
696
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100697 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 +0100698 if (size != NTP_MSGSIZE_NOAUTH && size != NTP_MSGSIZE) {
Denys Vlasenkoca6c7e42009-11-24 07:07:42 +0100699 char *addr;
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100700 if (size < 0) {
701 if (errno == EAGAIN)
702 goto bail;
Denys Vlasenko907647f2009-12-02 23:17:45 +0100703 bb_perror_msg_and_die("recv");
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100704 }
Denys Vlasenkoca6c7e42009-11-24 07:07:42 +0100705 addr = xmalloc_sockaddr2dotted_noport(from);
Denys Vlasenko907647f2009-12-02 23:17:45 +0100706 bb_error_msg("malformed packet received from %s: size %u", addr, (int)size);
Adam Tkacb1585062009-11-22 03:43:55 +0100707 free(addr);
708 goto bail;
709 }
710
Denys Vlasenko386960a2009-12-02 01:51:24 +0100711 query_status = msg.m_status;
712 query_ppoll = msg.m_ppoll;
713 query_xmttime = msg.m_xmttime;
Adam Tkacb1585062009-11-22 03:43:55 +0100714
Denys Vlasenkoca6c7e42009-11-24 07:07:42 +0100715 /* Build a reply packet */
716 memset(&msg, 0, sizeof(msg));
Denys Vlasenko386960a2009-12-02 01:51:24 +0100717 msg.m_status = G.synced ? G.leap : LI_ALARM;
718 msg.m_status |= (query_status & VERSION_MASK);
719 msg.m_status |= ((query_status & MODE_MASK) == MODE_CLIENT) ?
Adam Tkacb1585062009-11-22 03:43:55 +0100720 MODE_SERVER : MODE_SYM_PAS;
Denys Vlasenko386960a2009-12-02 01:51:24 +0100721 msg.m_stratum = G.stratum;
722 msg.m_ppoll = query_ppoll;
Denys Vlasenko907647f2009-12-02 23:17:45 +0100723 msg.m_precision = G_precision;
724 rectime = gettime1900d();
Denys Vlasenko386960a2009-12-02 01:51:24 +0100725 msg.m_xmttime = msg.m_rectime = d_to_lfp(rectime);
726 msg.m_reftime = d_to_lfp(G.reftime);
Denys Vlasenko907647f2009-12-02 23:17:45 +0100727 //msg.m_xmttime = d_to_lfp(gettime1900d()); // = msg.m_rectime
Denys Vlasenko386960a2009-12-02 01:51:24 +0100728 msg.m_orgtime = query_xmttime;
729 msg.m_rootdelay = d_to_sfp(G.rootdelay);
Denys Vlasenkoca6c7e42009-11-24 07:07:42 +0100730 version = (query_status & VERSION_MASK); /* ... >> VERSION_SHIFT - done below instead */
Denys Vlasenko386960a2009-12-02 01:51:24 +0100731 msg.m_refid = (version > (3 << VERSION_SHIFT)) ? G.refid4 : G.refid;
Adam Tkacb1585062009-11-22 03:43:55 +0100732
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100733 /* We reply from the local address packet was sent to,
Adam Tkacb1585062009-11-22 03:43:55 +0100734 * this makes to/from look swapped here: */
Denys Vlasenko386960a2009-12-02 01:51:24 +0100735 do_sendto(G.listen_fd,
Denys Vlasenkoca6c7e42009-11-24 07:07:42 +0100736 /*from:*/ &to->u.sa, /*to:*/ from, /*addrlen:*/ to->len,
737 &msg, size);
Adam Tkacb1585062009-11-22 03:43:55 +0100738
739 bail:
740 free(to);
741 free(from);
742}
743#endif
744
745/* Upstream ntpd's options:
746 *
747 * -4 Force DNS resolution of host names to the IPv4 namespace.
748 * -6 Force DNS resolution of host names to the IPv6 namespace.
749 * -a Require cryptographic authentication for broadcast client,
750 * multicast client and symmetric passive associations.
751 * This is the default.
752 * -A Do not require cryptographic authentication for broadcast client,
753 * multicast client and symmetric passive associations.
754 * This is almost never a good idea.
755 * -b Enable the client to synchronize to broadcast servers.
756 * -c conffile
757 * Specify the name and path of the configuration file,
758 * default /etc/ntp.conf
759 * -d Specify debugging mode. This option may occur more than once,
760 * with each occurrence indicating greater detail of display.
761 * -D level
762 * Specify debugging level directly.
763 * -f driftfile
764 * Specify the name and path of the frequency file.
765 * This is the same operation as the "driftfile FILE"
766 * configuration command.
767 * -g Normally, ntpd exits with a message to the system log
768 * if the offset exceeds the panic threshold, which is 1000 s
769 * by default. This option allows the time to be set to any value
770 * without restriction; however, this can happen only once.
771 * If the threshold is exceeded after that, ntpd will exit
772 * with a message to the system log. This option can be used
773 * with the -q and -x options. See the tinker command for other options.
774 * -i jaildir
775 * Chroot the server to the directory jaildir. This option also implies
776 * that the server attempts to drop root privileges at startup
777 * (otherwise, chroot gives very little additional security).
778 * You may need to also specify a -u option.
779 * -k keyfile
780 * Specify the name and path of the symmetric key file,
781 * default /etc/ntp/keys. This is the same operation
782 * as the "keys FILE" configuration command.
783 * -l logfile
784 * Specify the name and path of the log file. The default
785 * is the system log file. This is the same operation as
786 * the "logfile FILE" configuration command.
787 * -L Do not listen to virtual IPs. The default is to listen.
788 * -n Don't fork.
789 * -N To the extent permitted by the operating system,
790 * run the ntpd at the highest priority.
791 * -p pidfile
792 * Specify the name and path of the file used to record the ntpd
793 * process ID. This is the same operation as the "pidfile FILE"
794 * configuration command.
795 * -P priority
796 * To the extent permitted by the operating system,
797 * run the ntpd at the specified priority.
798 * -q Exit the ntpd just after the first time the clock is set.
799 * This behavior mimics that of the ntpdate program, which is
800 * to be retired. The -g and -x options can be used with this option.
801 * Note: The kernel time discipline is disabled with this option.
802 * -r broadcastdelay
803 * Specify the default propagation delay from the broadcast/multicast
804 * server to this client. This is necessary only if the delay
805 * cannot be computed automatically by the protocol.
806 * -s statsdir
807 * Specify the directory path for files created by the statistics
808 * facility. This is the same operation as the "statsdir DIR"
809 * configuration command.
810 * -t key
811 * Add a key number to the trusted key list. This option can occur
812 * more than once.
813 * -u user[:group]
814 * Specify a user, and optionally a group, to switch to.
815 * -v variable
816 * -V variable
817 * Add a system variable listed by default.
818 * -x Normally, the time is slewed if the offset is less than the step
819 * threshold, which is 128 ms by default, and stepped if above
820 * the threshold. This option sets the threshold to 600 s, which is
821 * well within the accuracy window to set the clock manually.
822 * Note: since the slew rate of typical Unix kernels is limited
823 * to 0.5 ms/s, each second of adjustment requires an amortization
824 * interval of 2000 s. Thus, an adjustment as much as 600 s
825 * will take almost 14 days to complete. This option can be used
826 * with the -g and -q options. See the tinker command for other options.
827 * Note: The kernel time discipline is disabled with this option.
828 */
829
Adam Tkacb1585062009-11-22 03:43:55 +0100830/* By doing init in a separate function we decrease stack usage
831 * in main loop.
832 */
833static NOINLINE void ntp_init(char **argv)
834{
835 unsigned opts;
836 llist_t *peers;
837
Denys Vlasenkoca6c7e42009-11-24 07:07:42 +0100838 srandom(getpid());
Adam Tkacb1585062009-11-22 03:43:55 +0100839
840 if (getuid())
Denys Vlasenkob2e5fc32009-11-25 14:52:47 +0100841 bb_error_msg_and_die(bb_msg_you_must_be_root);
Adam Tkacb1585062009-11-22 03:43:55 +0100842
843 peers = NULL;
844 opt_complementary = "dd:p::"; /* d: counter, p: list */
845 opts = getopt32(argv,
Denys Vlasenko907647f2009-12-02 23:17:45 +0100846 "nqNx" /* compat */
Adam Tkacb1585062009-11-22 03:43:55 +0100847 "p:"IF_FEATURE_NTPD_SERVER("l") /* NOT compat */
848 "d" /* compat */
Denys Vlasenko907647f2009-12-02 23:17:45 +0100849 "46aAbgL", /* compat, ignored */
Adam Tkacb1585062009-11-22 03:43:55 +0100850 &peers, &G.verbose);
Denys Vlasenkob2e5fc32009-11-25 14:52:47 +0100851 if (!(opts & (OPT_p|OPT_l)))
852 bb_show_usage();
Denys Vlasenko907647f2009-12-02 23:17:45 +0100853 if (opts & OPT_x) /* disable stepping, only slew is allowed */
854 G.time_is_stepped = 1;
Denys Vlasenko160b9ca2009-11-27 02:35:15 +0100855 while (peers)
856 add_peers(llist_pop(&peers));
857 if (!(opts & OPT_n)) {
858 bb_daemonize_or_rexec(DAEMON_DEVNULL_STDIO, argv);
859 logmode = LOGMODE_NONE;
860 }
Adam Tkacb1585062009-11-22 03:43:55 +0100861#if ENABLE_FEATURE_NTPD_SERVER
862 G.listen_fd = -1;
863 if (opts & OPT_l) {
864 G.listen_fd = create_and_bind_dgram_or_die(NULL, 123);
865 socket_want_pktinfo(G.listen_fd);
866 setsockopt(G.listen_fd, IPPROTO_IP, IP_TOS, &const_IPTOS_LOWDELAY, sizeof(const_IPTOS_LOWDELAY));
867 }
868#endif
Denys Vlasenkob2e5fc32009-11-25 14:52:47 +0100869 /* I hesitate to set -20 prio. -15 should be high enough for timekeeping */
870 if (opts & OPT_N)
871 setpriority(PRIO_PROCESS, 0, -15);
Adam Tkacb1585062009-11-22 03:43:55 +0100872
873 /* Set some globals */
Denys Vlasenko907647f2009-12-02 23:17:45 +0100874#if 0
875 /* With constant b = 100, G.precision is also constant -6.
876 * Uncomment this and you'll see */
Adam Tkacb1585062009-11-22 03:43:55 +0100877 {
878 int prec = 0;
879 int b;
Denys Vlasenko907647f2009-12-02 23:17:45 +0100880# if 0
Adam Tkacb1585062009-11-22 03:43:55 +0100881 struct timespec tp;
882 /* We can use sys_clock_getres but assuming 10ms tick should be fine */
883 clock_getres(CLOCK_REALTIME, &tp);
884 tp.tv_sec = 0;
885 tp.tv_nsec = 10000000;
886 b = 1000000000 / tp.tv_nsec; /* convert to Hz */
Denys Vlasenko907647f2009-12-02 23:17:45 +0100887# else
Adam Tkacb1585062009-11-22 03:43:55 +0100888 b = 100; /* b = 1000000000/10000000 = 100 */
Denys Vlasenko907647f2009-12-02 23:17:45 +0100889# endif
Adam Tkacb1585062009-11-22 03:43:55 +0100890 while (b > 1)
891 prec--, b >>= 1;
Denys Vlasenko907647f2009-12-02 23:17:45 +0100892 //G.precision = prec;
893 bb_error_msg("G.precision:%d", prec); /* -6 */
Adam Tkacb1585062009-11-22 03:43:55 +0100894 }
Denys Vlasenko907647f2009-12-02 23:17:45 +0100895#endif
Adam Tkacb1585062009-11-22 03:43:55 +0100896 G.scale = 1;
Adam Tkacb1585062009-11-22 03:43:55 +0100897
898 bb_signals((1 << SIGTERM) | (1 << SIGINT), record_signo);
899 bb_signals((1 << SIGPIPE) | (1 << SIGHUP), SIG_IGN);
900}
901
902int ntpd_main(int argc UNUSED_PARAM, char **argv) MAIN_EXTERNALLY_VISIBLE;
903int ntpd_main(int argc UNUSED_PARAM, char **argv)
904{
905 struct globals g;
Adam Tkacb1585062009-11-22 03:43:55 +0100906 struct pollfd *pfd;
907 ntp_peer_t **idx2peer;
908
909 memset(&g, 0, sizeof(g));
910 SET_PTR_TO_GLOBALS(&g);
911
912 ntp_init(argv);
913
Denys Vlasenko8d580c72009-11-23 16:27:16 +0100914 {
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100915 unsigned cnt = g.peer_cnt;
Denys Vlasenko8d580c72009-11-23 16:27:16 +0100916 /* if ENABLE_FEATURE_NTPD_SERVER, + 1 for listen_fd: */
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100917 idx2peer = xzalloc(sizeof(void *) * (cnt + ENABLE_FEATURE_NTPD_SERVER));
918 pfd = xzalloc(sizeof(pfd[0]) * (cnt + ENABLE_FEATURE_NTPD_SERVER));
Denys Vlasenko8d580c72009-11-23 16:27:16 +0100919 }
Adam Tkacb1585062009-11-22 03:43:55 +0100920
921 while (!bb_got_signal) {
922 llist_t *item;
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100923 unsigned i, j;
Adam Tkacb1585062009-11-22 03:43:55 +0100924 unsigned sent_cnt, trial_cnt;
925 int nfds, timeout;
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100926 time_t cur_time, nextaction;
Adam Tkacb1585062009-11-22 03:43:55 +0100927
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100928 /* Nothing between here and poll() blocks for any significant time */
929
930 cur_time = time(NULL);
931 nextaction = cur_time + 3600;
Adam Tkacb1585062009-11-22 03:43:55 +0100932
933 i = 0;
934#if ENABLE_FEATURE_NTPD_SERVER
935 if (g.listen_fd != -1) {
936 pfd[0].fd = g.listen_fd;
937 pfd[0].events = POLLIN;
938 i++;
939 }
940#endif
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100941 /* Pass over peer list, send requests, time out on receives */
Adam Tkacb1585062009-11-22 03:43:55 +0100942 sent_cnt = trial_cnt = 0;
943 for (item = g.ntp_peers; item != NULL; item = item->link) {
944 ntp_peer_t *p = (ntp_peer_t *) item->data;
945
Denys Vlasenko907647f2009-12-02 23:17:45 +0100946 /* Overflow-safe "if (p->next_action_time <= cur_time) ..." */
947 if ((int)(cur_time - p->next_action_time) >= 0) {
948 if (p->fd == -1) {
949 /* Time to send new req */
950 trial_cnt++;
951 if (send_query_to_peer(p) == 0)
952 sent_cnt++;
953 } else {
954 /* Timed out waiting for reply */
955 close(p->fd);
956 p->fd = -1;
957 timeout = error_interval();
958 bb_error_msg("timed out waiting for %s, "
959 "next query in %us", p->dotted, timeout);
960 if (p->trustlevel >= TRUSTLEVEL_BADPEER) {
961 p->trustlevel /= 2;
962 if (p->trustlevel < TRUSTLEVEL_BADPEER)
963 bb_error_msg("peer %s now invalid", p->dotted);
964 }
965 set_next(p, timeout);
Adam Tkacb1585062009-11-22 03:43:55 +0100966 }
Adam Tkacb1585062009-11-22 03:43:55 +0100967 }
968
Denys Vlasenko907647f2009-12-02 23:17:45 +0100969 if (p->next_action_time < nextaction)
970 nextaction = p->next_action_time;
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100971
Denys Vlasenko907647f2009-12-02 23:17:45 +0100972 if (p->fd >= 0) {
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100973 /* Wait for reply from this peer */
Denys Vlasenko386960a2009-12-02 01:51:24 +0100974 pfd[i].fd = p->fd;
Adam Tkacb1585062009-11-22 03:43:55 +0100975 pfd[i].events = POLLIN;
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100976 idx2peer[i] = p;
Adam Tkacb1585062009-11-22 03:43:55 +0100977 i++;
978 }
979 }
980
Denys Vlasenko8d580c72009-11-23 16:27:16 +0100981 if ((trial_cnt > 0 && sent_cnt == 0) || g.peer_cnt == 0)
Denys Vlasenkofae9f492009-12-01 02:32:01 +0100982 step_time_once(0); /* no good peers, don't wait */
Adam Tkacb1585062009-11-22 03:43:55 +0100983
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100984 timeout = nextaction - cur_time;
Denys Vlasenko386960a2009-12-02 01:51:24 +0100985 if (timeout < 1)
986 timeout = 1;
Adam Tkacb1585062009-11-22 03:43:55 +0100987
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100988 /* Here we may block */
Denys Vlasenko386960a2009-12-02 01:51:24 +0100989 if (g.verbose >= 2)
Denys Vlasenko907647f2009-12-02 23:17:45 +0100990 bb_error_msg("poll %us, sockets:%u", timeout, i);
Adam Tkacb1585062009-11-22 03:43:55 +0100991 nfds = poll(pfd, i, timeout * 1000);
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100992 if (nfds <= 0)
993 continue;
Adam Tkacb1585062009-11-22 03:43:55 +0100994
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100995 /* Process any received packets */
Adam Tkacb1585062009-11-22 03:43:55 +0100996 j = 0;
997#if ENABLE_FEATURE_NTPD_SERVER
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100998 if (g.listen_fd != -1) {
999 if (pfd[0].revents /* & (POLLIN|POLLERR)*/) {
Adam Tkacb1585062009-11-22 03:43:55 +01001000 nfds--;
Denys Vlasenko363e89b2009-11-24 14:04:15 +01001001 recv_and_process_client_pkt(/*g.listen_fd*/);
Adam Tkacb1585062009-11-22 03:43:55 +01001002 }
Denys Vlasenko363e89b2009-11-24 14:04:15 +01001003 j = 1;
Adam Tkacb1585062009-11-22 03:43:55 +01001004 }
1005#endif
Denys Vlasenko363e89b2009-11-24 14:04:15 +01001006 for (; nfds != 0 && j < i; j++) {
1007 if (pfd[j].revents /* & (POLLIN|POLLERR)*/) {
Adam Tkacb1585062009-11-22 03:43:55 +01001008 nfds--;
Denys Vlasenko363e89b2009-11-24 14:04:15 +01001009 recv_and_process_peer_pkt(idx2peer[j]);
Adam Tkacb1585062009-11-22 03:43:55 +01001010 }
1011 }
1012 } /* while (!bb_got_signal) */
1013
1014 kill_myself_with_sig(bb_got_signal);
1015}