blob: 12e498d48d1b6f3ae2882cf5dbc21492ebfa6d7c [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 */
10
11#ifndef IP_PKTINFO
12# error "Sorry, your kernel has to support IP_PKTINFO"
13#endif
14
Denys Vlasenkob1278a32009-11-24 16:03:47 +010015#define INTERVAL_QUERY_NORMAL 30 /* sync to peers every n secs */
16#define INTERVAL_QUERY_PATHETIC 60
17#define INTERVAL_QUERY_AGRESSIVE 5
Adam Tkacb1585062009-11-22 03:43:55 +010018
Denys Vlasenkob1278a32009-11-24 16:03:47 +010019#define TRUSTLEVEL_BADPEER 6 /* bad if *less than* TRUSTLEVEL_BADPEER */
20#define TRUSTLEVEL_PATHETIC 2
21#define TRUSTLEVEL_AGRESSIVE 8
22#define TRUSTLEVEL_MAX 10
Adam Tkacb1585062009-11-22 03:43:55 +010023
Denys Vlasenkob1278a32009-11-24 16:03:47 +010024#define QSCALE_OFF_MIN 0.05
25#define QSCALE_OFF_MAX 0.50
Adam Tkacb1585062009-11-22 03:43:55 +010026
Denys Vlasenkob1278a32009-11-24 16:03:47 +010027#define QUERYTIME_MAX 15 /* single query might take n secs max */
28#define OFFSET_ARRAY_SIZE 8
29#define SETTIME_MIN_OFFSET 180 /* min offset for settime at start */
30#define SETTIME_TIMEOUT 15 /* max seconds to wait with -s */
Adam Tkacb1585062009-11-22 03:43:55 +010031
32/* Style borrowed from NTP ref/tcpdump and updated for SNTPv4 (RFC2030). */
33
34/*
35 * RFC Section 3
36 *
37 * 0 1 2 3
38 * 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
39 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
40 * | Integer Part |
41 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
42 * | Fraction Part |
43 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
44 *
45 * 0 1 2 3
46 * 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
47 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
48 * | Integer Part | Fraction Part |
49 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
50*/
51typedef struct {
52 uint32_t int_partl;
53 uint32_t fractionl;
54} l_fixedpt_t;
55
56typedef struct {
57 uint16_t int_parts;
58 uint16_t fractions;
59} s_fixedpt_t;
60
Denys Vlasenkoca6c7e42009-11-24 07:07:42 +010061enum {
62 NTP_DIGESTSIZE = 16,
63 NTP_MSGSIZE_NOAUTH = 48,
64 NTP_MSGSIZE = (NTP_MSGSIZE_NOAUTH + 4 + NTP_DIGESTSIZE),
65};
Adam Tkacb1585062009-11-22 03:43:55 +010066
67typedef struct {
Denys Vlasenkoca6c7e42009-11-24 07:07:42 +010068 uint8_t status; /* status of local clock and leap info */
69 uint8_t stratum; /* stratum level */
70 uint8_t ppoll; /* poll value */
71 int8_t precision;
Adam Tkacb1585062009-11-22 03:43:55 +010072 s_fixedpt_t rootdelay;
73 s_fixedpt_t dispersion;
Denys Vlasenkoca6c7e42009-11-24 07:07:42 +010074 uint32_t refid;
Adam Tkacb1585062009-11-22 03:43:55 +010075 l_fixedpt_t reftime;
76 l_fixedpt_t orgtime;
77 l_fixedpt_t rectime;
78 l_fixedpt_t xmttime;
Denys Vlasenkoca6c7e42009-11-24 07:07:42 +010079 uint32_t keyid;
80 uint8_t digest[NTP_DIGESTSIZE];
Adam Tkacb1585062009-11-22 03:43:55 +010081} ntp_msg_t;
82
83typedef struct {
Denys Vlasenkoca6c7e42009-11-24 07:07:42 +010084 int fd;
85 ntp_msg_t msg;
86 double xmttime;
Adam Tkacb1585062009-11-22 03:43:55 +010087} ntp_query_t;
88
89enum {
90 NTP_VERSION = 4,
91 NTP_MAXSTRATUM = 15,
92 /* Leap Second Codes (high order two bits) */
93 LI_NOWARNING = (0 << 6), /* no warning */
94 LI_PLUSSEC = (1 << 6), /* add a second (61 seconds) */
95 LI_MINUSSEC = (2 << 6), /* minus a second (59 seconds) */
96 LI_ALARM = (3 << 6), /* alarm condition */
97
98 /* Status Masks */
99 MODE_MASK = (7 << 0),
100 VERSION_MASK = (7 << 3),
Denys Vlasenkoca6c7e42009-11-24 07:07:42 +0100101 VERSION_SHIFT = 3,
Adam Tkacb1585062009-11-22 03:43:55 +0100102 LI_MASK = (3 << 6),
103
104 /* Mode values */
105 MODE_RES0 = 0, /* reserved */
106 MODE_SYM_ACT = 1, /* symmetric active */
107 MODE_SYM_PAS = 2, /* symmetric passive */
108 MODE_CLIENT = 3, /* client */
109 MODE_SERVER = 4, /* server */
110 MODE_BROADCAST = 5, /* broadcast */
111 MODE_RES1 = 6, /* reserved for NTP control message */
Denys Vlasenkoca6c7e42009-11-24 07:07:42 +0100112 MODE_RES2 = 7, /* reserved for private use */
Adam Tkacb1585062009-11-22 03:43:55 +0100113};
114
Denys Vlasenkob1278a32009-11-24 16:03:47 +0100115#define OFFSET_1900_1970 2208988800UL /* 1970 - 1900 in seconds */
Adam Tkacb1585062009-11-22 03:43:55 +0100116
117enum client_state {
118 STATE_NONE,
119 STATE_QUERY_SENT,
Denys Vlasenkoca6c7e42009-11-24 07:07:42 +0100120 STATE_REPLY_RECEIVED,
Adam Tkacb1585062009-11-22 03:43:55 +0100121};
122
123typedef struct {
124 double rootdelay;
125 double rootdispersion;
126 double reftime;
127 uint32_t refid;
128 uint32_t refid4;
129 uint8_t synced;
130 uint8_t leap;
131 int8_t precision;
132 uint8_t poll;
133 uint8_t stratum;
134} ntp_status_t;
135
136typedef struct {
Denys Vlasenkoca6c7e42009-11-24 07:07:42 +0100137 ntp_status_t status;
138 double offset;
139 double delay;
140 double error;
141 time_t rcvd;
142 uint8_t good;
Adam Tkacb1585062009-11-22 03:43:55 +0100143} ntp_offset_t;
144
145typedef struct {
Denys Vlasenkoca6c7e42009-11-24 07:07:42 +0100146//TODO:
147// (1) store dotted addr str, to avoid constant translations
148// (2) periodically re-resolve DNS names
Adam Tkacb1585062009-11-22 03:43:55 +0100149 len_and_sockaddr *lsa;
Denys Vlasenkoca6c7e42009-11-24 07:07:42 +0100150 ntp_query_t query;
151 ntp_offset_t reply[OFFSET_ARRAY_SIZE];
152 ntp_offset_t update;
153 enum client_state state;
154 time_t next;
155 time_t deadline;
156 uint8_t shift;
157 uint8_t trustlevel;
Adam Tkacb1585062009-11-22 03:43:55 +0100158} ntp_peer_t;
159
Denys Vlasenko8d580c72009-11-23 16:27:16 +0100160enum {
161 OPT_n = (1 << 0),
162 OPT_g = (1 << 1),
163 OPT_q = (1 << 2),
164 /* Insert new options above this line. */
165 /* Non-compat options: */
166 OPT_p = (1 << 3),
167 OPT_l = (1 << 4),
168};
169
Adam Tkacb1585062009-11-22 03:43:55 +0100170
171struct globals {
172 unsigned verbose;
173#if ENABLE_FEATURE_NTPD_SERVER
174 int listen_fd;
175#endif
Denys Vlasenkob1278a32009-11-24 16:03:47 +0100176 unsigned peer_cnt;
Adam Tkacb1585062009-11-22 03:43:55 +0100177 llist_t *ntp_peers;
178 ntp_status_t status;
179 uint32_t scale;
180 uint8_t settime;
181 uint8_t firstadj;
Adam Tkacb1585062009-11-22 03:43:55 +0100182};
183#define G (*ptr_to_globals)
184
185
186static const int const_IPTOS_LOWDELAY = IPTOS_LOWDELAY;
187
188
189static void
190set_next(ntp_peer_t *p, time_t t)
191{
192 p->next = time(NULL) + t;
193 p->deadline = 0;
194}
195
196static void
197add_peers(const char *s)
198{
199 ntp_peer_t *p;
200
201 p = xzalloc(sizeof(*p));
202//TODO: big ntpd uses all IPs, not just 1st, do we need to mimic that?
203 p->lsa = xhost2sockaddr(s, 123);
204 p->query.fd = -1;
205 p->query.msg.status = MODE_CLIENT | (NTP_VERSION << 3);
206 if (STATE_NONE != 0)
207 p->state = STATE_NONE;
208 p->trustlevel = TRUSTLEVEL_PATHETIC;
209 p->query.fd = -1;
210 set_next(p, 0);
211
212 llist_add_to(&G.ntp_peers, p);
213 G.peer_cnt++;
214}
215
216static double
Denys Vlasenkob1278a32009-11-24 16:03:47 +0100217gettime1900fp(void)
Adam Tkacb1585062009-11-22 03:43:55 +0100218{
Denys Vlasenkoca6c7e42009-11-24 07:07:42 +0100219 struct timeval tv;
Adam Tkacb1585062009-11-22 03:43:55 +0100220 gettimeofday(&tv, NULL); /* never fails */
Denys Vlasenkob1278a32009-11-24 16:03:47 +0100221 return (tv.tv_sec + 1.0e-6 * tv.tv_usec + OFFSET_1900_1970);
Adam Tkacb1585062009-11-22 03:43:55 +0100222}
223
Adam Tkacb1585062009-11-22 03:43:55 +0100224static void
225d_to_tv(double d, struct timeval *tv)
226{
227 tv->tv_sec = (long)d;
228 tv->tv_usec = (d - tv->tv_sec) * 1000000;
229}
230
231static double
232lfp_to_d(l_fixedpt_t lfp)
233{
Denys Vlasenkoca6c7e42009-11-24 07:07:42 +0100234 double ret;
Adam Tkacb1585062009-11-22 03:43:55 +0100235 lfp.int_partl = ntohl(lfp.int_partl);
236 lfp.fractionl = ntohl(lfp.fractionl);
Denys Vlasenkoca6c7e42009-11-24 07:07:42 +0100237 ret = (double)lfp.int_partl + ((double)lfp.fractionl / UINT_MAX);
238 return ret;
239}
240
241static double
242sfp_to_d(s_fixedpt_t sfp)
243{
244 double ret;
245 sfp.int_parts = ntohs(sfp.int_parts);
246 sfp.fractions = ntohs(sfp.fractions);
247 ret = (double)sfp.int_parts + ((double)sfp.fractions / USHRT_MAX);
Adam Tkacb1585062009-11-22 03:43:55 +0100248 return ret;
249}
250
251#if ENABLE_FEATURE_NTPD_SERVER
252static l_fixedpt_t
253d_to_lfp(double d)
254{
Denys Vlasenkoca6c7e42009-11-24 07:07:42 +0100255 l_fixedpt_t lfp;
256 lfp.int_partl = (uint32_t)d;
257 lfp.fractionl = (uint32_t)((d - lfp.int_partl) * UINT_MAX);
258 lfp.int_partl = htonl(lfp.int_partl);
259 lfp.fractionl = htonl(lfp.fractionl);
Adam Tkacb1585062009-11-22 03:43:55 +0100260 return lfp;
261}
Adam Tkacb1585062009-11-22 03:43:55 +0100262
Adam Tkacb1585062009-11-22 03:43:55 +0100263static s_fixedpt_t
264d_to_sfp(double d)
265{
Denys Vlasenkoca6c7e42009-11-24 07:07:42 +0100266 s_fixedpt_t sfp;
267 sfp.int_parts = (uint16_t)d;
268 sfp.fractions = (uint16_t)((d - sfp.int_parts) * USHRT_MAX);
269 sfp.int_parts = htons(sfp.int_parts);
270 sfp.fractions = htons(sfp.fractions);
Adam Tkacb1585062009-11-22 03:43:55 +0100271 return sfp;
272}
273#endif
274
275static void
276set_deadline(ntp_peer_t *p, time_t t)
277{
278 p->deadline = time(NULL) + t;
279 p->next = 0;
280}
281
282static time_t
283error_interval(void)
284{
285 time_t interval, r;
Adam Tkacb1585062009-11-22 03:43:55 +0100286 interval = INTERVAL_QUERY_PATHETIC * QSCALE_OFF_MAX / QSCALE_OFF_MIN;
Denys Vlasenkoca6c7e42009-11-24 07:07:42 +0100287 r = (unsigned)random() % (unsigned long)(interval / 10);
Adam Tkacb1585062009-11-22 03:43:55 +0100288 return (interval + r);
289}
290
291static int
292sendmsg_wrap(int fd,
293 const struct sockaddr *from, const struct sockaddr *to, socklen_t addrlen,
294 ntp_msg_t *msg, ssize_t len)
295{
296 ssize_t ret;
297
298 errno = 0;
299 if (!from) {
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100300 ret = sendto(fd, msg, len, MSG_DONTWAIT, to, addrlen);
Adam Tkacb1585062009-11-22 03:43:55 +0100301 } else {
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100302 ret = send_to_from(fd, msg, len, MSG_DONTWAIT, to, from, addrlen);
Adam Tkacb1585062009-11-22 03:43:55 +0100303 }
304 if (ret != len) {
305 bb_perror_msg("send failed");
306 return -1;
307 }
308 return 0;
309}
310
311static int
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100312send_query_to_peer(ntp_peer_t *p)
Adam Tkacb1585062009-11-22 03:43:55 +0100313{
Denys Vlasenkob1278a32009-11-24 16:03:47 +0100314 // Why do we need to bind()?
315 // See what happens when we don't bind:
316 //
317 // socket(PF_INET, SOCK_DGRAM, IPPROTO_IP) = 3
318 // setsockopt(3, SOL_IP, IP_TOS, [16], 4) = 0
319 // gettimeofday({1259071266, 327885}, NULL) = 0
320 // sendto(3, "xxx", 48, MSG_DONTWAIT, {sa_family=AF_INET, sin_port=htons(123), sin_addr=inet_addr("10.34.32.125")}, 16) = 48
321 // ^^^ we sent it from some source port picked by kernel.
322 // time(NULL) = 1259071266
323 // write(2, "ntpd: entering poll 15 secs\n", 28) = 28
324 // poll([{fd=3, events=POLLIN}], 1, 15000) = 1 ([{fd=3, revents=POLLIN}])
325 // recv(3, "yyy", 68, MSG_DONTWAIT) = 48
326 // ^^^ this recv will receive packets to any local port!
327 //
328 // Uncomment this and use strace to see it in action:
329#define PROBE_LOCAL_ADDR // { len_and_sockaddr lsa; lsa.len = LSA_SIZEOF_SA; getsockname(p->query.fd, &lsa.u.sa, &lsa.len); }
330
Adam Tkacb1585062009-11-22 03:43:55 +0100331 if (p->query.fd == -1) {
Denys Vlasenkob1278a32009-11-24 16:03:47 +0100332 int fd, family;
333 len_and_sockaddr *local_lsa;
334
335 family = p->lsa->u.sa.sa_family;
336 //was: p->query.fd = xsocket(family, SOCK_DGRAM, 0);
337 p->query.fd = fd = xsocket_type(&local_lsa, family, SOCK_DGRAM);
338 /* local_lsa has "null" address and port 0 now.
339 * bind() ensures we have a *particular port* selected by kernel
340 * and remembered in p->query.fd, thus later recv(p->query.fd)
341 * receives only packets sent to this port.
342 */
343 PROBE_LOCAL_ADDR
344 xbind(fd, &local_lsa->u.sa, local_lsa->len);
345 PROBE_LOCAL_ADDR
Adam Tkacb1585062009-11-22 03:43:55 +0100346#if ENABLE_FEATURE_IPV6
Denys Vlasenkob1278a32009-11-24 16:03:47 +0100347 if (family == AF_INET)
Adam Tkacb1585062009-11-22 03:43:55 +0100348#endif
Denys Vlasenkob1278a32009-11-24 16:03:47 +0100349 setsockopt(fd, IPPROTO_IP, IP_TOS, &const_IPTOS_LOWDELAY, sizeof(const_IPTOS_LOWDELAY));
350 free(local_lsa);
Adam Tkacb1585062009-11-22 03:43:55 +0100351 }
352
353 /*
354 * Send out a random 64-bit number as our transmit time. The NTP
355 * server will copy said number into the originate field on the
356 * response that it sends us. This is totally legal per the SNTP spec.
357 *
358 * The impact of this is two fold: we no longer send out the current
359 * system time for the world to see (which may aid an attacker), and
360 * it gives us a (not very secure) way of knowing that we're not
361 * getting spoofed by an attacker that can't capture our traffic
362 * but can spoof packets from the NTP server we're communicating with.
363 *
364 * Save the real transmit timestamp locally.
365 */
366
367 p->query.msg.xmttime.int_partl = random();
368 p->query.msg.xmttime.fractionl = random();
Denys Vlasenkob1278a32009-11-24 16:03:47 +0100369 p->query.xmttime = gettime1900fp();
Adam Tkacb1585062009-11-22 03:43:55 +0100370
371 if (sendmsg_wrap(p->query.fd, /*from:*/ NULL, /*to:*/ &p->lsa->u.sa, /*addrlen:*/ p->lsa->len,
372 &p->query.msg, NTP_MSGSIZE_NOAUTH) == -1) {
373 set_next(p, INTERVAL_QUERY_PATHETIC);
374 return -1;
375 }
376
377 p->state = STATE_QUERY_SENT;
378 set_deadline(p, QUERYTIME_MAX);
379
380 return 0;
381}
382
383static int
384offset_compare(const void *aa, const void *bb)
385{
Denys Vlasenkoca6c7e42009-11-24 07:07:42 +0100386 const ntp_peer_t *const *a = aa;
387 const ntp_peer_t *const *b = bb;
Adam Tkacb1585062009-11-22 03:43:55 +0100388 if ((*a)->update.offset < (*b)->update.offset)
389 return -1;
390 return ((*a)->update.offset > (*b)->update.offset);
391}
392
393static uint32_t
394updated_scale(double offset)
395{
396 if (offset < 0)
397 offset = -offset;
Adam Tkacb1585062009-11-22 03:43:55 +0100398 if (offset > QSCALE_OFF_MAX)
399 return 1;
400 if (offset < QSCALE_OFF_MIN)
401 return QSCALE_OFF_MAX / QSCALE_OFF_MIN;
402 return QSCALE_OFF_MAX / offset;
403}
404
405static void
406adjtime_wrap(void)
407{
408 ntp_peer_t *p;
409 unsigned offset_cnt;
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100410 unsigned middle;
Adam Tkacb1585062009-11-22 03:43:55 +0100411 int i = 0;
412 ntp_peer_t **peers;
413 double offset_median;
414 llist_t *item;
415 len_and_sockaddr *lsa;
416 struct timeval tv, olddelta;
417
418 offset_cnt = 0;
419 for (item = G.ntp_peers; item != NULL; item = item->link) {
420 p = (ntp_peer_t *) item->data;
421 if (p->trustlevel < TRUSTLEVEL_BADPEER)
422 continue;
423 if (!p->update.good)
424 return;
425 offset_cnt++;
426 }
427
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100428 if (offset_cnt == 0)
429 goto clear_good;
430
431 peers = xzalloc(sizeof(peers[0]) * offset_cnt);
Adam Tkacb1585062009-11-22 03:43:55 +0100432 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
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100439 qsort(peers, offset_cnt, sizeof(peers[0]), offset_compare);
Adam Tkacb1585062009-11-22 03:43:55 +0100440
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100441 middle = offset_cnt / 2;
Denys Vlasenko9cc60d72009-11-24 14:43:20 +0100442 if ((offset_cnt & 1) == 0 && middle != 0) {
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100443 offset_median = (peers[middle-1]->update.offset + peers[middle]->update.offset) / 2;
444 G.status.rootdelay = (peers[middle-1]->update.delay + peers[middle]->update.delay) / 2;
445 G.status.stratum = MAX(peers[middle-1]->update.status.stratum, peers[middle]->update.status.stratum);
446 } else {
447 offset_median = peers[middle]->update.offset;
448 G.status.rootdelay = peers[middle]->update.delay;
449 G.status.stratum = peers[middle]->update.status.stratum;
Adam Tkacb1585062009-11-22 03:43:55 +0100450 }
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100451 G.status.leap = peers[middle]->update.status.leap;
452
453 bb_info_msg("adjusting local clock by %fs", offset_median);
454
455 d_to_tv(offset_median, &tv);
456 if (adjtime(&tv, &olddelta) == -1)
457 bb_error_msg("adjtime failed");
458 else if (!G.firstadj
459 && olddelta.tv_sec == 0
460 && olddelta.tv_usec == 0
461 && !G.status.synced
462 ) {
463 bb_info_msg("clock synced");
464 G.status.synced = 1;
465 } else if (G.status.synced) {
466 bb_info_msg("clock unsynced");
467 G.status.synced = 0;
468 }
469
470 G.firstadj = 0;
Denys Vlasenkob1278a32009-11-24 16:03:47 +0100471 G.status.reftime = gettime1900fp();
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100472 G.status.stratum++; /* one more than selected peer */
473 G.scale = updated_scale(offset_median);
474
475 G.status.refid4 = peers[middle]->update.status.refid4;
476
477 lsa = peers[middle]->lsa;
478 G.status.refid =
479#if ENABLE_FEATURE_IPV6
480 lsa->u.sa.sa_family != AF_INET ?
481 G.status.refid4 :
482#endif
483 lsa->u.sin.sin_addr.s_addr;
Adam Tkacb1585062009-11-22 03:43:55 +0100484
485 free(peers);
486
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100487 clear_good:
Adam Tkacb1585062009-11-22 03:43:55 +0100488 for (item = G.ntp_peers; item != NULL; item = item->link) {
489 p = (ntp_peer_t *) item->data;
490 p->update.good = 0;
491 }
492}
493
494static void
495settime(double offset)
496{
497 ntp_peer_t *p;
498 llist_t *item;
499 struct timeval tv, curtime;
500 char buf[80];
501 time_t tval;
502
Adam Tkacb1585062009-11-22 03:43:55 +0100503 if (!G.settime)
Denys Vlasenko8d580c72009-11-23 16:27:16 +0100504 goto bail;
505
506 G.settime = 0;
Adam Tkacb1585062009-11-22 03:43:55 +0100507
508 /* if the offset is small, don't call settimeofday */
509 if (offset < SETTIME_MIN_OFFSET && offset > -SETTIME_MIN_OFFSET)
Denys Vlasenko8d580c72009-11-23 16:27:16 +0100510 goto bail;
Adam Tkacb1585062009-11-22 03:43:55 +0100511
512 gettimeofday(&curtime, NULL); /* never fails */
513
514 d_to_tv(offset, &tv);
515 curtime.tv_usec += tv.tv_usec + 1000000;
516 curtime.tv_sec += tv.tv_sec - 1 + (curtime.tv_usec / 1000000);
517 curtime.tv_usec %= 1000000;
518
519 if (settimeofday(&curtime, NULL) == -1) {
520 bb_error_msg("settimeofday");
Denys Vlasenko8d580c72009-11-23 16:27:16 +0100521 goto bail;
Adam Tkacb1585062009-11-22 03:43:55 +0100522 }
523
Adam Tkacb1585062009-11-22 03:43:55 +0100524 tval = curtime.tv_sec;
525 strftime(buf, sizeof(buf), "%a %b %e %H:%M:%S %Z %Y", localtime(&tval));
526
527 /* Do we want to print message below to system log when daemonized? */
528 bb_info_msg("set local clock to %s (offset %fs)", buf, offset);
529
530 for (item = G.ntp_peers; item != NULL; item = item->link) {
531 p = (ntp_peer_t *) item->data;
532 if (p->next)
533 p->next -= offset;
534 if (p->deadline)
535 p->deadline -= offset;
536 }
Denys Vlasenko8d580c72009-11-23 16:27:16 +0100537
538 bail:
539 if (option_mask32 & OPT_q)
540 exit(0);
Adam Tkacb1585062009-11-22 03:43:55 +0100541}
542
543static void
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100544update_peer_data(ntp_peer_t *p)
Adam Tkacb1585062009-11-22 03:43:55 +0100545{
546 int i, best = 0, good = 0;
547
548 /*
549 * 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
553 */
554
555 for (i = 0; good == 0 && i < OFFSET_ARRAY_SIZE; i++) {
556 if (p->reply[i].good) {
557 good++;
558 best = i;
559 }
560 }
561
562 for (; i < OFFSET_ARRAY_SIZE; i++) {
563 if (p->reply[i].good) {
564 good++;
565 if (p->reply[i].delay < p->reply[best].delay)
566 best = i;
567 }
568 }
569
570 if (good < 8)
571 return;
572
573 memcpy(&p->update, &p->reply[best], sizeof(p->update));
574 adjtime_wrap();
575
576 for (i = 0; i < OFFSET_ARRAY_SIZE; i++)
577 if (p->reply[i].rcvd <= p->reply[best].rcvd)
578 p->reply[i].good = 0;
579}
580
581static time_t
582scale_interval(time_t requested)
583{
584 time_t interval, r;
Adam Tkacb1585062009-11-22 03:43:55 +0100585 interval = requested * G.scale;
Denys Vlasenkoca6c7e42009-11-24 07:07:42 +0100586 r = (unsigned)random() % (unsigned long)(MAX(5, interval / 10));
Adam Tkacb1585062009-11-22 03:43:55 +0100587 return (interval + r);
588}
589
590static void
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100591recv_and_process_peer_pkt(ntp_peer_t *p)
Adam Tkacb1585062009-11-22 03:43:55 +0100592{
593 char *addr;
594 ssize_t size;
595 ntp_msg_t msg;
596 double T1, T2, T3, T4;
597 time_t interval;
598 ntp_offset_t *offset;
599
600 addr = xmalloc_sockaddr2dotted_noport(&p->lsa->u.sa);
601
Denys Vlasenkob1278a32009-11-24 16:03:47 +0100602 /* We can recvfrom here and check from.IP, but some multihomed
603 * ntp servers reply from their *other IP*.
604 * TODO: maybe we should check at least what we can: from.port == 123?
605 */
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100606 size = recv(p->query.fd, &msg, sizeof(msg), MSG_DONTWAIT);
Adam Tkacb1585062009-11-22 03:43:55 +0100607 if (size == -1) {
Denys Vlasenkoca6c7e42009-11-24 07:07:42 +0100608 bb_perror_msg("recv(%s) error", addr);
Adam Tkacb1585062009-11-22 03:43:55 +0100609 if (errno == EHOSTUNREACH || errno == EHOSTDOWN
610 || errno == ENETUNREACH || errno == ENETDOWN
611 || errno == ECONNREFUSED || errno == EADDRNOTAVAIL
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100612 || errno == EAGAIN
Adam Tkacb1585062009-11-22 03:43:55 +0100613 ) {
614//TODO: always do this?
615 set_next(p, error_interval());
616 goto bail;
617 }
618 xfunc_die();
619 }
620
Denys Vlasenkob1278a32009-11-24 16:03:47 +0100621 T4 = gettime1900fp();
Adam Tkacb1585062009-11-22 03:43:55 +0100622
623 if (size != NTP_MSGSIZE_NOAUTH && size != NTP_MSGSIZE) {
624 bb_error_msg("malformed packet received from %s", addr);
625 goto bail;
626 }
627
628 if (msg.orgtime.int_partl != p->query.msg.xmttime.int_partl
629 || msg.orgtime.fractionl != p->query.msg.xmttime.fractionl
630 ) {
631 goto bail;
632 }
633
634 if ((msg.status & LI_ALARM) == LI_ALARM
635 || msg.stratum == 0
636 || msg.stratum > NTP_MAXSTRATUM
637 ) {
638 interval = error_interval();
639 bb_info_msg("reply from %s: not synced, next query %ds", addr, (int) interval);
640 goto bail;
641 }
642
643 /*
644 * From RFC 2030 (with a correction to the delay math):
645 *
646 * Timestamp Name ID When Generated
647 * ------------------------------------------------------------
648 * Originate Timestamp T1 time request sent by client
649 * Receive Timestamp T2 time request received by server
650 * Transmit Timestamp T3 time reply sent by server
651 * Destination Timestamp T4 time reply received by client
652 *
653 * The roundtrip delay d and local clock offset t are defined as
654 *
655 * d = (T4 - T1) - (T3 - T2) t = ((T2 - T1) + (T3 - T4)) / 2.
656 */
657
658 T1 = p->query.xmttime;
659 T2 = lfp_to_d(msg.rectime);
660 T3 = lfp_to_d(msg.xmttime);
661
662 offset = &p->reply[p->shift];
663
664 offset->offset = ((T2 - T1) + (T3 - T4)) / 2;
665 offset->delay = (T4 - T1) - (T3 - T2);
666 if (offset->delay < 0) {
667 interval = error_interval();
668 set_next(p, interval);
669 bb_info_msg("reply from %s: negative delay %f", addr, p->reply[p->shift].delay);
670 goto bail;
671 }
672 offset->error = (T2 - T1) - (T3 - T4);
Denys Vlasenkob1278a32009-11-24 16:03:47 +0100673// Can we use (T4 - OFFSET_1900_1970) instead of time(NULL)?
Adam Tkacb1585062009-11-22 03:43:55 +0100674 offset->rcvd = time(NULL);
675 offset->good = 1;
676
677 offset->status.leap = (msg.status & LI_MASK);
678 offset->status.precision = msg.precision;
679 offset->status.rootdelay = sfp_to_d(msg.rootdelay);
680 offset->status.rootdispersion = sfp_to_d(msg.dispersion);
681 offset->status.refid = ntohl(msg.refid);
682 offset->status.refid4 = msg.xmttime.fractionl;
683 offset->status.reftime = lfp_to_d(msg.reftime);
684 offset->status.poll = msg.ppoll;
685 offset->status.stratum = msg.stratum;
686
687 if (p->trustlevel < TRUSTLEVEL_PATHETIC)
688 interval = scale_interval(INTERVAL_QUERY_PATHETIC);
689 else if (p->trustlevel < TRUSTLEVEL_AGRESSIVE)
690 interval = scale_interval(INTERVAL_QUERY_AGRESSIVE);
691 else
692 interval = scale_interval(INTERVAL_QUERY_NORMAL);
693
694 set_next(p, interval);
695 p->state = STATE_REPLY_RECEIVED;
696
697 /* every received reply which we do not discard increases trust */
698 if (p->trustlevel < TRUSTLEVEL_MAX) {
Adam Tkacb1585062009-11-22 03:43:55 +0100699 p->trustlevel++;
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100700 if (p->trustlevel == TRUSTLEVEL_BADPEER)
701 bb_info_msg("peer %s now valid", addr);
Adam Tkacb1585062009-11-22 03:43:55 +0100702 }
703
704 bb_info_msg("reply from %s: offset %f delay %f, next query %ds", addr,
705 offset->offset, offset->delay, (int) interval);
706
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100707 update_peer_data(p);
Denys Vlasenko8d580c72009-11-23 16:27:16 +0100708 settime(offset->offset);
Adam Tkacb1585062009-11-22 03:43:55 +0100709
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100710 p->shift++;
711 if (p->shift >= OFFSET_ARRAY_SIZE)
Adam Tkacb1585062009-11-22 03:43:55 +0100712 p->shift = 0;
713
714 bail:
715 free(addr);
716}
717
718#if ENABLE_FEATURE_NTPD_SERVER
719static void
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100720recv_and_process_client_pkt(void /*int fd*/)
Adam Tkacb1585062009-11-22 03:43:55 +0100721{
Denys Vlasenkoca6c7e42009-11-24 07:07:42 +0100722 ssize_t size;
723 uint8_t version;
724 double rectime;
725 len_and_sockaddr *to;
726 struct sockaddr *from;
727 ntp_msg_t msg;
728 uint8_t query_status;
729 uint8_t query_ppoll;
730 l_fixedpt_t query_xmttime;
Adam Tkacb1585062009-11-22 03:43:55 +0100731
732 to = get_sock_lsa(G.listen_fd);
733 from = xzalloc(to->len);
734
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100735 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 +0100736 if (size != NTP_MSGSIZE_NOAUTH && size != NTP_MSGSIZE) {
Denys Vlasenkoca6c7e42009-11-24 07:07:42 +0100737 char *addr;
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100738 if (size < 0) {
739 if (errno == EAGAIN)
740 goto bail;
741 bb_perror_msg_and_die("recv_from_to");
742 }
Denys Vlasenkoca6c7e42009-11-24 07:07:42 +0100743 addr = xmalloc_sockaddr2dotted_noport(from);
Adam Tkacb1585062009-11-22 03:43:55 +0100744 bb_error_msg("malformed packet received from %s", addr);
745 free(addr);
746 goto bail;
747 }
748
Denys Vlasenkoca6c7e42009-11-24 07:07:42 +0100749 query_status = msg.status;
750 query_ppoll = msg.ppoll;
751 query_xmttime = msg.xmttime;
Adam Tkacb1585062009-11-22 03:43:55 +0100752
Denys Vlasenkoca6c7e42009-11-24 07:07:42 +0100753 /* Build a reply packet */
754 memset(&msg, 0, sizeof(msg));
755 msg.status = G.status.synced ? G.status.leap : LI_ALARM;
756 msg.status |= (query_status & VERSION_MASK);
757 msg.status |= ((query_status & MODE_MASK) == MODE_CLIENT) ?
Adam Tkacb1585062009-11-22 03:43:55 +0100758 MODE_SERVER : MODE_SYM_PAS;
Denys Vlasenkoca6c7e42009-11-24 07:07:42 +0100759 msg.stratum = G.status.stratum;
760 msg.ppoll = query_ppoll;
761 msg.precision = G.status.precision;
Denys Vlasenkob1278a32009-11-24 16:03:47 +0100762 rectime = gettime1900fp();
Denys Vlasenkoca6c7e42009-11-24 07:07:42 +0100763 msg.xmttime = msg.rectime = d_to_lfp(rectime);
764 msg.reftime = d_to_lfp(G.status.reftime);
Denys Vlasenkob1278a32009-11-24 16:03:47 +0100765 //msg.xmttime = d_to_lfp(gettime1900fp()); // = msg.rectime
Denys Vlasenkoca6c7e42009-11-24 07:07:42 +0100766 msg.orgtime = query_xmttime;
767 msg.rootdelay = d_to_sfp(G.status.rootdelay);
768 version = (query_status & VERSION_MASK); /* ... >> VERSION_SHIFT - done below instead */
769 msg.refid = (version > (3 << VERSION_SHIFT)) ? G.status.refid4 : G.status.refid;
Adam Tkacb1585062009-11-22 03:43:55 +0100770
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100771 /* We reply from the local address packet was sent to,
Adam Tkacb1585062009-11-22 03:43:55 +0100772 * this makes to/from look swapped here: */
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100773 sendmsg_wrap(G.listen_fd,
Denys Vlasenkoca6c7e42009-11-24 07:07:42 +0100774 /*from:*/ &to->u.sa, /*to:*/ from, /*addrlen:*/ to->len,
775 &msg, size);
Adam Tkacb1585062009-11-22 03:43:55 +0100776
777 bail:
778 free(to);
779 free(from);
780}
781#endif
782
783/* Upstream ntpd's options:
784 *
785 * -4 Force DNS resolution of host names to the IPv4 namespace.
786 * -6 Force DNS resolution of host names to the IPv6 namespace.
787 * -a Require cryptographic authentication for broadcast client,
788 * multicast client and symmetric passive associations.
789 * This is the default.
790 * -A Do not require cryptographic authentication for broadcast client,
791 * multicast client and symmetric passive associations.
792 * This is almost never a good idea.
793 * -b Enable the client to synchronize to broadcast servers.
794 * -c conffile
795 * Specify the name and path of the configuration file,
796 * default /etc/ntp.conf
797 * -d Specify debugging mode. This option may occur more than once,
798 * with each occurrence indicating greater detail of display.
799 * -D level
800 * Specify debugging level directly.
801 * -f driftfile
802 * Specify the name and path of the frequency file.
803 * This is the same operation as the "driftfile FILE"
804 * configuration command.
805 * -g Normally, ntpd exits with a message to the system log
806 * if the offset exceeds the panic threshold, which is 1000 s
807 * by default. This option allows the time to be set to any value
808 * without restriction; however, this can happen only once.
809 * If the threshold is exceeded after that, ntpd will exit
810 * with a message to the system log. This option can be used
811 * with the -q and -x options. See the tinker command for other options.
812 * -i jaildir
813 * Chroot the server to the directory jaildir. This option also implies
814 * that the server attempts to drop root privileges at startup
815 * (otherwise, chroot gives very little additional security).
816 * You may need to also specify a -u option.
817 * -k keyfile
818 * Specify the name and path of the symmetric key file,
819 * default /etc/ntp/keys. This is the same operation
820 * as the "keys FILE" configuration command.
821 * -l logfile
822 * Specify the name and path of the log file. The default
823 * is the system log file. This is the same operation as
824 * the "logfile FILE" configuration command.
825 * -L Do not listen to virtual IPs. The default is to listen.
826 * -n Don't fork.
827 * -N To the extent permitted by the operating system,
828 * run the ntpd at the highest priority.
829 * -p pidfile
830 * Specify the name and path of the file used to record the ntpd
831 * process ID. This is the same operation as the "pidfile FILE"
832 * configuration command.
833 * -P priority
834 * To the extent permitted by the operating system,
835 * run the ntpd at the specified priority.
836 * -q Exit the ntpd just after the first time the clock is set.
837 * This behavior mimics that of the ntpdate program, which is
838 * to be retired. The -g and -x options can be used with this option.
839 * Note: The kernel time discipline is disabled with this option.
840 * -r broadcastdelay
841 * Specify the default propagation delay from the broadcast/multicast
842 * server to this client. This is necessary only if the delay
843 * cannot be computed automatically by the protocol.
844 * -s statsdir
845 * Specify the directory path for files created by the statistics
846 * facility. This is the same operation as the "statsdir DIR"
847 * configuration command.
848 * -t key
849 * Add a key number to the trusted key list. This option can occur
850 * more than once.
851 * -u user[:group]
852 * Specify a user, and optionally a group, to switch to.
853 * -v variable
854 * -V variable
855 * Add a system variable listed by default.
856 * -x Normally, the time is slewed if the offset is less than the step
857 * threshold, which is 128 ms by default, and stepped if above
858 * the threshold. This option sets the threshold to 600 s, which is
859 * well within the accuracy window to set the clock manually.
860 * Note: since the slew rate of typical Unix kernels is limited
861 * to 0.5 ms/s, each second of adjustment requires an amortization
862 * interval of 2000 s. Thus, an adjustment as much as 600 s
863 * will take almost 14 days to complete. This option can be used
864 * with the -g and -q options. See the tinker command for other options.
865 * Note: The kernel time discipline is disabled with this option.
866 */
867
Adam Tkacb1585062009-11-22 03:43:55 +0100868/* By doing init in a separate function we decrease stack usage
869 * in main loop.
870 */
871static NOINLINE void ntp_init(char **argv)
872{
873 unsigned opts;
874 llist_t *peers;
875
Denys Vlasenkoca6c7e42009-11-24 07:07:42 +0100876 srandom(getpid());
877 /* tzset(); - why? it's called automatically when needed, no? */
Adam Tkacb1585062009-11-22 03:43:55 +0100878
879 if (getuid())
880 bb_error_msg_and_die("need root privileges");
881
882 peers = NULL;
883 opt_complementary = "dd:p::"; /* d: counter, p: list */
884 opts = getopt32(argv,
Denys Vlasenko8d580c72009-11-23 16:27:16 +0100885 "ngq" /* compat */
Adam Tkacb1585062009-11-22 03:43:55 +0100886 "p:"IF_FEATURE_NTPD_SERVER("l") /* NOT compat */
887 "d" /* compat */
888 "46aAbLNx", /* compat, ignored */
889 &peers, &G.verbose);
890#if ENABLE_FEATURE_NTPD_SERVER
891 G.listen_fd = -1;
892 if (opts & OPT_l) {
893 G.listen_fd = create_and_bind_dgram_or_die(NULL, 123);
894 socket_want_pktinfo(G.listen_fd);
895 setsockopt(G.listen_fd, IPPROTO_IP, IP_TOS, &const_IPTOS_LOWDELAY, sizeof(const_IPTOS_LOWDELAY));
896 }
897#endif
898 if (opts & OPT_g)
899 G.settime = 1;
900 while (peers)
901 add_peers(llist_pop(&peers));
902 if (!(opts & OPT_n)) {
903 logmode = LOGMODE_NONE;
904 bb_daemonize(DAEMON_DEVNULL_STDIO);
905 }
906
907 /* Set some globals */
908 {
909 int prec = 0;
910 int b;
911#if 0
912 struct timespec tp;
913 /* We can use sys_clock_getres but assuming 10ms tick should be fine */
914 clock_getres(CLOCK_REALTIME, &tp);
915 tp.tv_sec = 0;
916 tp.tv_nsec = 10000000;
917 b = 1000000000 / tp.tv_nsec; /* convert to Hz */
918#else
919 b = 100; /* b = 1000000000/10000000 = 100 */
920#endif
921 while (b > 1)
922 prec--, b >>= 1;
923 G.status.precision = prec;
924 }
925 G.scale = 1;
926 G.firstadj = 1;
927
928 bb_signals((1 << SIGTERM) | (1 << SIGINT), record_signo);
929 bb_signals((1 << SIGPIPE) | (1 << SIGHUP), SIG_IGN);
930}
931
932int ntpd_main(int argc UNUSED_PARAM, char **argv) MAIN_EXTERNALLY_VISIBLE;
933int ntpd_main(int argc UNUSED_PARAM, char **argv)
934{
935 struct globals g;
Adam Tkacb1585062009-11-22 03:43:55 +0100936 struct pollfd *pfd;
937 ntp_peer_t **idx2peer;
938
939 memset(&g, 0, sizeof(g));
940 SET_PTR_TO_GLOBALS(&g);
941
942 ntp_init(argv);
943
Denys Vlasenko8d580c72009-11-23 16:27:16 +0100944 {
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100945 unsigned cnt = g.peer_cnt;
Denys Vlasenko8d580c72009-11-23 16:27:16 +0100946 /* if ENABLE_FEATURE_NTPD_SERVER, + 1 for listen_fd: */
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100947 idx2peer = xzalloc(sizeof(void *) * (cnt + ENABLE_FEATURE_NTPD_SERVER));
948 pfd = xzalloc(sizeof(pfd[0]) * (cnt + ENABLE_FEATURE_NTPD_SERVER));
Denys Vlasenko8d580c72009-11-23 16:27:16 +0100949 }
Adam Tkacb1585062009-11-22 03:43:55 +0100950
951 while (!bb_got_signal) {
952 llist_t *item;
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100953 unsigned i, j;
Adam Tkacb1585062009-11-22 03:43:55 +0100954 unsigned sent_cnt, trial_cnt;
955 int nfds, timeout;
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100956 time_t cur_time, nextaction;
Adam Tkacb1585062009-11-22 03:43:55 +0100957
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100958 /* Nothing between here and poll() blocks for any significant time */
959
960 cur_time = time(NULL);
961 nextaction = cur_time + 3600;
Adam Tkacb1585062009-11-22 03:43:55 +0100962
963 i = 0;
964#if ENABLE_FEATURE_NTPD_SERVER
965 if (g.listen_fd != -1) {
966 pfd[0].fd = g.listen_fd;
967 pfd[0].events = POLLIN;
968 i++;
969 }
970#endif
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100971 /* Pass over peer list, send requests, time out on receives */
Adam Tkacb1585062009-11-22 03:43:55 +0100972 sent_cnt = trial_cnt = 0;
973 for (item = g.ntp_peers; item != NULL; item = item->link) {
974 ntp_peer_t *p = (ntp_peer_t *) item->data;
975
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100976 if (p->next != 0 && p->next <= cur_time) {
977 /* Time to send new req */
Adam Tkacb1585062009-11-22 03:43:55 +0100978 trial_cnt++;
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100979 if (send_query_to_peer(p) == 0)
Adam Tkacb1585062009-11-22 03:43:55 +0100980 sent_cnt++;
981 }
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100982 if (p->deadline != 0 && p->deadline <= cur_time) {
983 /* Timed out waiting for reply */
Adam Tkacb1585062009-11-22 03:43:55 +0100984 char *addr = xmalloc_sockaddr2dotted_noport(&p->lsa->u.sa);
985
986 timeout = error_interval();
987 bb_info_msg("no reply from %s received in time, "
988 "next query %ds", addr, timeout);
989 if (p->trustlevel >= TRUSTLEVEL_BADPEER) {
990 p->trustlevel /= 2;
991 if (p->trustlevel < TRUSTLEVEL_BADPEER)
992 bb_info_msg("peer %s now invalid", addr);
993 }
994 free(addr);
995
996 set_next(p, timeout);
997 }
998
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100999 if (p->next != 0 && p->next < nextaction)
1000 nextaction = p->next;
1001 if (p->deadline != 0 && p->deadline < nextaction)
1002 nextaction = p->deadline;
1003
Adam Tkacb1585062009-11-22 03:43:55 +01001004 if (p->state == STATE_QUERY_SENT) {
Denys Vlasenko363e89b2009-11-24 14:04:15 +01001005 /* Wait for reply from this peer */
Adam Tkacb1585062009-11-22 03:43:55 +01001006 pfd[i].fd = p->query.fd;
1007 pfd[i].events = POLLIN;
Denys Vlasenko363e89b2009-11-24 14:04:15 +01001008 idx2peer[i] = p;
Adam Tkacb1585062009-11-22 03:43:55 +01001009 i++;
1010 }
1011 }
1012
Denys Vlasenko8d580c72009-11-23 16:27:16 +01001013 if ((trial_cnt > 0 && sent_cnt == 0) || g.peer_cnt == 0)
Denys Vlasenko363e89b2009-11-24 14:04:15 +01001014 settime(0); /* no good peers, don't wait */
Adam Tkacb1585062009-11-22 03:43:55 +01001015
Denys Vlasenko363e89b2009-11-24 14:04:15 +01001016 timeout = nextaction - cur_time;
Adam Tkacb1585062009-11-22 03:43:55 +01001017 if (timeout < 0)
1018 timeout = 0;
1019
Denys Vlasenko363e89b2009-11-24 14:04:15 +01001020 /* Here we may block */
Adam Tkacb1585062009-11-22 03:43:55 +01001021 if (g.verbose)
1022 bb_error_msg("entering poll %u secs", timeout);
1023 nfds = poll(pfd, i, timeout * 1000);
Denys Vlasenko363e89b2009-11-24 14:04:15 +01001024 if (nfds <= 0)
1025 continue;
Adam Tkacb1585062009-11-22 03:43:55 +01001026
Denys Vlasenko363e89b2009-11-24 14:04:15 +01001027 /* Process any received packets */
Adam Tkacb1585062009-11-22 03:43:55 +01001028 j = 0;
1029#if ENABLE_FEATURE_NTPD_SERVER
Denys Vlasenko363e89b2009-11-24 14:04:15 +01001030 if (g.listen_fd != -1) {
1031 if (pfd[0].revents /* & (POLLIN|POLLERR)*/) {
Adam Tkacb1585062009-11-22 03:43:55 +01001032 nfds--;
Denys Vlasenko363e89b2009-11-24 14:04:15 +01001033 recv_and_process_client_pkt(/*g.listen_fd*/);
Adam Tkacb1585062009-11-22 03:43:55 +01001034 }
Denys Vlasenko363e89b2009-11-24 14:04:15 +01001035 j = 1;
Adam Tkacb1585062009-11-22 03:43:55 +01001036 }
1037#endif
Denys Vlasenko363e89b2009-11-24 14:04:15 +01001038 for (; nfds != 0 && j < i; j++) {
1039 if (pfd[j].revents /* & (POLLIN|POLLERR)*/) {
Adam Tkacb1585062009-11-22 03:43:55 +01001040 nfds--;
Denys Vlasenko363e89b2009-11-24 14:04:15 +01001041 recv_and_process_peer_pkt(idx2peer[j]);
Adam Tkacb1585062009-11-22 03:43:55 +01001042 }
1043 }
1044 } /* while (!bb_got_signal) */
1045
1046 kill_myself_with_sig(bb_got_signal);
1047}