blob: 3b9e7b7ff9f1c30371198de2b57ee4b22e493075 [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 Vlasenkob1278a32009-11-24 16:03:47 +010017#define INTERVAL_QUERY_NORMAL 30 /* sync to peers every n secs */
18#define INTERVAL_QUERY_PATHETIC 60
19#define INTERVAL_QUERY_AGRESSIVE 5
Adam Tkacb1585062009-11-22 03:43:55 +010020
Denys Vlasenkob1278a32009-11-24 16:03:47 +010021#define TRUSTLEVEL_BADPEER 6 /* bad if *less than* TRUSTLEVEL_BADPEER */
22#define TRUSTLEVEL_PATHETIC 2
23#define TRUSTLEVEL_AGRESSIVE 8
24#define TRUSTLEVEL_MAX 10
Adam Tkacb1585062009-11-22 03:43:55 +010025
Denys Vlasenkob1278a32009-11-24 16:03:47 +010026#define QSCALE_OFF_MIN 0.05
27#define QSCALE_OFF_MAX 0.50
Adam Tkacb1585062009-11-22 03:43:55 +010028
Denys Vlasenkob1278a32009-11-24 16:03:47 +010029#define QUERYTIME_MAX 15 /* single query might take n secs max */
30#define OFFSET_ARRAY_SIZE 8
31#define SETTIME_MIN_OFFSET 180 /* min offset for settime at start */
32#define SETTIME_TIMEOUT 15 /* max seconds to wait with -s */
Adam Tkacb1585062009-11-22 03:43:55 +010033
34/* Style borrowed from NTP ref/tcpdump and updated for SNTPv4 (RFC2030). */
35
36/*
37 * RFC Section 3
38 *
39 * 0 1 2 3
40 * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
41 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
42 * | Integer Part |
43 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
44 * | Fraction Part |
45 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
46 *
47 * 0 1 2 3
48 * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
49 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
50 * | Integer Part | Fraction Part |
51 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
52*/
53typedef struct {
54 uint32_t int_partl;
55 uint32_t fractionl;
56} l_fixedpt_t;
57
58typedef struct {
59 uint16_t int_parts;
60 uint16_t fractions;
61} s_fixedpt_t;
62
Denys Vlasenkoca6c7e42009-11-24 07:07:42 +010063enum {
64 NTP_DIGESTSIZE = 16,
65 NTP_MSGSIZE_NOAUTH = 48,
66 NTP_MSGSIZE = (NTP_MSGSIZE_NOAUTH + 4 + NTP_DIGESTSIZE),
67};
Adam Tkacb1585062009-11-22 03:43:55 +010068
69typedef struct {
Denys Vlasenko386960a2009-12-02 01:51:24 +010070 uint8_t m_status; /* status of local clock and leap info */
71 uint8_t m_stratum; /* stratum level */
72 uint8_t m_ppoll; /* poll value */
73 int8_t m_precision;
74 s_fixedpt_t m_rootdelay;
75 s_fixedpt_t m_dispersion;
76 uint32_t m_refid;
77 l_fixedpt_t m_reftime;
78 l_fixedpt_t m_orgtime;
79 l_fixedpt_t m_rectime;
80 l_fixedpt_t m_xmttime;
81 uint32_t m_keyid;
82 uint8_t m_digest[NTP_DIGESTSIZE];
Adam Tkacb1585062009-11-22 03:43:55 +010083} ntp_msg_t;
84
Adam Tkacb1585062009-11-22 03:43:55 +010085enum {
86 NTP_VERSION = 4,
87 NTP_MAXSTRATUM = 15,
88 /* Leap Second Codes (high order two bits) */
89 LI_NOWARNING = (0 << 6), /* no warning */
90 LI_PLUSSEC = (1 << 6), /* add a second (61 seconds) */
91 LI_MINUSSEC = (2 << 6), /* minus a second (59 seconds) */
92 LI_ALARM = (3 << 6), /* alarm condition */
93
94 /* Status Masks */
95 MODE_MASK = (7 << 0),
96 VERSION_MASK = (7 << 3),
Denys Vlasenkoca6c7e42009-11-24 07:07:42 +010097 VERSION_SHIFT = 3,
Adam Tkacb1585062009-11-22 03:43:55 +010098 LI_MASK = (3 << 6),
99
100 /* Mode values */
101 MODE_RES0 = 0, /* reserved */
102 MODE_SYM_ACT = 1, /* symmetric active */
103 MODE_SYM_PAS = 2, /* symmetric passive */
104 MODE_CLIENT = 3, /* client */
105 MODE_SERVER = 4, /* server */
106 MODE_BROADCAST = 5, /* broadcast */
107 MODE_RES1 = 6, /* reserved for NTP control message */
Denys Vlasenkoca6c7e42009-11-24 07:07:42 +0100108 MODE_RES2 = 7, /* reserved for private use */
Adam Tkacb1585062009-11-22 03:43:55 +0100109};
110
Denys Vlasenkob1278a32009-11-24 16:03:47 +0100111#define OFFSET_1900_1970 2208988800UL /* 1970 - 1900 in seconds */
Adam Tkacb1585062009-11-22 03:43:55 +0100112
Denys Vlasenko386960a2009-12-02 01:51:24 +0100113typedef struct {
114 double o_offset;
115 double o_delay;
116 //UNUSED: double o_error;
117 time_t o_rcvd;
118 uint32_t o_refid4;
119 uint8_t o_leap;
120 uint8_t o_stratum;
121 uint8_t o_good;
122} ntp_offset_t;
123
124typedef struct {
125//TODO: periodically re-resolve DNS names?
126 len_and_sockaddr *lsa;
127 char *dotted;
128 double xmttime;
129 time_t next;
130 time_t deadline;
131 int fd;
132 uint8_t state;
133 uint8_t shift;
134 uint8_t trustlevel;
135 ntp_msg_t msg;
136 ntp_offset_t update;
137 ntp_offset_t reply[OFFSET_ARRAY_SIZE];
138} ntp_peer_t;
139/* for ntp_peer_t::state */
140enum {
Adam Tkacb1585062009-11-22 03:43:55 +0100141 STATE_NONE,
142 STATE_QUERY_SENT,
Denys Vlasenkoca6c7e42009-11-24 07:07:42 +0100143 STATE_REPLY_RECEIVED,
Adam Tkacb1585062009-11-22 03:43:55 +0100144};
145
Denys Vlasenko8d580c72009-11-23 16:27:16 +0100146enum {
147 OPT_n = (1 << 0),
148 OPT_g = (1 << 1),
149 OPT_q = (1 << 2),
Denys Vlasenkob2e5fc32009-11-25 14:52:47 +0100150 OPT_N = (1 << 3),
Denys Vlasenko8d580c72009-11-23 16:27:16 +0100151 /* Insert new options above this line. */
152 /* Non-compat options: */
Denys Vlasenkob2e5fc32009-11-25 14:52:47 +0100153 OPT_p = (1 << 4),
154 OPT_l = (1 << 5) * ENABLE_FEATURE_NTPD_SERVER,
Denys Vlasenko8d580c72009-11-23 16:27:16 +0100155};
156
Adam Tkacb1585062009-11-22 03:43:55 +0100157
158struct globals {
Denys Vlasenko386960a2009-12-02 01:51:24 +0100159 double rootdelay;
160 double reftime;
161 llist_t *ntp_peers;
Adam Tkacb1585062009-11-22 03:43:55 +0100162#if ENABLE_FEATURE_NTPD_SERVER
163 int listen_fd;
164#endif
Denys Vlasenko386960a2009-12-02 01:51:24 +0100165 unsigned verbose;
Denys Vlasenkob1278a32009-11-24 16:03:47 +0100166 unsigned peer_cnt;
Denys Vlasenko386960a2009-12-02 01:51:24 +0100167 uint32_t refid;
168 uint32_t refid4;
Adam Tkacb1585062009-11-22 03:43:55 +0100169 uint32_t scale;
Denys Vlasenko386960a2009-12-02 01:51:24 +0100170 uint8_t synced;
171 uint8_t leap;
172 int8_t precision;
173 uint8_t stratum;
Denys Vlasenkofae9f492009-12-01 02:32:01 +0100174 uint8_t time_is_set;
175 uint8_t first_adj_done;
Adam Tkacb1585062009-11-22 03:43:55 +0100176};
177#define G (*ptr_to_globals)
178
179
180static const int const_IPTOS_LOWDELAY = IPTOS_LOWDELAY;
181
182
183static void
Denys Vlasenko386960a2009-12-02 01:51:24 +0100184set_next(ntp_peer_t *p, unsigned t)
Adam Tkacb1585062009-11-22 03:43:55 +0100185{
186 p->next = time(NULL) + t;
187 p->deadline = 0;
188}
189
190static void
191add_peers(const char *s)
192{
193 ntp_peer_t *p;
194
195 p = xzalloc(sizeof(*p));
196//TODO: big ntpd uses all IPs, not just 1st, do we need to mimic that?
197 p->lsa = xhost2sockaddr(s, 123);
Denys Vlasenko386960a2009-12-02 01:51:24 +0100198 p->dotted = xmalloc_sockaddr2dotted_noport(&p->lsa->u.sa);
199 p->fd = -1;
200 p->msg.m_status = MODE_CLIENT | (NTP_VERSION << 3);
Adam Tkacb1585062009-11-22 03:43:55 +0100201 if (STATE_NONE != 0)
202 p->state = STATE_NONE;
203 p->trustlevel = TRUSTLEVEL_PATHETIC;
Adam Tkacb1585062009-11-22 03:43:55 +0100204 set_next(p, 0);
205
206 llist_add_to(&G.ntp_peers, p);
207 G.peer_cnt++;
208}
209
210static double
Denys Vlasenkob1278a32009-11-24 16:03:47 +0100211gettime1900fp(void)
Adam Tkacb1585062009-11-22 03:43:55 +0100212{
Denys Vlasenkoca6c7e42009-11-24 07:07:42 +0100213 struct timeval tv;
Adam Tkacb1585062009-11-22 03:43:55 +0100214 gettimeofday(&tv, NULL); /* never fails */
Denys Vlasenkob1278a32009-11-24 16:03:47 +0100215 return (tv.tv_sec + 1.0e-6 * tv.tv_usec + OFFSET_1900_1970);
Adam Tkacb1585062009-11-22 03:43:55 +0100216}
217
Adam Tkacb1585062009-11-22 03:43:55 +0100218static void
219d_to_tv(double d, struct timeval *tv)
220{
221 tv->tv_sec = (long)d;
222 tv->tv_usec = (d - tv->tv_sec) * 1000000;
223}
224
225static double
226lfp_to_d(l_fixedpt_t lfp)
227{
Denys Vlasenkoca6c7e42009-11-24 07:07:42 +0100228 double ret;
Adam Tkacb1585062009-11-22 03:43:55 +0100229 lfp.int_partl = ntohl(lfp.int_partl);
230 lfp.fractionl = ntohl(lfp.fractionl);
Denys Vlasenkoca6c7e42009-11-24 07:07:42 +0100231 ret = (double)lfp.int_partl + ((double)lfp.fractionl / UINT_MAX);
232 return ret;
233}
234
Denys Vlasenko386960a2009-12-02 01:51:24 +0100235#if 0 //UNUSED
Denys Vlasenkoca6c7e42009-11-24 07:07:42 +0100236static double
237sfp_to_d(s_fixedpt_t sfp)
238{
239 double ret;
240 sfp.int_parts = ntohs(sfp.int_parts);
241 sfp.fractions = ntohs(sfp.fractions);
242 ret = (double)sfp.int_parts + ((double)sfp.fractions / USHRT_MAX);
Adam Tkacb1585062009-11-22 03:43:55 +0100243 return ret;
244}
Denys Vlasenko386960a2009-12-02 01:51:24 +0100245#endif
Adam Tkacb1585062009-11-22 03:43:55 +0100246
247#if ENABLE_FEATURE_NTPD_SERVER
248static l_fixedpt_t
249d_to_lfp(double d)
250{
Denys Vlasenkoca6c7e42009-11-24 07:07:42 +0100251 l_fixedpt_t lfp;
252 lfp.int_partl = (uint32_t)d;
253 lfp.fractionl = (uint32_t)((d - lfp.int_partl) * UINT_MAX);
254 lfp.int_partl = htonl(lfp.int_partl);
255 lfp.fractionl = htonl(lfp.fractionl);
Adam Tkacb1585062009-11-22 03:43:55 +0100256 return lfp;
257}
Adam Tkacb1585062009-11-22 03:43:55 +0100258
Adam Tkacb1585062009-11-22 03:43:55 +0100259static s_fixedpt_t
260d_to_sfp(double d)
261{
Denys Vlasenkoca6c7e42009-11-24 07:07:42 +0100262 s_fixedpt_t sfp;
263 sfp.int_parts = (uint16_t)d;
264 sfp.fractions = (uint16_t)((d - sfp.int_parts) * USHRT_MAX);
265 sfp.int_parts = htons(sfp.int_parts);
266 sfp.fractions = htons(sfp.fractions);
Adam Tkacb1585062009-11-22 03:43:55 +0100267 return sfp;
268}
269#endif
270
271static void
272set_deadline(ntp_peer_t *p, time_t t)
273{
274 p->deadline = time(NULL) + t;
275 p->next = 0;
276}
277
Denys Vlasenko386960a2009-12-02 01:51:24 +0100278static unsigned
Adam Tkacb1585062009-11-22 03:43:55 +0100279error_interval(void)
280{
Denys Vlasenko386960a2009-12-02 01:51:24 +0100281 unsigned interval, r;
Adam Tkacb1585062009-11-22 03:43:55 +0100282 interval = INTERVAL_QUERY_PATHETIC * QSCALE_OFF_MAX / QSCALE_OFF_MIN;
Denys Vlasenko386960a2009-12-02 01:51:24 +0100283 r = (unsigned)random() % (unsigned)(interval / 10);
Adam Tkacb1585062009-11-22 03:43:55 +0100284 return (interval + r);
285}
286
287static int
Denys Vlasenko386960a2009-12-02 01:51:24 +0100288do_sendto(int fd,
Adam Tkacb1585062009-11-22 03:43:55 +0100289 const struct sockaddr *from, const struct sockaddr *to, socklen_t addrlen,
290 ntp_msg_t *msg, ssize_t len)
291{
292 ssize_t ret;
293
294 errno = 0;
295 if (!from) {
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100296 ret = sendto(fd, msg, len, MSG_DONTWAIT, to, addrlen);
Adam Tkacb1585062009-11-22 03:43:55 +0100297 } else {
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100298 ret = send_to_from(fd, msg, len, MSG_DONTWAIT, to, from, addrlen);
Adam Tkacb1585062009-11-22 03:43:55 +0100299 }
300 if (ret != len) {
301 bb_perror_msg("send failed");
302 return -1;
303 }
304 return 0;
305}
306
307static int
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100308send_query_to_peer(ntp_peer_t *p)
Adam Tkacb1585062009-11-22 03:43:55 +0100309{
Denys Vlasenkob1278a32009-11-24 16:03:47 +0100310 // Why do we need to bind()?
311 // See what happens when we don't bind:
312 //
313 // socket(PF_INET, SOCK_DGRAM, IPPROTO_IP) = 3
314 // setsockopt(3, SOL_IP, IP_TOS, [16], 4) = 0
315 // gettimeofday({1259071266, 327885}, NULL) = 0
316 // sendto(3, "xxx", 48, MSG_DONTWAIT, {sa_family=AF_INET, sin_port=htons(123), sin_addr=inet_addr("10.34.32.125")}, 16) = 48
317 // ^^^ we sent it from some source port picked by kernel.
318 // time(NULL) = 1259071266
319 // write(2, "ntpd: entering poll 15 secs\n", 28) = 28
320 // poll([{fd=3, events=POLLIN}], 1, 15000) = 1 ([{fd=3, revents=POLLIN}])
321 // recv(3, "yyy", 68, MSG_DONTWAIT) = 48
322 // ^^^ this recv will receive packets to any local port!
323 //
324 // Uncomment this and use strace to see it in action:
325#define PROBE_LOCAL_ADDR // { len_and_sockaddr lsa; lsa.len = LSA_SIZEOF_SA; getsockname(p->query.fd, &lsa.u.sa, &lsa.len); }
326
Denys Vlasenko386960a2009-12-02 01:51:24 +0100327 if (p->fd == -1) {
Denys Vlasenkob1278a32009-11-24 16:03:47 +0100328 int fd, family;
329 len_and_sockaddr *local_lsa;
330
331 family = p->lsa->u.sa.sa_family;
Denys Vlasenko386960a2009-12-02 01:51:24 +0100332 //was: p->fd = xsocket(family, SOCK_DGRAM, 0);
333 p->fd = fd = xsocket_type(&local_lsa, family, SOCK_DGRAM);
Denys Vlasenkob1278a32009-11-24 16:03:47 +0100334 /* local_lsa has "null" address and port 0 now.
335 * bind() ensures we have a *particular port* selected by kernel
Denys Vlasenko386960a2009-12-02 01:51:24 +0100336 * and remembered in p->fd, thus later recv(p->fd)
Denys Vlasenkob1278a32009-11-24 16:03:47 +0100337 * receives only packets sent to this port.
338 */
339 PROBE_LOCAL_ADDR
340 xbind(fd, &local_lsa->u.sa, local_lsa->len);
341 PROBE_LOCAL_ADDR
Adam Tkacb1585062009-11-22 03:43:55 +0100342#if ENABLE_FEATURE_IPV6
Denys Vlasenkob1278a32009-11-24 16:03:47 +0100343 if (family == AF_INET)
Adam Tkacb1585062009-11-22 03:43:55 +0100344#endif
Denys Vlasenkob1278a32009-11-24 16:03:47 +0100345 setsockopt(fd, IPPROTO_IP, IP_TOS, &const_IPTOS_LOWDELAY, sizeof(const_IPTOS_LOWDELAY));
346 free(local_lsa);
Adam Tkacb1585062009-11-22 03:43:55 +0100347 }
348
349 /*
350 * Send out a random 64-bit number as our transmit time. The NTP
351 * server will copy said number into the originate field on the
352 * response that it sends us. This is totally legal per the SNTP spec.
353 *
354 * The impact of this is two fold: we no longer send out the current
355 * system time for the world to see (which may aid an attacker), and
356 * it gives us a (not very secure) way of knowing that we're not
357 * getting spoofed by an attacker that can't capture our traffic
358 * but can spoof packets from the NTP server we're communicating with.
359 *
360 * Save the real transmit timestamp locally.
361 */
362
Denys Vlasenko386960a2009-12-02 01:51:24 +0100363 p->msg.m_xmttime.int_partl = random();
364 p->msg.m_xmttime.fractionl = random();
365 p->xmttime = gettime1900fp();
Adam Tkacb1585062009-11-22 03:43:55 +0100366
Denys Vlasenko386960a2009-12-02 01:51:24 +0100367 if (do_sendto(p->fd, /*from:*/ NULL, /*to:*/ &p->lsa->u.sa, /*addrlen:*/ p->lsa->len,
368 &p->msg, NTP_MSGSIZE_NOAUTH) == -1
369 ) {
Adam Tkacb1585062009-11-22 03:43:55 +0100370 set_next(p, INTERVAL_QUERY_PATHETIC);
371 return -1;
372 }
373
Denys Vlasenko386960a2009-12-02 01:51:24 +0100374 if (G.verbose)
375 bb_error_msg("sent request to %s", p->dotted);
Adam Tkacb1585062009-11-22 03:43:55 +0100376 p->state = STATE_QUERY_SENT;
377 set_deadline(p, QUERYTIME_MAX);
378
379 return 0;
380}
381
382static int
Denys Vlasenko386960a2009-12-02 01:51:24 +0100383compare_offsets(const void *aa, const void *bb)
Adam Tkacb1585062009-11-22 03:43:55 +0100384{
Denys Vlasenkoca6c7e42009-11-24 07:07:42 +0100385 const ntp_peer_t *const *a = aa;
386 const ntp_peer_t *const *b = bb;
Denys Vlasenko386960a2009-12-02 01:51:24 +0100387 if ((*a)->update.o_offset < (*b)->update.o_offset)
Adam Tkacb1585062009-11-22 03:43:55 +0100388 return -1;
Denys Vlasenko386960a2009-12-02 01:51:24 +0100389 return ((*a)->update.o_offset > (*b)->update.o_offset);
Adam Tkacb1585062009-11-22 03:43:55 +0100390}
391
392static uint32_t
393updated_scale(double offset)
394{
395 if (offset < 0)
396 offset = -offset;
Adam Tkacb1585062009-11-22 03:43:55 +0100397 if (offset > QSCALE_OFF_MAX)
398 return 1;
399 if (offset < QSCALE_OFF_MIN)
400 return QSCALE_OFF_MAX / QSCALE_OFF_MIN;
401 return QSCALE_OFF_MAX / offset;
402}
403
404static void
Denys Vlasenko386960a2009-12-02 01:51:24 +0100405slew_time(void)
Adam Tkacb1585062009-11-22 03:43:55 +0100406{
407 ntp_peer_t *p;
Adam Tkacb1585062009-11-22 03:43:55 +0100408 llist_t *item;
Denys Vlasenko386960a2009-12-02 01:51:24 +0100409 unsigned offset_cnt;
410 double offset_median;
411 struct timeval tv;
Adam Tkacb1585062009-11-22 03:43:55 +0100412
413 offset_cnt = 0;
414 for (item = G.ntp_peers; item != NULL; item = item->link) {
415 p = (ntp_peer_t *) item->data;
416 if (p->trustlevel < TRUSTLEVEL_BADPEER)
417 continue;
Denys Vlasenko386960a2009-12-02 01:51:24 +0100418 if (!p->update.o_good)
Adam Tkacb1585062009-11-22 03:43:55 +0100419 return;
420 offset_cnt++;
421 }
422
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100423 if (offset_cnt == 0)
424 goto clear_good;
425
Denys Vlasenko386960a2009-12-02 01:51:24 +0100426 {
427 len_and_sockaddr *lsa;
428 unsigned middle;
429 unsigned i = 0;
430 ntp_peer_t **peers = xzalloc(sizeof(peers[0]) * offset_cnt);
431
432 for (item = G.ntp_peers; item != NULL; item = item->link) {
433 p = (ntp_peer_t *) item->data;
434 if (p->trustlevel < TRUSTLEVEL_BADPEER)
435 continue;
436 peers[i++] = p;
437 }
438
439 qsort(peers, offset_cnt, sizeof(peers[0]), compare_offsets);
440
441 middle = offset_cnt / 2;
442 if (middle != 0 && (offset_cnt & 1) == 0) {
443 offset_median = (peers[middle-1]->update.o_offset + peers[middle]->update.o_offset) / 2;
444 G.rootdelay = (peers[middle-1]->update.o_delay + peers[middle]->update.o_delay) / 2;
445 G.stratum = 1 + MAX(peers[middle-1]->update.o_stratum, peers[middle]->update.o_stratum);
446 } else {
447 offset_median = peers[middle]->update.o_offset;
448 G.rootdelay = peers[middle]->update.o_delay;
449 G.stratum = 1 + peers[middle]->update.o_stratum;
450 }
451 G.leap = peers[middle]->update.o_leap;
452 G.refid4 = peers[middle]->update.o_refid4;
453 lsa = peers[middle]->lsa;
454 G.refid =
455#if ENABLE_FEATURE_IPV6
456 lsa->u.sa.sa_family != AF_INET ?
457 G.refid4 :
458#endif
459 lsa->u.sin.sin_addr.s_addr;
460 free(peers);
Adam Tkacb1585062009-11-22 03:43:55 +0100461 }
462
Denys Vlasenko386960a2009-12-02 01:51:24 +0100463 bb_error_msg("adjusting clock by %fs, our stratum is %u", offset_median, G.stratum);
Adam Tkacb1585062009-11-22 03:43:55 +0100464
Denys Vlasenkofae9f492009-12-01 02:32:01 +0100465 errno = 0;
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100466 d_to_tv(offset_median, &tv);
Denys Vlasenko386960a2009-12-02 01:51:24 +0100467 if (adjtime(&tv, &tv) == -1) {
Denys Vlasenkofae9f492009-12-01 02:32:01 +0100468 bb_perror_msg("adjtime failed"); //TODO: maybe _and_die?
Denys Vlasenko386960a2009-12-02 01:51:24 +0100469 } else {
470 if (G.verbose >= 2)
471 bb_error_msg("old adjust: %d.%06u", (int)tv.tv_sec, (unsigned)tv.tv_usec);
472 if (G.first_adj_done
473 && tv.tv_sec == 0
474 && tv.tv_usec == 0 // TODO: allow for tiny values?
475 && !G.synced
476 ) {
477 G.synced = 1;
478 bb_error_msg("clock %ssynced", "");
479 } else
480 if (G.synced) {
481 G.synced = 0;
482 bb_error_msg("clock %ssynced", "un");
483 }
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100484 }
485
Denys Vlasenkofae9f492009-12-01 02:32:01 +0100486 G.first_adj_done = 1;
Denys Vlasenko386960a2009-12-02 01:51:24 +0100487 G.reftime = gettime1900fp();
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100488 G.scale = updated_scale(offset_median);
489
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100490 clear_good:
Adam Tkacb1585062009-11-22 03:43:55 +0100491 for (item = G.ntp_peers; item != NULL; item = item->link) {
492 p = (ntp_peer_t *) item->data;
Denys Vlasenko386960a2009-12-02 01:51:24 +0100493 p->update.o_good = 0;
Adam Tkacb1585062009-11-22 03:43:55 +0100494 }
495}
496
497static void
Denys Vlasenkofae9f492009-12-01 02:32:01 +0100498step_time_once(double offset)
Adam Tkacb1585062009-11-22 03:43:55 +0100499{
500 ntp_peer_t *p;
501 llist_t *item;
502 struct timeval tv, curtime;
503 char buf[80];
504 time_t tval;
505
Denys Vlasenkofae9f492009-12-01 02:32:01 +0100506 if (G.time_is_set)
Denys Vlasenko8d580c72009-11-23 16:27:16 +0100507 goto bail;
Denys Vlasenkofae9f492009-12-01 02:32:01 +0100508 G.time_is_set = 1;
Adam Tkacb1585062009-11-22 03:43:55 +0100509
510 /* if the offset is small, don't call settimeofday */
511 if (offset < SETTIME_MIN_OFFSET && offset > -SETTIME_MIN_OFFSET)
Denys Vlasenko8d580c72009-11-23 16:27:16 +0100512 goto bail;
Adam Tkacb1585062009-11-22 03:43:55 +0100513
514 gettimeofday(&curtime, NULL); /* never fails */
515
Denys Vlasenkofae9f492009-12-01 02:32:01 +0100516//isn't it simpler to: offset += curtime.tv_sec; offset += 1.0e-6 * curtime.tv_usec?
Adam Tkacb1585062009-11-22 03:43:55 +0100517 d_to_tv(offset, &tv);
518 curtime.tv_usec += tv.tv_usec + 1000000;
519 curtime.tv_sec += tv.tv_sec - 1 + (curtime.tv_usec / 1000000);
520 curtime.tv_usec %= 1000000;
521
522 if (settimeofday(&curtime, NULL) == -1) {
523 bb_error_msg("settimeofday");
Denys Vlasenko8d580c72009-11-23 16:27:16 +0100524 goto bail;
Adam Tkacb1585062009-11-22 03:43:55 +0100525 }
526
Adam Tkacb1585062009-11-22 03:43:55 +0100527 tval = curtime.tv_sec;
528 strftime(buf, sizeof(buf), "%a %b %e %H:%M:%S %Z %Y", localtime(&tval));
529
530 /* Do we want to print message below to system log when daemonized? */
Denys Vlasenko386960a2009-12-02 01:51:24 +0100531 bb_error_msg("set local clock to %s (offset %fs)", buf, offset);
Adam Tkacb1585062009-11-22 03:43:55 +0100532
533 for (item = G.ntp_peers; item != NULL; item = item->link) {
534 p = (ntp_peer_t *) item->data;
535 if (p->next)
536 p->next -= offset;
537 if (p->deadline)
538 p->deadline -= offset;
539 }
Denys Vlasenko8d580c72009-11-23 16:27:16 +0100540
541 bail:
542 if (option_mask32 & OPT_q)
543 exit(0);
Adam Tkacb1585062009-11-22 03:43:55 +0100544}
545
546static void
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100547update_peer_data(ntp_peer_t *p)
Adam Tkacb1585062009-11-22 03:43:55 +0100548{
Denys Vlasenko386960a2009-12-02 01:51:24 +0100549 /* Clock filter.
550 * Find the offset which arrived with the lowest delay.
551 * Use that as the peer update.
552 * Invalidate it and all older ones.
Adam Tkacb1585062009-11-22 03:43:55 +0100553 */
Denys Vlasenko386960a2009-12-02 01:51:24 +0100554 int i;
555 int best = best; /* for compiler */
556 int good;
Adam Tkacb1585062009-11-22 03:43:55 +0100557
Denys Vlasenko386960a2009-12-02 01:51:24 +0100558 good = 0;
559 for (i = 0; i < OFFSET_ARRAY_SIZE; i++) {
560 if (p->reply[i].o_good) {
Adam Tkacb1585062009-11-22 03:43:55 +0100561 good++;
Denys Vlasenko386960a2009-12-02 01:51:24 +0100562 best = i++;
563 break;
Adam Tkacb1585062009-11-22 03:43:55 +0100564 }
565 }
566
567 for (; i < OFFSET_ARRAY_SIZE; i++) {
Denys Vlasenko386960a2009-12-02 01:51:24 +0100568 if (p->reply[i].o_good) {
Adam Tkacb1585062009-11-22 03:43:55 +0100569 good++;
Denys Vlasenko386960a2009-12-02 01:51:24 +0100570 if (p->reply[i].o_delay < p->reply[best].o_delay)
Adam Tkacb1585062009-11-22 03:43:55 +0100571 best = i;
572 }
573 }
574
Denys Vlasenko386960a2009-12-02 01:51:24 +0100575 if (good < 8) //FIXME: was it meant to be OFFSET_ARRAY_SIZE, not 8?
Adam Tkacb1585062009-11-22 03:43:55 +0100576 return;
577
578 memcpy(&p->update, &p->reply[best], sizeof(p->update));
Denys Vlasenko386960a2009-12-02 01:51:24 +0100579 slew_time();
Adam Tkacb1585062009-11-22 03:43:55 +0100580
581 for (i = 0; i < OFFSET_ARRAY_SIZE; i++)
Denys Vlasenko386960a2009-12-02 01:51:24 +0100582 if (p->reply[i].o_rcvd <= p->reply[best].o_rcvd)
583 p->reply[i].o_good = 0;
Adam Tkacb1585062009-11-22 03:43:55 +0100584}
585
Denys Vlasenko386960a2009-12-02 01:51:24 +0100586static unsigned
587scale_interval(unsigned requested)
Adam Tkacb1585062009-11-22 03:43:55 +0100588{
Denys Vlasenko386960a2009-12-02 01:51:24 +0100589 unsigned interval, r;
Adam Tkacb1585062009-11-22 03:43:55 +0100590 interval = requested * G.scale;
Denys Vlasenko386960a2009-12-02 01:51:24 +0100591 r = (unsigned)random() % (unsigned)(MAX(5, interval / 10));
Adam Tkacb1585062009-11-22 03:43:55 +0100592 return (interval + r);
593}
594
595static void
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100596recv_and_process_peer_pkt(ntp_peer_t *p)
Adam Tkacb1585062009-11-22 03:43:55 +0100597{
Adam Tkacb1585062009-11-22 03:43:55 +0100598 ssize_t size;
599 ntp_msg_t msg;
600 double T1, T2, T3, T4;
Denys Vlasenko386960a2009-12-02 01:51:24 +0100601 unsigned interval;
Adam Tkacb1585062009-11-22 03:43:55 +0100602 ntp_offset_t *offset;
603
Denys Vlasenkob1278a32009-11-24 16:03:47 +0100604 /* We can recvfrom here and check from.IP, but some multihomed
605 * ntp servers reply from their *other IP*.
606 * TODO: maybe we should check at least what we can: from.port == 123?
607 */
Denys Vlasenko386960a2009-12-02 01:51:24 +0100608 size = recv(p->fd, &msg, sizeof(msg), MSG_DONTWAIT);
Adam Tkacb1585062009-11-22 03:43:55 +0100609 if (size == -1) {
Denys Vlasenko386960a2009-12-02 01:51:24 +0100610 bb_perror_msg("recv(%s) error", p->dotted);
Adam Tkacb1585062009-11-22 03:43:55 +0100611 if (errno == EHOSTUNREACH || errno == EHOSTDOWN
612 || errno == ENETUNREACH || errno == ENETDOWN
613 || errno == ECONNREFUSED || errno == EADDRNOTAVAIL
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100614 || errno == EAGAIN
Adam Tkacb1585062009-11-22 03:43:55 +0100615 ) {
616//TODO: always do this?
617 set_next(p, error_interval());
Denys Vlasenko386960a2009-12-02 01:51:24 +0100618 goto close_sock;
Adam Tkacb1585062009-11-22 03:43:55 +0100619 }
620 xfunc_die();
621 }
622
Denys Vlasenkob1278a32009-11-24 16:03:47 +0100623 T4 = gettime1900fp();
Adam Tkacb1585062009-11-22 03:43:55 +0100624
625 if (size != NTP_MSGSIZE_NOAUTH && size != NTP_MSGSIZE) {
Denys Vlasenko386960a2009-12-02 01:51:24 +0100626 bb_error_msg("malformed packet received from %s", p->dotted);
Adam Tkacb1585062009-11-22 03:43:55 +0100627 goto bail;
628 }
629
Denys Vlasenko386960a2009-12-02 01:51:24 +0100630 if (msg.m_orgtime.int_partl != p->msg.m_xmttime.int_partl
631 || msg.m_orgtime.fractionl != p->msg.m_xmttime.fractionl
Adam Tkacb1585062009-11-22 03:43:55 +0100632 ) {
633 goto bail;
634 }
635
Denys Vlasenko386960a2009-12-02 01:51:24 +0100636 if ((msg.m_status & LI_ALARM) == LI_ALARM
637 || msg.m_stratum == 0
638 || msg.m_stratum > NTP_MAXSTRATUM
Adam Tkacb1585062009-11-22 03:43:55 +0100639 ) {
640 interval = error_interval();
Denys Vlasenko386960a2009-12-02 01:51:24 +0100641 bb_error_msg("reply from %s: not synced, next query %us", p->dotted, interval);
642 goto close_sock;
Adam Tkacb1585062009-11-22 03:43:55 +0100643 }
644
645 /*
646 * From RFC 2030 (with a correction to the delay math):
647 *
648 * Timestamp Name ID When Generated
649 * ------------------------------------------------------------
650 * Originate Timestamp T1 time request sent by client
651 * Receive Timestamp T2 time request received by server
652 * Transmit Timestamp T3 time reply sent by server
653 * Destination Timestamp T4 time reply received by client
654 *
655 * The roundtrip delay d and local clock offset t are defined as
656 *
657 * d = (T4 - T1) - (T3 - T2) t = ((T2 - T1) + (T3 - T4)) / 2.
658 */
659
Denys Vlasenko386960a2009-12-02 01:51:24 +0100660 T1 = p->xmttime;
661 T2 = lfp_to_d(msg.m_rectime);
662 T3 = lfp_to_d(msg.m_xmttime);
Adam Tkacb1585062009-11-22 03:43:55 +0100663
664 offset = &p->reply[p->shift];
665
Denys Vlasenko386960a2009-12-02 01:51:24 +0100666 offset->o_offset = ((T2 - T1) + (T3 - T4)) / 2;
667 offset->o_delay = (T4 - T1) - (T3 - T2);
668 if (offset->o_delay < 0) {
Adam Tkacb1585062009-11-22 03:43:55 +0100669 interval = error_interval();
670 set_next(p, interval);
Denys Vlasenko386960a2009-12-02 01:51:24 +0100671 bb_error_msg("reply from %s: negative delay %f", p->dotted, p->reply[p->shift].o_delay);
672 goto close_sock;
Adam Tkacb1585062009-11-22 03:43:55 +0100673 }
Denys Vlasenko386960a2009-12-02 01:51:24 +0100674 //UNUSED: offset->o_error = (T2 - T1) - (T3 - T4);
Denys Vlasenkob1278a32009-11-24 16:03:47 +0100675// Can we use (T4 - OFFSET_1900_1970) instead of time(NULL)?
Denys Vlasenko386960a2009-12-02 01:51:24 +0100676 offset->o_rcvd = time(NULL);
677 offset->o_good = 1;
Adam Tkacb1585062009-11-22 03:43:55 +0100678
Denys Vlasenko386960a2009-12-02 01:51:24 +0100679 offset->o_leap = (msg.m_status & LI_MASK);
680 //UNUSED: offset->o_precision = msg.m_precision;
681 //UNUSED: offset->o_rootdelay = sfp_to_d(msg.m_rootdelay);
682 //UNUSED: offset->o_rootdispersion = sfp_to_d(msg.m_dispersion);
683 //UNUSED: offset->o_refid = ntohl(msg.m_refid);
684 offset->o_refid4 = msg.m_xmttime.fractionl;
685 //UNUSED: offset->o_reftime = lfp_to_d(msg.m_reftime);
686 //UNUSED: offset->o_poll = msg.m_ppoll;
687 offset->o_stratum = msg.m_stratum;
Adam Tkacb1585062009-11-22 03:43:55 +0100688
689 if (p->trustlevel < TRUSTLEVEL_PATHETIC)
690 interval = scale_interval(INTERVAL_QUERY_PATHETIC);
691 else if (p->trustlevel < TRUSTLEVEL_AGRESSIVE)
692 interval = scale_interval(INTERVAL_QUERY_AGRESSIVE);
693 else
694 interval = scale_interval(INTERVAL_QUERY_NORMAL);
695
696 set_next(p, interval);
697 p->state = STATE_REPLY_RECEIVED;
698
699 /* every received reply which we do not discard increases trust */
700 if (p->trustlevel < TRUSTLEVEL_MAX) {
Adam Tkacb1585062009-11-22 03:43:55 +0100701 p->trustlevel++;
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100702 if (p->trustlevel == TRUSTLEVEL_BADPEER)
Denys Vlasenko386960a2009-12-02 01:51:24 +0100703 bb_error_msg("peer %s now valid", p->dotted);
Adam Tkacb1585062009-11-22 03:43:55 +0100704 }
705
Denys Vlasenko386960a2009-12-02 01:51:24 +0100706 if (G.verbose)
707 bb_error_msg("reply from %s: offset %f delay %f, next query %us", p->dotted,
708 offset->o_offset, offset->o_delay, interval);
Adam Tkacb1585062009-11-22 03:43:55 +0100709
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100710 update_peer_data(p);
Denys Vlasenko386960a2009-12-02 01:51:24 +0100711 step_time_once(offset->o_offset);
Adam Tkacb1585062009-11-22 03:43:55 +0100712
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100713 p->shift++;
714 if (p->shift >= OFFSET_ARRAY_SIZE)
Adam Tkacb1585062009-11-22 03:43:55 +0100715 p->shift = 0;
716
Denys Vlasenko386960a2009-12-02 01:51:24 +0100717 close_sock:
718 /* We do not expect any more packets for now.
719 * Closing the socket informs kernel about it.
720 * We open a new socket when we send a new query.
721 */
722 close(p->fd);
723 p->fd = -1;
Adam Tkacb1585062009-11-22 03:43:55 +0100724 bail:
Denys Vlasenko386960a2009-12-02 01:51:24 +0100725 return;
Adam Tkacb1585062009-11-22 03:43:55 +0100726}
727
728#if ENABLE_FEATURE_NTPD_SERVER
729static void
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100730recv_and_process_client_pkt(void /*int fd*/)
Adam Tkacb1585062009-11-22 03:43:55 +0100731{
Denys Vlasenkoca6c7e42009-11-24 07:07:42 +0100732 ssize_t size;
733 uint8_t version;
734 double rectime;
735 len_and_sockaddr *to;
736 struct sockaddr *from;
737 ntp_msg_t msg;
738 uint8_t query_status;
739 uint8_t query_ppoll;
740 l_fixedpt_t query_xmttime;
Adam Tkacb1585062009-11-22 03:43:55 +0100741
742 to = get_sock_lsa(G.listen_fd);
743 from = xzalloc(to->len);
744
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100745 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 +0100746 if (size != NTP_MSGSIZE_NOAUTH && size != NTP_MSGSIZE) {
Denys Vlasenkoca6c7e42009-11-24 07:07:42 +0100747 char *addr;
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100748 if (size < 0) {
749 if (errno == EAGAIN)
750 goto bail;
751 bb_perror_msg_and_die("recv_from_to");
752 }
Denys Vlasenkoca6c7e42009-11-24 07:07:42 +0100753 addr = xmalloc_sockaddr2dotted_noport(from);
Adam Tkacb1585062009-11-22 03:43:55 +0100754 bb_error_msg("malformed packet received from %s", addr);
755 free(addr);
756 goto bail;
757 }
758
Denys Vlasenko386960a2009-12-02 01:51:24 +0100759 query_status = msg.m_status;
760 query_ppoll = msg.m_ppoll;
761 query_xmttime = msg.m_xmttime;
Adam Tkacb1585062009-11-22 03:43:55 +0100762
Denys Vlasenkoca6c7e42009-11-24 07:07:42 +0100763 /* Build a reply packet */
764 memset(&msg, 0, sizeof(msg));
Denys Vlasenko386960a2009-12-02 01:51:24 +0100765 msg.m_status = G.synced ? G.leap : LI_ALARM;
766 msg.m_status |= (query_status & VERSION_MASK);
767 msg.m_status |= ((query_status & MODE_MASK) == MODE_CLIENT) ?
Adam Tkacb1585062009-11-22 03:43:55 +0100768 MODE_SERVER : MODE_SYM_PAS;
Denys Vlasenko386960a2009-12-02 01:51:24 +0100769 msg.m_stratum = G.stratum;
770 msg.m_ppoll = query_ppoll;
771 msg.m_precision = G.precision;
Denys Vlasenkob1278a32009-11-24 16:03:47 +0100772 rectime = gettime1900fp();
Denys Vlasenko386960a2009-12-02 01:51:24 +0100773 msg.m_xmttime = msg.m_rectime = d_to_lfp(rectime);
774 msg.m_reftime = d_to_lfp(G.reftime);
775 //msg.m_xmttime = d_to_lfp(gettime1900fp()); // = msg.m_rectime
776 msg.m_orgtime = query_xmttime;
777 msg.m_rootdelay = d_to_sfp(G.rootdelay);
Denys Vlasenkoca6c7e42009-11-24 07:07:42 +0100778 version = (query_status & VERSION_MASK); /* ... >> VERSION_SHIFT - done below instead */
Denys Vlasenko386960a2009-12-02 01:51:24 +0100779 msg.m_refid = (version > (3 << VERSION_SHIFT)) ? G.refid4 : G.refid;
Adam Tkacb1585062009-11-22 03:43:55 +0100780
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100781 /* We reply from the local address packet was sent to,
Adam Tkacb1585062009-11-22 03:43:55 +0100782 * this makes to/from look swapped here: */
Denys Vlasenko386960a2009-12-02 01:51:24 +0100783 do_sendto(G.listen_fd,
Denys Vlasenkoca6c7e42009-11-24 07:07:42 +0100784 /*from:*/ &to->u.sa, /*to:*/ from, /*addrlen:*/ to->len,
785 &msg, size);
Adam Tkacb1585062009-11-22 03:43:55 +0100786
787 bail:
788 free(to);
789 free(from);
790}
791#endif
792
793/* Upstream ntpd's options:
794 *
795 * -4 Force DNS resolution of host names to the IPv4 namespace.
796 * -6 Force DNS resolution of host names to the IPv6 namespace.
797 * -a Require cryptographic authentication for broadcast client,
798 * multicast client and symmetric passive associations.
799 * This is the default.
800 * -A Do not require cryptographic authentication for broadcast client,
801 * multicast client and symmetric passive associations.
802 * This is almost never a good idea.
803 * -b Enable the client to synchronize to broadcast servers.
804 * -c conffile
805 * Specify the name and path of the configuration file,
806 * default /etc/ntp.conf
807 * -d Specify debugging mode. This option may occur more than once,
808 * with each occurrence indicating greater detail of display.
809 * -D level
810 * Specify debugging level directly.
811 * -f driftfile
812 * Specify the name and path of the frequency file.
813 * This is the same operation as the "driftfile FILE"
814 * configuration command.
815 * -g Normally, ntpd exits with a message to the system log
816 * if the offset exceeds the panic threshold, which is 1000 s
817 * by default. This option allows the time to be set to any value
818 * without restriction; however, this can happen only once.
819 * If the threshold is exceeded after that, ntpd will exit
820 * with a message to the system log. This option can be used
821 * with the -q and -x options. See the tinker command for other options.
822 * -i jaildir
823 * Chroot the server to the directory jaildir. This option also implies
824 * that the server attempts to drop root privileges at startup
825 * (otherwise, chroot gives very little additional security).
826 * You may need to also specify a -u option.
827 * -k keyfile
828 * Specify the name and path of the symmetric key file,
829 * default /etc/ntp/keys. This is the same operation
830 * as the "keys FILE" configuration command.
831 * -l logfile
832 * Specify the name and path of the log file. The default
833 * is the system log file. This is the same operation as
834 * the "logfile FILE" configuration command.
835 * -L Do not listen to virtual IPs. The default is to listen.
836 * -n Don't fork.
837 * -N To the extent permitted by the operating system,
838 * run the ntpd at the highest priority.
839 * -p pidfile
840 * Specify the name and path of the file used to record the ntpd
841 * process ID. This is the same operation as the "pidfile FILE"
842 * configuration command.
843 * -P priority
844 * To the extent permitted by the operating system,
845 * run the ntpd at the specified priority.
846 * -q Exit the ntpd just after the first time the clock is set.
847 * This behavior mimics that of the ntpdate program, which is
848 * to be retired. The -g and -x options can be used with this option.
849 * Note: The kernel time discipline is disabled with this option.
850 * -r broadcastdelay
851 * Specify the default propagation delay from the broadcast/multicast
852 * server to this client. This is necessary only if the delay
853 * cannot be computed automatically by the protocol.
854 * -s statsdir
855 * Specify the directory path for files created by the statistics
856 * facility. This is the same operation as the "statsdir DIR"
857 * configuration command.
858 * -t key
859 * Add a key number to the trusted key list. This option can occur
860 * more than once.
861 * -u user[:group]
862 * Specify a user, and optionally a group, to switch to.
863 * -v variable
864 * -V variable
865 * Add a system variable listed by default.
866 * -x Normally, the time is slewed if the offset is less than the step
867 * threshold, which is 128 ms by default, and stepped if above
868 * the threshold. This option sets the threshold to 600 s, which is
869 * well within the accuracy window to set the clock manually.
870 * Note: since the slew rate of typical Unix kernels is limited
871 * to 0.5 ms/s, each second of adjustment requires an amortization
872 * interval of 2000 s. Thus, an adjustment as much as 600 s
873 * will take almost 14 days to complete. This option can be used
874 * with the -g and -q options. See the tinker command for other options.
875 * Note: The kernel time discipline is disabled with this option.
876 */
877
Adam Tkacb1585062009-11-22 03:43:55 +0100878/* By doing init in a separate function we decrease stack usage
879 * in main loop.
880 */
881static NOINLINE void ntp_init(char **argv)
882{
883 unsigned opts;
884 llist_t *peers;
885
Denys Vlasenkoca6c7e42009-11-24 07:07:42 +0100886 srandom(getpid());
887 /* tzset(); - why? it's called automatically when needed, no? */
Adam Tkacb1585062009-11-22 03:43:55 +0100888
889 if (getuid())
Denys Vlasenkob2e5fc32009-11-25 14:52:47 +0100890 bb_error_msg_and_die(bb_msg_you_must_be_root);
Adam Tkacb1585062009-11-22 03:43:55 +0100891
892 peers = NULL;
893 opt_complementary = "dd:p::"; /* d: counter, p: list */
894 opts = getopt32(argv,
Denys Vlasenkob2e5fc32009-11-25 14:52:47 +0100895 "ngqN" /* compat */
Adam Tkacb1585062009-11-22 03:43:55 +0100896 "p:"IF_FEATURE_NTPD_SERVER("l") /* NOT compat */
897 "d" /* compat */
Denys Vlasenkob2e5fc32009-11-25 14:52:47 +0100898 "46aAbLx", /* compat, ignored */
Adam Tkacb1585062009-11-22 03:43:55 +0100899 &peers, &G.verbose);
Denys Vlasenkob2e5fc32009-11-25 14:52:47 +0100900 if (!(opts & (OPT_p|OPT_l)))
901 bb_show_usage();
Denys Vlasenkofae9f492009-12-01 02:32:01 +0100902//WRONG
903// if (opts & OPT_g)
904// G.time_is_set = 1;
Denys Vlasenko160b9ca2009-11-27 02:35:15 +0100905 while (peers)
906 add_peers(llist_pop(&peers));
907 if (!(opts & OPT_n)) {
908 bb_daemonize_or_rexec(DAEMON_DEVNULL_STDIO, argv);
909 logmode = LOGMODE_NONE;
910 }
Adam Tkacb1585062009-11-22 03:43:55 +0100911#if ENABLE_FEATURE_NTPD_SERVER
912 G.listen_fd = -1;
913 if (opts & OPT_l) {
914 G.listen_fd = create_and_bind_dgram_or_die(NULL, 123);
915 socket_want_pktinfo(G.listen_fd);
916 setsockopt(G.listen_fd, IPPROTO_IP, IP_TOS, &const_IPTOS_LOWDELAY, sizeof(const_IPTOS_LOWDELAY));
917 }
918#endif
Denys Vlasenkob2e5fc32009-11-25 14:52:47 +0100919 /* I hesitate to set -20 prio. -15 should be high enough for timekeeping */
920 if (opts & OPT_N)
921 setpriority(PRIO_PROCESS, 0, -15);
Adam Tkacb1585062009-11-22 03:43:55 +0100922
923 /* Set some globals */
924 {
925 int prec = 0;
926 int b;
927#if 0
928 struct timespec tp;
929 /* We can use sys_clock_getres but assuming 10ms tick should be fine */
930 clock_getres(CLOCK_REALTIME, &tp);
931 tp.tv_sec = 0;
932 tp.tv_nsec = 10000000;
933 b = 1000000000 / tp.tv_nsec; /* convert to Hz */
934#else
935 b = 100; /* b = 1000000000/10000000 = 100 */
936#endif
937 while (b > 1)
938 prec--, b >>= 1;
Denys Vlasenko386960a2009-12-02 01:51:24 +0100939 G.precision = prec;
Adam Tkacb1585062009-11-22 03:43:55 +0100940 }
941 G.scale = 1;
Adam Tkacb1585062009-11-22 03:43:55 +0100942
943 bb_signals((1 << SIGTERM) | (1 << SIGINT), record_signo);
944 bb_signals((1 << SIGPIPE) | (1 << SIGHUP), SIG_IGN);
945}
946
947int ntpd_main(int argc UNUSED_PARAM, char **argv) MAIN_EXTERNALLY_VISIBLE;
948int ntpd_main(int argc UNUSED_PARAM, char **argv)
949{
950 struct globals g;
Adam Tkacb1585062009-11-22 03:43:55 +0100951 struct pollfd *pfd;
952 ntp_peer_t **idx2peer;
953
954 memset(&g, 0, sizeof(g));
955 SET_PTR_TO_GLOBALS(&g);
956
957 ntp_init(argv);
958
Denys Vlasenko8d580c72009-11-23 16:27:16 +0100959 {
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100960 unsigned cnt = g.peer_cnt;
Denys Vlasenko8d580c72009-11-23 16:27:16 +0100961 /* if ENABLE_FEATURE_NTPD_SERVER, + 1 for listen_fd: */
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100962 idx2peer = xzalloc(sizeof(void *) * (cnt + ENABLE_FEATURE_NTPD_SERVER));
963 pfd = xzalloc(sizeof(pfd[0]) * (cnt + ENABLE_FEATURE_NTPD_SERVER));
Denys Vlasenko8d580c72009-11-23 16:27:16 +0100964 }
Adam Tkacb1585062009-11-22 03:43:55 +0100965
966 while (!bb_got_signal) {
967 llist_t *item;
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100968 unsigned i, j;
Adam Tkacb1585062009-11-22 03:43:55 +0100969 unsigned sent_cnt, trial_cnt;
970 int nfds, timeout;
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100971 time_t cur_time, nextaction;
Adam Tkacb1585062009-11-22 03:43:55 +0100972
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100973 /* Nothing between here and poll() blocks for any significant time */
974
975 cur_time = time(NULL);
976 nextaction = cur_time + 3600;
Adam Tkacb1585062009-11-22 03:43:55 +0100977
978 i = 0;
979#if ENABLE_FEATURE_NTPD_SERVER
980 if (g.listen_fd != -1) {
981 pfd[0].fd = g.listen_fd;
982 pfd[0].events = POLLIN;
983 i++;
984 }
985#endif
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100986 /* Pass over peer list, send requests, time out on receives */
Adam Tkacb1585062009-11-22 03:43:55 +0100987 sent_cnt = trial_cnt = 0;
988 for (item = g.ntp_peers; item != NULL; item = item->link) {
989 ntp_peer_t *p = (ntp_peer_t *) item->data;
990
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100991 if (p->next != 0 && p->next <= cur_time) {
992 /* Time to send new req */
Adam Tkacb1585062009-11-22 03:43:55 +0100993 trial_cnt++;
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100994 if (send_query_to_peer(p) == 0)
Adam Tkacb1585062009-11-22 03:43:55 +0100995 sent_cnt++;
996 }
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100997 if (p->deadline != 0 && p->deadline <= cur_time) {
998 /* Timed out waiting for reply */
Adam Tkacb1585062009-11-22 03:43:55 +0100999 timeout = error_interval();
Denys Vlasenko386960a2009-12-02 01:51:24 +01001000 bb_error_msg("timed out waiting for %s, "
1001 "next query %us", p->dotted, timeout);
Adam Tkacb1585062009-11-22 03:43:55 +01001002 if (p->trustlevel >= TRUSTLEVEL_BADPEER) {
1003 p->trustlevel /= 2;
1004 if (p->trustlevel < TRUSTLEVEL_BADPEER)
Denys Vlasenko386960a2009-12-02 01:51:24 +01001005 bb_error_msg("peer %s now invalid", p->dotted);
Adam Tkacb1585062009-11-22 03:43:55 +01001006 }
Adam Tkacb1585062009-11-22 03:43:55 +01001007 set_next(p, timeout);
1008 }
1009
Denys Vlasenko363e89b2009-11-24 14:04:15 +01001010 if (p->next != 0 && p->next < nextaction)
1011 nextaction = p->next;
1012 if (p->deadline != 0 && p->deadline < nextaction)
1013 nextaction = p->deadline;
1014
Adam Tkacb1585062009-11-22 03:43:55 +01001015 if (p->state == STATE_QUERY_SENT) {
Denys Vlasenko363e89b2009-11-24 14:04:15 +01001016 /* Wait for reply from this peer */
Denys Vlasenko386960a2009-12-02 01:51:24 +01001017 pfd[i].fd = p->fd;
Adam Tkacb1585062009-11-22 03:43:55 +01001018 pfd[i].events = POLLIN;
Denys Vlasenko363e89b2009-11-24 14:04:15 +01001019 idx2peer[i] = p;
Adam Tkacb1585062009-11-22 03:43:55 +01001020 i++;
1021 }
1022 }
1023
Denys Vlasenko8d580c72009-11-23 16:27:16 +01001024 if ((trial_cnt > 0 && sent_cnt == 0) || g.peer_cnt == 0)
Denys Vlasenkofae9f492009-12-01 02:32:01 +01001025 step_time_once(0); /* no good peers, don't wait */
Adam Tkacb1585062009-11-22 03:43:55 +01001026
Denys Vlasenko363e89b2009-11-24 14:04:15 +01001027 timeout = nextaction - cur_time;
Denys Vlasenko386960a2009-12-02 01:51:24 +01001028 if (timeout < 1)
1029 timeout = 1;
Adam Tkacb1585062009-11-22 03:43:55 +01001030
Denys Vlasenko363e89b2009-11-24 14:04:15 +01001031 /* Here we may block */
Denys Vlasenko386960a2009-12-02 01:51:24 +01001032 if (g.verbose >= 2)
1033 bb_error_msg("poll %u sec, waiting on %u sockets", timeout, i);
Adam Tkacb1585062009-11-22 03:43:55 +01001034 nfds = poll(pfd, i, timeout * 1000);
Denys Vlasenko363e89b2009-11-24 14:04:15 +01001035 if (nfds <= 0)
1036 continue;
Adam Tkacb1585062009-11-22 03:43:55 +01001037
Denys Vlasenko363e89b2009-11-24 14:04:15 +01001038 /* Process any received packets */
Adam Tkacb1585062009-11-22 03:43:55 +01001039 j = 0;
1040#if ENABLE_FEATURE_NTPD_SERVER
Denys Vlasenko363e89b2009-11-24 14:04:15 +01001041 if (g.listen_fd != -1) {
1042 if (pfd[0].revents /* & (POLLIN|POLLERR)*/) {
Adam Tkacb1585062009-11-22 03:43:55 +01001043 nfds--;
Denys Vlasenko363e89b2009-11-24 14:04:15 +01001044 recv_and_process_client_pkt(/*g.listen_fd*/);
Adam Tkacb1585062009-11-22 03:43:55 +01001045 }
Denys Vlasenko363e89b2009-11-24 14:04:15 +01001046 j = 1;
Adam Tkacb1585062009-11-22 03:43:55 +01001047 }
1048#endif
Denys Vlasenko363e89b2009-11-24 14:04:15 +01001049 for (; nfds != 0 && j < i; j++) {
1050 if (pfd[j].revents /* & (POLLIN|POLLERR)*/) {
Adam Tkacb1585062009-11-22 03:43:55 +01001051 nfds--;
Denys Vlasenko363e89b2009-11-24 14:04:15 +01001052 recv_and_process_peer_pkt(idx2peer[j]);
Adam Tkacb1585062009-11-22 03:43:55 +01001053 }
1054 }
1055 } /* while (!bb_got_signal) */
1056
1057 kill_myself_with_sig(bb_got_signal);
1058}