2 * ntpdate - set the time of day by polling one or more NTP servers
10 #include <netinfo/ni.h>
16 #include "ntp_unixtime.h"
18 #include "ntp_string.h"
19 #include "ntp_syslog.h"
20 #include "ntp_select.h"
21 #include "ntp_stdlib.h"
35 # include <sys/signal.h>
36 # ifdef HAVE_SYS_IOCTL_H
37 # include <sys/ioctl.h>
39 #endif /* SYS_WINNT */
40 #ifdef HAVE_SYS_RESOURCE_H
41 # include <sys/resource.h>
42 #endif /* HAVE_SYS_RESOURCE_H */
49 /* select wants a zero structure ... */
50 struct timeval timeout = {0,0};
52 struct timeval timeout = {60,0};
58 # define TARGET_RESOLUTION 1 /* Try for 1-millisecond accuracy
59 on Windows NT timers. */
60 #pragma comment(lib, "winmm")
61 #endif /* SYS_WINNT */
64 * Scheduling priority we run at
67 # define NTPDATE_PRIO (-12)
69 # define NTPDATE_PRIO (100)
72 #if defined(HAVE_TIMER_SETTIME) || defined (HAVE_TIMER_CREATE)
73 /* POSIX TIMERS - vxWorks doesn't have itimer - casey */
74 static timer_t ntpdate_timerid;
78 * Compatibility stuff for Version 2
80 #define NTP_MAXSKW 0x28f /* 0.01 sec in fp format */
81 #define NTP_MINDIST 0x51f /* 0.02 sec in fp format */
82 #define PEER_MAXDISP (64*FP_SECOND) /* maximum dispersion (fp 64) */
83 #define NTP_INFIN 15 /* max stratum, infinity a la Bellman-Ford */
84 #define NTP_MAXWGT (8*FP_SECOND) /* maximum select weight 8 seconds */
85 #define NTP_MAXLIST 5 /* maximum select list size */
86 #define PEER_SHIFT 8 /* 8 suitable for crystal time base */
91 volatile int debug = 0;
94 * File descriptor masks etc. for call to select
104 * Initializing flag. All async routines watch this and only do their
105 * thing when it is clear.
107 int initializing = 1;
110 * Alarm flag. Set when an alarm occurs
112 volatile int alarm_flag = 0;
117 int simple_query = 0;
120 * Unpriviledged port flag.
125 * Time to spend measuring drift rate
135 * Systemwide parameters and flags
137 int sys_samples = DEFSAMPLES; /* number of samples/server */
138 u_long sys_timeout = DEFTIMEOUT; /* timeout time, in TIMER_HZ units */
139 struct server *sys_servers; /* the server list */
140 int sys_numservers = 0; /* number of servers to poll */
141 int sys_authenticate = 0; /* true when authenticating */
142 u_int32 sys_authkey = 0; /* set to authentication key in use */
143 u_long sys_authdelay = 0; /* authentication delay */
144 int sys_version = NTP_VERSION; /* version to poll with */
147 * The current internal time
149 u_long current_time = 0;
152 * Counter for keeping track of completed servers
154 int complete_servers = 0;
157 * File of encryption keys
162 #define KEYFILE "/etc/ntp.keys"
164 #define KEYFILE "%windir%\\ntp.keys"
165 # endif /* SYS_WINNT */
169 const char *key_file = KEYFILE;
171 char key_file_storage[MAX_PATH+1], *key_file ;
172 #endif /* SYS_WINNT */
175 * Miscellaneous flags
181 int ntpdatemain P((int, char **));
182 static void transmit P((struct server *));
183 static void receive P((struct recvbuf *));
184 static void server_data P((struct server *, s_fp, l_fp *, u_fp));
185 static void clock_filter P((struct server *));
186 static struct server *clock_select P((void));
187 static int clock_adjust P((void));
188 static void addserver P((char *));
189 static struct server *findserver P((struct sockaddr_in *));
190 void timer P((void));
191 static void init_alarm P((void));
193 static RETSIGTYPE alarming P((int));
194 #endif /* SYS_WINNT */
195 static void init_io P((void));
196 static void sendpkt P((struct sockaddr_in *, struct pkt *, int));
197 void input_handler P((void));
199 static int l_adj_systime P((l_fp *));
200 static int l_step_systime P((l_fp *));
202 static int getnetnum P((const char *, u_int32 *));
203 static void printserver P((struct server *, FILE *));
207 WORD wVersionRequested;
209 HANDLE TimerThreadHandle = NULL;
210 #endif /* SYS_WINNT */
212 #ifdef NO_MAIN_ALLOWED
213 CALL(ntpdate,"ntpdate",ntpdatemain);
224 * Initializing flag. All async routines watch this and only do their
225 * thing when it is clear.
230 * Alarm flag. Set when an alarm occurs
240 * Unpriviledged port flag.
245 * Time to spend measuring drift rate
249 * Systemwide parameters and flags
251 sys_numservers = 0; /* number of servers to poll */
252 sys_authenticate = 0; /* true when authenticating */
253 sys_authkey = 0; /* set to authentication key in use */
254 sys_authdelay = 0; /* authentication delay */
255 sys_version = NTP_VERSION; /* version to poll with */
258 * The current internal time
263 * Counter for keeping track of completed servers
265 complete_servers = 0;
273 static ni_namelist *getnetinfoservers P((void));
277 * Main program. Initialize us and loop waiting for I/O and/or
280 #ifndef NO_MAIN_ALLOWED
287 return ntpdatemain (argc, argv);
289 #endif /* NO_MAIN_ALLOWED */
298 struct recvbuf *rbuflist;
299 struct recvbuf *rbuf;
304 ni_namelist *netinfoservers;
307 HANDLE process_handle;
309 wVersionRequested = MAKEWORD(1,1);
310 if (WSAStartup(wVersionRequested, &wsaData)) {
311 msyslog(LOG_ERR, "No useable winsock.dll: %m");
315 key_file = key_file_storage;
317 if (!ExpandEnvironmentStrings(KEYFILE, key_file, MAX_PATH))
319 msyslog(LOG_ERR, "ExpandEnvironmentStrings(KEYFILE) failed: %m\n");
321 #endif /* SYS_WINNT */
323 #ifdef NO_MAIN_ALLOWED
332 * Decode argument list
334 while ((c = ntp_getopt(argc, argv, "a:bBde:k:o:p:qr:st:uv")) != EOF)
338 c = atoi(ntp_optarg);
339 sys_authenticate = 1;
354 if (!atolfp(ntp_optarg, &tmp)
356 (void) fprintf(stderr,
357 "%s: encryption delay %s is unlikely\n",
358 progname, ntp_optarg);
361 sys_authdelay = tmp.l_uf;
365 key_file = ntp_optarg;
368 sys_version = atoi(ntp_optarg);
371 c = atoi(ntp_optarg);
372 if (c <= 0 || c > NTP_SHIFT) {
373 (void) fprintf(stderr,
374 "%s: number of samples (%d) is invalid\n",
385 c = atoi(ntp_optarg);
386 if (c <= 0 || c > (60 * 60)) {
387 (void) fprintf(stderr,
388 "%s: rate (%d) is invalid: 0 - %d\n",
389 progname, c, (60 * 60));
399 if (!atolfp(ntp_optarg, &tmp)) {
400 (void) fprintf(stderr,
401 "%s: timeout %s is undecodeable\n",
402 progname, ntp_optarg);
405 sys_timeout = ((LFPTOFP(&tmp) * TIMER_HZ)
407 if (sys_timeout == 0)
425 (void) fprintf(stderr,
426 "usage: %s [-bBdqsv] [-a key#] [-e delay] [-k file] [-p samples] [-o version#] [-r rate] [-t timeo] server ...\n",
431 if (debug || simple_query) {
433 static char buf[BUFSIZ];
434 setvbuf(stdout, buf, _IOLBF, BUFSIZ);
441 * Logging. Open the syslog if we have to
444 #if !defined (SYS_WINNT) && !defined (SYS_VXWORKS) && !defined SYS_CYGWIN32
446 openlog("ntpdate", LOG_PID);
450 # define LOG_NTP LOG_DAEMON
452 openlog("ntpdate", LOG_PID | LOG_NDELAY, LOG_NTP);
454 setlogmask(LOG_UPTO(LOG_DEBUG));
456 setlogmask(LOG_UPTO(LOG_INFO));
457 # endif /* LOG_DAEMON */
458 #endif /* SYS_WINNT */
461 if (debug || verbose)
462 msyslog(LOG_NOTICE, "%s", Version);
465 * Add servers we are going to be polling
468 netinfoservers = getnetinfoservers();
471 for ( ; ntp_optind < argc; ntp_optind++)
472 addserver(argv[ntp_optind]);
475 if (netinfoservers) {
476 if ( netinfoservers->ni_namelist_len &&
477 *netinfoservers->ni_namelist_val ) {
478 u_int servercount = 0;
479 while (servercount < netinfoservers->ni_namelist_len) {
480 if (debug) msyslog(LOG_DEBUG,
481 "Adding time server %s from NetInfo configuration.",
482 netinfoservers->ni_namelist_val[servercount]);
483 addserver(netinfoservers->ni_namelist_val[servercount++]);
486 ni_namelist_free(netinfoservers);
487 free(netinfoservers);
491 if (sys_numservers == 0) {
492 msyslog(LOG_ERR, "no servers can be used, exiting");
497 * Initialize the time of day routines and the I/O subsystem
499 if (sys_authenticate) {
501 if (!authreadkeys(key_file)) {
502 msyslog(LOG_ERR, "no key file <%s>, exiting", key_file);
505 authtrust(sys_authkey, 1);
506 if (!authistrusted(sys_authkey)) {
509 (void) sprintf(buf, "%lu", (unsigned long)sys_authkey);
510 msyslog(LOG_ERR, "authentication key %s unknown", buf);
521 taskPrioritySet( taskIdSelf(), NTPDATE_PRIO);
523 #if defined(HAVE_ATT_NICE)
526 #if defined(HAVE_BSD_NICE)
527 (void) setpriority(PRIO_PROCESS, 0, NTPDATE_PRIO);
530 process_handle = GetCurrentProcess();
531 if (!SetPriorityClass(process_handle, (DWORD) REALTIME_PRIORITY_CLASS)) {
532 msyslog(LOG_ERR, "SetPriorityClass failed: %m");
534 #endif /* SYS_WINNT */
539 rbuflist = (struct recvbuf *)0;
540 while (complete_servers < sys_numservers) {
542 struct pollfd rdfdes;
548 if (alarm_flag) { /* alarmed? */
552 rbuflist = getrecvbufs(); /* get received buffers */
554 if (!was_alarmed && rbuflist == (struct recvbuf *)0) {
556 * Nothing to do. Wait for something.
560 nfound = poll(&rdfdes, 1, timeout.tv_sec * 1000);
562 nfound = select(fd+1, &rdfdes, (fd_set *)0,
563 (fd_set *)0, &timeout);
571 nfound == SOCKET_ERROR
572 #endif /* SYS_WINNT */
588 "poll(): nfound = %d, error: %m",
590 "select(): nfound = %d, error: %m",
595 if (alarm_flag) { /* alarmed? */
599 rbuflist = getrecvbufs(); /* get received buffers */
603 * Out here, signals are unblocked. Call receive
604 * procedure for each incoming packet.
606 while (rbuflist != (struct recvbuf *)0) {
608 rbuflist = rbuf->next;
614 * Call timer to process any timeouts
627 * When we get here we've completed the polling of all servers.
628 * Adjust the clock, then exit.
635 timer_delete(ntpdate_timerid);
637 return clock_adjust();
642 * transmit - transmit a packet to the given server, or mark it completed.
643 * This is called by the timeout routine and by the receive
648 register struct server *server
654 printf("transmit(%s)\n", ntoa(&server->srcadr));
656 if (server->filter_nextpt < server->xmtcnt) {
659 * Last message to this server timed out. Shift
660 * zeros into the filter.
663 server_data(server, 0, &ts, 0);
666 if ((int)server->filter_nextpt >= sys_samples) {
668 * Got all the data we need. Mark this guy
669 * completed and return.
671 server->event_time = 0;
677 * If we're here, send another message to the server. Fill in
678 * the packet and let 'er rip.
680 xpkt.li_vn_mode = PKT_LI_VN_MODE(LEAP_NOTINSYNC,
681 sys_version, MODE_CLIENT);
682 xpkt.stratum = STRATUM_TO_PKT(STRATUM_UNSPEC);
683 xpkt.ppoll = NTP_MINPOLL;
684 xpkt.precision = NTPDATE_PRECISION;
685 xpkt.rootdelay = htonl(NTPDATE_DISTANCE);
686 xpkt.rootdispersion = htonl(NTPDATE_DISP);
687 xpkt.refid = htonl(NTPDATE_REFID);
688 L_CLR(&xpkt.reftime);
693 * Determine whether to authenticate or not. If so,
694 * fill in the extended part of the packet and do it.
695 * If not, just timestamp it and send it away.
697 if (sys_authenticate) {
700 xpkt.exten[0] = htonl(sys_authkey);
701 get_systime(&server->xmt);
702 L_ADDUF(&server->xmt, sys_authdelay);
703 HTONL_FP(&server->xmt, &xpkt.xmt);
704 len = authencrypt(sys_authkey, (u_int32 *)&xpkt, LEN_PKT_NOMAC);
705 sendpkt(&(server->srcadr), &xpkt, (int)(LEN_PKT_NOMAC + len));
708 printf("transmit auth to %s\n",
709 ntoa(&(server->srcadr)));
711 get_systime(&(server->xmt));
712 HTONL_FP(&server->xmt, &xpkt.xmt);
713 sendpkt(&(server->srcadr), &xpkt, LEN_PKT_NOMAC);
716 printf("transmit to %s\n", ntoa(&(server->srcadr)));
720 * Update the server timeout and transmit count
722 server->event_time = current_time + sys_timeout;
728 * receive - receive and process an incoming frame
732 struct recvbuf *rbufp
735 register struct pkt *rpkt;
736 register struct server *server;
746 printf("receive(%s)\n", ntoa(&rbufp->recv_srcadr));
748 * Check to see if the packet basically looks like something
751 if (rbufp->recv_length == LEN_PKT_NOMAC)
753 else if (rbufp->recv_length >= LEN_PKT_NOMAC)
757 printf("receive: packet length %d\n",
759 return; /* funny length packet */
762 rpkt = &(rbufp->recv_pkt);
763 if (PKT_VERSION(rpkt->li_vn_mode) < NTP_OLDVERSION ||
764 PKT_VERSION(rpkt->li_vn_mode) > NTP_VERSION) {
768 if ((PKT_MODE(rpkt->li_vn_mode) != MODE_SERVER
769 && PKT_MODE(rpkt->li_vn_mode) != MODE_PASSIVE)
770 || rpkt->stratum >= STRATUM_UNSPEC) {
772 printf("receive: mode %d stratum %d\n",
773 PKT_MODE(rpkt->li_vn_mode), rpkt->stratum);
778 * So far, so good. See if this is from a server we know.
780 server = findserver(&(rbufp->recv_srcadr));
781 if (server == NULL) {
783 printf("receive: server not found\n");
788 * Decode the org timestamp and make sure we're getting a response
789 * to our last request.
791 NTOHL_FP(&rpkt->org, &org);
792 if (!L_ISEQU(&org, &server->xmt)) {
794 printf("receive: pkt.org and peer.xmt differ\n");
799 * Check out the authenticity if we're doing that.
801 if (!sys_authenticate)
807 printf("receive: rpkt keyid=%ld sys_authkey=%ld decrypt=%ld\n",
808 (long int)ntohl(rpkt->exten[0]), (long int)sys_authkey,
809 (long int)authdecrypt(sys_authkey, (u_int32 *)rpkt,
810 LEN_PKT_NOMAC, (int)(rbufp->recv_length - LEN_PKT_NOMAC)));
812 if (has_mac && ntohl(rpkt->exten[0]) == sys_authkey &&
813 authdecrypt(sys_authkey, (u_int32 *)rpkt, LEN_PKT_NOMAC,
814 (int)(rbufp->recv_length - LEN_PKT_NOMAC)))
817 printf("receive: authentication %s\n",
818 is_authentic ? "passed" : "failed");
825 * Looks good. Record info from the packet.
827 server->leap = PKT_LEAP(rpkt->li_vn_mode);
828 server->stratum = PKT_TO_STRATUM(rpkt->stratum);
829 server->precision = rpkt->precision;
830 server->rootdelay = ntohl(rpkt->rootdelay);
831 server->rootdispersion = ntohl(rpkt->rootdispersion);
832 server->refid = rpkt->refid;
833 NTOHL_FP(&rpkt->reftime, &server->reftime);
834 NTOHL_FP(&rpkt->rec, &rec);
835 NTOHL_FP(&rpkt->xmt, &server->org);
838 * Make sure the server is at least somewhat sane. If not, try
841 if (L_ISZERO(&rec) || !L_ISHIS(&server->org, &rec)) {
847 * Calculate the round trip delay (di) and the clock offset (ci).
848 * We use the equations (reordered from those in the spec):
850 * d = (t2 - t3) - (t1 - t0)
851 * c = ((t2 - t3) + (t1 - t0)) / 2
853 t10 = server->org; /* pkt.xmt == t1 */
854 L_SUB(&t10, &rbufp->recv_time); /* recv_time == t0*/
856 t23 = rec; /* pkt.rec == t2 */
857 L_SUB(&t23, &org); /* pkt->org == t3 */
859 /* now have (t2 - t3) and (t0 - t1). Calculate (ci) and (di) */
865 * Calculate di in t23 in full precision, then truncate
872 printf("offset: %s, delay %s\n", lfptoa(&ci, 6), fptoa(di, 5));
874 di += (FP_SECOND >> (-(int)NTPDATE_PRECISION))
875 + (FP_SECOND >> (-(int)server->precision)) + NTP_MAXSKW;
877 if (di <= 0) { /* value still too raunchy to use? */
881 di = max(di, NTP_MINDIST);
885 * Shift this data in, then transmit again.
887 server_data(server, (s_fp) di, &ci, 0);
893 * server_data - add a sample to the server's filter registers
897 register struct server *server,
905 i = server->filter_nextpt;
907 server->filter_delay[i] = d;
908 server->filter_offset[i] = *c;
909 server->filter_soffset[i] = LFPTOFP(c);
910 server->filter_error[i] = e;
911 server->filter_nextpt = i + 1;
917 * clock_filter - determine a server's delay, dispersion and offset
921 register struct server *server
928 * Sort indices into increasing delay order
930 for (i = 0; i < sys_samples; i++)
933 for (i = 0; i < (sys_samples-1); i++) {
934 for (j = i+1; j < sys_samples; j++) {
935 if (server->filter_delay[ord[j]] == 0)
937 if (server->filter_delay[ord[i]] == 0
938 || (server->filter_delay[ord[i]]
939 > server->filter_delay[ord[j]])) {
950 * Now compute the dispersion, and assign values to delay and
951 * offset. If there are no samples in the register, delay and
952 * offset go to zero and dispersion is set to the maximum.
954 if (server->filter_delay[ord[0]] == 0) {
956 L_CLR(&server->offset);
958 server->dispersion = PEER_MAXDISP;
962 server->delay = server->filter_delay[ord[0]];
963 server->offset = server->filter_offset[ord[0]];
964 server->soffset = LFPTOFP(&server->offset);
965 server->dispersion = 0;
966 for (i = 1; i < sys_samples; i++) {
967 if (server->filter_delay[ord[i]] == 0)
970 d = server->filter_soffset[ord[i]]
971 - server->filter_soffset[ord[0]];
974 if (d > PEER_MAXDISP)
978 * XXX This *knows* PEER_FILTER is 1/2
980 server->dispersion += (u_fp)(d) >> i;
990 * clock_select - select the pick-of-the-litter clock from the samples
993 static struct server *
996 register struct server *server;
1002 s_fp local_threshold;
1003 struct server *server_list[NTP_MAXCLOCK];
1004 u_fp server_badness[NTP_MAXCLOCK];
1005 struct server *sys_server;
1008 * This first chunk of code is supposed to go through all
1009 * servers we know about to find the NTP_MAXLIST servers which
1010 * are most likely to succeed. We run through the list
1011 * doing the sanity checks and trying to insert anyone who
1012 * looks okay. We are at all times aware that we should
1013 * only keep samples from the top two strata and we only need
1014 * NTP_MAXLIST of them.
1016 nlist = 0; /* none yet */
1017 for (server = sys_servers; server != NULL; server = server->next_server) {
1018 if (server->delay == 0)
1019 continue; /* no data */
1020 if (server->stratum > NTP_INFIN)
1021 continue; /* stratum no good */
1022 if (server->delay > NTP_MAXWGT) {
1023 continue; /* too far away */
1025 if (server->leap == LEAP_NOTINSYNC)
1026 continue; /* he's in trouble */
1027 if (!L_ISHIS(&server->org, &server->reftime)) {
1028 continue; /* very broken host */
1030 if ((server->org.l_ui - server->reftime.l_ui)
1032 continue; /* too long without sync */
1034 if (server->trust != 0) {
1039 * This one seems sane. Find where he belongs
1042 d = server->dispersion + server->dispersion;
1043 for (i = 0; i < nlist; i++)
1044 if (server->stratum <= server_list[i]->stratum)
1046 for ( ; i < nlist; i++) {
1047 if (server->stratum < server_list[i]->stratum)
1049 if (d < (s_fp) server_badness[i])
1054 * If i points past the end of the list, this
1055 * guy is a loser, else stick him in.
1057 if (i >= NTP_MAXLIST)
1059 for (j = nlist; j > i; j--)
1060 if (j < NTP_MAXLIST) {
1061 server_list[j] = server_list[j-1];
1063 = server_badness[j-1];
1066 server_list[i] = server;
1067 server_badness[i] = d;
1068 if (nlist < NTP_MAXLIST)
1073 * Got the five-or-less best. Cut the list where the number of
1074 * strata exceeds two.
1077 for (i = 1; i < nlist; i++)
1078 if (server_list[i]->stratum > server_list[i-1]->stratum)
1085 * Whew! What we should have by now is 0 to 5 candidates for
1086 * the job of syncing us. If we have none, we're out of luck.
1087 * If we have one, he's a winner. If we have more, do falseticker
1093 else if (nlist == 1) {
1094 sys_server = server_list[0];
1097 * Re-sort by stratum, bdelay estimate quality and
1100 for (i = 0; i < nlist-1; i++)
1101 for (j = i+1; j < nlist; j++) {
1102 if (server_list[i]->stratum
1103 < server_list[j]->stratum)
1104 break; /* already sorted by stratum */
1105 if (server_list[i]->delay
1106 < server_list[j]->delay)
1108 server = server_list[i];
1109 server_list[i] = server_list[j];
1110 server_list[j] = server;
1114 * Calculate the fixed part of the dispersion limit
1116 local_threshold = (FP_SECOND >> (-(int)NTPDATE_PRECISION))
1120 * Now drop samples until we're down to one.
1123 for (n = 0; n < nlist; n++) {
1124 server_badness[n] = 0;
1125 for (j = 0; j < nlist; j++) {
1126 if (j == n) /* with self? */
1128 d = server_list[j]->soffset
1129 - server_list[n]->soffset;
1130 if (d < 0) /* absolute value */
1133 * XXX This code *knows* that
1136 for (i = 0; i < j; i++)
1137 d = (d>>1) + (d>>2);
1138 server_badness[n] += d;
1143 * We now have an array of nlist badness
1144 * coefficients. Find the badest. Find
1145 * the minimum precision while we're at
1149 n = server_list[0]->precision;;
1150 for (j = 1; j < nlist; j++) {
1151 if (server_badness[j] >= server_badness[i])
1153 if (n > server_list[j]->precision)
1154 n = server_list[j]->precision;
1158 * i is the index of the server with the worst
1159 * dispersion. If his dispersion is less than
1160 * the threshold, stop now, else delete him and
1161 * continue around again.
1163 if ( (s_fp) server_badness[i] < (local_threshold
1164 + (FP_SECOND >> (-n))))
1166 for (j = i + 1; j < nlist; j++)
1167 server_list[j-1] = server_list[j];
1172 * What remains is a list of less than 5 servers. Take
1175 sys_server = server_list[0];
1179 * That's it. Return our server.
1186 * clock_adjust - process what we've received, and adjust the time
1187 * if we got anything decent.
1192 register struct server *sp, *server;
1196 for (sp = sys_servers; sp != NULL; sp = sp->next_server)
1198 server = clock_select();
1200 if (debug || simple_query) {
1201 for (sp = sys_servers; sp != NULL; sp = sp->next_server)
1202 printserver(sp, stdout);
1207 "no server suitable for synchronization found");
1213 } else if (never_step) {
1216 absoffset = server->soffset;
1218 absoffset = -absoffset;
1219 dostep = (absoffset >= NTPDATE_THRESHOLD);
1223 if (simple_query || l_step_systime(&server->offset)) {
1224 msyslog(LOG_NOTICE, "step time server %s offset %s sec",
1225 ntoa(&server->srcadr),
1226 lfptoa(&server->offset, 6));
1229 #if !defined SYS_WINNT && !defined SYS_CYGWIN32
1230 if (simple_query || l_adj_systime(&server->offset)) {
1231 msyslog(LOG_NOTICE, "adjust time server %s offset %s sec",
1232 ntoa(&server->srcadr),
1233 lfptoa(&server->offset, 6));
1236 /* The NT SetSystemTimeAdjustment() call achieves slewing by
1237 * changing the clock frequency. This means that we cannot specify
1238 * it to slew the clock by a definite amount and then stop like
1239 * the Unix adjtime() routine. We can technically adjust the clock
1240 * frequency, have ntpdate sleep for a while, and then wake
1241 * up and reset the clock frequency, but this might cause some
1242 * grief if the user attempts to run ntpd immediately after
1243 * ntpdate and the socket is in use.
1245 printf("\nThe -b option is required by ntpdate on Windows NT platforms\n");
1247 #endif /* SYS_WINNT */
1253 /* XXX ELIMINATE: merge BIG slew into adj_systime in lib/systime.c */
1255 * addserver - determine a server's address and allocate a new structure
1263 register struct server *server;
1266 if (!getnetnum(serv, &netnum)) {
1267 msyslog(LOG_ERR, "can't find host %s\n", serv);
1271 server = (struct server *)emalloc(sizeof(struct server));
1272 memset((char *)server, 0, sizeof(struct server));
1274 server->srcadr.sin_family = AF_INET;
1275 server->srcadr.sin_addr.s_addr = netnum;
1276 server->srcadr.sin_port = htons(NTP_PORT);
1278 server->event_time = ++sys_numservers;
1279 if (sys_servers == NULL)
1280 sys_servers = server;
1284 for (sp = sys_servers; sp->next_server != NULL;
1285 sp = sp->next_server) ;
1286 sp->next_server = server;
1292 * findserver - find a server in the list given its address
1294 static struct server *
1296 struct sockaddr_in *addr
1299 register u_int32 netnum;
1300 struct server *server;
1301 struct server *mc_server;
1304 if (htons(addr->sin_port) != NTP_PORT)
1306 netnum = addr->sin_addr.s_addr;
1308 for (server = sys_servers; server != NULL;
1309 server = server->next_server) {
1310 register u_int32 servnum;
1312 servnum = server->srcadr.sin_addr.s_addr;
1313 if (netnum == servnum)
1315 if (IN_MULTICAST(ntohl(servnum)))
1319 if (mc_server != NULL) {
1322 if (mc_server->event_time != 0) {
1323 mc_server->event_time = 0;
1326 server = (struct server *)emalloc(sizeof(struct server));
1327 memset((char *)server, 0, sizeof(struct server));
1329 server->srcadr.sin_family = AF_INET;
1330 server->srcadr.sin_addr.s_addr = netnum;
1331 server->srcadr.sin_port = htons(NTP_PORT);
1333 server->event_time = ++sys_numservers;
1334 for (sp = sys_servers; sp->next_server != NULL;
1335 sp = sp->next_server) ;
1336 sp->next_server = server;
1344 * timer - process a timer interrupt
1349 struct server *server;
1352 * Bump the current idea of the time
1357 * Search through the server list looking for guys
1358 * who's event timers have expired. Give these to
1359 * the transmit routine.
1361 for (server = sys_servers; server != NULL;
1362 server = server->next_server) {
1363 if (server->event_time != 0
1364 && server->event_time <= current_time)
1371 * The code duplication in the following subroutine sucks, but
1372 * we need to appease ansi2knr.
1377 * alarming - record the occurance of an alarm interrupt
1388 alarming(UINT uTimerID, UINT uMsg, DWORD dwUser, DWORD dw1, DWORD dw2)
1392 #endif /* SYS_WINNT */
1396 * init_alarm - set up the timer interrupt
1402 # ifndef HAVE_TIMER_SETTIME
1403 struct itimerval itimer;
1405 struct itimerspec ntpdate_itimer;
1409 UINT wTimerRes, wTimerID;
1410 # endif /* SYS_WINNT */
1411 #if defined SYS_CYGWIN32 || defined SYS_WINNT
1413 TOKEN_PRIVILEGES tkp;
1415 #endif /* SYS_WINNT */
1420 # if defined(HAVE_TIMER_CREATE) && defined(HAVE_TIMER_SETTIME)
1422 /* this code was put in as setitimer() is non existant this us the
1423 * POSIX "equivalents" setup - casey
1425 /* ntpdate_timerid is global - so we can kill timer later */
1426 if (timer_create (CLOCK_REALTIME, NULL, &ntpdate_timerid) ==
1434 fprintf (stderr, "init_alarm(): timer_create (...) FAILED\n");
1439 * Set up the alarm interrupt. The first comes 1/(2*TIMER_HZ)
1440 * seconds from now and they continue on every 1/TIMER_HZ seconds.
1442 (void) signal_no_reset(SIGALRM, alarming);
1443 ntpdate_itimer.it_interval.tv_sec = ntpdate_itimer.it_value.tv_sec = 0;
1444 ntpdate_itimer.it_interval.tv_nsec = 1000000000/TIMER_HZ;
1445 ntpdate_itimer.it_value.tv_nsec = 1000000000/(TIMER_HZ<<1);
1446 timer_settime(ntpdate_timerid, 0 /* !TIMER_ABSTIME */, &ntpdate_itimer, NULL);
1449 * Set up the alarm interrupt. The first comes 1/(2*TIMER_HZ)
1450 * seconds from now and they continue on every 1/TIMER_HZ seconds.
1452 (void) signal_no_reset(SIGALRM, alarming);
1453 itimer.it_interval.tv_sec = itimer.it_value.tv_sec = 0;
1454 itimer.it_interval.tv_usec = 1000000/TIMER_HZ;
1455 itimer.it_value.tv_usec = 1000000/(TIMER_HZ<<1);
1456 setitimer(ITIMER_REAL, &itimer, (struct itimerval *)0);
1458 #if defined SYS_CYGWIN32
1460 * Get previleges needed for fiddling with the clock
1463 /* get the current process token handle */
1464 if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken)) {
1465 msyslog(LOG_ERR, "OpenProcessToken failed: %m");
1468 /* get the LUID for system-time privilege. */
1469 LookupPrivilegeValue(NULL, SE_SYSTEMTIME_NAME, &tkp.Privileges[0].Luid);
1470 tkp.PrivilegeCount = 1; /* one privilege to set */
1471 tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
1472 /* get set-time privilege for this process. */
1473 AdjustTokenPrivileges(hToken, FALSE, &tkp, 0,(PTOKEN_PRIVILEGES) NULL, 0);
1474 /* cannot test return value of AdjustTokenPrivileges. */
1475 if (GetLastError() != ERROR_SUCCESS)
1476 msyslog(LOG_ERR, "AdjustTokenPrivileges failed: %m");
1478 #else /* SYS_WINNT */
1482 * Get previleges needed for fiddling with the clock
1485 /* get the current process token handle */
1486 if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken)) {
1487 msyslog(LOG_ERR, "OpenProcessToken failed: %m");
1490 /* get the LUID for system-time privilege. */
1491 LookupPrivilegeValue(NULL, SE_SYSTEMTIME_NAME, &tkp.Privileges[0].Luid);
1492 tkp.PrivilegeCount = 1; /* one privilege to set */
1493 tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
1494 /* get set-time privilege for this process. */
1495 AdjustTokenPrivileges(hToken, FALSE, &tkp, 0,(PTOKEN_PRIVILEGES) NULL, 0);
1496 /* cannot test return value of AdjustTokenPrivileges. */
1497 if (GetLastError() != ERROR_SUCCESS)
1498 msyslog(LOG_ERR, "AdjustTokenPrivileges failed: %m");
1501 * Set up timer interrupts for every 2**EVENT_TIMEOUT seconds
1502 * Under Win/NT, expiry of timer interval leads to invocation
1503 * of a callback function (on a different thread) rather than
1504 * generating an alarm signal
1507 /* determine max and min resolution supported */
1508 if(timeGetDevCaps(&tc, sizeof(TIMECAPS)) != TIMERR_NOERROR) {
1509 msyslog(LOG_ERR, "timeGetDevCaps failed: %m");
1512 wTimerRes = min(max(tc.wPeriodMin, TARGET_RESOLUTION), tc.wPeriodMax);
1513 /* establish the minimum timer resolution that we'll use */
1514 timeBeginPeriod(wTimerRes);
1516 /* start the timer event */
1517 wTimerID = timeSetEvent(
1518 (UINT) (1000/TIMER_HZ), /* Delay */
1519 wTimerRes, /* Resolution */
1520 (LPTIMECALLBACK) alarming, /* Callback function */
1521 (DWORD) dwUser, /* User data */
1522 TIME_PERIODIC); /* Event type (periodic) */
1523 if (wTimerID == 0) {
1524 msyslog(LOG_ERR, "timeSetEvent failed: %m");
1527 #endif /* SYS_WINNT */
1534 * We do asynchronous input using the SIGIO facility. A number of
1535 * recvbuf buffers are preallocated for input. In the signal
1536 * handler we poll to see if the socket is ready and read the
1537 * packets from it into the recvbuf's along with a time stamp and
1538 * an indication of the source host and the interface it was received
1539 * through. This allows us to get as accurate receive time stamps
1540 * as possible independent of other processing going on.
1542 * We allocate a number of recvbufs equal to the number of servers
1543 * plus 2. This should be plenty.
1548 * init_io - initialize I/O data and open socket
1554 * Init buffer free list and stat counters
1556 init_recvbuff(sys_numservers + 2);
1561 /* create a datagram (UDP) socket */
1562 if ((fd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
1563 msyslog(LOG_ERR, "socket() failed: %m");
1569 * bind the socket to the NTP port
1571 if (!debug && !simple_query && !unpriv_port) {
1572 struct sockaddr_in addr;
1574 memset((char *)&addr, 0, sizeof addr);
1575 addr.sin_family = AF_INET;
1576 addr.sin_port = htons(NTP_PORT);
1577 addr.sin_addr.s_addr = htonl(INADDR_ANY);
1578 if (bind(fd, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
1580 if (errno == EADDRINUSE)
1582 if (WSAGetLastError() == WSAEADDRINUSE)
1583 #endif /* SYS_WINNT */
1585 "the NTP socket is in use, exiting");
1587 msyslog(LOG_ERR, "bind() fails: %m");
1594 fdmask.events = POLLIN;
1597 FD_SET(fd, &fdmask);
1608 if (ioctl(fd,FIONBIO, &on) == ERROR) {
1609 msyslog(LOG_ERR, "ioctl(FIONBIO) fails: %m");
1613 # else /* not SYS_VXWORKS */
1614 # if defined(O_NONBLOCK)
1615 if (fcntl(fd, F_SETFL, O_NONBLOCK) < 0) {
1616 msyslog(LOG_ERR, "fcntl(FNDELAY|FASYNC) fails: %m");
1620 # else /* not O_NONBLOCK */
1621 # if defined(FNDELAY)
1622 if (fcntl(fd, F_SETFL, FNDELAY) < 0) {
1623 msyslog(LOG_ERR, "fcntl(FNDELAY|FASYNC) fails: %m");
1627 # else /* FNDELAY */
1628 # include "Bletch: Need non blocking I/O"
1629 # endif /* FNDELAY */
1630 # endif /* not O_NONBLOCK */
1631 # endif /* SYS_VXWORKS */
1632 #else /* SYS_WINNT */
1633 if (ioctlsocket(fd, FIONBIO, (u_long *) &on) == SOCKET_ERROR) {
1634 msyslog(LOG_ERR, "ioctlsocket(FIONBIO) fails: %m");
1637 #endif /* SYS_WINNT */
1642 * sendpkt - send a packet to the specified destination
1646 struct sockaddr_in *dest,
1655 #endif /* SYS_WINNT */
1657 cc = sendto(fd, (char *)pkt, (size_t)len, 0, (struct sockaddr *)dest,
1658 sizeof(struct sockaddr_in));
1661 if (errno != EWOULDBLOCK && errno != ENOBUFS)
1663 if (cc == SOCKET_ERROR) {
1664 err = WSAGetLastError();
1665 if (err != WSAEWOULDBLOCK && err != WSAENOBUFS)
1666 #endif /* SYS_WINNT */
1667 msyslog(LOG_ERR, "sendto(%s): %m", ntoa(dest));
1673 * input_handler - receive packets asynchronously
1679 register struct recvbuf *rb;
1680 struct timeval tvzero;
1690 * Do a poll to see if we have data
1694 tvzero.tv_sec = tvzero.tv_usec = 0;
1696 n = poll(&fds, 1, tvzero.tv_sec * 1000);
1698 n = select(fd+1, &fds, (fd_set *)0, (fd_set *)0, &tvzero);
1702 * If nothing to do, just return. If an error occurred,
1703 * complain and return. If we've got some, freeze a
1714 "select() error: %m"
1722 * Get a buffer and read the frame. If we
1723 * haven't got a buffer, or this is received
1724 * on the wild card socket, just dump the packet.
1726 if (initializing || free_recvbuffs() == 0) {
1730 (void) read(fd, buf, sizeof buf);
1732 /* NT's _read does not operate on nonblocking sockets
1733 * either recvfrom or ReadFile() has to be used here.
1734 * ReadFile is used in [ntpd]ntp_intres() and ntpdc,
1735 * just to be different use recvfrom() here
1737 recvfrom(fd, buf, sizeof(buf), 0, (struct sockaddr *)0, NULL);
1738 #endif /* SYS_WINNT */
1742 rb = get_free_recv_buffer();
1744 fromlen = sizeof(struct sockaddr_in);
1745 rb->recv_length = recvfrom(fd, (char *)&rb->recv_pkt,
1746 sizeof(rb->recv_pkt), 0,
1747 (struct sockaddr *)&rb->recv_srcadr, &fromlen);
1748 if (rb->recv_length == -1) {
1754 * Got one. Mark how and when it got here,
1755 * put it on the full list.
1758 add_full_recv_buffer(rb);
1763 #if !defined SYS_WINNT && !defined SYS_CYGWIN32
1765 * adj_systime - do a big long slew of the system time
1772 struct timeval adjtv, oadjtv;
1780 * Take the absolute value of the offset
1783 if (L_ISNEG(&offset)) {
1790 * Calculate the overshoot. XXX N.B. This code *knows*
1791 * ADJ_OVERSHOOT is 1/2.
1794 L_RSHIFTU(&overshoot);
1795 if (overshoot.l_ui != 0 || (overshoot.l_uf > ADJ_MAXOVERSHOOT)) {
1797 overshoot.l_uf = ADJ_MAXOVERSHOOT;
1799 L_ADD(&offset, &overshoot);
1801 TSTOTV(&offset, &adjtv);
1804 adjtv.tv_sec = -adjtv.tv_sec;
1805 adjtv.tv_usec = -adjtv.tv_usec;
1808 if (adjtv.tv_usec != 0 && !debug) {
1809 if (adjtime(&adjtv, &oadjtv) < 0) {
1810 msyslog(LOG_ERR, "Can't adjust the time of day: %m");
1816 #endif /* SYS_WINNT */
1820 * This fuction is not the same as lib/systime step_systime!!!
1835 if (debug) return 1;
1837 * Take the absolute value of the offset
1840 if (L_ISNEG(&ftmp)) {
1846 if (ftmp.l_ui >= 3) { /* Step it and slew - we might win */
1848 n = step_systime(dtemp);
1857 * Just add adjustment into the current offset. The update
1858 * routine will take care of bringing the system clock into
1864 #ifdef FORCE_NTPDATE_STEP
1866 return step_systime(dtemp);
1871 #else /* SLEWALWAYS */
1875 return step_systime(dtemp);
1876 #endif /* SLEWALWAYS */
1880 * getnetnum - given a host name, return its net number
1890 if (decodenetnum(host, num)) {
1892 } else if ((hp = gethostbyname(host)) != 0) {
1893 memmove((char *)num, hp->h_addr, sizeof(u_int32));
1899 /* XXX ELIMINATE printserver similar in ntptrace.c, ntpdate.c */
1901 * printserver - print detail information for a server
1905 register struct server *pp,
1914 (void) fprintf(fp, "server %s, stratum %d, offset %s, delay %s\n",
1915 ntoa(&pp->srcadr), pp->stratum,
1916 lfptoa(&pp->offset, 6), fptoa((s_fp)pp->delay, 5));
1920 (void) fprintf(fp, "server %s, port %d\n",
1921 ntoa(&pp->srcadr), ntohs(pp->srcadr.sin_port));
1923 (void) fprintf(fp, "stratum %d, precision %d, leap %c%c, trust %03o\n",
1924 pp->stratum, pp->precision,
1925 pp->leap & 0x2 ? '1' : '0',
1926 pp->leap & 0x1 ? '1' : '0',
1929 if (pp->stratum == 1) {
1931 memmove(junk, (char *)&pp->refid, 4);
1934 str = numtoa(pp->refid);
1937 "refid [%s], delay %s, dispersion %s\n",
1938 str, fptoa((s_fp)pp->delay, 5),
1939 ufptoa(pp->dispersion, 5));
1941 (void) fprintf(fp, "transmitted %d, in filter %d\n",
1942 pp->xmtcnt, pp->filter_nextpt);
1944 (void) fprintf(fp, "reference time: %s\n",
1945 prettydate(&pp->reftime));
1946 (void) fprintf(fp, "originate timestamp: %s\n",
1947 prettydate(&pp->org));
1948 (void) fprintf(fp, "transmit timestamp: %s\n",
1949 prettydate(&pp->xmt));
1951 (void) fprintf(fp, "filter delay: ");
1952 for (i = 0; i < NTP_SHIFT; i++) {
1953 (void) fprintf(fp, " %-8.8s", fptoa(pp->filter_delay[i], 5));
1954 if (i == (NTP_SHIFT>>1)-1)
1955 (void) fprintf(fp, "\n ");
1957 (void) fprintf(fp, "\n");
1959 (void) fprintf(fp, "filter offset:");
1960 for (i = 0; i < PEER_SHIFT; i++) {
1961 (void) fprintf(fp, " %-8.8s", lfptoa(&pp->filter_offset[i], 6));
1962 if (i == (PEER_SHIFT>>1)-1)
1963 (void) fprintf(fp, "\n ");
1965 (void) fprintf(fp, "\n");
1967 (void) fprintf(fp, "delay %s, dispersion %s\n",
1968 fptoa((s_fp)pp->delay, 5), ufptoa(pp->dispersion, 5));
1970 (void) fprintf(fp, "offset %s\n\n",
1971 lfptoa(&pp->offset, 6));
1974 #if !defined(HAVE_VSPRINTF)
1985 f._flag = _IOWRT+_IOSTRG;
1988 len = _doprnt(fmt, ap, &f);
1995 /* override function in library since SA_RESTART makes ALL syscalls restart */
2004 struct sigaction vec;
2006 vec.sa_handler = func;
2007 sigemptyset(&vec.sa_mask);
2012 n = sigaction(sig, &vec, NULL);
2013 if (n == -1 && errno == EINTR)
2019 perror("sigaction");
2027 static ni_namelist *
2028 getnetinfoservers(void)
2033 ni_namelist *namelist = (ni_namelist*)malloc(sizeof(ni_namelist));
2035 /* Find a time server in NetInfo */
2036 if ((status = ni_open(NULL, ".", &domain)) != NI_OK) return NULL;
2038 while (status = ni_pathsearch(domain, &confdir, NETINFO_CONFIG_DIR) == NI_NODIR) {
2040 if (ni_open(domain, "..", &next_domain) != NI_OK) break;
2042 domain = next_domain;
2044 if (status != NI_OK) return NULL;
2047 if (ni_lookupprop(domain, &confdir, "server", namelist) != NI_OK) {
2048 ni_namelist_free(namelist);