blob: f10a81cee289dac00ea845e340d2e2a554de9cb8 [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 Vlasenkoca6c7e42009-11-24 07:07:42 +010070 uint8_t status; /* status of local clock and leap info */
71 uint8_t stratum; /* stratum level */
72 uint8_t ppoll; /* poll value */
73 int8_t precision;
Adam Tkacb1585062009-11-22 03:43:55 +010074 s_fixedpt_t rootdelay;
75 s_fixedpt_t dispersion;
Denys Vlasenkoca6c7e42009-11-24 07:07:42 +010076 uint32_t refid;
Adam Tkacb1585062009-11-22 03:43:55 +010077 l_fixedpt_t reftime;
78 l_fixedpt_t orgtime;
79 l_fixedpt_t rectime;
80 l_fixedpt_t xmttime;
Denys Vlasenkoca6c7e42009-11-24 07:07:42 +010081 uint32_t keyid;
82 uint8_t digest[NTP_DIGESTSIZE];
Adam Tkacb1585062009-11-22 03:43:55 +010083} ntp_msg_t;
84
85typedef struct {
Denys Vlasenkoca6c7e42009-11-24 07:07:42 +010086 int fd;
87 ntp_msg_t msg;
88 double xmttime;
Adam Tkacb1585062009-11-22 03:43:55 +010089} ntp_query_t;
90
91enum {
92 NTP_VERSION = 4,
93 NTP_MAXSTRATUM = 15,
94 /* Leap Second Codes (high order two bits) */
95 LI_NOWARNING = (0 << 6), /* no warning */
96 LI_PLUSSEC = (1 << 6), /* add a second (61 seconds) */
97 LI_MINUSSEC = (2 << 6), /* minus a second (59 seconds) */
98 LI_ALARM = (3 << 6), /* alarm condition */
99
100 /* Status Masks */
101 MODE_MASK = (7 << 0),
102 VERSION_MASK = (7 << 3),
Denys Vlasenkoca6c7e42009-11-24 07:07:42 +0100103 VERSION_SHIFT = 3,
Adam Tkacb1585062009-11-22 03:43:55 +0100104 LI_MASK = (3 << 6),
105
106 /* Mode values */
107 MODE_RES0 = 0, /* reserved */
108 MODE_SYM_ACT = 1, /* symmetric active */
109 MODE_SYM_PAS = 2, /* symmetric passive */
110 MODE_CLIENT = 3, /* client */
111 MODE_SERVER = 4, /* server */
112 MODE_BROADCAST = 5, /* broadcast */
113 MODE_RES1 = 6, /* reserved for NTP control message */
Denys Vlasenkoca6c7e42009-11-24 07:07:42 +0100114 MODE_RES2 = 7, /* reserved for private use */
Adam Tkacb1585062009-11-22 03:43:55 +0100115};
116
Denys Vlasenkob1278a32009-11-24 16:03:47 +0100117#define OFFSET_1900_1970 2208988800UL /* 1970 - 1900 in seconds */
Adam Tkacb1585062009-11-22 03:43:55 +0100118
119enum client_state {
120 STATE_NONE,
121 STATE_QUERY_SENT,
Denys Vlasenkoca6c7e42009-11-24 07:07:42 +0100122 STATE_REPLY_RECEIVED,
Adam Tkacb1585062009-11-22 03:43:55 +0100123};
124
125typedef struct {
126 double rootdelay;
127 double rootdispersion;
128 double reftime;
129 uint32_t refid;
130 uint32_t refid4;
131 uint8_t synced;
132 uint8_t leap;
133 int8_t precision;
134 uint8_t poll;
135 uint8_t stratum;
136} ntp_status_t;
137
138typedef struct {
Denys Vlasenkoca6c7e42009-11-24 07:07:42 +0100139 ntp_status_t status;
140 double offset;
141 double delay;
142 double error;
143 time_t rcvd;
144 uint8_t good;
Adam Tkacb1585062009-11-22 03:43:55 +0100145} ntp_offset_t;
146
147typedef struct {
Denys Vlasenkoca6c7e42009-11-24 07:07:42 +0100148//TODO:
149// (1) store dotted addr str, to avoid constant translations
150// (2) periodically re-resolve DNS names
Adam Tkacb1585062009-11-22 03:43:55 +0100151 len_and_sockaddr *lsa;
Denys Vlasenkoca6c7e42009-11-24 07:07:42 +0100152 ntp_query_t query;
153 ntp_offset_t reply[OFFSET_ARRAY_SIZE];
154 ntp_offset_t update;
155 enum client_state state;
156 time_t next;
157 time_t deadline;
158 uint8_t shift;
159 uint8_t trustlevel;
Adam Tkacb1585062009-11-22 03:43:55 +0100160} ntp_peer_t;
161
Denys Vlasenko8d580c72009-11-23 16:27:16 +0100162enum {
163 OPT_n = (1 << 0),
164 OPT_g = (1 << 1),
165 OPT_q = (1 << 2),
Denys Vlasenkob2e5fc32009-11-25 14:52:47 +0100166 OPT_N = (1 << 3),
Denys Vlasenko8d580c72009-11-23 16:27:16 +0100167 /* Insert new options above this line. */
168 /* Non-compat options: */
Denys Vlasenkob2e5fc32009-11-25 14:52:47 +0100169 OPT_p = (1 << 4),
170 OPT_l = (1 << 5) * ENABLE_FEATURE_NTPD_SERVER,
Denys Vlasenko8d580c72009-11-23 16:27:16 +0100171};
172
Adam Tkacb1585062009-11-22 03:43:55 +0100173
174struct globals {
175 unsigned verbose;
176#if ENABLE_FEATURE_NTPD_SERVER
177 int listen_fd;
178#endif
Denys Vlasenkob1278a32009-11-24 16:03:47 +0100179 unsigned peer_cnt;
Adam Tkacb1585062009-11-22 03:43:55 +0100180 llist_t *ntp_peers;
181 ntp_status_t status;
182 uint32_t scale;
Denys Vlasenkofae9f492009-12-01 02:32:01 +0100183 uint8_t time_is_set;
184 uint8_t first_adj_done;
Adam Tkacb1585062009-11-22 03:43:55 +0100185};
186#define G (*ptr_to_globals)
187
188
189static const int const_IPTOS_LOWDELAY = IPTOS_LOWDELAY;
190
191
192static void
193set_next(ntp_peer_t *p, time_t t)
194{
195 p->next = time(NULL) + t;
196 p->deadline = 0;
197}
198
199static void
200add_peers(const char *s)
201{
202 ntp_peer_t *p;
203
204 p = xzalloc(sizeof(*p));
205//TODO: big ntpd uses all IPs, not just 1st, do we need to mimic that?
206 p->lsa = xhost2sockaddr(s, 123);
207 p->query.fd = -1;
208 p->query.msg.status = MODE_CLIENT | (NTP_VERSION << 3);
209 if (STATE_NONE != 0)
210 p->state = STATE_NONE;
211 p->trustlevel = TRUSTLEVEL_PATHETIC;
212 p->query.fd = -1;
213 set_next(p, 0);
214
215 llist_add_to(&G.ntp_peers, p);
216 G.peer_cnt++;
217}
218
219static double
Denys Vlasenkob1278a32009-11-24 16:03:47 +0100220gettime1900fp(void)
Adam Tkacb1585062009-11-22 03:43:55 +0100221{
Denys Vlasenkoca6c7e42009-11-24 07:07:42 +0100222 struct timeval tv;
Adam Tkacb1585062009-11-22 03:43:55 +0100223 gettimeofday(&tv, NULL); /* never fails */
Denys Vlasenkob1278a32009-11-24 16:03:47 +0100224 return (tv.tv_sec + 1.0e-6 * tv.tv_usec + OFFSET_1900_1970);
Adam Tkacb1585062009-11-22 03:43:55 +0100225}
226
Adam Tkacb1585062009-11-22 03:43:55 +0100227static void
228d_to_tv(double d, struct timeval *tv)
229{
230 tv->tv_sec = (long)d;
231 tv->tv_usec = (d - tv->tv_sec) * 1000000;
232}
233
234static double
235lfp_to_d(l_fixedpt_t lfp)
236{
Denys Vlasenkoca6c7e42009-11-24 07:07:42 +0100237 double ret;
Adam Tkacb1585062009-11-22 03:43:55 +0100238 lfp.int_partl = ntohl(lfp.int_partl);
239 lfp.fractionl = ntohl(lfp.fractionl);
Denys Vlasenkoca6c7e42009-11-24 07:07:42 +0100240 ret = (double)lfp.int_partl + ((double)lfp.fractionl / UINT_MAX);
241 return ret;
242}
243
244static double
245sfp_to_d(s_fixedpt_t sfp)
246{
247 double ret;
248 sfp.int_parts = ntohs(sfp.int_parts);
249 sfp.fractions = ntohs(sfp.fractions);
250 ret = (double)sfp.int_parts + ((double)sfp.fractions / USHRT_MAX);
Adam Tkacb1585062009-11-22 03:43:55 +0100251 return ret;
252}
253
254#if ENABLE_FEATURE_NTPD_SERVER
255static l_fixedpt_t
256d_to_lfp(double d)
257{
Denys Vlasenkoca6c7e42009-11-24 07:07:42 +0100258 l_fixedpt_t lfp;
259 lfp.int_partl = (uint32_t)d;
260 lfp.fractionl = (uint32_t)((d - lfp.int_partl) * UINT_MAX);
261 lfp.int_partl = htonl(lfp.int_partl);
262 lfp.fractionl = htonl(lfp.fractionl);
Adam Tkacb1585062009-11-22 03:43:55 +0100263 return lfp;
264}
Adam Tkacb1585062009-11-22 03:43:55 +0100265
Adam Tkacb1585062009-11-22 03:43:55 +0100266static s_fixedpt_t
267d_to_sfp(double d)
268{
Denys Vlasenkoca6c7e42009-11-24 07:07:42 +0100269 s_fixedpt_t sfp;
270 sfp.int_parts = (uint16_t)d;
271 sfp.fractions = (uint16_t)((d - sfp.int_parts) * USHRT_MAX);
272 sfp.int_parts = htons(sfp.int_parts);
273 sfp.fractions = htons(sfp.fractions);
Adam Tkacb1585062009-11-22 03:43:55 +0100274 return sfp;
275}
276#endif
277
278static void
279set_deadline(ntp_peer_t *p, time_t t)
280{
281 p->deadline = time(NULL) + t;
282 p->next = 0;
283}
284
285static time_t
286error_interval(void)
287{
288 time_t interval, r;
Adam Tkacb1585062009-11-22 03:43:55 +0100289 interval = INTERVAL_QUERY_PATHETIC * QSCALE_OFF_MAX / QSCALE_OFF_MIN;
Denys Vlasenkoca6c7e42009-11-24 07:07:42 +0100290 r = (unsigned)random() % (unsigned long)(interval / 10);
Adam Tkacb1585062009-11-22 03:43:55 +0100291 return (interval + r);
292}
293
294static int
295sendmsg_wrap(int fd,
296 const struct sockaddr *from, const struct sockaddr *to, socklen_t addrlen,
297 ntp_msg_t *msg, ssize_t len)
298{
299 ssize_t ret;
300
301 errno = 0;
302 if (!from) {
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100303 ret = sendto(fd, msg, len, MSG_DONTWAIT, to, addrlen);
Adam Tkacb1585062009-11-22 03:43:55 +0100304 } else {
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100305 ret = send_to_from(fd, msg, len, MSG_DONTWAIT, to, from, addrlen);
Adam Tkacb1585062009-11-22 03:43:55 +0100306 }
307 if (ret != len) {
308 bb_perror_msg("send failed");
309 return -1;
310 }
311 return 0;
312}
313
314static int
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100315send_query_to_peer(ntp_peer_t *p)
Adam Tkacb1585062009-11-22 03:43:55 +0100316{
Denys Vlasenkob1278a32009-11-24 16:03:47 +0100317 // Why do we need to bind()?
318 // See what happens when we don't bind:
319 //
320 // socket(PF_INET, SOCK_DGRAM, IPPROTO_IP) = 3
321 // setsockopt(3, SOL_IP, IP_TOS, [16], 4) = 0
322 // gettimeofday({1259071266, 327885}, NULL) = 0
323 // sendto(3, "xxx", 48, MSG_DONTWAIT, {sa_family=AF_INET, sin_port=htons(123), sin_addr=inet_addr("10.34.32.125")}, 16) = 48
324 // ^^^ we sent it from some source port picked by kernel.
325 // time(NULL) = 1259071266
326 // write(2, "ntpd: entering poll 15 secs\n", 28) = 28
327 // poll([{fd=3, events=POLLIN}], 1, 15000) = 1 ([{fd=3, revents=POLLIN}])
328 // recv(3, "yyy", 68, MSG_DONTWAIT) = 48
329 // ^^^ this recv will receive packets to any local port!
330 //
331 // Uncomment this and use strace to see it in action:
332#define PROBE_LOCAL_ADDR // { len_and_sockaddr lsa; lsa.len = LSA_SIZEOF_SA; getsockname(p->query.fd, &lsa.u.sa, &lsa.len); }
333
Adam Tkacb1585062009-11-22 03:43:55 +0100334 if (p->query.fd == -1) {
Denys Vlasenkob1278a32009-11-24 16:03:47 +0100335 int fd, family;
336 len_and_sockaddr *local_lsa;
337
338 family = p->lsa->u.sa.sa_family;
339 //was: p->query.fd = xsocket(family, SOCK_DGRAM, 0);
340 p->query.fd = fd = xsocket_type(&local_lsa, family, SOCK_DGRAM);
341 /* local_lsa has "null" address and port 0 now.
342 * bind() ensures we have a *particular port* selected by kernel
343 * and remembered in p->query.fd, thus later recv(p->query.fd)
344 * receives only packets sent to this port.
345 */
346 PROBE_LOCAL_ADDR
347 xbind(fd, &local_lsa->u.sa, local_lsa->len);
348 PROBE_LOCAL_ADDR
Adam Tkacb1585062009-11-22 03:43:55 +0100349#if ENABLE_FEATURE_IPV6
Denys Vlasenkob1278a32009-11-24 16:03:47 +0100350 if (family == AF_INET)
Adam Tkacb1585062009-11-22 03:43:55 +0100351#endif
Denys Vlasenkob1278a32009-11-24 16:03:47 +0100352 setsockopt(fd, IPPROTO_IP, IP_TOS, &const_IPTOS_LOWDELAY, sizeof(const_IPTOS_LOWDELAY));
353 free(local_lsa);
Adam Tkacb1585062009-11-22 03:43:55 +0100354 }
355
356 /*
357 * Send out a random 64-bit number as our transmit time. The NTP
358 * server will copy said number into the originate field on the
359 * response that it sends us. This is totally legal per the SNTP spec.
360 *
361 * The impact of this is two fold: we no longer send out the current
362 * system time for the world to see (which may aid an attacker), and
363 * it gives us a (not very secure) way of knowing that we're not
364 * getting spoofed by an attacker that can't capture our traffic
365 * but can spoof packets from the NTP server we're communicating with.
366 *
367 * Save the real transmit timestamp locally.
368 */
369
370 p->query.msg.xmttime.int_partl = random();
371 p->query.msg.xmttime.fractionl = random();
Denys Vlasenkob1278a32009-11-24 16:03:47 +0100372 p->query.xmttime = gettime1900fp();
Adam Tkacb1585062009-11-22 03:43:55 +0100373
374 if (sendmsg_wrap(p->query.fd, /*from:*/ NULL, /*to:*/ &p->lsa->u.sa, /*addrlen:*/ p->lsa->len,
375 &p->query.msg, NTP_MSGSIZE_NOAUTH) == -1) {
376 set_next(p, INTERVAL_QUERY_PATHETIC);
377 return -1;
378 }
379
380 p->state = STATE_QUERY_SENT;
381 set_deadline(p, QUERYTIME_MAX);
382
383 return 0;
384}
385
386static int
387offset_compare(const void *aa, const void *bb)
388{
Denys Vlasenkoca6c7e42009-11-24 07:07:42 +0100389 const ntp_peer_t *const *a = aa;
390 const ntp_peer_t *const *b = bb;
Adam Tkacb1585062009-11-22 03:43:55 +0100391 if ((*a)->update.offset < (*b)->update.offset)
392 return -1;
393 return ((*a)->update.offset > (*b)->update.offset);
394}
395
396static uint32_t
397updated_scale(double offset)
398{
399 if (offset < 0)
400 offset = -offset;
Adam Tkacb1585062009-11-22 03:43:55 +0100401 if (offset > QSCALE_OFF_MAX)
402 return 1;
403 if (offset < QSCALE_OFF_MIN)
404 return QSCALE_OFF_MAX / QSCALE_OFF_MIN;
405 return QSCALE_OFF_MAX / offset;
406}
407
408static void
409adjtime_wrap(void)
410{
411 ntp_peer_t *p;
412 unsigned offset_cnt;
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100413 unsigned middle;
Adam Tkacb1585062009-11-22 03:43:55 +0100414 int i = 0;
415 ntp_peer_t **peers;
416 double offset_median;
417 llist_t *item;
418 len_and_sockaddr *lsa;
419 struct timeval tv, olddelta;
420
421 offset_cnt = 0;
422 for (item = G.ntp_peers; item != NULL; item = item->link) {
423 p = (ntp_peer_t *) item->data;
424 if (p->trustlevel < TRUSTLEVEL_BADPEER)
425 continue;
426 if (!p->update.good)
427 return;
428 offset_cnt++;
429 }
430
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100431 if (offset_cnt == 0)
432 goto clear_good;
433
434 peers = xzalloc(sizeof(peers[0]) * offset_cnt);
Adam Tkacb1585062009-11-22 03:43:55 +0100435 for (item = G.ntp_peers; item != NULL; item = item->link) {
436 p = (ntp_peer_t *) item->data;
437 if (p->trustlevel < TRUSTLEVEL_BADPEER)
438 continue;
439 peers[i++] = p;
440 }
441
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100442 qsort(peers, offset_cnt, sizeof(peers[0]), offset_compare);
Adam Tkacb1585062009-11-22 03:43:55 +0100443
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100444 middle = offset_cnt / 2;
Denys Vlasenko650a7012009-11-26 07:11:12 +0100445 if (middle != 0 && (offset_cnt & 1) == 0) {
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100446 offset_median = (peers[middle-1]->update.offset + peers[middle]->update.offset) / 2;
447 G.status.rootdelay = (peers[middle-1]->update.delay + peers[middle]->update.delay) / 2;
448 G.status.stratum = MAX(peers[middle-1]->update.status.stratum, peers[middle]->update.status.stratum);
449 } else {
450 offset_median = peers[middle]->update.offset;
451 G.status.rootdelay = peers[middle]->update.delay;
452 G.status.stratum = peers[middle]->update.status.stratum;
Adam Tkacb1585062009-11-22 03:43:55 +0100453 }
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100454 G.status.leap = peers[middle]->update.status.leap;
455
456 bb_info_msg("adjusting local clock by %fs", offset_median);
Denys Vlasenkofae9f492009-12-01 02:32:01 +0100457 errno = 0;
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100458 d_to_tv(offset_median, &tv);
Denys Vlasenkofae9f492009-12-01 02:32:01 +0100459 if (adjtime(&tv, &olddelta) == -1) {
460 bb_perror_msg("adjtime failed"); //TODO: maybe _and_die?
461 } else
462 if (G.first_adj_done
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100463 && olddelta.tv_sec == 0
464 && olddelta.tv_usec == 0
465 && !G.status.synced
466 ) {
467 bb_info_msg("clock synced");
468 G.status.synced = 1;
Denys Vlasenkofae9f492009-12-01 02:32:01 +0100469 } else
470 if (G.status.synced) {
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100471 bb_info_msg("clock unsynced");
472 G.status.synced = 0;
473 }
474
Denys Vlasenkofae9f492009-12-01 02:32:01 +0100475 G.first_adj_done = 1;
Denys Vlasenkob1278a32009-11-24 16:03:47 +0100476 G.status.reftime = gettime1900fp();
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100477 G.status.stratum++; /* one more than selected peer */
478 G.scale = updated_scale(offset_median);
479
480 G.status.refid4 = peers[middle]->update.status.refid4;
481
482 lsa = peers[middle]->lsa;
483 G.status.refid =
484#if ENABLE_FEATURE_IPV6
485 lsa->u.sa.sa_family != AF_INET ?
486 G.status.refid4 :
487#endif
488 lsa->u.sin.sin_addr.s_addr;
Adam Tkacb1585062009-11-22 03:43:55 +0100489
490 free(peers);
491
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100492 clear_good:
Adam Tkacb1585062009-11-22 03:43:55 +0100493 for (item = G.ntp_peers; item != NULL; item = item->link) {
494 p = (ntp_peer_t *) item->data;
495 p->update.good = 0;
496 }
497}
498
499static void
Denys Vlasenkofae9f492009-12-01 02:32:01 +0100500step_time_once(double offset)
Adam Tkacb1585062009-11-22 03:43:55 +0100501{
502 ntp_peer_t *p;
503 llist_t *item;
504 struct timeval tv, curtime;
505 char buf[80];
506 time_t tval;
507
Denys Vlasenkofae9f492009-12-01 02:32:01 +0100508 if (G.time_is_set)
Denys Vlasenko8d580c72009-11-23 16:27:16 +0100509 goto bail;
Denys Vlasenkofae9f492009-12-01 02:32:01 +0100510 G.time_is_set = 1;
Adam Tkacb1585062009-11-22 03:43:55 +0100511
512 /* if the offset is small, don't call settimeofday */
513 if (offset < SETTIME_MIN_OFFSET && offset > -SETTIME_MIN_OFFSET)
Denys Vlasenko8d580c72009-11-23 16:27:16 +0100514 goto bail;
Adam Tkacb1585062009-11-22 03:43:55 +0100515
516 gettimeofday(&curtime, NULL); /* never fails */
517
Denys Vlasenkofae9f492009-12-01 02:32:01 +0100518//isn't it simpler to: offset += curtime.tv_sec; offset += 1.0e-6 * curtime.tv_usec?
Adam Tkacb1585062009-11-22 03:43:55 +0100519 d_to_tv(offset, &tv);
520 curtime.tv_usec += tv.tv_usec + 1000000;
521 curtime.tv_sec += tv.tv_sec - 1 + (curtime.tv_usec / 1000000);
522 curtime.tv_usec %= 1000000;
523
524 if (settimeofday(&curtime, NULL) == -1) {
525 bb_error_msg("settimeofday");
Denys Vlasenko8d580c72009-11-23 16:27:16 +0100526 goto bail;
Adam Tkacb1585062009-11-22 03:43:55 +0100527 }
528
Adam Tkacb1585062009-11-22 03:43:55 +0100529 tval = curtime.tv_sec;
530 strftime(buf, sizeof(buf), "%a %b %e %H:%M:%S %Z %Y", localtime(&tval));
531
532 /* Do we want to print message below to system log when daemonized? */
533 bb_info_msg("set local clock to %s (offset %fs)", buf, offset);
534
535 for (item = G.ntp_peers; item != NULL; item = item->link) {
536 p = (ntp_peer_t *) item->data;
537 if (p->next)
538 p->next -= offset;
539 if (p->deadline)
540 p->deadline -= offset;
541 }
Denys Vlasenko8d580c72009-11-23 16:27:16 +0100542
543 bail:
544 if (option_mask32 & OPT_q)
545 exit(0);
Adam Tkacb1585062009-11-22 03:43:55 +0100546}
547
548static void
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100549update_peer_data(ntp_peer_t *p)
Adam Tkacb1585062009-11-22 03:43:55 +0100550{
551 int i, best = 0, good = 0;
552
553 /*
554 * clock filter
555 * find the offset which arrived with the lowest delay
556 * use that as the peer update
557 * invalidate it and all older ones
558 */
559
560 for (i = 0; good == 0 && i < OFFSET_ARRAY_SIZE; i++) {
561 if (p->reply[i].good) {
562 good++;
563 best = i;
564 }
565 }
566
567 for (; i < OFFSET_ARRAY_SIZE; i++) {
568 if (p->reply[i].good) {
569 good++;
570 if (p->reply[i].delay < p->reply[best].delay)
571 best = i;
572 }
573 }
574
575 if (good < 8)
576 return;
577
578 memcpy(&p->update, &p->reply[best], sizeof(p->update));
579 adjtime_wrap();
580
581 for (i = 0; i < OFFSET_ARRAY_SIZE; i++)
582 if (p->reply[i].rcvd <= p->reply[best].rcvd)
583 p->reply[i].good = 0;
584}
585
586static time_t
587scale_interval(time_t requested)
588{
589 time_t interval, r;
Adam Tkacb1585062009-11-22 03:43:55 +0100590 interval = requested * G.scale;
Denys Vlasenkoca6c7e42009-11-24 07:07:42 +0100591 r = (unsigned)random() % (unsigned long)(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{
598 char *addr;
599 ssize_t size;
600 ntp_msg_t msg;
601 double T1, T2, T3, T4;
602 time_t interval;
603 ntp_offset_t *offset;
604
605 addr = xmalloc_sockaddr2dotted_noport(&p->lsa->u.sa);
606
Denys Vlasenkob1278a32009-11-24 16:03:47 +0100607 /* We can recvfrom here and check from.IP, but some multihomed
608 * ntp servers reply from their *other IP*.
609 * TODO: maybe we should check at least what we can: from.port == 123?
610 */
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100611 size = recv(p->query.fd, &msg, sizeof(msg), MSG_DONTWAIT);
Adam Tkacb1585062009-11-22 03:43:55 +0100612 if (size == -1) {
Denys Vlasenkoca6c7e42009-11-24 07:07:42 +0100613 bb_perror_msg("recv(%s) error", addr);
Adam Tkacb1585062009-11-22 03:43:55 +0100614 if (errno == EHOSTUNREACH || errno == EHOSTDOWN
615 || errno == ENETUNREACH || errno == ENETDOWN
616 || errno == ECONNREFUSED || errno == EADDRNOTAVAIL
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100617 || errno == EAGAIN
Adam Tkacb1585062009-11-22 03:43:55 +0100618 ) {
619//TODO: always do this?
620 set_next(p, error_interval());
621 goto bail;
622 }
623 xfunc_die();
624 }
625
Denys Vlasenkob1278a32009-11-24 16:03:47 +0100626 T4 = gettime1900fp();
Adam Tkacb1585062009-11-22 03:43:55 +0100627
628 if (size != NTP_MSGSIZE_NOAUTH && size != NTP_MSGSIZE) {
629 bb_error_msg("malformed packet received from %s", addr);
630 goto bail;
631 }
632
633 if (msg.orgtime.int_partl != p->query.msg.xmttime.int_partl
634 || msg.orgtime.fractionl != p->query.msg.xmttime.fractionl
635 ) {
636 goto bail;
637 }
638
639 if ((msg.status & LI_ALARM) == LI_ALARM
640 || msg.stratum == 0
641 || msg.stratum > NTP_MAXSTRATUM
642 ) {
643 interval = error_interval();
644 bb_info_msg("reply from %s: not synced, next query %ds", addr, (int) interval);
645 goto bail;
646 }
647
648 /*
649 * From RFC 2030 (with a correction to the delay math):
650 *
651 * Timestamp Name ID When Generated
652 * ------------------------------------------------------------
653 * Originate Timestamp T1 time request sent by client
654 * Receive Timestamp T2 time request received by server
655 * Transmit Timestamp T3 time reply sent by server
656 * Destination Timestamp T4 time reply received by client
657 *
658 * The roundtrip delay d and local clock offset t are defined as
659 *
660 * d = (T4 - T1) - (T3 - T2) t = ((T2 - T1) + (T3 - T4)) / 2.
661 */
662
663 T1 = p->query.xmttime;
664 T2 = lfp_to_d(msg.rectime);
665 T3 = lfp_to_d(msg.xmttime);
666
667 offset = &p->reply[p->shift];
668
669 offset->offset = ((T2 - T1) + (T3 - T4)) / 2;
670 offset->delay = (T4 - T1) - (T3 - T2);
671 if (offset->delay < 0) {
672 interval = error_interval();
673 set_next(p, interval);
674 bb_info_msg("reply from %s: negative delay %f", addr, p->reply[p->shift].delay);
675 goto bail;
676 }
677 offset->error = (T2 - T1) - (T3 - T4);
Denys Vlasenkob1278a32009-11-24 16:03:47 +0100678// Can we use (T4 - OFFSET_1900_1970) instead of time(NULL)?
Adam Tkacb1585062009-11-22 03:43:55 +0100679 offset->rcvd = time(NULL);
680 offset->good = 1;
681
682 offset->status.leap = (msg.status & LI_MASK);
683 offset->status.precision = msg.precision;
684 offset->status.rootdelay = sfp_to_d(msg.rootdelay);
685 offset->status.rootdispersion = sfp_to_d(msg.dispersion);
686 offset->status.refid = ntohl(msg.refid);
687 offset->status.refid4 = msg.xmttime.fractionl;
688 offset->status.reftime = lfp_to_d(msg.reftime);
689 offset->status.poll = msg.ppoll;
690 offset->status.stratum = msg.stratum;
691
692 if (p->trustlevel < TRUSTLEVEL_PATHETIC)
693 interval = scale_interval(INTERVAL_QUERY_PATHETIC);
694 else if (p->trustlevel < TRUSTLEVEL_AGRESSIVE)
695 interval = scale_interval(INTERVAL_QUERY_AGRESSIVE);
696 else
697 interval = scale_interval(INTERVAL_QUERY_NORMAL);
698
699 set_next(p, interval);
700 p->state = STATE_REPLY_RECEIVED;
701
702 /* every received reply which we do not discard increases trust */
703 if (p->trustlevel < TRUSTLEVEL_MAX) {
Adam Tkacb1585062009-11-22 03:43:55 +0100704 p->trustlevel++;
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100705 if (p->trustlevel == TRUSTLEVEL_BADPEER)
706 bb_info_msg("peer %s now valid", addr);
Adam Tkacb1585062009-11-22 03:43:55 +0100707 }
708
709 bb_info_msg("reply from %s: offset %f delay %f, next query %ds", addr,
710 offset->offset, offset->delay, (int) interval);
711
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100712 update_peer_data(p);
Denys Vlasenkofae9f492009-12-01 02:32:01 +0100713 step_time_once(offset->offset);
Adam Tkacb1585062009-11-22 03:43:55 +0100714
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100715 p->shift++;
716 if (p->shift >= OFFSET_ARRAY_SIZE)
Adam Tkacb1585062009-11-22 03:43:55 +0100717 p->shift = 0;
718
719 bail:
720 free(addr);
721}
722
723#if ENABLE_FEATURE_NTPD_SERVER
724static void
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100725recv_and_process_client_pkt(void /*int fd*/)
Adam Tkacb1585062009-11-22 03:43:55 +0100726{
Denys Vlasenkoca6c7e42009-11-24 07:07:42 +0100727 ssize_t size;
728 uint8_t version;
729 double rectime;
730 len_and_sockaddr *to;
731 struct sockaddr *from;
732 ntp_msg_t msg;
733 uint8_t query_status;
734 uint8_t query_ppoll;
735 l_fixedpt_t query_xmttime;
Adam Tkacb1585062009-11-22 03:43:55 +0100736
737 to = get_sock_lsa(G.listen_fd);
738 from = xzalloc(to->len);
739
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100740 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 +0100741 if (size != NTP_MSGSIZE_NOAUTH && size != NTP_MSGSIZE) {
Denys Vlasenkoca6c7e42009-11-24 07:07:42 +0100742 char *addr;
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100743 if (size < 0) {
744 if (errno == EAGAIN)
745 goto bail;
746 bb_perror_msg_and_die("recv_from_to");
747 }
Denys Vlasenkoca6c7e42009-11-24 07:07:42 +0100748 addr = xmalloc_sockaddr2dotted_noport(from);
Adam Tkacb1585062009-11-22 03:43:55 +0100749 bb_error_msg("malformed packet received from %s", addr);
750 free(addr);
751 goto bail;
752 }
753
Denys Vlasenkoca6c7e42009-11-24 07:07:42 +0100754 query_status = msg.status;
755 query_ppoll = msg.ppoll;
756 query_xmttime = msg.xmttime;
Adam Tkacb1585062009-11-22 03:43:55 +0100757
Denys Vlasenkoca6c7e42009-11-24 07:07:42 +0100758 /* Build a reply packet */
759 memset(&msg, 0, sizeof(msg));
760 msg.status = G.status.synced ? G.status.leap : LI_ALARM;
761 msg.status |= (query_status & VERSION_MASK);
762 msg.status |= ((query_status & MODE_MASK) == MODE_CLIENT) ?
Adam Tkacb1585062009-11-22 03:43:55 +0100763 MODE_SERVER : MODE_SYM_PAS;
Denys Vlasenkoca6c7e42009-11-24 07:07:42 +0100764 msg.stratum = G.status.stratum;
765 msg.ppoll = query_ppoll;
766 msg.precision = G.status.precision;
Denys Vlasenkob1278a32009-11-24 16:03:47 +0100767 rectime = gettime1900fp();
Denys Vlasenkoca6c7e42009-11-24 07:07:42 +0100768 msg.xmttime = msg.rectime = d_to_lfp(rectime);
769 msg.reftime = d_to_lfp(G.status.reftime);
Denys Vlasenkob1278a32009-11-24 16:03:47 +0100770 //msg.xmttime = d_to_lfp(gettime1900fp()); // = msg.rectime
Denys Vlasenkoca6c7e42009-11-24 07:07:42 +0100771 msg.orgtime = query_xmttime;
772 msg.rootdelay = d_to_sfp(G.status.rootdelay);
773 version = (query_status & VERSION_MASK); /* ... >> VERSION_SHIFT - done below instead */
774 msg.refid = (version > (3 << VERSION_SHIFT)) ? G.status.refid4 : G.status.refid;
Adam Tkacb1585062009-11-22 03:43:55 +0100775
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100776 /* We reply from the local address packet was sent to,
Adam Tkacb1585062009-11-22 03:43:55 +0100777 * this makes to/from look swapped here: */
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100778 sendmsg_wrap(G.listen_fd,
Denys Vlasenkoca6c7e42009-11-24 07:07:42 +0100779 /*from:*/ &to->u.sa, /*to:*/ from, /*addrlen:*/ to->len,
780 &msg, size);
Adam Tkacb1585062009-11-22 03:43:55 +0100781
782 bail:
783 free(to);
784 free(from);
785}
786#endif
787
788/* Upstream ntpd's options:
789 *
790 * -4 Force DNS resolution of host names to the IPv4 namespace.
791 * -6 Force DNS resolution of host names to the IPv6 namespace.
792 * -a Require cryptographic authentication for broadcast client,
793 * multicast client and symmetric passive associations.
794 * This is the default.
795 * -A Do not require cryptographic authentication for broadcast client,
796 * multicast client and symmetric passive associations.
797 * This is almost never a good idea.
798 * -b Enable the client to synchronize to broadcast servers.
799 * -c conffile
800 * Specify the name and path of the configuration file,
801 * default /etc/ntp.conf
802 * -d Specify debugging mode. This option may occur more than once,
803 * with each occurrence indicating greater detail of display.
804 * -D level
805 * Specify debugging level directly.
806 * -f driftfile
807 * Specify the name and path of the frequency file.
808 * This is the same operation as the "driftfile FILE"
809 * configuration command.
810 * -g Normally, ntpd exits with a message to the system log
811 * if the offset exceeds the panic threshold, which is 1000 s
812 * by default. This option allows the time to be set to any value
813 * without restriction; however, this can happen only once.
814 * If the threshold is exceeded after that, ntpd will exit
815 * with a message to the system log. This option can be used
816 * with the -q and -x options. See the tinker command for other options.
817 * -i jaildir
818 * Chroot the server to the directory jaildir. This option also implies
819 * that the server attempts to drop root privileges at startup
820 * (otherwise, chroot gives very little additional security).
821 * You may need to also specify a -u option.
822 * -k keyfile
823 * Specify the name and path of the symmetric key file,
824 * default /etc/ntp/keys. This is the same operation
825 * as the "keys FILE" configuration command.
826 * -l logfile
827 * Specify the name and path of the log file. The default
828 * is the system log file. This is the same operation as
829 * the "logfile FILE" configuration command.
830 * -L Do not listen to virtual IPs. The default is to listen.
831 * -n Don't fork.
832 * -N To the extent permitted by the operating system,
833 * run the ntpd at the highest priority.
834 * -p pidfile
835 * Specify the name and path of the file used to record the ntpd
836 * process ID. This is the same operation as the "pidfile FILE"
837 * configuration command.
838 * -P priority
839 * To the extent permitted by the operating system,
840 * run the ntpd at the specified priority.
841 * -q Exit the ntpd just after the first time the clock is set.
842 * This behavior mimics that of the ntpdate program, which is
843 * to be retired. The -g and -x options can be used with this option.
844 * Note: The kernel time discipline is disabled with this option.
845 * -r broadcastdelay
846 * Specify the default propagation delay from the broadcast/multicast
847 * server to this client. This is necessary only if the delay
848 * cannot be computed automatically by the protocol.
849 * -s statsdir
850 * Specify the directory path for files created by the statistics
851 * facility. This is the same operation as the "statsdir DIR"
852 * configuration command.
853 * -t key
854 * Add a key number to the trusted key list. This option can occur
855 * more than once.
856 * -u user[:group]
857 * Specify a user, and optionally a group, to switch to.
858 * -v variable
859 * -V variable
860 * Add a system variable listed by default.
861 * -x Normally, the time is slewed if the offset is less than the step
862 * threshold, which is 128 ms by default, and stepped if above
863 * the threshold. This option sets the threshold to 600 s, which is
864 * well within the accuracy window to set the clock manually.
865 * Note: since the slew rate of typical Unix kernels is limited
866 * to 0.5 ms/s, each second of adjustment requires an amortization
867 * interval of 2000 s. Thus, an adjustment as much as 600 s
868 * will take almost 14 days to complete. This option can be used
869 * with the -g and -q options. See the tinker command for other options.
870 * Note: The kernel time discipline is disabled with this option.
871 */
872
Adam Tkacb1585062009-11-22 03:43:55 +0100873/* By doing init in a separate function we decrease stack usage
874 * in main loop.
875 */
876static NOINLINE void ntp_init(char **argv)
877{
878 unsigned opts;
879 llist_t *peers;
880
Denys Vlasenkoca6c7e42009-11-24 07:07:42 +0100881 srandom(getpid());
882 /* tzset(); - why? it's called automatically when needed, no? */
Adam Tkacb1585062009-11-22 03:43:55 +0100883
884 if (getuid())
Denys Vlasenkob2e5fc32009-11-25 14:52:47 +0100885 bb_error_msg_and_die(bb_msg_you_must_be_root);
Adam Tkacb1585062009-11-22 03:43:55 +0100886
887 peers = NULL;
888 opt_complementary = "dd:p::"; /* d: counter, p: list */
889 opts = getopt32(argv,
Denys Vlasenkob2e5fc32009-11-25 14:52:47 +0100890 "ngqN" /* compat */
Adam Tkacb1585062009-11-22 03:43:55 +0100891 "p:"IF_FEATURE_NTPD_SERVER("l") /* NOT compat */
892 "d" /* compat */
Denys Vlasenkob2e5fc32009-11-25 14:52:47 +0100893 "46aAbLx", /* compat, ignored */
Adam Tkacb1585062009-11-22 03:43:55 +0100894 &peers, &G.verbose);
Denys Vlasenkob2e5fc32009-11-25 14:52:47 +0100895 if (!(opts & (OPT_p|OPT_l)))
896 bb_show_usage();
Denys Vlasenkofae9f492009-12-01 02:32:01 +0100897//WRONG
898// if (opts & OPT_g)
899// G.time_is_set = 1;
Denys Vlasenko160b9ca2009-11-27 02:35:15 +0100900 while (peers)
901 add_peers(llist_pop(&peers));
902 if (!(opts & OPT_n)) {
903 bb_daemonize_or_rexec(DAEMON_DEVNULL_STDIO, argv);
904 logmode = LOGMODE_NONE;
905 }
Adam Tkacb1585062009-11-22 03:43:55 +0100906#if ENABLE_FEATURE_NTPD_SERVER
907 G.listen_fd = -1;
908 if (opts & OPT_l) {
909 G.listen_fd = create_and_bind_dgram_or_die(NULL, 123);
910 socket_want_pktinfo(G.listen_fd);
911 setsockopt(G.listen_fd, IPPROTO_IP, IP_TOS, &const_IPTOS_LOWDELAY, sizeof(const_IPTOS_LOWDELAY));
912 }
913#endif
Denys Vlasenkob2e5fc32009-11-25 14:52:47 +0100914 /* I hesitate to set -20 prio. -15 should be high enough for timekeeping */
915 if (opts & OPT_N)
916 setpriority(PRIO_PROCESS, 0, -15);
Adam Tkacb1585062009-11-22 03:43:55 +0100917
918 /* Set some globals */
919 {
920 int prec = 0;
921 int b;
922#if 0
923 struct timespec tp;
924 /* We can use sys_clock_getres but assuming 10ms tick should be fine */
925 clock_getres(CLOCK_REALTIME, &tp);
926 tp.tv_sec = 0;
927 tp.tv_nsec = 10000000;
928 b = 1000000000 / tp.tv_nsec; /* convert to Hz */
929#else
930 b = 100; /* b = 1000000000/10000000 = 100 */
931#endif
932 while (b > 1)
933 prec--, b >>= 1;
934 G.status.precision = prec;
935 }
936 G.scale = 1;
Adam Tkacb1585062009-11-22 03:43:55 +0100937
938 bb_signals((1 << SIGTERM) | (1 << SIGINT), record_signo);
939 bb_signals((1 << SIGPIPE) | (1 << SIGHUP), SIG_IGN);
940}
941
942int ntpd_main(int argc UNUSED_PARAM, char **argv) MAIN_EXTERNALLY_VISIBLE;
943int ntpd_main(int argc UNUSED_PARAM, char **argv)
944{
945 struct globals g;
Adam Tkacb1585062009-11-22 03:43:55 +0100946 struct pollfd *pfd;
947 ntp_peer_t **idx2peer;
948
949 memset(&g, 0, sizeof(g));
950 SET_PTR_TO_GLOBALS(&g);
951
952 ntp_init(argv);
953
Denys Vlasenko8d580c72009-11-23 16:27:16 +0100954 {
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100955 unsigned cnt = g.peer_cnt;
Denys Vlasenko8d580c72009-11-23 16:27:16 +0100956 /* if ENABLE_FEATURE_NTPD_SERVER, + 1 for listen_fd: */
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100957 idx2peer = xzalloc(sizeof(void *) * (cnt + ENABLE_FEATURE_NTPD_SERVER));
958 pfd = xzalloc(sizeof(pfd[0]) * (cnt + ENABLE_FEATURE_NTPD_SERVER));
Denys Vlasenko8d580c72009-11-23 16:27:16 +0100959 }
Adam Tkacb1585062009-11-22 03:43:55 +0100960
961 while (!bb_got_signal) {
962 llist_t *item;
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100963 unsigned i, j;
Adam Tkacb1585062009-11-22 03:43:55 +0100964 unsigned sent_cnt, trial_cnt;
965 int nfds, timeout;
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100966 time_t cur_time, nextaction;
Adam Tkacb1585062009-11-22 03:43:55 +0100967
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100968 /* Nothing between here and poll() blocks for any significant time */
969
970 cur_time = time(NULL);
971 nextaction = cur_time + 3600;
Adam Tkacb1585062009-11-22 03:43:55 +0100972
973 i = 0;
974#if ENABLE_FEATURE_NTPD_SERVER
975 if (g.listen_fd != -1) {
976 pfd[0].fd = g.listen_fd;
977 pfd[0].events = POLLIN;
978 i++;
979 }
980#endif
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100981 /* Pass over peer list, send requests, time out on receives */
Adam Tkacb1585062009-11-22 03:43:55 +0100982 sent_cnt = trial_cnt = 0;
983 for (item = g.ntp_peers; item != NULL; item = item->link) {
984 ntp_peer_t *p = (ntp_peer_t *) item->data;
985
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100986 if (p->next != 0 && p->next <= cur_time) {
987 /* Time to send new req */
Adam Tkacb1585062009-11-22 03:43:55 +0100988 trial_cnt++;
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100989 if (send_query_to_peer(p) == 0)
Adam Tkacb1585062009-11-22 03:43:55 +0100990 sent_cnt++;
991 }
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100992 if (p->deadline != 0 && p->deadline <= cur_time) {
993 /* Timed out waiting for reply */
Adam Tkacb1585062009-11-22 03:43:55 +0100994 char *addr = xmalloc_sockaddr2dotted_noport(&p->lsa->u.sa);
995
996 timeout = error_interval();
997 bb_info_msg("no reply from %s received in time, "
998 "next query %ds", addr, timeout);
999 if (p->trustlevel >= TRUSTLEVEL_BADPEER) {
1000 p->trustlevel /= 2;
1001 if (p->trustlevel < TRUSTLEVEL_BADPEER)
1002 bb_info_msg("peer %s now invalid", addr);
1003 }
1004 free(addr);
1005
1006 set_next(p, timeout);
1007 }
1008
Denys Vlasenko363e89b2009-11-24 14:04:15 +01001009 if (p->next != 0 && p->next < nextaction)
1010 nextaction = p->next;
1011 if (p->deadline != 0 && p->deadline < nextaction)
1012 nextaction = p->deadline;
1013
Adam Tkacb1585062009-11-22 03:43:55 +01001014 if (p->state == STATE_QUERY_SENT) {
Denys Vlasenko363e89b2009-11-24 14:04:15 +01001015 /* Wait for reply from this peer */
Adam Tkacb1585062009-11-22 03:43:55 +01001016 pfd[i].fd = p->query.fd;
1017 pfd[i].events = POLLIN;
Denys Vlasenko363e89b2009-11-24 14:04:15 +01001018 idx2peer[i] = p;
Adam Tkacb1585062009-11-22 03:43:55 +01001019 i++;
1020 }
1021 }
1022
Denys Vlasenko8d580c72009-11-23 16:27:16 +01001023 if ((trial_cnt > 0 && sent_cnt == 0) || g.peer_cnt == 0)
Denys Vlasenkofae9f492009-12-01 02:32:01 +01001024 step_time_once(0); /* no good peers, don't wait */
Adam Tkacb1585062009-11-22 03:43:55 +01001025
Denys Vlasenko363e89b2009-11-24 14:04:15 +01001026 timeout = nextaction - cur_time;
Adam Tkacb1585062009-11-22 03:43:55 +01001027 if (timeout < 0)
1028 timeout = 0;
1029
Denys Vlasenko363e89b2009-11-24 14:04:15 +01001030 /* Here we may block */
Adam Tkacb1585062009-11-22 03:43:55 +01001031 if (g.verbose)
1032 bb_error_msg("entering poll %u secs", timeout);
1033 nfds = poll(pfd, i, timeout * 1000);
Denys Vlasenko363e89b2009-11-24 14:04:15 +01001034 if (nfds <= 0)
1035 continue;
Adam Tkacb1585062009-11-22 03:43:55 +01001036
Denys Vlasenko363e89b2009-11-24 14:04:15 +01001037 /* Process any received packets */
Adam Tkacb1585062009-11-22 03:43:55 +01001038 j = 0;
1039#if ENABLE_FEATURE_NTPD_SERVER
Denys Vlasenko363e89b2009-11-24 14:04:15 +01001040 if (g.listen_fd != -1) {
1041 if (pfd[0].revents /* & (POLLIN|POLLERR)*/) {
Adam Tkacb1585062009-11-22 03:43:55 +01001042 nfds--;
Denys Vlasenko363e89b2009-11-24 14:04:15 +01001043 recv_and_process_client_pkt(/*g.listen_fd*/);
Adam Tkacb1585062009-11-22 03:43:55 +01001044 }
Denys Vlasenko363e89b2009-11-24 14:04:15 +01001045 j = 1;
Adam Tkacb1585062009-11-22 03:43:55 +01001046 }
1047#endif
Denys Vlasenko363e89b2009-11-24 14:04:15 +01001048 for (; nfds != 0 && j < i; j++) {
1049 if (pfd[j].revents /* & (POLLIN|POLLERR)*/) {
Adam Tkacb1585062009-11-22 03:43:55 +01001050 nfds--;
Denys Vlasenko363e89b2009-11-24 14:04:15 +01001051 recv_and_process_peer_pkt(idx2peer[j]);
Adam Tkacb1585062009-11-22 03:43:55 +01001052 }
1053 }
1054 } /* while (!bb_got_signal) */
1055
1056 kill_myself_with_sig(bb_got_signal);
1057}