blob: 4ad44e4f35bbfbfb1a1f9460505a3d668ba9d9b9 [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 *
Denys Vlasenko0ef64bd2010-08-16 20:14:46 +02006 * Licensed under GPLv2, see file LICENSE in this source tree.
Adam Tkacb1585062009-11-22 03:43:55 +01007 */
Adam Tkacb1585062009-11-22 03:43:55 +01008#include "libbb.h"
9#include <netinet/ip.h> /* For IPTOS_LOWDELAY definition */
Denys Vlasenkob2e5fc32009-11-25 14:52:47 +010010#ifndef IPTOS_LOWDELAY
11# define IPTOS_LOWDELAY 0x10
12#endif
Adam Tkacb1585062009-11-22 03:43:55 +010013#ifndef IP_PKTINFO
14# error "Sorry, your kernel has to support IP_PKTINFO"
15#endif
16
Denys Vlasenko907647f2009-12-02 23:17:45 +010017
18/* Sync to peers every N secs */
Denys Vlasenkoafa2d332009-12-17 23:29:33 +010019#define INTERVAL_QUERY_NORMAL 30
20#define INTERVAL_QUERY_PATHETIC 60
21#define INTERVAL_QUERY_AGRESSIVE 5
Adam Tkacb1585062009-11-22 03:43:55 +010022
Denys Vlasenko907647f2009-12-02 23:17:45 +010023/* Bad if *less than* TRUSTLEVEL_BADPEER */
Denys Vlasenkoafa2d332009-12-17 23:29:33 +010024#define TRUSTLEVEL_BADPEER 6
25#define TRUSTLEVEL_PATHETIC 2
26#define TRUSTLEVEL_AGRESSIVE 8
27#define TRUSTLEVEL_MAX 10
Adam Tkacb1585062009-11-22 03:43:55 +010028
Denys Vlasenkoafa2d332009-12-17 23:29:33 +010029#define QSCALE_OFF_MIN 0.05
30#define QSCALE_OFF_MAX 0.50
Adam Tkacb1585062009-11-22 03:43:55 +010031
Denys Vlasenkod2fe69f2009-12-30 18:38:05 +010032/* Single query might take N secs max */
Denys Vlasenkoafa2d332009-12-17 23:29:33 +010033#define QUERYTIME_MAX 15
Denys Vlasenko907647f2009-12-02 23:17:45 +010034/* Min offset for settime at start. "man ntpd" says it's 128 ms */
Denys Vlasenkoafa2d332009-12-17 23:29:33 +010035#define STEPTIME_MIN_OFFSET 0.128
Adam Tkacb1585062009-11-22 03:43:55 +010036
Adam Tkacb1585062009-11-22 03:43:55 +010037typedef struct {
38 uint32_t int_partl;
39 uint32_t fractionl;
40} l_fixedpt_t;
41
42typedef struct {
43 uint16_t int_parts;
44 uint16_t fractions;
45} s_fixedpt_t;
46
Denys Vlasenkoca6c7e42009-11-24 07:07:42 +010047enum {
48 NTP_DIGESTSIZE = 16,
49 NTP_MSGSIZE_NOAUTH = 48,
50 NTP_MSGSIZE = (NTP_MSGSIZE_NOAUTH + 4 + NTP_DIGESTSIZE),
51};
Adam Tkacb1585062009-11-22 03:43:55 +010052
53typedef struct {
Denys Vlasenko386960a2009-12-02 01:51:24 +010054 uint8_t m_status; /* status of local clock and leap info */
55 uint8_t m_stratum; /* stratum level */
56 uint8_t m_ppoll; /* poll value */
Denys Vlasenkod2fe69f2009-12-30 18:38:05 +010057 int8_t m_precision_exp;
Denys Vlasenko386960a2009-12-02 01:51:24 +010058 s_fixedpt_t m_rootdelay;
59 s_fixedpt_t m_dispersion;
60 uint32_t m_refid;
61 l_fixedpt_t m_reftime;
62 l_fixedpt_t m_orgtime;
63 l_fixedpt_t m_rectime;
64 l_fixedpt_t m_xmttime;
65 uint32_t m_keyid;
66 uint8_t m_digest[NTP_DIGESTSIZE];
Denys Vlasenkod2fe69f2009-12-30 18:38:05 +010067} msg_t;
Adam Tkacb1585062009-11-22 03:43:55 +010068
Adam Tkacb1585062009-11-22 03:43:55 +010069enum {
Denys Vlasenkoafa2d332009-12-17 23:29:33 +010070 NTP_VERSION = 4,
71 NTP_MAXSTRATUM = 15,
Adam Tkacb1585062009-11-22 03:43:55 +010072
73 /* Status Masks */
Denys Vlasenkoafa2d332009-12-17 23:29:33 +010074 MODE_MASK = (7 << 0),
75 VERSION_MASK = (7 << 3),
76 VERSION_SHIFT = 3,
77 LI_MASK = (3 << 6),
Adam Tkacb1585062009-11-22 03:43:55 +010078
Denys Vlasenkod2fe69f2009-12-30 18:38:05 +010079 /* Leap Second Codes (high order two bits of m_status) */
80 LI_NOWARNING = (0 << 6), /* no warning */
81 LI_PLUSSEC = (1 << 6), /* add a second (61 seconds) */
82 LI_MINUSSEC = (2 << 6), /* minus a second (59 seconds) */
83 LI_ALARM = (3 << 6), /* alarm condition */
84
Adam Tkacb1585062009-11-22 03:43:55 +010085 /* Mode values */
Denys Vlasenkoafa2d332009-12-17 23:29:33 +010086 MODE_RES0 = 0, /* reserved */
87 MODE_SYM_ACT = 1, /* symmetric active */
88 MODE_SYM_PAS = 2, /* symmetric passive */
89 MODE_CLIENT = 3, /* client */
90 MODE_SERVER = 4, /* server */
91 MODE_BROADCAST = 5, /* broadcast */
92 MODE_RES1 = 6, /* reserved for NTP control message */
93 MODE_RES2 = 7, /* reserved for private use */
Adam Tkacb1585062009-11-22 03:43:55 +010094};
95
Denys Vlasenkob1278a32009-11-24 16:03:47 +010096#define OFFSET_1900_1970 2208988800UL /* 1970 - 1900 in seconds */
Adam Tkacb1585062009-11-22 03:43:55 +010097
Denys Vlasenko386960a2009-12-02 01:51:24 +010098typedef struct {
Denys Vlasenkoafa2d332009-12-17 23:29:33 +010099 double d_offset;
100 double d_delay;
101 //UNUSED: double d_error;
Denys Vlasenko6879a7a2009-12-18 18:50:29 +0100102 time_t d_rcv_time;
Denys Vlasenkoafa2d332009-12-17 23:29:33 +0100103 uint32_t d_refid4;
104 uint8_t d_leap;
105 uint8_t d_stratum;
106 uint8_t d_good;
Denys Vlasenkod2fe69f2009-12-30 18:38:05 +0100107} datapoint_t;
Denys Vlasenko386960a2009-12-02 01:51:24 +0100108
Denys Vlasenkoafa2d332009-12-17 23:29:33 +0100109#define NUM_DATAPOINTS 8
Denys Vlasenko386960a2009-12-02 01:51:24 +0100110typedef struct {
Denys Vlasenkoafa2d332009-12-17 23:29:33 +0100111 len_and_sockaddr *p_lsa;
112 char *p_dotted;
113 /* When to send new query (if p_fd == -1)
114 * or when receive times out (if p_fd >= 0): */
115 time_t next_action_time;
116 int p_fd;
117 uint8_t p_datapoint_idx;
Denys Vlasenkod2fe69f2009-12-30 18:38:05 +0100118 uint8_t p_trustlevel;
Denys Vlasenkoafa2d332009-12-17 23:29:33 +0100119 double p_xmttime;
Denys Vlasenkod2fe69f2009-12-30 18:38:05 +0100120 datapoint_t update;
121 datapoint_t p_datapoint[NUM_DATAPOINTS];
122 msg_t p_xmt_msg;
123} peer_t;
Adam Tkacb1585062009-11-22 03:43:55 +0100124
Denys Vlasenko8d580c72009-11-23 16:27:16 +0100125enum {
126 OPT_n = (1 << 0),
Denys Vlasenko907647f2009-12-02 23:17:45 +0100127 OPT_q = (1 << 1),
128 OPT_N = (1 << 2),
129 OPT_x = (1 << 3),
Denys Vlasenko8d580c72009-11-23 16:27:16 +0100130 /* Insert new options above this line. */
131 /* Non-compat options: */
Denys Vlasenkob2e5fc32009-11-25 14:52:47 +0100132 OPT_p = (1 << 4),
133 OPT_l = (1 << 5) * ENABLE_FEATURE_NTPD_SERVER,
Denys Vlasenko8d580c72009-11-23 16:27:16 +0100134};
135
Adam Tkacb1585062009-11-22 03:43:55 +0100136
137struct globals {
Denys Vlasenkod2fe69f2009-12-30 18:38:05 +0100138 /* total round trip delay to currently selected reference clock */
Denys Vlasenkoafa2d332009-12-17 23:29:33 +0100139 double rootdelay;
Denys Vlasenkod2fe69f2009-12-30 18:38:05 +0100140 /* reference timestamp: time when the system clock was last set or corrected */
Denys Vlasenkoafa2d332009-12-17 23:29:33 +0100141 double reftime;
142 llist_t *ntp_peers;
Adam Tkacb1585062009-11-22 03:43:55 +0100143#if ENABLE_FEATURE_NTPD_SERVER
Denys Vlasenkoafa2d332009-12-17 23:29:33 +0100144 int listen_fd;
Adam Tkacb1585062009-11-22 03:43:55 +0100145#endif
Denys Vlasenkoafa2d332009-12-17 23:29:33 +0100146 unsigned verbose;
147 unsigned peer_cnt;
148 unsigned scale;
149 uint32_t refid;
150 uint32_t refid4;
151 uint8_t synced;
152 uint8_t leap;
Denys Vlasenko6879a7a2009-12-18 18:50:29 +0100153#define G_precision_exp -6
154// int8_t precision_exp;
Denys Vlasenkoafa2d332009-12-17 23:29:33 +0100155 uint8_t stratum;
156 uint8_t time_was_stepped;
157 uint8_t first_adj_done;
Adam Tkacb1585062009-11-22 03:43:55 +0100158};
159#define G (*ptr_to_globals)
160
Adam Tkacb1585062009-11-22 03:43:55 +0100161static const int const_IPTOS_LOWDELAY = IPTOS_LOWDELAY;
162
163
164static void
Denys Vlasenkod2fe69f2009-12-30 18:38:05 +0100165set_next(peer_t *p, unsigned t)
Adam Tkacb1585062009-11-22 03:43:55 +0100166{
Denys Vlasenko907647f2009-12-02 23:17:45 +0100167 p->next_action_time = time(NULL) + t;
Adam Tkacb1585062009-11-22 03:43:55 +0100168}
169
170static void
Denys Vlasenko907647f2009-12-02 23:17:45 +0100171add_peers(char *s)
Adam Tkacb1585062009-11-22 03:43:55 +0100172{
Denys Vlasenkod2fe69f2009-12-30 18:38:05 +0100173 peer_t *p;
Adam Tkacb1585062009-11-22 03:43:55 +0100174
175 p = xzalloc(sizeof(*p));
Denys Vlasenkoafa2d332009-12-17 23:29:33 +0100176 p->p_lsa = xhost2sockaddr(s, 123);
177 p->p_dotted = xmalloc_sockaddr2dotted_noport(&p->p_lsa->u.sa);
178 p->p_fd = -1;
Denys Vlasenkod2fe69f2009-12-30 18:38:05 +0100179 p->p_xmt_msg.m_status = MODE_CLIENT | (NTP_VERSION << 3);
180 p->p_trustlevel = TRUSTLEVEL_PATHETIC;
Denys Vlasenko907647f2009-12-02 23:17:45 +0100181 p->next_action_time = time(NULL); /* = set_next(p, 0); */
Adam Tkacb1585062009-11-22 03:43:55 +0100182
183 llist_add_to(&G.ntp_peers, p);
184 G.peer_cnt++;
185}
186
187static double
Denys Vlasenko907647f2009-12-02 23:17:45 +0100188gettime1900d(void)
Adam Tkacb1585062009-11-22 03:43:55 +0100189{
Denys Vlasenkoca6c7e42009-11-24 07:07:42 +0100190 struct timeval tv;
Adam Tkacb1585062009-11-22 03:43:55 +0100191 gettimeofday(&tv, NULL); /* never fails */
Denys Vlasenkob1278a32009-11-24 16:03:47 +0100192 return (tv.tv_sec + 1.0e-6 * tv.tv_usec + OFFSET_1900_1970);
Adam Tkacb1585062009-11-22 03:43:55 +0100193}
194
Adam Tkacb1585062009-11-22 03:43:55 +0100195static void
196d_to_tv(double d, struct timeval *tv)
197{
198 tv->tv_sec = (long)d;
199 tv->tv_usec = (d - tv->tv_sec) * 1000000;
200}
201
202static double
203lfp_to_d(l_fixedpt_t lfp)
204{
Denys Vlasenkoca6c7e42009-11-24 07:07:42 +0100205 double ret;
Adam Tkacb1585062009-11-22 03:43:55 +0100206 lfp.int_partl = ntohl(lfp.int_partl);
207 lfp.fractionl = ntohl(lfp.fractionl);
Denys Vlasenkoca6c7e42009-11-24 07:07:42 +0100208 ret = (double)lfp.int_partl + ((double)lfp.fractionl / UINT_MAX);
209 return ret;
210}
211
Denys Vlasenko386960a2009-12-02 01:51:24 +0100212#if 0 //UNUSED
Denys Vlasenkoca6c7e42009-11-24 07:07:42 +0100213static double
214sfp_to_d(s_fixedpt_t sfp)
215{
216 double ret;
217 sfp.int_parts = ntohs(sfp.int_parts);
218 sfp.fractions = ntohs(sfp.fractions);
219 ret = (double)sfp.int_parts + ((double)sfp.fractions / USHRT_MAX);
Adam Tkacb1585062009-11-22 03:43:55 +0100220 return ret;
221}
Denys Vlasenko386960a2009-12-02 01:51:24 +0100222#endif
Adam Tkacb1585062009-11-22 03:43:55 +0100223
224#if ENABLE_FEATURE_NTPD_SERVER
225static l_fixedpt_t
226d_to_lfp(double d)
227{
Denys Vlasenkoca6c7e42009-11-24 07:07:42 +0100228 l_fixedpt_t lfp;
229 lfp.int_partl = (uint32_t)d;
230 lfp.fractionl = (uint32_t)((d - lfp.int_partl) * UINT_MAX);
231 lfp.int_partl = htonl(lfp.int_partl);
232 lfp.fractionl = htonl(lfp.fractionl);
Adam Tkacb1585062009-11-22 03:43:55 +0100233 return lfp;
234}
Adam Tkacb1585062009-11-22 03:43:55 +0100235
Adam Tkacb1585062009-11-22 03:43:55 +0100236static s_fixedpt_t
237d_to_sfp(double d)
238{
Denys Vlasenkoca6c7e42009-11-24 07:07:42 +0100239 s_fixedpt_t sfp;
240 sfp.int_parts = (uint16_t)d;
241 sfp.fractions = (uint16_t)((d - sfp.int_parts) * USHRT_MAX);
242 sfp.int_parts = htons(sfp.int_parts);
243 sfp.fractions = htons(sfp.fractions);
Adam Tkacb1585062009-11-22 03:43:55 +0100244 return sfp;
245}
246#endif
247
Denys Vlasenko386960a2009-12-02 01:51:24 +0100248static unsigned
Adam Tkacb1585062009-11-22 03:43:55 +0100249error_interval(void)
250{
Denys Vlasenko386960a2009-12-02 01:51:24 +0100251 unsigned interval, r;
Adam Tkacb1585062009-11-22 03:43:55 +0100252 interval = INTERVAL_QUERY_PATHETIC * QSCALE_OFF_MAX / QSCALE_OFF_MIN;
Denys Vlasenko386960a2009-12-02 01:51:24 +0100253 r = (unsigned)random() % (unsigned)(interval / 10);
Adam Tkacb1585062009-11-22 03:43:55 +0100254 return (interval + r);
255}
256
257static int
Denys Vlasenko386960a2009-12-02 01:51:24 +0100258do_sendto(int fd,
Adam Tkacb1585062009-11-22 03:43:55 +0100259 const struct sockaddr *from, const struct sockaddr *to, socklen_t addrlen,
Denys Vlasenkod2fe69f2009-12-30 18:38:05 +0100260 msg_t *msg, ssize_t len)
Adam Tkacb1585062009-11-22 03:43:55 +0100261{
262 ssize_t ret;
263
264 errno = 0;
265 if (!from) {
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100266 ret = sendto(fd, msg, len, MSG_DONTWAIT, to, addrlen);
Adam Tkacb1585062009-11-22 03:43:55 +0100267 } else {
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100268 ret = send_to_from(fd, msg, len, MSG_DONTWAIT, to, from, addrlen);
Adam Tkacb1585062009-11-22 03:43:55 +0100269 }
270 if (ret != len) {
271 bb_perror_msg("send failed");
272 return -1;
273 }
274 return 0;
275}
276
277static int
Denys Vlasenkod2fe69f2009-12-30 18:38:05 +0100278send_query_to_peer(peer_t *p)
Adam Tkacb1585062009-11-22 03:43:55 +0100279{
Denys Vlasenkob1278a32009-11-24 16:03:47 +0100280 // Why do we need to bind()?
281 // See what happens when we don't bind:
282 //
283 // socket(PF_INET, SOCK_DGRAM, IPPROTO_IP) = 3
284 // setsockopt(3, SOL_IP, IP_TOS, [16], 4) = 0
285 // gettimeofday({1259071266, 327885}, NULL) = 0
286 // sendto(3, "xxx", 48, MSG_DONTWAIT, {sa_family=AF_INET, sin_port=htons(123), sin_addr=inet_addr("10.34.32.125")}, 16) = 48
287 // ^^^ we sent it from some source port picked by kernel.
288 // time(NULL) = 1259071266
289 // write(2, "ntpd: entering poll 15 secs\n", 28) = 28
290 // poll([{fd=3, events=POLLIN}], 1, 15000) = 1 ([{fd=3, revents=POLLIN}])
291 // recv(3, "yyy", 68, MSG_DONTWAIT) = 48
292 // ^^^ this recv will receive packets to any local port!
293 //
294 // Uncomment this and use strace to see it in action:
295#define PROBE_LOCAL_ADDR // { len_and_sockaddr lsa; lsa.len = LSA_SIZEOF_SA; getsockname(p->query.fd, &lsa.u.sa, &lsa.len); }
296
Denys Vlasenkoafa2d332009-12-17 23:29:33 +0100297 if (p->p_fd == -1) {
Denys Vlasenkob1278a32009-11-24 16:03:47 +0100298 int fd, family;
299 len_and_sockaddr *local_lsa;
300
Denys Vlasenkoafa2d332009-12-17 23:29:33 +0100301 family = p->p_lsa->u.sa.sa_family;
302 p->p_fd = fd = xsocket_type(&local_lsa, family, SOCK_DGRAM);
Denys Vlasenkob1278a32009-11-24 16:03:47 +0100303 /* local_lsa has "null" address and port 0 now.
304 * bind() ensures we have a *particular port* selected by kernel
Denys Vlasenkoafa2d332009-12-17 23:29:33 +0100305 * and remembered in p->p_fd, thus later recv(p->p_fd)
Denys Vlasenkob1278a32009-11-24 16:03:47 +0100306 * receives only packets sent to this port.
307 */
308 PROBE_LOCAL_ADDR
309 xbind(fd, &local_lsa->u.sa, local_lsa->len);
310 PROBE_LOCAL_ADDR
Adam Tkacb1585062009-11-22 03:43:55 +0100311#if ENABLE_FEATURE_IPV6
Denys Vlasenkob1278a32009-11-24 16:03:47 +0100312 if (family == AF_INET)
Adam Tkacb1585062009-11-22 03:43:55 +0100313#endif
Denys Vlasenkob1278a32009-11-24 16:03:47 +0100314 setsockopt(fd, IPPROTO_IP, IP_TOS, &const_IPTOS_LOWDELAY, sizeof(const_IPTOS_LOWDELAY));
315 free(local_lsa);
Adam Tkacb1585062009-11-22 03:43:55 +0100316 }
317
318 /*
319 * Send out a random 64-bit number as our transmit time. The NTP
320 * server will copy said number into the originate field on the
321 * response that it sends us. This is totally legal per the SNTP spec.
322 *
323 * The impact of this is two fold: we no longer send out the current
324 * system time for the world to see (which may aid an attacker), and
325 * it gives us a (not very secure) way of knowing that we're not
326 * getting spoofed by an attacker that can't capture our traffic
327 * but can spoof packets from the NTP server we're communicating with.
328 *
329 * Save the real transmit timestamp locally.
330 */
Denys Vlasenkod2fe69f2009-12-30 18:38:05 +0100331 p->p_xmt_msg.m_xmttime.int_partl = random();
332 p->p_xmt_msg.m_xmttime.fractionl = random();
Denys Vlasenkoafa2d332009-12-17 23:29:33 +0100333 p->p_xmttime = gettime1900d();
Adam Tkacb1585062009-11-22 03:43:55 +0100334
Denys Vlasenkoafa2d332009-12-17 23:29:33 +0100335 if (do_sendto(p->p_fd, /*from:*/ NULL, /*to:*/ &p->p_lsa->u.sa, /*addrlen:*/ p->p_lsa->len,
Denys Vlasenkod2fe69f2009-12-30 18:38:05 +0100336 &p->p_xmt_msg, NTP_MSGSIZE_NOAUTH) == -1
Denys Vlasenko386960a2009-12-02 01:51:24 +0100337 ) {
Denys Vlasenkoafa2d332009-12-17 23:29:33 +0100338 close(p->p_fd);
339 p->p_fd = -1;
Adam Tkacb1585062009-11-22 03:43:55 +0100340 set_next(p, INTERVAL_QUERY_PATHETIC);
341 return -1;
342 }
343
Denys Vlasenko386960a2009-12-02 01:51:24 +0100344 if (G.verbose)
Denys Vlasenkoafa2d332009-12-17 23:29:33 +0100345 bb_error_msg("sent query to %s", p->p_dotted);
Denys Vlasenko907647f2009-12-02 23:17:45 +0100346 set_next(p, QUERYTIME_MAX);
Adam Tkacb1585062009-11-22 03:43:55 +0100347
348 return 0;
349}
350
Denys Vlasenko907647f2009-12-02 23:17:45 +0100351
352/* Time is stepped only once, when the first packet from a peer is received.
353 */
354static void
355step_time_once(double offset)
356{
Denys Vlasenko6879a7a2009-12-18 18:50:29 +0100357 double dtime;
Denys Vlasenko907647f2009-12-02 23:17:45 +0100358 llist_t *item;
359 struct timeval tv;
360 char buf[80];
361 time_t tval;
362
Denys Vlasenkoafa2d332009-12-17 23:29:33 +0100363 if (G.time_was_stepped)
Denys Vlasenko907647f2009-12-02 23:17:45 +0100364 goto bail;
Denys Vlasenkoafa2d332009-12-17 23:29:33 +0100365 G.time_was_stepped = 1;
Denys Vlasenko907647f2009-12-02 23:17:45 +0100366
367 /* if the offset is small, don't step, slew (later) */
368 if (offset < STEPTIME_MIN_OFFSET && offset > -STEPTIME_MIN_OFFSET)
369 goto bail;
370
371 gettimeofday(&tv, NULL); /* never fails */
Denys Vlasenko6879a7a2009-12-18 18:50:29 +0100372 dtime = offset + tv.tv_sec;
373 dtime += 1.0e-6 * tv.tv_usec;
374 d_to_tv(dtime, &tv);
Denys Vlasenko907647f2009-12-02 23:17:45 +0100375
376 if (settimeofday(&tv, NULL) == -1)
377 bb_perror_msg_and_die("settimeofday");
378
379 tval = tv.tv_sec;
380 strftime(buf, sizeof(buf), "%a %b %e %H:%M:%S %Z %Y", localtime(&tval));
381
382 bb_error_msg("setting clock to %s (offset %fs)", buf, offset);
383
384 for (item = G.ntp_peers; item != NULL; item = item->link) {
Denys Vlasenkod2fe69f2009-12-30 18:38:05 +0100385 peer_t *p = (peer_t *) item->data;
Denys Vlasenko6879a7a2009-12-18 18:50:29 +0100386 p->next_action_time -= (time_t)offset;
Denys Vlasenko907647f2009-12-02 23:17:45 +0100387 }
388
389 bail:
390 if (option_mask32 & OPT_q)
391 exit(0);
392}
393
394
395/* Time is periodically slewed when we collect enough
396 * good data points.
397 */
Adam Tkacb1585062009-11-22 03:43:55 +0100398static int
Denys Vlasenko386960a2009-12-02 01:51:24 +0100399compare_offsets(const void *aa, const void *bb)
Adam Tkacb1585062009-11-22 03:43:55 +0100400{
Denys Vlasenkod2fe69f2009-12-30 18:38:05 +0100401 const peer_t *const *a = aa;
402 const peer_t *const *b = bb;
Denys Vlasenkoafa2d332009-12-17 23:29:33 +0100403 if ((*a)->update.d_offset < (*b)->update.d_offset)
Adam Tkacb1585062009-11-22 03:43:55 +0100404 return -1;
Denys Vlasenkoafa2d332009-12-17 23:29:33 +0100405 return ((*a)->update.d_offset > (*b)->update.d_offset);
Adam Tkacb1585062009-11-22 03:43:55 +0100406}
Denys Vlasenko907647f2009-12-02 23:17:45 +0100407static unsigned
Adam Tkacb1585062009-11-22 03:43:55 +0100408updated_scale(double offset)
409{
410 if (offset < 0)
411 offset = -offset;
Adam Tkacb1585062009-11-22 03:43:55 +0100412 if (offset > QSCALE_OFF_MAX)
413 return 1;
414 if (offset < QSCALE_OFF_MIN)
415 return QSCALE_OFF_MAX / QSCALE_OFF_MIN;
416 return QSCALE_OFF_MAX / offset;
417}
Adam Tkacb1585062009-11-22 03:43:55 +0100418static void
Denys Vlasenko386960a2009-12-02 01:51:24 +0100419slew_time(void)
Adam Tkacb1585062009-11-22 03:43:55 +0100420{
Denys Vlasenko4bd51892009-12-02 13:43:06 +0100421 llist_t *item;
422 double offset_median;
423 struct timeval tv;
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100424
Denys Vlasenko386960a2009-12-02 01:51:24 +0100425 {
Denys Vlasenkod2fe69f2009-12-30 18:38:05 +0100426 peer_t **peers = xzalloc(sizeof(peers[0]) * G.peer_cnt);
Denys Vlasenko4bd51892009-12-02 13:43:06 +0100427 unsigned goodpeer_cnt = 0;
Denys Vlasenko386960a2009-12-02 01:51:24 +0100428 unsigned middle;
Denys Vlasenko386960a2009-12-02 01:51:24 +0100429
430 for (item = G.ntp_peers; item != NULL; item = item->link) {
Denys Vlasenkod2fe69f2009-12-30 18:38:05 +0100431 peer_t *p = (peer_t *) item->data;
432 if (p->p_trustlevel < TRUSTLEVEL_BADPEER)
Denys Vlasenko386960a2009-12-02 01:51:24 +0100433 continue;
Denys Vlasenkoafa2d332009-12-17 23:29:33 +0100434 if (!p->update.d_good) {
Denys Vlasenko907647f2009-12-02 23:17:45 +0100435 free(peers);
Denys Vlasenko4bd51892009-12-02 13:43:06 +0100436 return;
Denys Vlasenko907647f2009-12-02 23:17:45 +0100437 }
Denys Vlasenko4bd51892009-12-02 13:43:06 +0100438 peers[goodpeer_cnt++] = p;
Denys Vlasenko386960a2009-12-02 01:51:24 +0100439 }
440
Denys Vlasenko4bd51892009-12-02 13:43:06 +0100441 if (goodpeer_cnt == 0) {
442 free(peers);
443 goto clear_good;
444 }
Denys Vlasenko386960a2009-12-02 01:51:24 +0100445
Denys Vlasenko4bd51892009-12-02 13:43:06 +0100446 qsort(peers, goodpeer_cnt, sizeof(peers[0]), compare_offsets);
447
448 middle = goodpeer_cnt / 2;
449 if (middle != 0 && (goodpeer_cnt & 1) == 0) {
Denys Vlasenkoafa2d332009-12-17 23:29:33 +0100450 offset_median = (peers[middle-1]->update.d_offset + peers[middle]->update.d_offset) / 2;
451 G.rootdelay = (peers[middle-1]->update.d_delay + peers[middle]->update.d_delay) / 2;
452 G.stratum = 1 + MAX(peers[middle-1]->update.d_stratum, peers[middle]->update.d_stratum);
Denys Vlasenko386960a2009-12-02 01:51:24 +0100453 } else {
Denys Vlasenkoafa2d332009-12-17 23:29:33 +0100454 offset_median = peers[middle]->update.d_offset;
455 G.rootdelay = peers[middle]->update.d_delay;
456 G.stratum = 1 + peers[middle]->update.d_stratum;
Denys Vlasenko386960a2009-12-02 01:51:24 +0100457 }
Denys Vlasenkoafa2d332009-12-17 23:29:33 +0100458 G.leap = peers[middle]->update.d_leap;
459 G.refid4 = peers[middle]->update.d_refid4;
Denys Vlasenko386960a2009-12-02 01:51:24 +0100460 G.refid =
461#if ENABLE_FEATURE_IPV6
Denys Vlasenkoafa2d332009-12-17 23:29:33 +0100462 peers[middle]->p_lsa->u.sa.sa_family != AF_INET ?
Denys Vlasenko386960a2009-12-02 01:51:24 +0100463 G.refid4 :
464#endif
Denys Vlasenkoafa2d332009-12-17 23:29:33 +0100465 peers[middle]->p_lsa->u.sin.sin_addr.s_addr;
Denys Vlasenko386960a2009-12-02 01:51:24 +0100466 free(peers);
Adam Tkacb1585062009-11-22 03:43:55 +0100467 }
Denys Vlasenko907647f2009-12-02 23:17:45 +0100468//TODO: if (offset_median > BIG) step_time(offset_median)?
Adam Tkacb1585062009-11-22 03:43:55 +0100469
Denys Vlasenko907647f2009-12-02 23:17:45 +0100470 G.scale = updated_scale(offset_median);
471
472 bb_error_msg("adjusting clock by %fs, our stratum is %u, time scale %u",
473 offset_median, G.stratum, G.scale);
Adam Tkacb1585062009-11-22 03:43:55 +0100474
Denys Vlasenkofae9f492009-12-01 02:32:01 +0100475 errno = 0;
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100476 d_to_tv(offset_median, &tv);
Denys Vlasenko907647f2009-12-02 23:17:45 +0100477 if (adjtime(&tv, &tv) == -1)
478 bb_perror_msg_and_die("adjtime failed");
479 if (G.verbose >= 2)
480 bb_error_msg("old adjust: %d.%06u", (int)tv.tv_sec, (unsigned)tv.tv_usec);
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100481
Denys Vlasenko907647f2009-12-02 23:17:45 +0100482 if (G.first_adj_done) {
483 uint8_t synced = (tv.tv_sec == 0 && tv.tv_usec == 0);
484 if (synced != G.synced) {
485 G.synced = synced;
486 bb_error_msg("clock is %ssynced", synced ? "" : "un");
487 }
488 }
489 G.first_adj_done = 1;
490
491 G.reftime = gettime1900d();
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100492
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100493 clear_good:
Adam Tkacb1585062009-11-22 03:43:55 +0100494 for (item = G.ntp_peers; item != NULL; item = item->link) {
Denys Vlasenkod2fe69f2009-12-30 18:38:05 +0100495 peer_t *p = (peer_t *) item->data;
Denys Vlasenkoafa2d332009-12-17 23:29:33 +0100496 p->update.d_good = 0;
Adam Tkacb1585062009-11-22 03:43:55 +0100497 }
498}
499
500static void
Denys Vlasenkod2fe69f2009-12-30 18:38:05 +0100501update_peer_data(peer_t *p)
Adam Tkacb1585062009-11-22 03:43:55 +0100502{
Denys Vlasenko386960a2009-12-02 01:51:24 +0100503 /* Clock filter.
Denys Vlasenkoafa2d332009-12-17 23:29:33 +0100504 * Find the datapoint with the lowest delay.
Denys Vlasenko386960a2009-12-02 01:51:24 +0100505 * Use that as the peer update.
506 * Invalidate it and all older ones.
Adam Tkacb1585062009-11-22 03:43:55 +0100507 */
Denys Vlasenko386960a2009-12-02 01:51:24 +0100508 int i;
Denys Vlasenko4bd51892009-12-02 13:43:06 +0100509 int best = -1;
510 int good = 0;
Adam Tkacb1585062009-11-22 03:43:55 +0100511
Denys Vlasenkoafa2d332009-12-17 23:29:33 +0100512 for (i = 0; i < NUM_DATAPOINTS; i++) {
513 if (p->p_datapoint[i].d_good) {
Adam Tkacb1585062009-11-22 03:43:55 +0100514 good++;
Denys Vlasenkoafa2d332009-12-17 23:29:33 +0100515 if (best < 0 || p->p_datapoint[i].d_delay < p->p_datapoint[best].d_delay)
Adam Tkacb1585062009-11-22 03:43:55 +0100516 best = i;
517 }
518 }
519
Denys Vlasenkoafa2d332009-12-17 23:29:33 +0100520 if (good < 8) //FIXME: was it meant to be NUM_DATAPOINTS, not 8?
Adam Tkacb1585062009-11-22 03:43:55 +0100521 return;
522
Denys Vlasenko6879a7a2009-12-18 18:50:29 +0100523 p->update = p->p_datapoint[best]; /* struct copy */
Denys Vlasenko386960a2009-12-02 01:51:24 +0100524 slew_time();
Adam Tkacb1585062009-11-22 03:43:55 +0100525
Denys Vlasenkoafa2d332009-12-17 23:29:33 +0100526 for (i = 0; i < NUM_DATAPOINTS; i++)
Denys Vlasenko6879a7a2009-12-18 18:50:29 +0100527 if (p->p_datapoint[i].d_rcv_time <= p->p_datapoint[best].d_rcv_time)
Denys Vlasenkoafa2d332009-12-17 23:29:33 +0100528 p->p_datapoint[i].d_good = 0;
Adam Tkacb1585062009-11-22 03:43:55 +0100529}
530
Denys Vlasenko386960a2009-12-02 01:51:24 +0100531static unsigned
532scale_interval(unsigned requested)
Adam Tkacb1585062009-11-22 03:43:55 +0100533{
Denys Vlasenko386960a2009-12-02 01:51:24 +0100534 unsigned interval, r;
Adam Tkacb1585062009-11-22 03:43:55 +0100535 interval = requested * G.scale;
Denys Vlasenko386960a2009-12-02 01:51:24 +0100536 r = (unsigned)random() % (unsigned)(MAX(5, interval / 10));
Adam Tkacb1585062009-11-22 03:43:55 +0100537 return (interval + r);
538}
Adam Tkacb1585062009-11-22 03:43:55 +0100539static void
Denys Vlasenkod2fe69f2009-12-30 18:38:05 +0100540recv_and_process_peer_pkt(peer_t *p)
Adam Tkacb1585062009-11-22 03:43:55 +0100541{
Denys Vlasenkod2fe69f2009-12-30 18:38:05 +0100542 ssize_t size;
543 msg_t msg;
544 double T1, T2, T3, T4;
545 unsigned interval;
546 datapoint_t *datapoint;
Adam Tkacb1585062009-11-22 03:43:55 +0100547
Denys Vlasenkob1278a32009-11-24 16:03:47 +0100548 /* We can recvfrom here and check from.IP, but some multihomed
549 * ntp servers reply from their *other IP*.
550 * TODO: maybe we should check at least what we can: from.port == 123?
551 */
Denys Vlasenkoafa2d332009-12-17 23:29:33 +0100552 size = recv(p->p_fd, &msg, sizeof(msg), MSG_DONTWAIT);
Adam Tkacb1585062009-11-22 03:43:55 +0100553 if (size == -1) {
Denys Vlasenkoafa2d332009-12-17 23:29:33 +0100554 bb_perror_msg("recv(%s) error", p->p_dotted);
Adam Tkacb1585062009-11-22 03:43:55 +0100555 if (errno == EHOSTUNREACH || errno == EHOSTDOWN
556 || errno == ENETUNREACH || errno == ENETDOWN
557 || errno == ECONNREFUSED || errno == EADDRNOTAVAIL
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100558 || errno == EAGAIN
Adam Tkacb1585062009-11-22 03:43:55 +0100559 ) {
560//TODO: always do this?
561 set_next(p, error_interval());
Denys Vlasenko386960a2009-12-02 01:51:24 +0100562 goto close_sock;
Adam Tkacb1585062009-11-22 03:43:55 +0100563 }
564 xfunc_die();
565 }
566
Adam Tkacb1585062009-11-22 03:43:55 +0100567 if (size != NTP_MSGSIZE_NOAUTH && size != NTP_MSGSIZE) {
Denys Vlasenkoafa2d332009-12-17 23:29:33 +0100568 bb_error_msg("malformed packet received from %s", p->p_dotted);
Adam Tkacb1585062009-11-22 03:43:55 +0100569 goto bail;
570 }
571
Denys Vlasenkod2fe69f2009-12-30 18:38:05 +0100572 if (msg.m_orgtime.int_partl != p->p_xmt_msg.m_xmttime.int_partl
573 || msg.m_orgtime.fractionl != p->p_xmt_msg.m_xmttime.fractionl
Adam Tkacb1585062009-11-22 03:43:55 +0100574 ) {
575 goto bail;
576 }
577
Denys Vlasenko386960a2009-12-02 01:51:24 +0100578 if ((msg.m_status & LI_ALARM) == LI_ALARM
579 || msg.m_stratum == 0
580 || msg.m_stratum > NTP_MAXSTRATUM
Adam Tkacb1585062009-11-22 03:43:55 +0100581 ) {
Denys Vlasenkoe99c8d22009-12-17 12:17:41 +0100582// TODO: stratum 0 responses may have commands in 32-bit m_refid field:
583// "DENY", "RSTR" - peer does not like us at all
584// "RATE" - peer is overloaded, reduce polling freq
Adam Tkacb1585062009-11-22 03:43:55 +0100585 interval = error_interval();
Denys Vlasenkoafa2d332009-12-17 23:29:33 +0100586 bb_error_msg("reply from %s: not synced, next query in %us", p->p_dotted, interval);
Denys Vlasenko386960a2009-12-02 01:51:24 +0100587 goto close_sock;
Adam Tkacb1585062009-11-22 03:43:55 +0100588 }
589
590 /*
591 * From RFC 2030 (with a correction to the delay math):
592 *
Denys Vlasenkoafa2d332009-12-17 23:29:33 +0100593 * Timestamp Name ID When Generated
594 * ------------------------------------------------------------
595 * Originate Timestamp T1 time request sent by client
596 * Receive Timestamp T2 time request received by server
597 * Transmit Timestamp T3 time reply sent by server
598 * Destination Timestamp T4 time reply received by client
Adam Tkacb1585062009-11-22 03:43:55 +0100599 *
Denys Vlasenkoafa2d332009-12-17 23:29:33 +0100600 * The roundtrip delay and local clock offset are defined as
Adam Tkacb1585062009-11-22 03:43:55 +0100601 *
Denys Vlasenkoafa2d332009-12-17 23:29:33 +0100602 * delay = (T4 - T1) - (T3 - T2); offset = ((T2 - T1) + (T3 - T4)) / 2
Adam Tkacb1585062009-11-22 03:43:55 +0100603 */
Denys Vlasenkoafa2d332009-12-17 23:29:33 +0100604 T1 = p->p_xmttime;
Denys Vlasenko386960a2009-12-02 01:51:24 +0100605 T2 = lfp_to_d(msg.m_rectime);
606 T3 = lfp_to_d(msg.m_xmttime);
Denys Vlasenkod2fe69f2009-12-30 18:38:05 +0100607 T4 = gettime1900d();
Adam Tkacb1585062009-11-22 03:43:55 +0100608
Denys Vlasenkoafa2d332009-12-17 23:29:33 +0100609 datapoint = &p->p_datapoint[p->p_datapoint_idx];
Adam Tkacb1585062009-11-22 03:43:55 +0100610
Denys Vlasenkoafa2d332009-12-17 23:29:33 +0100611 datapoint->d_offset = ((T2 - T1) + (T3 - T4)) / 2;
612 datapoint->d_delay = (T4 - T1) - (T3 - T2);
613 if (datapoint->d_delay < 0) {
614 bb_error_msg("reply from %s: negative delay %f", p->p_dotted, datapoint->d_delay);
Adam Tkacb1585062009-11-22 03:43:55 +0100615 interval = error_interval();
616 set_next(p, interval);
Denys Vlasenko386960a2009-12-02 01:51:24 +0100617 goto close_sock;
Adam Tkacb1585062009-11-22 03:43:55 +0100618 }
Denys Vlasenkoafa2d332009-12-17 23:29:33 +0100619 //UNUSED: datapoint->d_error = (T2 - T1) - (T3 - T4);
Denys Vlasenko6879a7a2009-12-18 18:50:29 +0100620 datapoint->d_rcv_time = (time_t)(T4 - OFFSET_1900_1970); /* = time(NULL); */
Denys Vlasenkoafa2d332009-12-17 23:29:33 +0100621 datapoint->d_good = 1;
Adam Tkacb1585062009-11-22 03:43:55 +0100622
Denys Vlasenkoafa2d332009-12-17 23:29:33 +0100623 datapoint->d_leap = (msg.m_status & LI_MASK);
Denys Vlasenkod2fe69f2009-12-30 18:38:05 +0100624 //UNUSED: datapoint->o_precision = msg.m_precision_exp;
Denys Vlasenkoafa2d332009-12-17 23:29:33 +0100625 //UNUSED: datapoint->o_rootdelay = sfp_to_d(msg.m_rootdelay);
626 //UNUSED: datapoint->o_rootdispersion = sfp_to_d(msg.m_dispersion);
627 //UNUSED: datapoint->d_refid = ntohl(msg.m_refid);
628 datapoint->d_refid4 = msg.m_xmttime.fractionl;
629 //UNUSED: datapoint->o_reftime = lfp_to_d(msg.m_reftime);
630 //UNUSED: datapoint->o_poll = msg.m_ppoll;
631 datapoint->d_stratum = msg.m_stratum;
Adam Tkacb1585062009-11-22 03:43:55 +0100632
Denys Vlasenkod2fe69f2009-12-30 18:38:05 +0100633 if (p->p_trustlevel < TRUSTLEVEL_PATHETIC)
Adam Tkacb1585062009-11-22 03:43:55 +0100634 interval = scale_interval(INTERVAL_QUERY_PATHETIC);
Denys Vlasenkod2fe69f2009-12-30 18:38:05 +0100635 else if (p->p_trustlevel < TRUSTLEVEL_AGRESSIVE)
Adam Tkacb1585062009-11-22 03:43:55 +0100636 interval = scale_interval(INTERVAL_QUERY_AGRESSIVE);
637 else
638 interval = scale_interval(INTERVAL_QUERY_NORMAL);
639
640 set_next(p, interval);
Adam Tkacb1585062009-11-22 03:43:55 +0100641
Denys Vlasenkod2fe69f2009-12-30 18:38:05 +0100642 /* Every received reply which we do not discard increases trust */
643 if (p->p_trustlevel < TRUSTLEVEL_MAX) {
644 p->p_trustlevel++;
645 if (p->p_trustlevel == TRUSTLEVEL_BADPEER)
Denys Vlasenkoafa2d332009-12-17 23:29:33 +0100646 bb_error_msg("peer %s now valid", p->p_dotted);
Adam Tkacb1585062009-11-22 03:43:55 +0100647 }
648
Denys Vlasenko386960a2009-12-02 01:51:24 +0100649 if (G.verbose)
Denys Vlasenkoafa2d332009-12-17 23:29:33 +0100650 bb_error_msg("reply from %s: offset %f delay %f, next query in %us", p->p_dotted,
651 datapoint->d_offset, datapoint->d_delay, interval);
Adam Tkacb1585062009-11-22 03:43:55 +0100652
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100653 update_peer_data(p);
Denys Vlasenkof91e63c2009-12-02 02:30:31 +0100654//TODO: do it after all peers had a chance to return at least one reply?
Denys Vlasenkoafa2d332009-12-17 23:29:33 +0100655 step_time_once(datapoint->d_offset);
Adam Tkacb1585062009-11-22 03:43:55 +0100656
Denys Vlasenkoafa2d332009-12-17 23:29:33 +0100657 p->p_datapoint_idx++;
658 if (p->p_datapoint_idx >= NUM_DATAPOINTS)
659 p->p_datapoint_idx = 0;
Adam Tkacb1585062009-11-22 03:43:55 +0100660
Denys Vlasenko386960a2009-12-02 01:51:24 +0100661 close_sock:
Denys Vlasenko907647f2009-12-02 23:17:45 +0100662 /* We do not expect any more packets from this peer for now.
Denys Vlasenko386960a2009-12-02 01:51:24 +0100663 * Closing the socket informs kernel about it.
664 * We open a new socket when we send a new query.
665 */
Denys Vlasenkoafa2d332009-12-17 23:29:33 +0100666 close(p->p_fd);
667 p->p_fd = -1;
Adam Tkacb1585062009-11-22 03:43:55 +0100668 bail:
Denys Vlasenko386960a2009-12-02 01:51:24 +0100669 return;
Adam Tkacb1585062009-11-22 03:43:55 +0100670}
671
672#if ENABLE_FEATURE_NTPD_SERVER
673static void
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100674recv_and_process_client_pkt(void /*int fd*/)
Adam Tkacb1585062009-11-22 03:43:55 +0100675{
Denys Vlasenkoca6c7e42009-11-24 07:07:42 +0100676 ssize_t size;
677 uint8_t version;
678 double rectime;
679 len_and_sockaddr *to;
680 struct sockaddr *from;
Denys Vlasenkod2fe69f2009-12-30 18:38:05 +0100681 msg_t msg;
Denys Vlasenkoca6c7e42009-11-24 07:07:42 +0100682 uint8_t query_status;
683 uint8_t query_ppoll;
684 l_fixedpt_t query_xmttime;
Adam Tkacb1585062009-11-22 03:43:55 +0100685
686 to = get_sock_lsa(G.listen_fd);
687 from = xzalloc(to->len);
688
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100689 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 +0100690 if (size != NTP_MSGSIZE_NOAUTH && size != NTP_MSGSIZE) {
Denys Vlasenkoca6c7e42009-11-24 07:07:42 +0100691 char *addr;
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100692 if (size < 0) {
693 if (errno == EAGAIN)
694 goto bail;
Denys Vlasenko907647f2009-12-02 23:17:45 +0100695 bb_perror_msg_and_die("recv");
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100696 }
Denys Vlasenkoca6c7e42009-11-24 07:07:42 +0100697 addr = xmalloc_sockaddr2dotted_noport(from);
Denys Vlasenko907647f2009-12-02 23:17:45 +0100698 bb_error_msg("malformed packet received from %s: size %u", addr, (int)size);
Adam Tkacb1585062009-11-22 03:43:55 +0100699 free(addr);
700 goto bail;
701 }
702
Denys Vlasenko386960a2009-12-02 01:51:24 +0100703 query_status = msg.m_status;
704 query_ppoll = msg.m_ppoll;
705 query_xmttime = msg.m_xmttime;
Adam Tkacb1585062009-11-22 03:43:55 +0100706
Denys Vlasenkoca6c7e42009-11-24 07:07:42 +0100707 /* Build a reply packet */
708 memset(&msg, 0, sizeof(msg));
Denys Vlasenko386960a2009-12-02 01:51:24 +0100709 msg.m_status = G.synced ? G.leap : LI_ALARM;
710 msg.m_status |= (query_status & VERSION_MASK);
711 msg.m_status |= ((query_status & MODE_MASK) == MODE_CLIENT) ?
Adam Tkacb1585062009-11-22 03:43:55 +0100712 MODE_SERVER : MODE_SYM_PAS;
Denys Vlasenko386960a2009-12-02 01:51:24 +0100713 msg.m_stratum = G.stratum;
714 msg.m_ppoll = query_ppoll;
Denys Vlasenkod2fe69f2009-12-30 18:38:05 +0100715 msg.m_precision_exp = G_precision_exp;
Denys Vlasenko907647f2009-12-02 23:17:45 +0100716 rectime = gettime1900d();
Denys Vlasenko386960a2009-12-02 01:51:24 +0100717 msg.m_xmttime = msg.m_rectime = d_to_lfp(rectime);
718 msg.m_reftime = d_to_lfp(G.reftime);
Denys Vlasenko907647f2009-12-02 23:17:45 +0100719 //msg.m_xmttime = d_to_lfp(gettime1900d()); // = msg.m_rectime
Denys Vlasenko386960a2009-12-02 01:51:24 +0100720 msg.m_orgtime = query_xmttime;
721 msg.m_rootdelay = d_to_sfp(G.rootdelay);
Denys Vlasenkoca6c7e42009-11-24 07:07:42 +0100722 version = (query_status & VERSION_MASK); /* ... >> VERSION_SHIFT - done below instead */
Denys Vlasenko386960a2009-12-02 01:51:24 +0100723 msg.m_refid = (version > (3 << VERSION_SHIFT)) ? G.refid4 : G.refid;
Adam Tkacb1585062009-11-22 03:43:55 +0100724
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100725 /* We reply from the local address packet was sent to,
Adam Tkacb1585062009-11-22 03:43:55 +0100726 * this makes to/from look swapped here: */
Denys Vlasenko386960a2009-12-02 01:51:24 +0100727 do_sendto(G.listen_fd,
Denys Vlasenkoca6c7e42009-11-24 07:07:42 +0100728 /*from:*/ &to->u.sa, /*to:*/ from, /*addrlen:*/ to->len,
729 &msg, size);
Adam Tkacb1585062009-11-22 03:43:55 +0100730
731 bail:
732 free(to);
733 free(from);
734}
735#endif
736
737/* Upstream ntpd's options:
738 *
739 * -4 Force DNS resolution of host names to the IPv4 namespace.
740 * -6 Force DNS resolution of host names to the IPv6 namespace.
741 * -a Require cryptographic authentication for broadcast client,
742 * multicast client and symmetric passive associations.
743 * This is the default.
744 * -A Do not require cryptographic authentication for broadcast client,
745 * multicast client and symmetric passive associations.
746 * This is almost never a good idea.
747 * -b Enable the client to synchronize to broadcast servers.
748 * -c conffile
749 * Specify the name and path of the configuration file,
750 * default /etc/ntp.conf
751 * -d Specify debugging mode. This option may occur more than once,
752 * with each occurrence indicating greater detail of display.
753 * -D level
754 * Specify debugging level directly.
755 * -f driftfile
756 * Specify the name and path of the frequency file.
757 * This is the same operation as the "driftfile FILE"
758 * configuration command.
759 * -g Normally, ntpd exits with a message to the system log
760 * if the offset exceeds the panic threshold, which is 1000 s
761 * by default. This option allows the time to be set to any value
762 * without restriction; however, this can happen only once.
763 * If the threshold is exceeded after that, ntpd will exit
764 * with a message to the system log. This option can be used
765 * with the -q and -x options. See the tinker command for other options.
766 * -i jaildir
767 * Chroot the server to the directory jaildir. This option also implies
768 * that the server attempts to drop root privileges at startup
769 * (otherwise, chroot gives very little additional security).
770 * You may need to also specify a -u option.
771 * -k keyfile
772 * Specify the name and path of the symmetric key file,
773 * default /etc/ntp/keys. This is the same operation
774 * as the "keys FILE" configuration command.
775 * -l logfile
776 * Specify the name and path of the log file. The default
777 * is the system log file. This is the same operation as
778 * the "logfile FILE" configuration command.
779 * -L Do not listen to virtual IPs. The default is to listen.
780 * -n Don't fork.
781 * -N To the extent permitted by the operating system,
782 * run the ntpd at the highest priority.
783 * -p pidfile
784 * Specify the name and path of the file used to record the ntpd
785 * process ID. This is the same operation as the "pidfile FILE"
786 * configuration command.
787 * -P priority
788 * To the extent permitted by the operating system,
789 * run the ntpd at the specified priority.
790 * -q Exit the ntpd just after the first time the clock is set.
791 * This behavior mimics that of the ntpdate program, which is
792 * to be retired. The -g and -x options can be used with this option.
793 * Note: The kernel time discipline is disabled with this option.
794 * -r broadcastdelay
795 * Specify the default propagation delay from the broadcast/multicast
796 * server to this client. This is necessary only if the delay
797 * cannot be computed automatically by the protocol.
798 * -s statsdir
799 * Specify the directory path for files created by the statistics
800 * facility. This is the same operation as the "statsdir DIR"
801 * configuration command.
802 * -t key
803 * Add a key number to the trusted key list. This option can occur
804 * more than once.
805 * -u user[:group]
806 * Specify a user, and optionally a group, to switch to.
807 * -v variable
808 * -V variable
809 * Add a system variable listed by default.
810 * -x Normally, the time is slewed if the offset is less than the step
811 * threshold, which is 128 ms by default, and stepped if above
812 * the threshold. This option sets the threshold to 600 s, which is
813 * well within the accuracy window to set the clock manually.
814 * Note: since the slew rate of typical Unix kernels is limited
815 * to 0.5 ms/s, each second of adjustment requires an amortization
816 * interval of 2000 s. Thus, an adjustment as much as 600 s
817 * will take almost 14 days to complete. This option can be used
818 * with the -g and -q options. See the tinker command for other options.
819 * Note: The kernel time discipline is disabled with this option.
820 */
821
Adam Tkacb1585062009-11-22 03:43:55 +0100822/* By doing init in a separate function we decrease stack usage
823 * in main loop.
824 */
825static NOINLINE void ntp_init(char **argv)
826{
827 unsigned opts;
828 llist_t *peers;
829
Denys Vlasenkoca6c7e42009-11-24 07:07:42 +0100830 srandom(getpid());
Adam Tkacb1585062009-11-22 03:43:55 +0100831
832 if (getuid())
Denys Vlasenkob2e5fc32009-11-25 14:52:47 +0100833 bb_error_msg_and_die(bb_msg_you_must_be_root);
Adam Tkacb1585062009-11-22 03:43:55 +0100834
835 peers = NULL;
836 opt_complementary = "dd:p::"; /* d: counter, p: list */
837 opts = getopt32(argv,
Denys Vlasenko907647f2009-12-02 23:17:45 +0100838 "nqNx" /* compat */
Adam Tkacb1585062009-11-22 03:43:55 +0100839 "p:"IF_FEATURE_NTPD_SERVER("l") /* NOT compat */
840 "d" /* compat */
Denys Vlasenko907647f2009-12-02 23:17:45 +0100841 "46aAbgL", /* compat, ignored */
Adam Tkacb1585062009-11-22 03:43:55 +0100842 &peers, &G.verbose);
Denys Vlasenkob2e5fc32009-11-25 14:52:47 +0100843 if (!(opts & (OPT_p|OPT_l)))
844 bb_show_usage();
Denys Vlasenko907647f2009-12-02 23:17:45 +0100845 if (opts & OPT_x) /* disable stepping, only slew is allowed */
Denys Vlasenkoafa2d332009-12-17 23:29:33 +0100846 G.time_was_stepped = 1;
Denys Vlasenko160b9ca2009-11-27 02:35:15 +0100847 while (peers)
848 add_peers(llist_pop(&peers));
849 if (!(opts & OPT_n)) {
850 bb_daemonize_or_rexec(DAEMON_DEVNULL_STDIO, argv);
851 logmode = LOGMODE_NONE;
852 }
Adam Tkacb1585062009-11-22 03:43:55 +0100853#if ENABLE_FEATURE_NTPD_SERVER
854 G.listen_fd = -1;
855 if (opts & OPT_l) {
856 G.listen_fd = create_and_bind_dgram_or_die(NULL, 123);
857 socket_want_pktinfo(G.listen_fd);
858 setsockopt(G.listen_fd, IPPROTO_IP, IP_TOS, &const_IPTOS_LOWDELAY, sizeof(const_IPTOS_LOWDELAY));
859 }
860#endif
Denys Vlasenkob2e5fc32009-11-25 14:52:47 +0100861 /* I hesitate to set -20 prio. -15 should be high enough for timekeeping */
862 if (opts & OPT_N)
863 setpriority(PRIO_PROCESS, 0, -15);
Adam Tkacb1585062009-11-22 03:43:55 +0100864
865 /* Set some globals */
Denys Vlasenko907647f2009-12-02 23:17:45 +0100866#if 0
Denys Vlasenko6879a7a2009-12-18 18:50:29 +0100867 /* With constant b = 100, G.precision_exp is also constant -6.
Denys Vlasenko907647f2009-12-02 23:17:45 +0100868 * Uncomment this and you'll see */
Adam Tkacb1585062009-11-22 03:43:55 +0100869 {
870 int prec = 0;
871 int b;
Denys Vlasenko907647f2009-12-02 23:17:45 +0100872# if 0
Denys Vlasenkofb132e42010-10-29 11:46:52 +0200873 struct timespec tp;
Adam Tkacb1585062009-11-22 03:43:55 +0100874 /* We can use sys_clock_getres but assuming 10ms tick should be fine */
875 clock_getres(CLOCK_REALTIME, &tp);
876 tp.tv_sec = 0;
877 tp.tv_nsec = 10000000;
Denys Vlasenkoafa2d332009-12-17 23:29:33 +0100878 b = 1000000000 / tp.tv_nsec; /* convert to Hz */
Denys Vlasenko907647f2009-12-02 23:17:45 +0100879# else
Adam Tkacb1585062009-11-22 03:43:55 +0100880 b = 100; /* b = 1000000000/10000000 = 100 */
Denys Vlasenko907647f2009-12-02 23:17:45 +0100881# endif
Adam Tkacb1585062009-11-22 03:43:55 +0100882 while (b > 1)
883 prec--, b >>= 1;
Denys Vlasenko6879a7a2009-12-18 18:50:29 +0100884 //G.precision_exp = prec;
885 bb_error_msg("G.precision_exp:%d", prec); /* -6 */
Adam Tkacb1585062009-11-22 03:43:55 +0100886 }
Denys Vlasenko907647f2009-12-02 23:17:45 +0100887#endif
Adam Tkacb1585062009-11-22 03:43:55 +0100888 G.scale = 1;
Adam Tkacb1585062009-11-22 03:43:55 +0100889
890 bb_signals((1 << SIGTERM) | (1 << SIGINT), record_signo);
891 bb_signals((1 << SIGPIPE) | (1 << SIGHUP), SIG_IGN);
892}
893
894int ntpd_main(int argc UNUSED_PARAM, char **argv) MAIN_EXTERNALLY_VISIBLE;
895int ntpd_main(int argc UNUSED_PARAM, char **argv)
896{
897 struct globals g;
Adam Tkacb1585062009-11-22 03:43:55 +0100898 struct pollfd *pfd;
Denys Vlasenkod2fe69f2009-12-30 18:38:05 +0100899 peer_t **idx2peer;
Adam Tkacb1585062009-11-22 03:43:55 +0100900
901 memset(&g, 0, sizeof(g));
902 SET_PTR_TO_GLOBALS(&g);
903
904 ntp_init(argv);
905
Denys Vlasenko8d580c72009-11-23 16:27:16 +0100906 {
Denys Vlasenko8d580c72009-11-23 16:27:16 +0100907 /* if ENABLE_FEATURE_NTPD_SERVER, + 1 for listen_fd: */
Denys Vlasenkod2fe69f2009-12-30 18:38:05 +0100908 unsigned cnt = g.peer_cnt + ENABLE_FEATURE_NTPD_SERVER;
909 idx2peer = xzalloc(sizeof(idx2peer[0]) * cnt);
910 pfd = xzalloc(sizeof(pfd[0]) * cnt);
Denys Vlasenko8d580c72009-11-23 16:27:16 +0100911 }
Adam Tkacb1585062009-11-22 03:43:55 +0100912
913 while (!bb_got_signal) {
914 llist_t *item;
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100915 unsigned i, j;
Adam Tkacb1585062009-11-22 03:43:55 +0100916 unsigned sent_cnt, trial_cnt;
917 int nfds, timeout;
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100918 time_t cur_time, nextaction;
Adam Tkacb1585062009-11-22 03:43:55 +0100919
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100920 /* Nothing between here and poll() blocks for any significant time */
921
922 cur_time = time(NULL);
923 nextaction = cur_time + 3600;
Adam Tkacb1585062009-11-22 03:43:55 +0100924
925 i = 0;
926#if ENABLE_FEATURE_NTPD_SERVER
927 if (g.listen_fd != -1) {
928 pfd[0].fd = g.listen_fd;
929 pfd[0].events = POLLIN;
930 i++;
931 }
932#endif
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100933 /* Pass over peer list, send requests, time out on receives */
Adam Tkacb1585062009-11-22 03:43:55 +0100934 sent_cnt = trial_cnt = 0;
935 for (item = g.ntp_peers; item != NULL; item = item->link) {
Denys Vlasenkod2fe69f2009-12-30 18:38:05 +0100936 peer_t *p = (peer_t *) item->data;
Adam Tkacb1585062009-11-22 03:43:55 +0100937
Denys Vlasenko907647f2009-12-02 23:17:45 +0100938 /* Overflow-safe "if (p->next_action_time <= cur_time) ..." */
939 if ((int)(cur_time - p->next_action_time) >= 0) {
Denys Vlasenkoafa2d332009-12-17 23:29:33 +0100940 if (p->p_fd == -1) {
Denys Vlasenko907647f2009-12-02 23:17:45 +0100941 /* Time to send new req */
942 trial_cnt++;
943 if (send_query_to_peer(p) == 0)
944 sent_cnt++;
945 } else {
946 /* Timed out waiting for reply */
Denys Vlasenkoafa2d332009-12-17 23:29:33 +0100947 close(p->p_fd);
948 p->p_fd = -1;
Denys Vlasenko907647f2009-12-02 23:17:45 +0100949 timeout = error_interval();
950 bb_error_msg("timed out waiting for %s, "
Denys Vlasenkoafa2d332009-12-17 23:29:33 +0100951 "next query in %us", p->p_dotted, timeout);
Denys Vlasenkod2fe69f2009-12-30 18:38:05 +0100952 if (p->p_trustlevel >= TRUSTLEVEL_BADPEER) {
953 p->p_trustlevel /= 2;
954 if (p->p_trustlevel < TRUSTLEVEL_BADPEER)
Denys Vlasenkoafa2d332009-12-17 23:29:33 +0100955 bb_error_msg("peer %s now invalid", p->p_dotted);
Denys Vlasenko907647f2009-12-02 23:17:45 +0100956 }
957 set_next(p, timeout);
Adam Tkacb1585062009-11-22 03:43:55 +0100958 }
Adam Tkacb1585062009-11-22 03:43:55 +0100959 }
960
Denys Vlasenko907647f2009-12-02 23:17:45 +0100961 if (p->next_action_time < nextaction)
962 nextaction = p->next_action_time;
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100963
Denys Vlasenkoafa2d332009-12-17 23:29:33 +0100964 if (p->p_fd >= 0) {
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100965 /* Wait for reply from this peer */
Denys Vlasenkoafa2d332009-12-17 23:29:33 +0100966 pfd[i].fd = p->p_fd;
Adam Tkacb1585062009-11-22 03:43:55 +0100967 pfd[i].events = POLLIN;
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100968 idx2peer[i] = p;
Adam Tkacb1585062009-11-22 03:43:55 +0100969 i++;
970 }
971 }
972
Denys Vlasenko8d580c72009-11-23 16:27:16 +0100973 if ((trial_cnt > 0 && sent_cnt == 0) || g.peer_cnt == 0)
Denys Vlasenkofae9f492009-12-01 02:32:01 +0100974 step_time_once(0); /* no good peers, don't wait */
Adam Tkacb1585062009-11-22 03:43:55 +0100975
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100976 timeout = nextaction - cur_time;
Denys Vlasenko386960a2009-12-02 01:51:24 +0100977 if (timeout < 1)
978 timeout = 1;
Adam Tkacb1585062009-11-22 03:43:55 +0100979
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100980 /* Here we may block */
Denys Vlasenko386960a2009-12-02 01:51:24 +0100981 if (g.verbose >= 2)
Denys Vlasenko907647f2009-12-02 23:17:45 +0100982 bb_error_msg("poll %us, sockets:%u", timeout, i);
Adam Tkacb1585062009-11-22 03:43:55 +0100983 nfds = poll(pfd, i, timeout * 1000);
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100984 if (nfds <= 0)
985 continue;
Adam Tkacb1585062009-11-22 03:43:55 +0100986
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100987 /* Process any received packets */
Adam Tkacb1585062009-11-22 03:43:55 +0100988 j = 0;
989#if ENABLE_FEATURE_NTPD_SERVER
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100990 if (g.listen_fd != -1) {
991 if (pfd[0].revents /* & (POLLIN|POLLERR)*/) {
Adam Tkacb1585062009-11-22 03:43:55 +0100992 nfds--;
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100993 recv_and_process_client_pkt(/*g.listen_fd*/);
Adam Tkacb1585062009-11-22 03:43:55 +0100994 }
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100995 j = 1;
Adam Tkacb1585062009-11-22 03:43:55 +0100996 }
997#endif
Denys Vlasenko363e89b2009-11-24 14:04:15 +0100998 for (; nfds != 0 && j < i; j++) {
999 if (pfd[j].revents /* & (POLLIN|POLLERR)*/) {
Adam Tkacb1585062009-11-22 03:43:55 +01001000 nfds--;
Denys Vlasenko363e89b2009-11-24 14:04:15 +01001001 recv_and_process_peer_pkt(idx2peer[j]);
Adam Tkacb1585062009-11-22 03:43:55 +01001002 }
1003 }
1004 } /* while (!bb_got_signal) */
1005
1006 kill_myself_with_sig(bb_got_signal);
1007}