2 * NTP client/server, based on OpenNTPD 3.9p1
4 * Author: Adam Tkac <vonsch@gmail.com>
6 * Licensed under GPLv2, see file LICENSE in this tarball for details.
9 #include <netinet/ip.h> /* For IPTOS_LOWDELAY definition */
10 #ifndef IPTOS_LOWDELAY
11 # define IPTOS_LOWDELAY 0x10
14 # error "Sorry, your kernel has to support IP_PKTINFO"
17 #define INTERVAL_QUERY_NORMAL 30 /* sync to peers every n secs */
18 #define INTERVAL_QUERY_PATHETIC 60
19 #define INTERVAL_QUERY_AGRESSIVE 5
21 #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
26 #define QSCALE_OFF_MIN 0.05
27 #define QSCALE_OFF_MAX 0.50
29 #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 */
34 /* Style borrowed from NTP ref/tcpdump and updated for SNTPv4 (RFC2030). */
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 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
43 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
45 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
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 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
65 NTP_MSGSIZE_NOAUTH = 48,
66 NTP_MSGSIZE = (NTP_MSGSIZE_NOAUTH + 4 + NTP_DIGESTSIZE),
70 uint8_t m_status; /* status of local clock and leap info */
71 uint8_t m_stratum; /* stratum level */
72 uint8_t m_ppoll; /* poll value */
74 s_fixedpt_t m_rootdelay;
75 s_fixedpt_t m_dispersion;
77 l_fixedpt_t m_reftime;
78 l_fixedpt_t m_orgtime;
79 l_fixedpt_t m_rectime;
80 l_fixedpt_t m_xmttime;
82 uint8_t m_digest[NTP_DIGESTSIZE];
88 /* Leap Second Codes (high order two bits) */
89 LI_NOWARNING = (0 << 6), /* no warning */
90 LI_PLUSSEC = (1 << 6), /* add a second (61 seconds) */
91 LI_MINUSSEC = (2 << 6), /* minus a second (59 seconds) */
92 LI_ALARM = (3 << 6), /* alarm condition */
96 VERSION_MASK = (7 << 3),
101 MODE_RES0 = 0, /* reserved */
102 MODE_SYM_ACT = 1, /* symmetric active */
103 MODE_SYM_PAS = 2, /* symmetric passive */
104 MODE_CLIENT = 3, /* client */
105 MODE_SERVER = 4, /* server */
106 MODE_BROADCAST = 5, /* broadcast */
107 MODE_RES1 = 6, /* reserved for NTP control message */
108 MODE_RES2 = 7, /* reserved for private use */
111 #define OFFSET_1900_1970 2208988800UL /* 1970 - 1900 in seconds */
116 //UNUSED: double o_error;
125 //TODO: periodically re-resolve DNS names?
126 len_and_sockaddr *lsa;
137 ntp_offset_t reply[OFFSET_ARRAY_SIZE];
139 /* for ntp_peer_t::state */
143 STATE_REPLY_RECEIVED,
151 /* Insert new options above this line. */
152 /* Non-compat options: */
154 OPT_l = (1 << 5) * ENABLE_FEATURE_NTPD_SERVER,
162 #if ENABLE_FEATURE_NTPD_SERVER
174 uint8_t time_is_stepped;
175 uint8_t first_adj_done;
177 #define G (*ptr_to_globals)
180 static const int const_IPTOS_LOWDELAY = IPTOS_LOWDELAY;
184 set_next(ntp_peer_t *p, unsigned t)
186 p->next = time(NULL) + t;
191 add_peers(const char *s)
195 p = xzalloc(sizeof(*p));
196 //TODO: big ntpd uses all IPs, not just 1st, do we need to mimic that?
197 p->lsa = xhost2sockaddr(s, 123);
198 p->dotted = xmalloc_sockaddr2dotted_noport(&p->lsa->u.sa);
200 p->msg.m_status = MODE_CLIENT | (NTP_VERSION << 3);
202 p->state = STATE_NONE;
203 p->trustlevel = TRUSTLEVEL_PATHETIC;
206 llist_add_to(&G.ntp_peers, p);
214 gettimeofday(&tv, NULL); /* never fails */
215 return (tv.tv_sec + 1.0e-6 * tv.tv_usec + OFFSET_1900_1970);
219 d_to_tv(double d, struct timeval *tv)
221 tv->tv_sec = (long)d;
222 tv->tv_usec = (d - tv->tv_sec) * 1000000;
226 lfp_to_d(l_fixedpt_t lfp)
229 lfp.int_partl = ntohl(lfp.int_partl);
230 lfp.fractionl = ntohl(lfp.fractionl);
231 ret = (double)lfp.int_partl + ((double)lfp.fractionl / UINT_MAX);
237 sfp_to_d(s_fixedpt_t sfp)
240 sfp.int_parts = ntohs(sfp.int_parts);
241 sfp.fractions = ntohs(sfp.fractions);
242 ret = (double)sfp.int_parts + ((double)sfp.fractions / USHRT_MAX);
247 #if ENABLE_FEATURE_NTPD_SERVER
252 lfp.int_partl = (uint32_t)d;
253 lfp.fractionl = (uint32_t)((d - lfp.int_partl) * UINT_MAX);
254 lfp.int_partl = htonl(lfp.int_partl);
255 lfp.fractionl = htonl(lfp.fractionl);
263 sfp.int_parts = (uint16_t)d;
264 sfp.fractions = (uint16_t)((d - sfp.int_parts) * USHRT_MAX);
265 sfp.int_parts = htons(sfp.int_parts);
266 sfp.fractions = htons(sfp.fractions);
272 set_deadline(ntp_peer_t *p, time_t t)
274 p->deadline = time(NULL) + t;
281 unsigned interval, r;
282 interval = INTERVAL_QUERY_PATHETIC * QSCALE_OFF_MAX / QSCALE_OFF_MIN;
283 r = (unsigned)random() % (unsigned)(interval / 10);
284 return (interval + r);
289 const struct sockaddr *from, const struct sockaddr *to, socklen_t addrlen,
290 ntp_msg_t *msg, ssize_t len)
296 ret = sendto(fd, msg, len, MSG_DONTWAIT, to, addrlen);
298 ret = send_to_from(fd, msg, len, MSG_DONTWAIT, to, from, addrlen);
301 bb_perror_msg("send failed");
308 send_query_to_peer(ntp_peer_t *p)
310 // Why do we need to bind()?
311 // See what happens when we don't bind:
313 // socket(PF_INET, SOCK_DGRAM, IPPROTO_IP) = 3
314 // setsockopt(3, SOL_IP, IP_TOS, [16], 4) = 0
315 // gettimeofday({1259071266, 327885}, NULL) = 0
316 // sendto(3, "xxx", 48, MSG_DONTWAIT, {sa_family=AF_INET, sin_port=htons(123), sin_addr=inet_addr("10.34.32.125")}, 16) = 48
317 // ^^^ we sent it from some source port picked by kernel.
318 // time(NULL) = 1259071266
319 // write(2, "ntpd: entering poll 15 secs\n", 28) = 28
320 // poll([{fd=3, events=POLLIN}], 1, 15000) = 1 ([{fd=3, revents=POLLIN}])
321 // recv(3, "yyy", 68, MSG_DONTWAIT) = 48
322 // ^^^ this recv will receive packets to any local port!
324 // Uncomment this and use strace to see it in action:
325 #define PROBE_LOCAL_ADDR // { len_and_sockaddr lsa; lsa.len = LSA_SIZEOF_SA; getsockname(p->query.fd, &lsa.u.sa, &lsa.len); }
329 len_and_sockaddr *local_lsa;
331 family = p->lsa->u.sa.sa_family;
332 //was: p->fd = xsocket(family, SOCK_DGRAM, 0);
333 p->fd = fd = xsocket_type(&local_lsa, family, SOCK_DGRAM);
334 /* local_lsa has "null" address and port 0 now.
335 * bind() ensures we have a *particular port* selected by kernel
336 * and remembered in p->fd, thus later recv(p->fd)
337 * receives only packets sent to this port.
340 xbind(fd, &local_lsa->u.sa, local_lsa->len);
342 #if ENABLE_FEATURE_IPV6
343 if (family == AF_INET)
345 setsockopt(fd, IPPROTO_IP, IP_TOS, &const_IPTOS_LOWDELAY, sizeof(const_IPTOS_LOWDELAY));
350 * Send out a random 64-bit number as our transmit time. The NTP
351 * server will copy said number into the originate field on the
352 * response that it sends us. This is totally legal per the SNTP spec.
354 * The impact of this is two fold: we no longer send out the current
355 * system time for the world to see (which may aid an attacker), and
356 * it gives us a (not very secure) way of knowing that we're not
357 * getting spoofed by an attacker that can't capture our traffic
358 * but can spoof packets from the NTP server we're communicating with.
360 * Save the real transmit timestamp locally.
363 p->msg.m_xmttime.int_partl = random();
364 p->msg.m_xmttime.fractionl = random();
365 p->xmttime = gettime1900fp();
367 if (do_sendto(p->fd, /*from:*/ NULL, /*to:*/ &p->lsa->u.sa, /*addrlen:*/ p->lsa->len,
368 &p->msg, NTP_MSGSIZE_NOAUTH) == -1
370 set_next(p, INTERVAL_QUERY_PATHETIC);
375 bb_error_msg("sent query to %s", p->dotted);
376 p->state = STATE_QUERY_SENT;
377 set_deadline(p, QUERYTIME_MAX);
383 compare_offsets(const void *aa, const void *bb)
385 const ntp_peer_t *const *a = aa;
386 const ntp_peer_t *const *b = bb;
387 if ((*a)->update.o_offset < (*b)->update.o_offset)
389 return ((*a)->update.o_offset > (*b)->update.o_offset);
393 updated_scale(double offset)
397 if (offset > QSCALE_OFF_MAX)
399 if (offset < QSCALE_OFF_MIN)
400 return QSCALE_OFF_MAX / QSCALE_OFF_MIN;
401 return QSCALE_OFF_MAX / offset;
410 double offset_median;
414 for (item = G.ntp_peers; item != NULL; item = item->link) {
415 p = (ntp_peer_t *) item->data;
416 if (p->trustlevel < TRUSTLEVEL_BADPEER)
418 if (!p->update.o_good)
427 len_and_sockaddr *lsa;
430 ntp_peer_t **peers = xzalloc(sizeof(peers[0]) * offset_cnt);
432 for (item = G.ntp_peers; item != NULL; item = item->link) {
433 p = (ntp_peer_t *) item->data;
434 if (p->trustlevel < TRUSTLEVEL_BADPEER)
439 qsort(peers, offset_cnt, sizeof(peers[0]), compare_offsets);
441 middle = offset_cnt / 2;
442 if (middle != 0 && (offset_cnt & 1) == 0) {
443 offset_median = (peers[middle-1]->update.o_offset + peers[middle]->update.o_offset) / 2;
444 G.rootdelay = (peers[middle-1]->update.o_delay + peers[middle]->update.o_delay) / 2;
445 G.stratum = 1 + MAX(peers[middle-1]->update.o_stratum, peers[middle]->update.o_stratum);
447 offset_median = peers[middle]->update.o_offset;
448 G.rootdelay = peers[middle]->update.o_delay;
449 G.stratum = 1 + peers[middle]->update.o_stratum;
451 G.leap = peers[middle]->update.o_leap;
452 G.refid4 = peers[middle]->update.o_refid4;
453 lsa = peers[middle]->lsa;
455 #if ENABLE_FEATURE_IPV6
456 lsa->u.sa.sa_family != AF_INET ?
459 lsa->u.sin.sin_addr.s_addr;
463 bb_error_msg("adjusting clock by %fs, our stratum is %u", offset_median, G.stratum);
466 d_to_tv(offset_median, &tv);
467 if (adjtime(&tv, &tv) == -1) {
468 bb_perror_msg("adjtime failed"); //TODO: maybe _and_die?
471 bb_error_msg("old adjust: %d.%06u", (int)tv.tv_sec, (unsigned)tv.tv_usec);
474 && tv.tv_usec == 0 // TODO: allow for tiny values?
478 bb_error_msg("clock %ssynced", "");
482 bb_error_msg("clock %ssynced", "un");
486 G.first_adj_done = 1;
487 G.reftime = gettime1900fp();
488 G.scale = updated_scale(offset_median);
491 for (item = G.ntp_peers; item != NULL; item = item->link) {
492 p = (ntp_peer_t *) item->data;
493 p->update.o_good = 0;
498 step_time_once(double offset)
506 if (G.time_is_stepped)
508 G.time_is_stepped = 1;
510 /* if the offset is small, don't call settimeofday */
511 if (offset < SETTIME_MIN_OFFSET && offset > -SETTIME_MIN_OFFSET)
514 gettimeofday(&tv, NULL); /* never fails */
516 offset += 1.0e-6 * tv.tv_usec;
517 d_to_tv(offset, &tv);
519 if (settimeofday(&tv, NULL) == -1) {
520 bb_error_msg("settimeofday");
525 strftime(buf, sizeof(buf), "%a %b %e %H:%M:%S %Z %Y", localtime(&tval));
527 // Do we want to print message below to system log when daemonized?
528 bb_error_msg("setting clock to %s (offset %fs)", buf, offset);
530 for (item = G.ntp_peers; item != NULL; item = item->link) {
531 p = (ntp_peer_t *) item->data;
535 p->deadline -= offset;
539 if (option_mask32 & OPT_q)
544 update_peer_data(ntp_peer_t *p)
547 * Find the offset which arrived with the lowest delay.
548 * Use that as the peer update.
549 * Invalidate it and all older ones.
552 int best = best; /* for compiler */
556 for (i = 0; i < OFFSET_ARRAY_SIZE; i++) {
557 if (p->reply[i].o_good) {
564 for (; i < OFFSET_ARRAY_SIZE; i++) {
565 if (p->reply[i].o_good) {
567 if (p->reply[i].o_delay < p->reply[best].o_delay)
572 if (good < 8) //FIXME: was it meant to be OFFSET_ARRAY_SIZE, not 8?
575 memcpy(&p->update, &p->reply[best], sizeof(p->update));
578 for (i = 0; i < OFFSET_ARRAY_SIZE; i++)
579 if (p->reply[i].o_rcvd <= p->reply[best].o_rcvd)
580 p->reply[i].o_good = 0;
584 scale_interval(unsigned requested)
586 unsigned interval, r;
587 interval = requested * G.scale;
588 r = (unsigned)random() % (unsigned)(MAX(5, interval / 10));
589 return (interval + r);
593 recv_and_process_peer_pkt(ntp_peer_t *p)
597 double T1, T2, T3, T4;
599 ntp_offset_t *offset;
601 /* We can recvfrom here and check from.IP, but some multihomed
602 * ntp servers reply from their *other IP*.
603 * TODO: maybe we should check at least what we can: from.port == 123?
605 size = recv(p->fd, &msg, sizeof(msg), MSG_DONTWAIT);
607 bb_perror_msg("recv(%s) error", p->dotted);
608 if (errno == EHOSTUNREACH || errno == EHOSTDOWN
609 || errno == ENETUNREACH || errno == ENETDOWN
610 || errno == ECONNREFUSED || errno == EADDRNOTAVAIL
613 //TODO: always do this?
614 set_next(p, error_interval());
620 T4 = gettime1900fp();
622 if (size != NTP_MSGSIZE_NOAUTH && size != NTP_MSGSIZE) {
623 bb_error_msg("malformed packet received from %s", p->dotted);
627 if (msg.m_orgtime.int_partl != p->msg.m_xmttime.int_partl
628 || msg.m_orgtime.fractionl != p->msg.m_xmttime.fractionl
633 if ((msg.m_status & LI_ALARM) == LI_ALARM
634 || msg.m_stratum == 0
635 || msg.m_stratum > NTP_MAXSTRATUM
637 interval = error_interval();
638 bb_error_msg("reply from %s: not synced, next query in %us", p->dotted, interval);
643 * From RFC 2030 (with a correction to the delay math):
645 * Timestamp Name ID When Generated
646 * ------------------------------------------------------------
647 * Originate Timestamp T1 time request sent by client
648 * Receive Timestamp T2 time request received by server
649 * Transmit Timestamp T3 time reply sent by server
650 * Destination Timestamp T4 time reply received by client
652 * The roundtrip delay d and local clock offset t are defined as
654 * d = (T4 - T1) - (T3 - T2) t = ((T2 - T1) + (T3 - T4)) / 2.
658 T2 = lfp_to_d(msg.m_rectime);
659 T3 = lfp_to_d(msg.m_xmttime);
661 offset = &p->reply[p->shift];
663 offset->o_offset = ((T2 - T1) + (T3 - T4)) / 2;
664 offset->o_delay = (T4 - T1) - (T3 - T2);
665 if (offset->o_delay < 0) {
666 interval = error_interval();
667 set_next(p, interval);
668 bb_error_msg("reply from %s: negative delay %f", p->dotted, p->reply[p->shift].o_delay);
671 //UNUSED: offset->o_error = (T2 - T1) - (T3 - T4);
672 // Can we use (T4 - OFFSET_1900_1970) instead of time(NULL)?
673 offset->o_rcvd = time(NULL);
676 offset->o_leap = (msg.m_status & LI_MASK);
677 //UNUSED: offset->o_precision = msg.m_precision;
678 //UNUSED: offset->o_rootdelay = sfp_to_d(msg.m_rootdelay);
679 //UNUSED: offset->o_rootdispersion = sfp_to_d(msg.m_dispersion);
680 //UNUSED: offset->o_refid = ntohl(msg.m_refid);
681 offset->o_refid4 = msg.m_xmttime.fractionl;
682 //UNUSED: offset->o_reftime = lfp_to_d(msg.m_reftime);
683 //UNUSED: offset->o_poll = msg.m_ppoll;
684 offset->o_stratum = msg.m_stratum;
686 if (p->trustlevel < TRUSTLEVEL_PATHETIC)
687 interval = scale_interval(INTERVAL_QUERY_PATHETIC);
688 else if (p->trustlevel < TRUSTLEVEL_AGRESSIVE)
689 interval = scale_interval(INTERVAL_QUERY_AGRESSIVE);
691 interval = scale_interval(INTERVAL_QUERY_NORMAL);
693 set_next(p, interval);
694 p->state = STATE_REPLY_RECEIVED;
696 /* every received reply which we do not discard increases trust */
697 if (p->trustlevel < TRUSTLEVEL_MAX) {
699 if (p->trustlevel == TRUSTLEVEL_BADPEER)
700 bb_error_msg("peer %s now valid", p->dotted);
704 bb_error_msg("reply from %s: offset %f delay %f, next query in %us", p->dotted,
705 offset->o_offset, offset->o_delay, interval);
708 //TODO: do it after all peers had a chance to return at least one reply?
709 step_time_once(offset->o_offset);
712 if (p->shift >= OFFSET_ARRAY_SIZE)
716 /* We do not expect any more packets for now.
717 * Closing the socket informs kernel about it.
718 * We open a new socket when we send a new query.
726 #if ENABLE_FEATURE_NTPD_SERVER
728 recv_and_process_client_pkt(void /*int fd*/)
733 len_and_sockaddr *to;
734 struct sockaddr *from;
736 uint8_t query_status;
738 l_fixedpt_t query_xmttime;
740 to = get_sock_lsa(G.listen_fd);
741 from = xzalloc(to->len);
743 size = recv_from_to(G.listen_fd, &msg, sizeof(msg), MSG_DONTWAIT, from, &to->u.sa, to->len);
744 if (size != NTP_MSGSIZE_NOAUTH && size != NTP_MSGSIZE) {
749 bb_perror_msg_and_die("recv_from_to");
751 addr = xmalloc_sockaddr2dotted_noport(from);
752 bb_error_msg("malformed packet received from %s", addr);
757 query_status = msg.m_status;
758 query_ppoll = msg.m_ppoll;
759 query_xmttime = msg.m_xmttime;
761 /* Build a reply packet */
762 memset(&msg, 0, sizeof(msg));
763 msg.m_status = G.synced ? G.leap : LI_ALARM;
764 msg.m_status |= (query_status & VERSION_MASK);
765 msg.m_status |= ((query_status & MODE_MASK) == MODE_CLIENT) ?
766 MODE_SERVER : MODE_SYM_PAS;
767 msg.m_stratum = G.stratum;
768 msg.m_ppoll = query_ppoll;
769 msg.m_precision = G.precision;
770 rectime = gettime1900fp();
771 msg.m_xmttime = msg.m_rectime = d_to_lfp(rectime);
772 msg.m_reftime = d_to_lfp(G.reftime);
773 //msg.m_xmttime = d_to_lfp(gettime1900fp()); // = msg.m_rectime
774 msg.m_orgtime = query_xmttime;
775 msg.m_rootdelay = d_to_sfp(G.rootdelay);
776 version = (query_status & VERSION_MASK); /* ... >> VERSION_SHIFT - done below instead */
777 msg.m_refid = (version > (3 << VERSION_SHIFT)) ? G.refid4 : G.refid;
779 /* We reply from the local address packet was sent to,
780 * this makes to/from look swapped here: */
781 do_sendto(G.listen_fd,
782 /*from:*/ &to->u.sa, /*to:*/ from, /*addrlen:*/ to->len,
791 /* Upstream ntpd's options:
793 * -4 Force DNS resolution of host names to the IPv4 namespace.
794 * -6 Force DNS resolution of host names to the IPv6 namespace.
795 * -a Require cryptographic authentication for broadcast client,
796 * multicast client and symmetric passive associations.
797 * This is the default.
798 * -A Do not require cryptographic authentication for broadcast client,
799 * multicast client and symmetric passive associations.
800 * This is almost never a good idea.
801 * -b Enable the client to synchronize to broadcast servers.
803 * Specify the name and path of the configuration file,
804 * default /etc/ntp.conf
805 * -d Specify debugging mode. This option may occur more than once,
806 * with each occurrence indicating greater detail of display.
808 * Specify debugging level directly.
810 * Specify the name and path of the frequency file.
811 * This is the same operation as the "driftfile FILE"
812 * configuration command.
813 * -g Normally, ntpd exits with a message to the system log
814 * if the offset exceeds the panic threshold, which is 1000 s
815 * by default. This option allows the time to be set to any value
816 * without restriction; however, this can happen only once.
817 * If the threshold is exceeded after that, ntpd will exit
818 * with a message to the system log. This option can be used
819 * with the -q and -x options. See the tinker command for other options.
821 * Chroot the server to the directory jaildir. This option also implies
822 * that the server attempts to drop root privileges at startup
823 * (otherwise, chroot gives very little additional security).
824 * You may need to also specify a -u option.
826 * Specify the name and path of the symmetric key file,
827 * default /etc/ntp/keys. This is the same operation
828 * as the "keys FILE" configuration command.
830 * Specify the name and path of the log file. The default
831 * is the system log file. This is the same operation as
832 * the "logfile FILE" configuration command.
833 * -L Do not listen to virtual IPs. The default is to listen.
835 * -N To the extent permitted by the operating system,
836 * run the ntpd at the highest priority.
838 * Specify the name and path of the file used to record the ntpd
839 * process ID. This is the same operation as the "pidfile FILE"
840 * configuration command.
842 * To the extent permitted by the operating system,
843 * run the ntpd at the specified priority.
844 * -q Exit the ntpd just after the first time the clock is set.
845 * This behavior mimics that of the ntpdate program, which is
846 * to be retired. The -g and -x options can be used with this option.
847 * Note: The kernel time discipline is disabled with this option.
849 * Specify the default propagation delay from the broadcast/multicast
850 * server to this client. This is necessary only if the delay
851 * cannot be computed automatically by the protocol.
853 * Specify the directory path for files created by the statistics
854 * facility. This is the same operation as the "statsdir DIR"
855 * configuration command.
857 * Add a key number to the trusted key list. This option can occur
860 * Specify a user, and optionally a group, to switch to.
863 * Add a system variable listed by default.
864 * -x Normally, the time is slewed if the offset is less than the step
865 * threshold, which is 128 ms by default, and stepped if above
866 * the threshold. This option sets the threshold to 600 s, which is
867 * well within the accuracy window to set the clock manually.
868 * Note: since the slew rate of typical Unix kernels is limited
869 * to 0.5 ms/s, each second of adjustment requires an amortization
870 * interval of 2000 s. Thus, an adjustment as much as 600 s
871 * will take almost 14 days to complete. This option can be used
872 * with the -g and -q options. See the tinker command for other options.
873 * Note: The kernel time discipline is disabled with this option.
876 /* By doing init in a separate function we decrease stack usage
879 static NOINLINE void ntp_init(char **argv)
885 /* tzset(); - why? it's called automatically when needed, no? */
888 bb_error_msg_and_die(bb_msg_you_must_be_root);
891 opt_complementary = "dd:p::"; /* d: counter, p: list */
892 opts = getopt32(argv,
894 "p:"IF_FEATURE_NTPD_SERVER("l") /* NOT compat */
896 "46aAbLx", /* compat, ignored */
898 if (!(opts & (OPT_p|OPT_l)))
902 // G.time_is_stepped = 1;
904 add_peers(llist_pop(&peers));
905 if (!(opts & OPT_n)) {
906 bb_daemonize_or_rexec(DAEMON_DEVNULL_STDIO, argv);
907 logmode = LOGMODE_NONE;
909 #if ENABLE_FEATURE_NTPD_SERVER
912 G.listen_fd = create_and_bind_dgram_or_die(NULL, 123);
913 socket_want_pktinfo(G.listen_fd);
914 setsockopt(G.listen_fd, IPPROTO_IP, IP_TOS, &const_IPTOS_LOWDELAY, sizeof(const_IPTOS_LOWDELAY));
917 /* I hesitate to set -20 prio. -15 should be high enough for timekeeping */
919 setpriority(PRIO_PROCESS, 0, -15);
921 /* Set some globals */
927 /* We can use sys_clock_getres but assuming 10ms tick should be fine */
928 clock_getres(CLOCK_REALTIME, &tp);
930 tp.tv_nsec = 10000000;
931 b = 1000000000 / tp.tv_nsec; /* convert to Hz */
933 b = 100; /* b = 1000000000/10000000 = 100 */
941 bb_signals((1 << SIGTERM) | (1 << SIGINT), record_signo);
942 bb_signals((1 << SIGPIPE) | (1 << SIGHUP), SIG_IGN);
945 int ntpd_main(int argc UNUSED_PARAM, char **argv) MAIN_EXTERNALLY_VISIBLE;
946 int ntpd_main(int argc UNUSED_PARAM, char **argv)
950 ntp_peer_t **idx2peer;
952 memset(&g, 0, sizeof(g));
953 SET_PTR_TO_GLOBALS(&g);
958 unsigned cnt = g.peer_cnt;
959 /* if ENABLE_FEATURE_NTPD_SERVER, + 1 for listen_fd: */
960 idx2peer = xzalloc(sizeof(void *) * (cnt + ENABLE_FEATURE_NTPD_SERVER));
961 pfd = xzalloc(sizeof(pfd[0]) * (cnt + ENABLE_FEATURE_NTPD_SERVER));
964 while (!bb_got_signal) {
967 unsigned sent_cnt, trial_cnt;
969 time_t cur_time, nextaction;
971 /* Nothing between here and poll() blocks for any significant time */
973 cur_time = time(NULL);
974 nextaction = cur_time + 3600;
977 #if ENABLE_FEATURE_NTPD_SERVER
978 if (g.listen_fd != -1) {
979 pfd[0].fd = g.listen_fd;
980 pfd[0].events = POLLIN;
984 /* Pass over peer list, send requests, time out on receives */
985 sent_cnt = trial_cnt = 0;
986 for (item = g.ntp_peers; item != NULL; item = item->link) {
987 ntp_peer_t *p = (ntp_peer_t *) item->data;
989 if (p->next != 0 && p->next <= cur_time) {
990 /* Time to send new req */
992 if (send_query_to_peer(p) == 0)
995 if (p->deadline != 0 && p->deadline <= cur_time) {
996 /* Timed out waiting for reply */
997 timeout = error_interval();
998 bb_error_msg("timed out waiting for %s, "
999 "next query in %us", p->dotted, timeout);
1000 if (p->trustlevel >= TRUSTLEVEL_BADPEER) {
1002 if (p->trustlevel < TRUSTLEVEL_BADPEER)
1003 bb_error_msg("peer %s now invalid", p->dotted);
1005 set_next(p, timeout);
1008 if (p->next != 0 && p->next < nextaction)
1009 nextaction = p->next;
1010 if (p->deadline != 0 && p->deadline < nextaction)
1011 nextaction = p->deadline;
1013 if (p->state == STATE_QUERY_SENT) {
1014 /* Wait for reply from this peer */
1016 pfd[i].events = POLLIN;
1022 if ((trial_cnt > 0 && sent_cnt == 0) || g.peer_cnt == 0)
1023 step_time_once(0); /* no good peers, don't wait */
1025 timeout = nextaction - cur_time;
1029 /* Here we may block */
1031 bb_error_msg("poll %u sec, sockets:%u", timeout, i);
1032 nfds = poll(pfd, i, timeout * 1000);
1036 /* Process any received packets */
1038 #if ENABLE_FEATURE_NTPD_SERVER
1039 if (g.listen_fd != -1) {
1040 if (pfd[0].revents /* & (POLLIN|POLLERR)*/) {
1042 recv_and_process_client_pkt(/*g.listen_fd*/);
1047 for (; nfds != 0 && j < i; j++) {
1048 if (pfd[j].revents /* & (POLLIN|POLLERR)*/) {
1050 recv_and_process_peer_pkt(idx2peer[j]);
1053 } /* while (!bb_got_signal) */
1055 kill_myself_with_sig(bb_got_signal);