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 status; /* status of local clock and leap info */
71 uint8_t stratum; /* stratum level */
72 uint8_t ppoll; /* poll value */
74 s_fixedpt_t rootdelay;
75 s_fixedpt_t dispersion;
82 uint8_t digest[NTP_DIGESTSIZE];
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 */
101 MODE_MASK = (7 << 0),
102 VERSION_MASK = (7 << 3),
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 */
114 MODE_RES2 = 7, /* reserved for private use */
117 #define OFFSET_1900_1970 2208988800UL /* 1970 - 1900 in seconds */
122 STATE_REPLY_RECEIVED,
127 double rootdispersion;
149 // (1) store dotted addr str, to avoid constant translations
150 // (2) periodically re-resolve DNS names
151 len_and_sockaddr *lsa;
153 ntp_offset_t reply[OFFSET_ARRAY_SIZE];
155 enum client_state state;
167 /* Insert new options above this line. */
168 /* Non-compat options: */
170 OPT_l = (1 << 5) * ENABLE_FEATURE_NTPD_SERVER,
176 #if ENABLE_FEATURE_NTPD_SERVER
186 #define G (*ptr_to_globals)
189 static const int const_IPTOS_LOWDELAY = IPTOS_LOWDELAY;
193 set_next(ntp_peer_t *p, time_t t)
195 p->next = time(NULL) + t;
200 add_peers(const char *s)
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);
208 p->query.msg.status = MODE_CLIENT | (NTP_VERSION << 3);
210 p->state = STATE_NONE;
211 p->trustlevel = TRUSTLEVEL_PATHETIC;
215 llist_add_to(&G.ntp_peers, p);
223 gettimeofday(&tv, NULL); /* never fails */
224 return (tv.tv_sec + 1.0e-6 * tv.tv_usec + OFFSET_1900_1970);
228 d_to_tv(double d, struct timeval *tv)
230 tv->tv_sec = (long)d;
231 tv->tv_usec = (d - tv->tv_sec) * 1000000;
235 lfp_to_d(l_fixedpt_t lfp)
238 lfp.int_partl = ntohl(lfp.int_partl);
239 lfp.fractionl = ntohl(lfp.fractionl);
240 ret = (double)lfp.int_partl + ((double)lfp.fractionl / UINT_MAX);
245 sfp_to_d(s_fixedpt_t sfp)
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);
254 #if ENABLE_FEATURE_NTPD_SERVER
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);
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);
279 set_deadline(ntp_peer_t *p, time_t t)
281 p->deadline = time(NULL) + t;
289 interval = INTERVAL_QUERY_PATHETIC * QSCALE_OFF_MAX / QSCALE_OFF_MIN;
290 r = (unsigned)random() % (unsigned long)(interval / 10);
291 return (interval + r);
296 const struct sockaddr *from, const struct sockaddr *to, socklen_t addrlen,
297 ntp_msg_t *msg, ssize_t len)
303 ret = sendto(fd, msg, len, MSG_DONTWAIT, to, addrlen);
305 ret = send_to_from(fd, msg, len, MSG_DONTWAIT, to, from, addrlen);
308 bb_perror_msg("send failed");
315 send_query_to_peer(ntp_peer_t *p)
317 // Why do we need to bind()?
318 // See what happens when we don't bind:
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!
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); }
334 if (p->query.fd == -1) {
336 len_and_sockaddr *local_lsa;
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.
347 xbind(fd, &local_lsa->u.sa, local_lsa->len);
349 #if ENABLE_FEATURE_IPV6
350 if (family == AF_INET)
352 setsockopt(fd, IPPROTO_IP, IP_TOS, &const_IPTOS_LOWDELAY, sizeof(const_IPTOS_LOWDELAY));
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.
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.
367 * Save the real transmit timestamp locally.
370 p->query.msg.xmttime.int_partl = random();
371 p->query.msg.xmttime.fractionl = random();
372 p->query.xmttime = gettime1900fp();
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);
380 p->state = STATE_QUERY_SENT;
381 set_deadline(p, QUERYTIME_MAX);
387 offset_compare(const void *aa, const void *bb)
389 const ntp_peer_t *const *a = aa;
390 const ntp_peer_t *const *b = bb;
391 if ((*a)->update.offset < (*b)->update.offset)
393 return ((*a)->update.offset > (*b)->update.offset);
397 updated_scale(double offset)
401 if (offset > QSCALE_OFF_MAX)
403 if (offset < QSCALE_OFF_MIN)
404 return QSCALE_OFF_MAX / QSCALE_OFF_MIN;
405 return QSCALE_OFF_MAX / offset;
416 double offset_median;
418 len_and_sockaddr *lsa;
419 struct timeval tv, olddelta;
422 for (item = G.ntp_peers; item != NULL; item = item->link) {
423 p = (ntp_peer_t *) item->data;
424 if (p->trustlevel < TRUSTLEVEL_BADPEER)
434 peers = xzalloc(sizeof(peers[0]) * offset_cnt);
435 for (item = G.ntp_peers; item != NULL; item = item->link) {
436 p = (ntp_peer_t *) item->data;
437 if (p->trustlevel < TRUSTLEVEL_BADPEER)
442 qsort(peers, offset_cnt, sizeof(peers[0]), offset_compare);
444 middle = offset_cnt / 2;
445 if (middle != 0 && (offset_cnt & 1) == 0) {
446 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);
450 offset_median = peers[middle]->update.offset;
451 G.status.rootdelay = peers[middle]->update.delay;
452 G.status.stratum = peers[middle]->update.status.stratum;
454 G.status.leap = peers[middle]->update.status.leap;
456 bb_info_msg("adjusting local clock by %fs", offset_median);
458 d_to_tv(offset_median, &tv);
459 if (adjtime(&tv, &olddelta) == -1)
460 bb_error_msg("adjtime failed");
462 && olddelta.tv_sec == 0
463 && olddelta.tv_usec == 0
466 bb_info_msg("clock synced");
468 } else if (G.status.synced) {
469 bb_info_msg("clock unsynced");
474 G.status.reftime = gettime1900fp();
475 G.status.stratum++; /* one more than selected peer */
476 G.scale = updated_scale(offset_median);
478 G.status.refid4 = peers[middle]->update.status.refid4;
480 lsa = peers[middle]->lsa;
482 #if ENABLE_FEATURE_IPV6
483 lsa->u.sa.sa_family != AF_INET ?
486 lsa->u.sin.sin_addr.s_addr;
491 for (item = G.ntp_peers; item != NULL; item = item->link) {
492 p = (ntp_peer_t *) item->data;
498 settime(double offset)
502 struct timeval tv, curtime;
511 /* if the offset is small, don't call settimeofday */
512 if (offset < SETTIME_MIN_OFFSET && offset > -SETTIME_MIN_OFFSET)
515 gettimeofday(&curtime, NULL); /* never fails */
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;
522 if (settimeofday(&curtime, NULL) == -1) {
523 bb_error_msg("settimeofday");
527 tval = curtime.tv_sec;
528 strftime(buf, sizeof(buf), "%a %b %e %H:%M:%S %Z %Y", localtime(&tval));
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);
533 for (item = G.ntp_peers; item != NULL; item = item->link) {
534 p = (ntp_peer_t *) item->data;
538 p->deadline -= offset;
542 if (option_mask32 & OPT_q)
547 update_peer_data(ntp_peer_t *p)
549 int i, best = 0, good = 0;
553 * find the offset which arrived with the lowest delay
554 * use that as the peer update
555 * invalidate it and all older ones
558 for (i = 0; good == 0 && i < OFFSET_ARRAY_SIZE; i++) {
559 if (p->reply[i].good) {
565 for (; i < OFFSET_ARRAY_SIZE; i++) {
566 if (p->reply[i].good) {
568 if (p->reply[i].delay < p->reply[best].delay)
576 memcpy(&p->update, &p->reply[best], sizeof(p->update));
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;
585 scale_interval(time_t requested)
588 interval = requested * G.scale;
589 r = (unsigned)random() % (unsigned long)(MAX(5, interval / 10));
590 return (interval + r);
594 recv_and_process_peer_pkt(ntp_peer_t *p)
599 double T1, T2, T3, T4;
601 ntp_offset_t *offset;
603 addr = xmalloc_sockaddr2dotted_noport(&p->lsa->u.sa);
605 /* 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?
609 size = recv(p->query.fd, &msg, sizeof(msg), MSG_DONTWAIT);
611 bb_perror_msg("recv(%s) error", addr);
612 if (errno == EHOSTUNREACH || errno == EHOSTDOWN
613 || errno == ENETUNREACH || errno == ENETDOWN
614 || errno == ECONNREFUSED || errno == EADDRNOTAVAIL
617 //TODO: always do this?
618 set_next(p, error_interval());
624 T4 = gettime1900fp();
626 if (size != NTP_MSGSIZE_NOAUTH && size != NTP_MSGSIZE) {
627 bb_error_msg("malformed packet received from %s", addr);
631 if (msg.orgtime.int_partl != p->query.msg.xmttime.int_partl
632 || msg.orgtime.fractionl != p->query.msg.xmttime.fractionl
637 if ((msg.status & LI_ALARM) == LI_ALARM
639 || msg.stratum > NTP_MAXSTRATUM
641 interval = error_interval();
642 bb_info_msg("reply from %s: not synced, next query %ds", addr, (int) interval);
647 * From RFC 2030 (with a correction to the delay math):
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
656 * The roundtrip delay d and local clock offset t are defined as
658 * d = (T4 - T1) - (T3 - T2) t = ((T2 - T1) + (T3 - T4)) / 2.
661 T1 = p->query.xmttime;
662 T2 = lfp_to_d(msg.rectime);
663 T3 = lfp_to_d(msg.xmttime);
665 offset = &p->reply[p->shift];
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);
675 offset->error = (T2 - T1) - (T3 - T4);
676 // Can we use (T4 - OFFSET_1900_1970) instead of time(NULL)?
677 offset->rcvd = time(NULL);
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;
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);
695 interval = scale_interval(INTERVAL_QUERY_NORMAL);
697 set_next(p, interval);
698 p->state = STATE_REPLY_RECEIVED;
700 /* every received reply which we do not discard increases trust */
701 if (p->trustlevel < TRUSTLEVEL_MAX) {
703 if (p->trustlevel == TRUSTLEVEL_BADPEER)
704 bb_info_msg("peer %s now valid", addr);
707 bb_info_msg("reply from %s: offset %f delay %f, next query %ds", addr,
708 offset->offset, offset->delay, (int) interval);
711 settime(offset->offset);
714 if (p->shift >= OFFSET_ARRAY_SIZE)
721 #if ENABLE_FEATURE_NTPD_SERVER
723 recv_and_process_client_pkt(void /*int fd*/)
728 len_and_sockaddr *to;
729 struct sockaddr *from;
731 uint8_t query_status;
733 l_fixedpt_t query_xmttime;
735 to = get_sock_lsa(G.listen_fd);
736 from = xzalloc(to->len);
738 size = recv_from_to(G.listen_fd, &msg, sizeof(msg), MSG_DONTWAIT, from, &to->u.sa, to->len);
739 if (size != NTP_MSGSIZE_NOAUTH && size != NTP_MSGSIZE) {
744 bb_perror_msg_and_die("recv_from_to");
746 addr = xmalloc_sockaddr2dotted_noport(from);
747 bb_error_msg("malformed packet received from %s", addr);
752 query_status = msg.status;
753 query_ppoll = msg.ppoll;
754 query_xmttime = msg.xmttime;
756 /* 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) ?
761 MODE_SERVER : MODE_SYM_PAS;
762 msg.stratum = G.status.stratum;
763 msg.ppoll = query_ppoll;
764 msg.precision = G.status.precision;
765 rectime = gettime1900fp();
766 msg.xmttime = msg.rectime = d_to_lfp(rectime);
767 msg.reftime = d_to_lfp(G.status.reftime);
768 //msg.xmttime = d_to_lfp(gettime1900fp()); // = msg.rectime
769 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;
774 /* We reply from the local address packet was sent to,
775 * this makes to/from look swapped here: */
776 sendmsg_wrap(G.listen_fd,
777 /*from:*/ &to->u.sa, /*to:*/ from, /*addrlen:*/ to->len,
786 /* Upstream ntpd's options:
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.
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.
803 * Specify debugging level directly.
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.
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.
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.
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.
830 * -N To the extent permitted by the operating system,
831 * run the ntpd at the highest priority.
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.
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.
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.
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.
852 * Add a key number to the trusted key list. This option can occur
855 * Specify a user, and optionally a group, to switch to.
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.
871 /* By doing init in a separate function we decrease stack usage
874 static NOINLINE void ntp_init(char **argv)
880 /* tzset(); - why? it's called automatically when needed, no? */
883 bb_error_msg_and_die(bb_msg_you_must_be_root);
886 opt_complementary = "dd:p::"; /* d: counter, p: list */
887 opts = getopt32(argv,
889 "p:"IF_FEATURE_NTPD_SERVER("l") /* NOT compat */
891 "46aAbLx", /* compat, ignored */
893 if (!(opts & (OPT_p|OPT_l)))
898 add_peers(llist_pop(&peers));
899 if (!(opts & OPT_n)) {
900 bb_daemonize_or_rexec(DAEMON_DEVNULL_STDIO, argv);
901 logmode = LOGMODE_NONE;
903 #if ENABLE_FEATURE_NTPD_SERVER
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));
911 /* I hesitate to set -20 prio. -15 should be high enough for timekeeping */
913 setpriority(PRIO_PROCESS, 0, -15);
915 /* Set some globals */
921 /* We can use sys_clock_getres but assuming 10ms tick should be fine */
922 clock_getres(CLOCK_REALTIME, &tp);
924 tp.tv_nsec = 10000000;
925 b = 1000000000 / tp.tv_nsec; /* convert to Hz */
927 b = 100; /* b = 1000000000/10000000 = 100 */
931 G.status.precision = prec;
936 bb_signals((1 << SIGTERM) | (1 << SIGINT), record_signo);
937 bb_signals((1 << SIGPIPE) | (1 << SIGHUP), SIG_IGN);
940 int ntpd_main(int argc UNUSED_PARAM, char **argv) MAIN_EXTERNALLY_VISIBLE;
941 int ntpd_main(int argc UNUSED_PARAM, char **argv)
945 ntp_peer_t **idx2peer;
947 memset(&g, 0, sizeof(g));
948 SET_PTR_TO_GLOBALS(&g);
953 unsigned cnt = g.peer_cnt;
954 /* if ENABLE_FEATURE_NTPD_SERVER, + 1 for listen_fd: */
955 idx2peer = xzalloc(sizeof(void *) * (cnt + ENABLE_FEATURE_NTPD_SERVER));
956 pfd = xzalloc(sizeof(pfd[0]) * (cnt + ENABLE_FEATURE_NTPD_SERVER));
959 while (!bb_got_signal) {
962 unsigned sent_cnt, trial_cnt;
964 time_t cur_time, nextaction;
966 /* Nothing between here and poll() blocks for any significant time */
968 cur_time = time(NULL);
969 nextaction = cur_time + 3600;
972 #if ENABLE_FEATURE_NTPD_SERVER
973 if (g.listen_fd != -1) {
974 pfd[0].fd = g.listen_fd;
975 pfd[0].events = POLLIN;
979 /* Pass over peer list, send requests, time out on receives */
980 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;
984 if (p->next != 0 && p->next <= cur_time) {
985 /* Time to send new req */
987 if (send_query_to_peer(p) == 0)
990 if (p->deadline != 0 && p->deadline <= cur_time) {
991 /* Timed out waiting for reply */
992 char *addr = xmalloc_sockaddr2dotted_noport(&p->lsa->u.sa);
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) {
999 if (p->trustlevel < TRUSTLEVEL_BADPEER)
1000 bb_info_msg("peer %s now invalid", addr);
1004 set_next(p, timeout);
1007 if (p->next != 0 && p->next < nextaction)
1008 nextaction = p->next;
1009 if (p->deadline != 0 && p->deadline < nextaction)
1010 nextaction = p->deadline;
1012 if (p->state == STATE_QUERY_SENT) {
1013 /* Wait for reply from this peer */
1014 pfd[i].fd = p->query.fd;
1015 pfd[i].events = POLLIN;
1021 if ((trial_cnt > 0 && sent_cnt == 0) || g.peer_cnt == 0)
1022 settime(0); /* no good peers, don't wait */
1024 timeout = nextaction - cur_time;
1028 /* Here we may block */
1030 bb_error_msg("entering poll %u secs", timeout);
1031 nfds = poll(pfd, i, timeout * 1000);
1035 /* Process any received packets */
1037 #if ENABLE_FEATURE_NTPD_SERVER
1038 if (g.listen_fd != -1) {
1039 if (pfd[0].revents /* & (POLLIN|POLLERR)*/) {
1041 recv_and_process_client_pkt(/*g.listen_fd*/);
1046 for (; nfds != 0 && j < i; j++) {
1047 if (pfd[j].revents /* & (POLLIN|POLLERR)*/) {
1049 recv_and_process_peer_pkt(idx2peer[j]);
1052 } /* while (!bb_got_signal) */
1054 kill_myself_with_sig(bb_got_signal);