blob: c374120e20830ead769a019cf049b2abce0d9ad7 [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;
183 uint8_t settime;
184 uint8_t firstadj;
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);
457
458 d_to_tv(offset_median, &tv);
459 if (adjtime(&tv, &olddelta) == -1)
460 bb_error_msg("adjtime failed");
461 else if (!G.firstadj
462 && olddelta.tv_sec == 0
463 && olddelta.tv_usec == 0
464 && !G.status.synced
465 ) {
466 bb_info_msg("clock synced");
467 G.status.synced = 1;
468 } else if (G.status.synced) {
469 bb_info_msg("clock unsynced");
470 G.status.synced = 0;
471 }
472
473 G.firstadj = 0;
Denys Vlasenkob1278a32009-11-24 16:03:47 +0100474 G.status.reftime = gettime1900fp();
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100475 G.status.stratum++; /* one more than selected peer */
476 G.scale = updated_scale(offset_median);
477
478 G.status.refid4 = peers[middle]->update.status.refid4;
479
480 lsa = peers[middle]->lsa;
481 G.status.refid =
482#if ENABLE_FEATURE_IPV6
483 lsa->u.sa.sa_family != AF_INET ?
484 G.status.refid4 :
485#endif
486 lsa->u.sin.sin_addr.s_addr;
Adam Tkacb1585062009-11-22 03:43:55 +0100487
488 free(peers);
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;
493 p->update.good = 0;
494 }
495}
496
497static void
498settime(double offset)
499{
500 ntp_peer_t *p;
501 llist_t *item;
502 struct timeval tv, curtime;
503 char buf[80];
504 time_t tval;
505
Adam Tkacb1585062009-11-22 03:43:55 +0100506 if (!G.settime)
Denys Vlasenko8d580c72009-11-23 16:27:16 +0100507 goto bail;
508
509 G.settime = 0;
Adam Tkacb1585062009-11-22 03:43:55 +0100510
511 /* if the offset is small, don't call settimeofday */
512 if (offset < SETTIME_MIN_OFFSET && offset > -SETTIME_MIN_OFFSET)
Denys Vlasenko8d580c72009-11-23 16:27:16 +0100513 goto bail;
Adam Tkacb1585062009-11-22 03:43:55 +0100514
515 gettimeofday(&curtime, NULL); /* never fails */
516
517 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? */
531 bb_info_msg("set local clock to %s (offset %fs)", buf, offset);
532
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{
549 int i, best = 0, good = 0;
550
551 /*
552 * clock filter
553 * find the offset which arrived with the lowest delay
554 * use that as the peer update
555 * invalidate it and all older ones
556 */
557
558 for (i = 0; good == 0 && i < OFFSET_ARRAY_SIZE; i++) {
559 if (p->reply[i].good) {
560 good++;
561 best = i;
562 }
563 }
564
565 for (; i < OFFSET_ARRAY_SIZE; i++) {
566 if (p->reply[i].good) {
567 good++;
568 if (p->reply[i].delay < p->reply[best].delay)
569 best = i;
570 }
571 }
572
573 if (good < 8)
574 return;
575
576 memcpy(&p->update, &p->reply[best], sizeof(p->update));
577 adjtime_wrap();
578
579 for (i = 0; i < OFFSET_ARRAY_SIZE; i++)
580 if (p->reply[i].rcvd <= p->reply[best].rcvd)
581 p->reply[i].good = 0;
582}
583
584static time_t
585scale_interval(time_t requested)
586{
587 time_t interval, r;
Adam Tkacb1585062009-11-22 03:43:55 +0100588 interval = requested * G.scale;
Denys Vlasenkoca6c7e42009-11-24 07:07:42 +0100589 r = (unsigned)random() % (unsigned long)(MAX(5, interval / 10));
Adam Tkacb1585062009-11-22 03:43:55 +0100590 return (interval + r);
591}
592
593static void
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100594recv_and_process_peer_pkt(ntp_peer_t *p)
Adam Tkacb1585062009-11-22 03:43:55 +0100595{
596 char *addr;
597 ssize_t size;
598 ntp_msg_t msg;
599 double T1, T2, T3, T4;
600 time_t interval;
601 ntp_offset_t *offset;
602
603 addr = xmalloc_sockaddr2dotted_noport(&p->lsa->u.sa);
604
Denys Vlasenkob1278a32009-11-24 16:03:47 +0100605 /* We can recvfrom here and check from.IP, but some multihomed
606 * ntp servers reply from their *other IP*.
607 * TODO: maybe we should check at least what we can: from.port == 123?
608 */
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100609 size = recv(p->query.fd, &msg, sizeof(msg), MSG_DONTWAIT);
Adam Tkacb1585062009-11-22 03:43:55 +0100610 if (size == -1) {
Denys Vlasenkoca6c7e42009-11-24 07:07:42 +0100611 bb_perror_msg("recv(%s) error", addr);
Adam Tkacb1585062009-11-22 03:43:55 +0100612 if (errno == EHOSTUNREACH || errno == EHOSTDOWN
613 || errno == ENETUNREACH || errno == ENETDOWN
614 || errno == ECONNREFUSED || errno == EADDRNOTAVAIL
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100615 || errno == EAGAIN
Adam Tkacb1585062009-11-22 03:43:55 +0100616 ) {
617//TODO: always do this?
618 set_next(p, error_interval());
619 goto bail;
620 }
621 xfunc_die();
622 }
623
Denys Vlasenkob1278a32009-11-24 16:03:47 +0100624 T4 = gettime1900fp();
Adam Tkacb1585062009-11-22 03:43:55 +0100625
626 if (size != NTP_MSGSIZE_NOAUTH && size != NTP_MSGSIZE) {
627 bb_error_msg("malformed packet received from %s", addr);
628 goto bail;
629 }
630
631 if (msg.orgtime.int_partl != p->query.msg.xmttime.int_partl
632 || msg.orgtime.fractionl != p->query.msg.xmttime.fractionl
633 ) {
634 goto bail;
635 }
636
637 if ((msg.status & LI_ALARM) == LI_ALARM
638 || msg.stratum == 0
639 || msg.stratum > NTP_MAXSTRATUM
640 ) {
641 interval = error_interval();
642 bb_info_msg("reply from %s: not synced, next query %ds", addr, (int) interval);
643 goto bail;
644 }
645
646 /*
647 * From RFC 2030 (with a correction to the delay math):
648 *
649 * Timestamp Name ID When Generated
650 * ------------------------------------------------------------
651 * Originate Timestamp T1 time request sent by client
652 * Receive Timestamp T2 time request received by server
653 * Transmit Timestamp T3 time reply sent by server
654 * Destination Timestamp T4 time reply received by client
655 *
656 * The roundtrip delay d and local clock offset t are defined as
657 *
658 * d = (T4 - T1) - (T3 - T2) t = ((T2 - T1) + (T3 - T4)) / 2.
659 */
660
661 T1 = p->query.xmttime;
662 T2 = lfp_to_d(msg.rectime);
663 T3 = lfp_to_d(msg.xmttime);
664
665 offset = &p->reply[p->shift];
666
667 offset->offset = ((T2 - T1) + (T3 - T4)) / 2;
668 offset->delay = (T4 - T1) - (T3 - T2);
669 if (offset->delay < 0) {
670 interval = error_interval();
671 set_next(p, interval);
672 bb_info_msg("reply from %s: negative delay %f", addr, p->reply[p->shift].delay);
673 goto bail;
674 }
675 offset->error = (T2 - T1) - (T3 - T4);
Denys Vlasenkob1278a32009-11-24 16:03:47 +0100676// Can we use (T4 - OFFSET_1900_1970) instead of time(NULL)?
Adam Tkacb1585062009-11-22 03:43:55 +0100677 offset->rcvd = time(NULL);
678 offset->good = 1;
679
680 offset->status.leap = (msg.status & LI_MASK);
681 offset->status.precision = msg.precision;
682 offset->status.rootdelay = sfp_to_d(msg.rootdelay);
683 offset->status.rootdispersion = sfp_to_d(msg.dispersion);
684 offset->status.refid = ntohl(msg.refid);
685 offset->status.refid4 = msg.xmttime.fractionl;
686 offset->status.reftime = lfp_to_d(msg.reftime);
687 offset->status.poll = msg.ppoll;
688 offset->status.stratum = msg.stratum;
689
690 if (p->trustlevel < TRUSTLEVEL_PATHETIC)
691 interval = scale_interval(INTERVAL_QUERY_PATHETIC);
692 else if (p->trustlevel < TRUSTLEVEL_AGRESSIVE)
693 interval = scale_interval(INTERVAL_QUERY_AGRESSIVE);
694 else
695 interval = scale_interval(INTERVAL_QUERY_NORMAL);
696
697 set_next(p, interval);
698 p->state = STATE_REPLY_RECEIVED;
699
700 /* every received reply which we do not discard increases trust */
701 if (p->trustlevel < TRUSTLEVEL_MAX) {
Adam Tkacb1585062009-11-22 03:43:55 +0100702 p->trustlevel++;
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100703 if (p->trustlevel == TRUSTLEVEL_BADPEER)
704 bb_info_msg("peer %s now valid", addr);
Adam Tkacb1585062009-11-22 03:43:55 +0100705 }
706
707 bb_info_msg("reply from %s: offset %f delay %f, next query %ds", addr,
708 offset->offset, offset->delay, (int) interval);
709
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100710 update_peer_data(p);
Denys Vlasenko8d580c72009-11-23 16:27:16 +0100711 settime(offset->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
717 bail:
718 free(addr);
719}
720
721#if ENABLE_FEATURE_NTPD_SERVER
722static void
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100723recv_and_process_client_pkt(void /*int fd*/)
Adam Tkacb1585062009-11-22 03:43:55 +0100724{
Denys Vlasenkoca6c7e42009-11-24 07:07:42 +0100725 ssize_t size;
726 uint8_t version;
727 double rectime;
728 len_and_sockaddr *to;
729 struct sockaddr *from;
730 ntp_msg_t msg;
731 uint8_t query_status;
732 uint8_t query_ppoll;
733 l_fixedpt_t query_xmttime;
Adam Tkacb1585062009-11-22 03:43:55 +0100734
735 to = get_sock_lsa(G.listen_fd);
736 from = xzalloc(to->len);
737
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100738 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 +0100739 if (size != NTP_MSGSIZE_NOAUTH && size != NTP_MSGSIZE) {
Denys Vlasenkoca6c7e42009-11-24 07:07:42 +0100740 char *addr;
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100741 if (size < 0) {
742 if (errno == EAGAIN)
743 goto bail;
744 bb_perror_msg_and_die("recv_from_to");
745 }
Denys Vlasenkoca6c7e42009-11-24 07:07:42 +0100746 addr = xmalloc_sockaddr2dotted_noport(from);
Adam Tkacb1585062009-11-22 03:43:55 +0100747 bb_error_msg("malformed packet received from %s", addr);
748 free(addr);
749 goto bail;
750 }
751
Denys Vlasenkoca6c7e42009-11-24 07:07:42 +0100752 query_status = msg.status;
753 query_ppoll = msg.ppoll;
754 query_xmttime = msg.xmttime;
Adam Tkacb1585062009-11-22 03:43:55 +0100755
Denys Vlasenkoca6c7e42009-11-24 07:07:42 +0100756 /* Build a reply packet */
757 memset(&msg, 0, sizeof(msg));
758 msg.status = G.status.synced ? G.status.leap : LI_ALARM;
759 msg.status |= (query_status & VERSION_MASK);
760 msg.status |= ((query_status & MODE_MASK) == MODE_CLIENT) ?
Adam Tkacb1585062009-11-22 03:43:55 +0100761 MODE_SERVER : MODE_SYM_PAS;
Denys Vlasenkoca6c7e42009-11-24 07:07:42 +0100762 msg.stratum = G.status.stratum;
763 msg.ppoll = query_ppoll;
764 msg.precision = G.status.precision;
Denys Vlasenkob1278a32009-11-24 16:03:47 +0100765 rectime = gettime1900fp();
Denys Vlasenkoca6c7e42009-11-24 07:07:42 +0100766 msg.xmttime = msg.rectime = d_to_lfp(rectime);
767 msg.reftime = d_to_lfp(G.status.reftime);
Denys Vlasenkob1278a32009-11-24 16:03:47 +0100768 //msg.xmttime = d_to_lfp(gettime1900fp()); // = msg.rectime
Denys Vlasenkoca6c7e42009-11-24 07:07:42 +0100769 msg.orgtime = query_xmttime;
770 msg.rootdelay = d_to_sfp(G.status.rootdelay);
771 version = (query_status & VERSION_MASK); /* ... >> VERSION_SHIFT - done below instead */
772 msg.refid = (version > (3 << VERSION_SHIFT)) ? G.status.refid4 : G.status.refid;
Adam Tkacb1585062009-11-22 03:43:55 +0100773
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100774 /* We reply from the local address packet was sent to,
Adam Tkacb1585062009-11-22 03:43:55 +0100775 * this makes to/from look swapped here: */
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100776 sendmsg_wrap(G.listen_fd,
Denys Vlasenkoca6c7e42009-11-24 07:07:42 +0100777 /*from:*/ &to->u.sa, /*to:*/ from, /*addrlen:*/ to->len,
778 &msg, size);
Adam Tkacb1585062009-11-22 03:43:55 +0100779
780 bail:
781 free(to);
782 free(from);
783}
784#endif
785
786/* Upstream ntpd's options:
787 *
788 * -4 Force DNS resolution of host names to the IPv4 namespace.
789 * -6 Force DNS resolution of host names to the IPv6 namespace.
790 * -a Require cryptographic authentication for broadcast client,
791 * multicast client and symmetric passive associations.
792 * This is the default.
793 * -A Do not require cryptographic authentication for broadcast client,
794 * multicast client and symmetric passive associations.
795 * This is almost never a good idea.
796 * -b Enable the client to synchronize to broadcast servers.
797 * -c conffile
798 * Specify the name and path of the configuration file,
799 * default /etc/ntp.conf
800 * -d Specify debugging mode. This option may occur more than once,
801 * with each occurrence indicating greater detail of display.
802 * -D level
803 * Specify debugging level directly.
804 * -f driftfile
805 * Specify the name and path of the frequency file.
806 * This is the same operation as the "driftfile FILE"
807 * configuration command.
808 * -g Normally, ntpd exits with a message to the system log
809 * if the offset exceeds the panic threshold, which is 1000 s
810 * by default. This option allows the time to be set to any value
811 * without restriction; however, this can happen only once.
812 * If the threshold is exceeded after that, ntpd will exit
813 * with a message to the system log. This option can be used
814 * with the -q and -x options. See the tinker command for other options.
815 * -i jaildir
816 * Chroot the server to the directory jaildir. This option also implies
817 * that the server attempts to drop root privileges at startup
818 * (otherwise, chroot gives very little additional security).
819 * You may need to also specify a -u option.
820 * -k keyfile
821 * Specify the name and path of the symmetric key file,
822 * default /etc/ntp/keys. This is the same operation
823 * as the "keys FILE" configuration command.
824 * -l logfile
825 * Specify the name and path of the log file. The default
826 * is the system log file. This is the same operation as
827 * the "logfile FILE" configuration command.
828 * -L Do not listen to virtual IPs. The default is to listen.
829 * -n Don't fork.
830 * -N To the extent permitted by the operating system,
831 * run the ntpd at the highest priority.
832 * -p pidfile
833 * Specify the name and path of the file used to record the ntpd
834 * process ID. This is the same operation as the "pidfile FILE"
835 * configuration command.
836 * -P priority
837 * To the extent permitted by the operating system,
838 * run the ntpd at the specified priority.
839 * -q Exit the ntpd just after the first time the clock is set.
840 * This behavior mimics that of the ntpdate program, which is
841 * to be retired. The -g and -x options can be used with this option.
842 * Note: The kernel time discipline is disabled with this option.
843 * -r broadcastdelay
844 * Specify the default propagation delay from the broadcast/multicast
845 * server to this client. This is necessary only if the delay
846 * cannot be computed automatically by the protocol.
847 * -s statsdir
848 * Specify the directory path for files created by the statistics
849 * facility. This is the same operation as the "statsdir DIR"
850 * configuration command.
851 * -t key
852 * Add a key number to the trusted key list. This option can occur
853 * more than once.
854 * -u user[:group]
855 * Specify a user, and optionally a group, to switch to.
856 * -v variable
857 * -V variable
858 * Add a system variable listed by default.
859 * -x Normally, the time is slewed if the offset is less than the step
860 * threshold, which is 128 ms by default, and stepped if above
861 * the threshold. This option sets the threshold to 600 s, which is
862 * well within the accuracy window to set the clock manually.
863 * Note: since the slew rate of typical Unix kernels is limited
864 * to 0.5 ms/s, each second of adjustment requires an amortization
865 * interval of 2000 s. Thus, an adjustment as much as 600 s
866 * will take almost 14 days to complete. This option can be used
867 * with the -g and -q options. See the tinker command for other options.
868 * Note: The kernel time discipline is disabled with this option.
869 */
870
Adam Tkacb1585062009-11-22 03:43:55 +0100871/* By doing init in a separate function we decrease stack usage
872 * in main loop.
873 */
874static NOINLINE void ntp_init(char **argv)
875{
876 unsigned opts;
877 llist_t *peers;
878
Denys Vlasenkoca6c7e42009-11-24 07:07:42 +0100879 srandom(getpid());
880 /* tzset(); - why? it's called automatically when needed, no? */
Adam Tkacb1585062009-11-22 03:43:55 +0100881
882 if (getuid())
Denys Vlasenkob2e5fc32009-11-25 14:52:47 +0100883 bb_error_msg_and_die(bb_msg_you_must_be_root);
Adam Tkacb1585062009-11-22 03:43:55 +0100884
885 peers = NULL;
886 opt_complementary = "dd:p::"; /* d: counter, p: list */
887 opts = getopt32(argv,
Denys Vlasenkob2e5fc32009-11-25 14:52:47 +0100888 "ngqN" /* compat */
Adam Tkacb1585062009-11-22 03:43:55 +0100889 "p:"IF_FEATURE_NTPD_SERVER("l") /* NOT compat */
890 "d" /* compat */
Denys Vlasenkob2e5fc32009-11-25 14:52:47 +0100891 "46aAbLx", /* compat, ignored */
Adam Tkacb1585062009-11-22 03:43:55 +0100892 &peers, &G.verbose);
Denys Vlasenkob2e5fc32009-11-25 14:52:47 +0100893 if (!(opts & (OPT_p|OPT_l)))
894 bb_show_usage();
Denys Vlasenko160b9ca2009-11-27 02:35:15 +0100895 if (opts & OPT_g)
896 G.settime = 1;
897 while (peers)
898 add_peers(llist_pop(&peers));
899 if (!(opts & OPT_n)) {
900 bb_daemonize_or_rexec(DAEMON_DEVNULL_STDIO, argv);
901 logmode = LOGMODE_NONE;
902 }
Adam Tkacb1585062009-11-22 03:43:55 +0100903#if ENABLE_FEATURE_NTPD_SERVER
904 G.listen_fd = -1;
905 if (opts & OPT_l) {
906 G.listen_fd = create_and_bind_dgram_or_die(NULL, 123);
907 socket_want_pktinfo(G.listen_fd);
908 setsockopt(G.listen_fd, IPPROTO_IP, IP_TOS, &const_IPTOS_LOWDELAY, sizeof(const_IPTOS_LOWDELAY));
909 }
910#endif
Denys Vlasenkob2e5fc32009-11-25 14:52:47 +0100911 /* I hesitate to set -20 prio. -15 should be high enough for timekeeping */
912 if (opts & OPT_N)
913 setpriority(PRIO_PROCESS, 0, -15);
Adam Tkacb1585062009-11-22 03:43:55 +0100914
915 /* Set some globals */
916 {
917 int prec = 0;
918 int b;
919#if 0
920 struct timespec tp;
921 /* We can use sys_clock_getres but assuming 10ms tick should be fine */
922 clock_getres(CLOCK_REALTIME, &tp);
923 tp.tv_sec = 0;
924 tp.tv_nsec = 10000000;
925 b = 1000000000 / tp.tv_nsec; /* convert to Hz */
926#else
927 b = 100; /* b = 1000000000/10000000 = 100 */
928#endif
929 while (b > 1)
930 prec--, b >>= 1;
931 G.status.precision = prec;
932 }
933 G.scale = 1;
934 G.firstadj = 1;
935
936 bb_signals((1 << SIGTERM) | (1 << SIGINT), record_signo);
937 bb_signals((1 << SIGPIPE) | (1 << SIGHUP), SIG_IGN);
938}
939
940int ntpd_main(int argc UNUSED_PARAM, char **argv) MAIN_EXTERNALLY_VISIBLE;
941int ntpd_main(int argc UNUSED_PARAM, char **argv)
942{
943 struct globals g;
Adam Tkacb1585062009-11-22 03:43:55 +0100944 struct pollfd *pfd;
945 ntp_peer_t **idx2peer;
946
947 memset(&g, 0, sizeof(g));
948 SET_PTR_TO_GLOBALS(&g);
949
950 ntp_init(argv);
951
Denys Vlasenko8d580c72009-11-23 16:27:16 +0100952 {
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100953 unsigned cnt = g.peer_cnt;
Denys Vlasenko8d580c72009-11-23 16:27:16 +0100954 /* if ENABLE_FEATURE_NTPD_SERVER, + 1 for listen_fd: */
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100955 idx2peer = xzalloc(sizeof(void *) * (cnt + ENABLE_FEATURE_NTPD_SERVER));
956 pfd = xzalloc(sizeof(pfd[0]) * (cnt + ENABLE_FEATURE_NTPD_SERVER));
Denys Vlasenko8d580c72009-11-23 16:27:16 +0100957 }
Adam Tkacb1585062009-11-22 03:43:55 +0100958
959 while (!bb_got_signal) {
960 llist_t *item;
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100961 unsigned i, j;
Adam Tkacb1585062009-11-22 03:43:55 +0100962 unsigned sent_cnt, trial_cnt;
963 int nfds, timeout;
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100964 time_t cur_time, nextaction;
Adam Tkacb1585062009-11-22 03:43:55 +0100965
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100966 /* Nothing between here and poll() blocks for any significant time */
967
968 cur_time = time(NULL);
969 nextaction = cur_time + 3600;
Adam Tkacb1585062009-11-22 03:43:55 +0100970
971 i = 0;
972#if ENABLE_FEATURE_NTPD_SERVER
973 if (g.listen_fd != -1) {
974 pfd[0].fd = g.listen_fd;
975 pfd[0].events = POLLIN;
976 i++;
977 }
978#endif
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100979 /* Pass over peer list, send requests, time out on receives */
Adam Tkacb1585062009-11-22 03:43:55 +0100980 sent_cnt = trial_cnt = 0;
981 for (item = g.ntp_peers; item != NULL; item = item->link) {
982 ntp_peer_t *p = (ntp_peer_t *) item->data;
983
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100984 if (p->next != 0 && p->next <= cur_time) {
985 /* Time to send new req */
Adam Tkacb1585062009-11-22 03:43:55 +0100986 trial_cnt++;
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100987 if (send_query_to_peer(p) == 0)
Adam Tkacb1585062009-11-22 03:43:55 +0100988 sent_cnt++;
989 }
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100990 if (p->deadline != 0 && p->deadline <= cur_time) {
991 /* Timed out waiting for reply */
Adam Tkacb1585062009-11-22 03:43:55 +0100992 char *addr = xmalloc_sockaddr2dotted_noport(&p->lsa->u.sa);
993
994 timeout = error_interval();
995 bb_info_msg("no reply from %s received in time, "
996 "next query %ds", addr, timeout);
997 if (p->trustlevel >= TRUSTLEVEL_BADPEER) {
998 p->trustlevel /= 2;
999 if (p->trustlevel < TRUSTLEVEL_BADPEER)
1000 bb_info_msg("peer %s now invalid", addr);
1001 }
1002 free(addr);
1003
1004 set_next(p, timeout);
1005 }
1006
Denys Vlasenko363e89b2009-11-24 14:04:15 +01001007 if (p->next != 0 && p->next < nextaction)
1008 nextaction = p->next;
1009 if (p->deadline != 0 && p->deadline < nextaction)
1010 nextaction = p->deadline;
1011
Adam Tkacb1585062009-11-22 03:43:55 +01001012 if (p->state == STATE_QUERY_SENT) {
Denys Vlasenko363e89b2009-11-24 14:04:15 +01001013 /* Wait for reply from this peer */
Adam Tkacb1585062009-11-22 03:43:55 +01001014 pfd[i].fd = p->query.fd;
1015 pfd[i].events = POLLIN;
Denys Vlasenko363e89b2009-11-24 14:04:15 +01001016 idx2peer[i] = p;
Adam Tkacb1585062009-11-22 03:43:55 +01001017 i++;
1018 }
1019 }
1020
Denys Vlasenko8d580c72009-11-23 16:27:16 +01001021 if ((trial_cnt > 0 && sent_cnt == 0) || g.peer_cnt == 0)
Denys Vlasenko363e89b2009-11-24 14:04:15 +01001022 settime(0); /* no good peers, don't wait */
Adam Tkacb1585062009-11-22 03:43:55 +01001023
Denys Vlasenko363e89b2009-11-24 14:04:15 +01001024 timeout = nextaction - cur_time;
Adam Tkacb1585062009-11-22 03:43:55 +01001025 if (timeout < 0)
1026 timeout = 0;
1027
Denys Vlasenko363e89b2009-11-24 14:04:15 +01001028 /* Here we may block */
Adam Tkacb1585062009-11-22 03:43:55 +01001029 if (g.verbose)
1030 bb_error_msg("entering poll %u secs", timeout);
1031 nfds = poll(pfd, i, timeout * 1000);
Denys Vlasenko363e89b2009-11-24 14:04:15 +01001032 if (nfds <= 0)
1033 continue;
Adam Tkacb1585062009-11-22 03:43:55 +01001034
Denys Vlasenko363e89b2009-11-24 14:04:15 +01001035 /* Process any received packets */
Adam Tkacb1585062009-11-22 03:43:55 +01001036 j = 0;
1037#if ENABLE_FEATURE_NTPD_SERVER
Denys Vlasenko363e89b2009-11-24 14:04:15 +01001038 if (g.listen_fd != -1) {
1039 if (pfd[0].revents /* & (POLLIN|POLLERR)*/) {
Adam Tkacb1585062009-11-22 03:43:55 +01001040 nfds--;
Denys Vlasenko363e89b2009-11-24 14:04:15 +01001041 recv_and_process_client_pkt(/*g.listen_fd*/);
Adam Tkacb1585062009-11-22 03:43:55 +01001042 }
Denys Vlasenko363e89b2009-11-24 14:04:15 +01001043 j = 1;
Adam Tkacb1585062009-11-22 03:43:55 +01001044 }
1045#endif
Denys Vlasenko363e89b2009-11-24 14:04:15 +01001046 for (; nfds != 0 && j < i; j++) {
1047 if (pfd[j].revents /* & (POLLIN|POLLERR)*/) {
Adam Tkacb1585062009-11-22 03:43:55 +01001048 nfds--;
Denys Vlasenko363e89b2009-11-24 14:04:15 +01001049 recv_and_process_peer_pkt(idx2peer[j]);
Adam Tkacb1585062009-11-22 03:43:55 +01001050 }
1051 }
1052 } /* while (!bb_got_signal) */
1053
1054 kill_myself_with_sig(bb_got_signal);
1055}