4 * ntpdate - set the time of day by polling one or more NTP servers
12 #include <netinfo/ni.h>
15 #include "ntp_machine.h"
19 #include "ntp_unixtime.h"
21 #include "ntp_string.h"
22 #include "ntp_syslog.h"
23 #include "ntp_select.h"
24 #include "ntp_stdlib.h"
25 #include <ssl_applink.c>
28 #include "isc/result.h"
29 #include "isc/sockaddr.h"
41 #ifdef HAVE_SYS_SIGNAL_H
42 # include <sys/signal.h>
44 #ifdef HAVE_SYS_IOCTL_H
45 # include <sys/ioctl.h>
47 #ifdef HAVE_SYS_RESOURCE_H
48 # include <sys/resource.h>
51 #include <arpa/inet.h>
58 /* select wants a zero structure ... */
59 struct timeval timeout
= {0,0};
60 #elif defined(SYS_WINNT)
62 * Windows does not abort a select select call if SIGALRM goes off
63 * so a 200 ms timeout is needed
65 struct sock_timeval timeout
= {0,1000000/TIMER_HZ
};
67 struct timeval timeout
= {60,0};
71 #include <netinfo/ni.h>
77 #define TARGET_RESOLUTION 1 /* Try for 1-millisecond accuracy
78 on Windows NT timers. */
79 #pragma comment(lib, "winmm")
80 isc_boolean_t
ntp_port_inuse(int af
, u_short port
);
82 #endif /* SYS_WINNT */
85 * Scheduling priority we run at
88 # define NTPDATE_PRIO (-12)
90 # define NTPDATE_PRIO (100)
93 #if defined(HAVE_TIMER_SETTIME) || defined (HAVE_TIMER_CREATE)
94 /* POSIX TIMERS - vxWorks doesn't have itimer - casey */
95 static timer_t ntpdate_timerid
;
99 * Compatibility stuff for Version 2
101 #define NTP_MAXSKW 0x28f /* 0.01 sec in fp format */
102 #define NTP_MINDIST 0x51f /* 0.02 sec in fp format */
103 #define PEER_MAXDISP (64*FP_SECOND) /* maximum dispersion (fp 64) */
104 #define NTP_INFIN 15 /* max stratum, infinity a la Bellman-Ford */
105 #define NTP_MAXWGT (8*FP_SECOND) /* maximum select weight 8 seconds */
106 #define NTP_MAXLIST 5 /* maximum select list size */
107 #define PEER_SHIFT 8 /* 8 suitable for crystal time base */
112 s_char sys_precision
; /* local clock precision (log2 s) */
117 volatile int debug
= 0;
120 * File descriptor masks etc. for call to select
124 int nbsock
; /* the number of sockets used */
126 int fd_family
[MAX_AF
]; /* to remember the socket family */
128 struct pollfd fdmask
[MAX_AF
];
136 * Initializing flag. All async routines watch this and only do their
137 * thing when it is clear.
139 int initializing
= 1;
142 * Alarm flag. Set when an alarm occurs
144 volatile int alarm_flag
= 0;
149 int simple_query
= 0;
152 * Unprivileged port flag.
162 * Systemwide parameters and flags
164 int sys_samples
= DEFSAMPLES
; /* number of samples/server */
165 u_long sys_timeout
= DEFTIMEOUT
; /* timeout time, in TIMER_HZ units */
166 struct server
*sys_servers
; /* the server list */
167 int sys_numservers
= 0; /* number of servers to poll */
168 int sys_authenticate
= 0; /* true when authenticating */
169 u_int32 sys_authkey
= 0; /* set to authentication key in use */
170 u_long sys_authdelay
= 0; /* authentication delay */
171 int sys_version
= NTP_VERSION
; /* version to poll with */
174 * The current internal time
176 u_long current_time
= 0;
179 * Counter for keeping track of completed servers
181 int complete_servers
= 0;
184 * File of encryption keys
189 #define KEYFILE "/etc/ntp.keys"
191 #define KEYFILE "%windir%\\ntp.keys"
192 # endif /* SYS_WINNT */
196 const char *key_file
= KEYFILE
;
198 char key_file_storage
[MAX_PATH
+1], *key_file
;
199 #endif /* SYS_WINNT */
202 * Miscellaneous flags
208 int ntpdatemain (int, char **);
210 static void transmit (struct server
*);
211 static void receive (struct recvbuf
*);
212 static void server_data (struct server
*, s_fp
, l_fp
*, u_fp
);
213 static void clock_filter (struct server
*);
214 static struct server
*clock_select (void);
215 static int clock_adjust (void);
216 static void addserver (char *);
217 static struct server
*findserver (sockaddr_u
*);
219 static void init_alarm (void);
221 static RETSIGTYPE
alarming (int);
222 #endif /* SYS_WINNT */
223 static void init_io (void);
224 static void sendpkt (sockaddr_u
*, struct pkt
*, int);
225 void input_handler (void);
227 static int l_adj_systime (l_fp
*);
228 static int l_step_systime (l_fp
*);
230 static void printserver (struct server
*, FILE *);
234 WORD wVersionRequested
;
236 #endif /* SYS_WINNT */
238 #ifdef NO_MAIN_ALLOWED
239 CALL(ntpdate
,"ntpdate",ntpdatemain
);
250 * Initializing flag. All async routines watch this and only do their
251 * thing when it is clear.
256 * Alarm flag. Set when an alarm occurs
266 * Unprivileged port flag.
271 * Systemwide parameters and flags
273 sys_numservers
= 0; /* number of servers to poll */
274 sys_authenticate
= 0; /* true when authenticating */
275 sys_authkey
= 0; /* set to authentication key in use */
276 sys_authdelay
= 0; /* authentication delay */
277 sys_version
= NTP_VERSION
; /* version to poll with */
280 * The current internal time
285 * Counter for keeping track of completed servers
287 complete_servers
= 0;
295 static ni_namelist
*getnetinfoservers (void);
299 * Main program. Initialize us and loop waiting for I/O and/or
302 #ifndef NO_MAIN_ALLOWED
309 return ntpdatemain (argc
, argv
);
311 #endif /* NO_MAIN_ALLOWED */
321 struct recvbuf
*rbuf
;
328 ni_namelist
*netinfoservers
;
331 key_file
= key_file_storage
;
333 if (!ExpandEnvironmentStrings(KEYFILE
, key_file
, MAX_PATH
))
334 msyslog(LOG_ERR
, "ExpandEnvironmentStrings(KEYFILE) failed: %m\n");
337 #endif /* SYS_WINNT */
339 #ifdef NO_MAIN_ALLOWED
343 init_lib(); /* sets up ipv4_works, ipv6_works */
345 /* Check to see if we have IPv6. Otherwise default to IPv4 */
347 ai_fam_templ
= AF_INET
;
354 * Decode argument list
356 while ((c
= ntp_getopt(argc
, argv
, "46a:bBde:k:o:p:qst:uv")) != EOF
)
360 ai_fam_templ
= AF_INET
;
363 ai_fam_templ
= AF_INET6
;
366 c
= atoi(ntp_optarg
);
367 sys_authenticate
= 1;
382 if (!atolfp(ntp_optarg
, &tmp
)
384 (void) fprintf(stderr
,
385 "%s: encryption delay %s is unlikely\n",
386 progname
, ntp_optarg
);
389 sys_authdelay
= tmp
.l_uf
;
393 key_file
= ntp_optarg
;
396 sys_version
= atoi(ntp_optarg
);
399 c
= atoi(ntp_optarg
);
400 if (c
<= 0 || c
> NTP_SHIFT
) {
401 (void) fprintf(stderr
,
402 "%s: number of samples (%d) is invalid\n",
416 if (!atolfp(ntp_optarg
, &tmp
)) {
417 (void) fprintf(stderr
,
418 "%s: timeout %s is undecodeable\n",
419 progname
, ntp_optarg
);
422 sys_timeout
= ((LFPTOFP(&tmp
) * TIMER_HZ
)
424 if (sys_timeout
== 0)
442 (void) fprintf(stderr
,
443 "usage: %s [-46bBdqsuv] [-a key#] [-e delay] [-k file] [-p samples] [-o version#] [-t timeo] server ...\n",
448 if (debug
|| simple_query
) {
450 static char buf
[BUFSIZ
];
451 setvbuf(stdout
, buf
, _IOLBF
, BUFSIZ
);
458 * Logging. Open the syslog if we have to
461 #if !defined (SYS_WINNT) && !defined (SYS_VXWORKS) && !defined SYS_CYGWIN32
463 openlog("ntpdate", LOG_PID
);
467 # define LOG_NTP LOG_DAEMON
469 openlog("ntpdate", LOG_PID
| LOG_NDELAY
, LOG_NTP
);
471 setlogmask(LOG_UPTO(LOG_DEBUG
));
473 setlogmask(LOG_UPTO(LOG_INFO
));
474 # endif /* LOG_DAEMON */
475 #endif /* SYS_WINNT */
478 if (debug
|| verbose
)
479 msyslog(LOG_NOTICE
, "%s", Version
);
482 * Add servers we are going to be polling
485 netinfoservers
= getnetinfoservers();
488 for ( ; ntp_optind
< argc
; ntp_optind
++)
489 addserver(argv
[ntp_optind
]);
492 if (netinfoservers
) {
493 if ( netinfoservers
->ni_namelist_len
&&
494 *netinfoservers
->ni_namelist_val
) {
495 u_int servercount
= 0;
496 while (servercount
< netinfoservers
->ni_namelist_len
) {
497 if (debug
) msyslog(LOG_DEBUG
,
498 "Adding time server %s from NetInfo configuration.",
499 netinfoservers
->ni_namelist_val
[servercount
]);
500 addserver(netinfoservers
->ni_namelist_val
[servercount
++]);
503 ni_namelist_free(netinfoservers
);
504 free(netinfoservers
);
508 if (sys_numservers
== 0) {
509 msyslog(LOG_ERR
, "no servers can be used, exiting");
514 * Initialize the time of day routines and the I/O subsystem
516 if (sys_authenticate
) {
518 if (!authreadkeys(key_file
)) {
519 msyslog(LOG_ERR
, "no key file <%s>, exiting", key_file
);
522 authtrust(sys_authkey
, 1);
523 if (!authistrusted(sys_authkey
)) {
524 msyslog(LOG_ERR
, "authentication key %lu unknown",
525 (unsigned long) sys_authkey
);
536 taskPrioritySet( taskIdSelf(), NTPDATE_PRIO
);
538 #if defined(HAVE_ATT_NICE)
541 #if defined(HAVE_BSD_NICE)
542 (void) setpriority(PRIO_PROCESS
, 0, NTPDATE_PRIO
);
549 while (complete_servers
< sys_numservers
) {
551 struct pollfd
* rdfdes
;
558 if (alarm_flag
) { /* alarmed? */
562 tot_recvbufs
= full_recvbuffs(); /* get received buffers */
564 if (!was_alarmed
&& tot_recvbufs
== 0) {
566 * Nothing to do. Wait for something.
569 nfound
= poll(rdfdes
, (unsigned int)nbsock
, timeout
.tv_sec
* 1000);
572 nfound
= select(maxfd
, &rdfdes
, (fd_set
*)0,
573 (fd_set
*)0, &timeout
);
577 else if (nfound
== SOCKET_ERROR
)
582 if (WSAGetLastError() != WSAEINTR
)
591 } else if (errno
!= 0) {
595 "poll(): nfound = %d, error: %m",
597 "select(): nfound = %d, error: %m",
602 if (alarm_flag
) { /* alarmed? */
606 tot_recvbufs
= full_recvbuffs(); /* get received buffers */
610 * Out here, signals are unblocked. Call receive
611 * procedure for each incoming packet.
613 rbuf
= get_full_recv_buffer();
618 rbuf
= get_full_recv_buffer();
622 * Call timer to process any timeouts
635 * When we get here we've completed the polling of all servers.
636 * Adjust the clock, then exit.
643 timer_delete(ntpdate_timerid
);
646 return clock_adjust();
651 * transmit - transmit a packet to the given server, or mark it completed.
652 * This is called by the timeout routine and by the receive
657 register struct server
*server
663 printf("transmit(%s)\n", stoa(&server
->srcadr
));
665 if (server
->filter_nextpt
< server
->xmtcnt
) {
668 * Last message to this server timed out. Shift
669 * zeros into the filter.
672 server_data(server
, 0, &ts
, 0);
675 if ((int)server
->filter_nextpt
>= sys_samples
) {
677 * Got all the data we need. Mark this guy
678 * completed and return.
680 server
->event_time
= 0;
686 * If we're here, send another message to the server. Fill in
687 * the packet and let 'er rip.
689 xpkt
.li_vn_mode
= PKT_LI_VN_MODE(LEAP_NOTINSYNC
,
690 sys_version
, MODE_CLIENT
);
691 xpkt
.stratum
= STRATUM_TO_PKT(STRATUM_UNSPEC
);
692 xpkt
.ppoll
= NTP_MINPOLL
;
693 xpkt
.precision
= NTPDATE_PRECISION
;
694 xpkt
.rootdelay
= htonl(NTPDATE_DISTANCE
);
695 xpkt
.rootdisp
= htonl(NTPDATE_DISP
);
696 xpkt
.refid
= htonl(NTPDATE_REFID
);
697 L_CLR(&xpkt
.reftime
);
702 * Determine whether to authenticate or not. If so,
703 * fill in the extended part of the packet and do it.
704 * If not, just timestamp it and send it away.
706 if (sys_authenticate
) {
709 xpkt
.exten
[0] = htonl(sys_authkey
);
710 get_systime(&server
->xmt
);
711 L_ADDUF(&server
->xmt
, sys_authdelay
);
712 HTONL_FP(&server
->xmt
, &xpkt
.xmt
);
713 len
= authencrypt(sys_authkey
, (u_int32
*)&xpkt
, LEN_PKT_NOMAC
);
714 sendpkt(&server
->srcadr
, &xpkt
, (int)(LEN_PKT_NOMAC
+ len
));
717 printf("transmit auth to %s\n",
718 stoa(&server
->srcadr
));
720 get_systime(&(server
->xmt
));
721 HTONL_FP(&server
->xmt
, &xpkt
.xmt
);
722 sendpkt(&server
->srcadr
, &xpkt
, LEN_PKT_NOMAC
);
725 printf("transmit to %s\n", stoa(&server
->srcadr
));
729 * Update the server timeout and transmit count
731 server
->event_time
= current_time
+ sys_timeout
;
737 * receive - receive and process an incoming frame
741 struct recvbuf
*rbufp
744 register struct pkt
*rpkt
;
745 register struct server
*server
;
755 printf("receive(%s)\n", stoa(&rbufp
->recv_srcadr
));
757 * Check to see if the packet basically looks like something
760 if (rbufp
->recv_length
== LEN_PKT_NOMAC
)
762 else if (rbufp
->recv_length
>= LEN_PKT_NOMAC
)
766 printf("receive: packet length %d\n",
768 return; /* funny length packet */
771 rpkt
= &(rbufp
->recv_pkt
);
772 if (PKT_VERSION(rpkt
->li_vn_mode
) < NTP_OLDVERSION
||
773 PKT_VERSION(rpkt
->li_vn_mode
) > NTP_VERSION
) {
777 if ((PKT_MODE(rpkt
->li_vn_mode
) != MODE_SERVER
778 && PKT_MODE(rpkt
->li_vn_mode
) != MODE_PASSIVE
)
779 || rpkt
->stratum
>= STRATUM_UNSPEC
) {
781 printf("receive: mode %d stratum %d\n",
782 PKT_MODE(rpkt
->li_vn_mode
), rpkt
->stratum
);
787 * So far, so good. See if this is from a server we know.
789 server
= findserver(&(rbufp
->recv_srcadr
));
790 if (server
== NULL
) {
792 printf("receive: server not found\n");
797 * Decode the org timestamp and make sure we're getting a response
798 * to our last request.
800 NTOHL_FP(&rpkt
->org
, &org
);
801 if (!L_ISEQU(&org
, &server
->xmt
)) {
803 printf("receive: pkt.org and peer.xmt differ\n");
808 * Check out the authenticity if we're doing that.
810 if (!sys_authenticate
)
816 printf("receive: rpkt keyid=%ld sys_authkey=%ld decrypt=%ld\n",
817 (long int)ntohl(rpkt
->exten
[0]), (long int)sys_authkey
,
818 (long int)authdecrypt(sys_authkey
, (u_int32
*)rpkt
,
819 LEN_PKT_NOMAC
, (int)(rbufp
->recv_length
- LEN_PKT_NOMAC
)));
821 if (has_mac
&& ntohl(rpkt
->exten
[0]) == sys_authkey
&&
822 authdecrypt(sys_authkey
, (u_int32
*)rpkt
, LEN_PKT_NOMAC
,
823 (int)(rbufp
->recv_length
- LEN_PKT_NOMAC
)))
826 printf("receive: authentication %s\n",
827 is_authentic
? "passed" : "failed");
834 * Looks good. Record info from the packet.
836 server
->leap
= PKT_LEAP(rpkt
->li_vn_mode
);
837 server
->stratum
= PKT_TO_STRATUM(rpkt
->stratum
);
838 server
->precision
= rpkt
->precision
;
839 server
->rootdelay
= ntohl(rpkt
->rootdelay
);
840 server
->rootdisp
= ntohl(rpkt
->rootdisp
);
841 server
->refid
= rpkt
->refid
;
842 NTOHL_FP(&rpkt
->reftime
, &server
->reftime
);
843 NTOHL_FP(&rpkt
->rec
, &rec
);
844 NTOHL_FP(&rpkt
->xmt
, &server
->org
);
847 * Make sure the server is at least somewhat sane. If not, try
850 if (L_ISZERO(&rec
) || !L_ISHIS(&server
->org
, &rec
)) {
856 * Calculate the round trip delay (di) and the clock offset (ci).
857 * We use the equations (reordered from those in the spec):
859 * d = (t2 - t3) - (t1 - t0)
860 * c = ((t2 - t3) + (t1 - t0)) / 2
862 t10
= server
->org
; /* pkt.xmt == t1 */
863 L_SUB(&t10
, &rbufp
->recv_time
); /* recv_time == t0*/
865 t23
= rec
; /* pkt.rec == t2 */
866 L_SUB(&t23
, &org
); /* pkt->org == t3 */
868 /* now have (t2 - t3) and (t0 - t1). Calculate (ci) and (di) */
870 * Calculate (ci) = ((t1 - t0) / 2) + ((t2 - t3) / 2)
871 * For large offsets this may prevent an overflow on '+'
880 * Calculate di in t23 in full precision, then truncate
887 printf("offset: %s, delay %s\n", lfptoa(&ci
, 6), fptoa(di
, 5));
889 di
+= (FP_SECOND
>> (-(int)NTPDATE_PRECISION
))
890 + (FP_SECOND
>> (-(int)server
->precision
)) + NTP_MAXSKW
;
892 if (di
<= 0) { /* value still too raunchy to use? */
896 di
= max(di
, NTP_MINDIST
);
900 * Shift this data in, then transmit again.
902 server_data(server
, (s_fp
) di
, &ci
, 0);
908 * server_data - add a sample to the server's filter registers
912 register struct server
*server
,
920 i
= server
->filter_nextpt
;
922 server
->filter_delay
[i
] = d
;
923 server
->filter_offset
[i
] = *c
;
924 server
->filter_soffset
[i
] = LFPTOFP(c
);
925 server
->filter_error
[i
] = e
;
926 server
->filter_nextpt
= (u_short
)(i
+ 1);
932 * clock_filter - determine a server's delay, dispersion and offset
936 register struct server
*server
943 * Sort indices into increasing delay order
945 for (i
= 0; i
< sys_samples
; i
++)
948 for (i
= 0; i
< (sys_samples
-1); i
++) {
949 for (j
= i
+1; j
< sys_samples
; j
++) {
950 if (server
->filter_delay
[ord
[j
]] == 0)
952 if (server
->filter_delay
[ord
[i
]] == 0
953 || (server
->filter_delay
[ord
[i
]]
954 > server
->filter_delay
[ord
[j
]])) {
965 * Now compute the dispersion, and assign values to delay and
966 * offset. If there are no samples in the register, delay and
967 * offset go to zero and dispersion is set to the maximum.
969 if (server
->filter_delay
[ord
[0]] == 0) {
971 L_CLR(&server
->offset
);
973 server
->dispersion
= PEER_MAXDISP
;
977 server
->delay
= server
->filter_delay
[ord
[0]];
978 server
->offset
= server
->filter_offset
[ord
[0]];
979 server
->soffset
= LFPTOFP(&server
->offset
);
980 server
->dispersion
= 0;
981 for (i
= 1; i
< sys_samples
; i
++) {
982 if (server
->filter_delay
[ord
[i
]] == 0)
985 d
= server
->filter_soffset
[ord
[i
]]
986 - server
->filter_soffset
[ord
[0]];
989 if (d
> PEER_MAXDISP
)
993 * XXX This *knows* PEER_FILTER is 1/2
995 server
->dispersion
+= (u_fp
)(d
) >> i
;
1005 * clock_select - select the pick-of-the-litter clock from the samples
1008 static struct server
*
1011 register struct server
*server
;
1017 s_fp local_threshold
;
1018 struct server
*server_list
[NTP_MAXCLOCK
];
1019 u_fp server_badness
[NTP_MAXCLOCK
];
1020 struct server
*sys_server
;
1023 * This first chunk of code is supposed to go through all
1024 * servers we know about to find the NTP_MAXLIST servers which
1025 * are most likely to succeed. We run through the list
1026 * doing the sanity checks and trying to insert anyone who
1027 * looks okay. We are at all times aware that we should
1028 * only keep samples from the top two strata and we only need
1029 * NTP_MAXLIST of them.
1031 nlist
= 0; /* none yet */
1032 for (server
= sys_servers
; server
!= NULL
; server
= server
->next_server
) {
1033 if (server
->delay
== 0) {
1035 printf("%s: Server dropped: no data\n", ntoa(&server
->srcadr
));
1036 continue; /* no data */
1038 if (server
->stratum
> NTP_INFIN
) {
1040 printf("%s: Server dropped: strata too high\n", ntoa(&server
->srcadr
));
1041 continue; /* stratum no good */
1043 if (server
->delay
> NTP_MAXWGT
) {
1045 printf("%s: Server dropped: server too far away\n",
1046 ntoa(&server
->srcadr
));
1047 continue; /* too far away */
1049 if (server
->leap
== LEAP_NOTINSYNC
) {
1051 printf("%s: Server dropped: Leap not in sync\n", ntoa(&server
->srcadr
));
1052 continue; /* he's in trouble */
1054 if (!L_ISHIS(&server
->org
, &server
->reftime
)) {
1056 printf("%s: Server dropped: server is very broken\n",
1057 ntoa(&server
->srcadr
));
1058 continue; /* very broken host */
1060 if ((server
->org
.l_ui
- server
->reftime
.l_ui
)
1063 printf("%s: Server dropped: Server has gone too long without sync\n",
1064 ntoa(&server
->srcadr
));
1065 continue; /* too long without sync */
1067 if (server
->trust
!= 0) {
1069 printf("%s: Server dropped: Server is untrusted\n",
1070 ntoa(&server
->srcadr
));
1075 * This one seems sane. Find where he belongs
1078 d
= server
->dispersion
+ server
->dispersion
;
1079 for (i
= 0; i
< nlist
; i
++)
1080 if (server
->stratum
<= server_list
[i
]->stratum
)
1082 for ( ; i
< nlist
; i
++) {
1083 if (server
->stratum
< server_list
[i
]->stratum
)
1085 if (d
< (s_fp
) server_badness
[i
])
1090 * If i points past the end of the list, this
1091 * guy is a loser, else stick him in.
1093 if (i
>= NTP_MAXLIST
)
1095 for (j
= nlist
; j
> i
; j
--)
1096 if (j
< NTP_MAXLIST
) {
1097 server_list
[j
] = server_list
[j
-1];
1099 = server_badness
[j
-1];
1102 server_list
[i
] = server
;
1103 server_badness
[i
] = d
;
1104 if (nlist
< NTP_MAXLIST
)
1109 * Got the five-or-less best. Cut the list where the number of
1110 * strata exceeds two.
1113 for (i
= 1; i
< nlist
; i
++)
1114 if (server_list
[i
]->stratum
> server_list
[i
-1]->stratum
)
1121 * Whew! What we should have by now is 0 to 5 candidates for
1122 * the job of syncing us. If we have none, we're out of luck.
1123 * If we have one, he's a winner. If we have more, do falseticker
1129 else if (nlist
== 1) {
1130 sys_server
= server_list
[0];
1133 * Re-sort by stratum, bdelay estimate quality and
1136 for (i
= 0; i
< nlist
-1; i
++)
1137 for (j
= i
+1; j
< nlist
; j
++) {
1138 if (server_list
[i
]->stratum
1139 < server_list
[j
]->stratum
)
1140 break; /* already sorted by stratum */
1141 if (server_list
[i
]->delay
1142 < server_list
[j
]->delay
)
1144 server
= server_list
[i
];
1145 server_list
[i
] = server_list
[j
];
1146 server_list
[j
] = server
;
1150 * Calculate the fixed part of the dispersion limit
1152 local_threshold
= (FP_SECOND
>> (-(int)NTPDATE_PRECISION
))
1156 * Now drop samples until we're down to one.
1159 for (n
= 0; n
< nlist
; n
++) {
1160 server_badness
[n
] = 0;
1161 for (j
= 0; j
< nlist
; j
++) {
1162 if (j
== n
) /* with self? */
1164 d
= server_list
[j
]->soffset
1165 - server_list
[n
]->soffset
;
1166 if (d
< 0) /* absolute value */
1169 * XXX This code *knows* that
1172 for (i
= 0; i
< j
; i
++)
1173 d
= (d
>>1) + (d
>>2);
1174 server_badness
[n
] += d
;
1179 * We now have an array of nlist badness
1180 * coefficients. Find the badest. Find
1181 * the minimum precision while we're at
1185 n
= server_list
[0]->precision
;;
1186 for (j
= 1; j
< nlist
; j
++) {
1187 if (server_badness
[j
] >= server_badness
[i
])
1189 if (n
> server_list
[j
]->precision
)
1190 n
= server_list
[j
]->precision
;
1194 * i is the index of the server with the worst
1195 * dispersion. If his dispersion is less than
1196 * the threshold, stop now, else delete him and
1197 * continue around again.
1199 if ( (s_fp
) server_badness
[i
] < (local_threshold
1200 + (FP_SECOND
>> (-n
))))
1202 for (j
= i
+ 1; j
< nlist
; j
++)
1203 server_list
[j
-1] = server_list
[j
];
1208 * What remains is a list of less than 5 servers. Take
1211 sys_server
= server_list
[0];
1215 * That's it. Return our server.
1222 * clock_adjust - process what we've received, and adjust the time
1223 * if we got anything decent.
1228 register struct server
*sp
, *server
;
1232 for (sp
= sys_servers
; sp
!= NULL
; sp
= sp
->next_server
)
1234 server
= clock_select();
1236 if (debug
|| simple_query
) {
1237 for (sp
= sys_servers
; sp
!= NULL
; sp
= sp
->next_server
)
1238 printserver(sp
, stdout
);
1243 "no server suitable for synchronization found");
1249 } else if (never_step
) {
1252 absoffset
= server
->soffset
;
1254 absoffset
= -absoffset
;
1255 dostep
= (absoffset
>= NTPDATE_THRESHOLD
|| absoffset
< 0);
1259 if (simple_query
|| debug
|| l_step_systime(&server
->offset
)){
1260 msyslog(LOG_NOTICE
, "step time server %s offset %s sec",
1261 stoa(&server
->srcadr
),
1262 lfptoa(&server
->offset
, 6));
1265 #if !defined SYS_WINNT && !defined SYS_CYGWIN32
1266 if (simple_query
|| l_adj_systime(&server
->offset
)) {
1267 msyslog(LOG_NOTICE
, "adjust time server %s offset %s sec",
1268 stoa(&server
->srcadr
),
1269 lfptoa(&server
->offset
, 6));
1272 /* The NT SetSystemTimeAdjustment() call achieves slewing by
1273 * changing the clock frequency. This means that we cannot specify
1274 * it to slew the clock by a definite amount and then stop like
1275 * the Unix adjtime() routine. We can technically adjust the clock
1276 * frequency, have ntpdate sleep for a while, and then wake
1277 * up and reset the clock frequency, but this might cause some
1278 * grief if the user attempts to run ntpd immediately after
1279 * ntpdate and the socket is in use.
1281 printf("\nThe -b option is required by ntpdate on Windows NT platforms\n");
1283 #endif /* SYS_WINNT */
1290 * is_unreachable - check to see if we have a route to given destination
1294 is_reachable (sockaddr_u
*dst
)
1298 sockfd
= socket(AF(dst
), SOCK_DGRAM
, 0);
1303 if (connect(sockfd
, &dst
->sa
, SOCKLEN(dst
))) {
1304 closesocket(sockfd
);
1307 closesocket(sockfd
);
1313 /* XXX ELIMINATE: merge BIG slew into adj_systime in lib/systime.c */
1315 * addserver - determine a server's address and allocate a new structure
1323 register struct server
*server
;
1324 /* Address infos structure to store result of getaddrinfo */
1325 struct addrinfo
*addrResult
, *ptr
;
1326 /* Address infos structure to store hints for getaddrinfo */
1327 struct addrinfo hints
;
1328 /* Error variable for getaddrinfo */
1332 strcpy(service
, "ntp");
1334 /* Get host address. Looking for UDP datagram connection. */
1335 memset(&hints
, 0, sizeof(hints
));
1336 hints
.ai_family
= ai_fam_templ
;
1337 hints
.ai_socktype
= SOCK_DGRAM
;
1341 printf("Looking for host %s and service %s\n", serv
, service
);
1344 error
= getaddrinfo(serv
, service
, &hints
, &addrResult
);
1346 /* Conduct more refined error analysis */
1347 if (error
== EAI_FAIL
|| error
== EAI_AGAIN
){
1348 /* Name server is unusable. Exit after failing on the
1349 first server, in order to shorten the timeout caused
1350 by waiting for resolution of several servers */
1351 fprintf(stderr
, "Name server cannot be used, exiting");
1352 msyslog(LOG_ERR
, "name server cannot be used, reason: %s\n", gai_strerror(error
));
1355 fprintf(stderr
, "Error : %s\n", gai_strerror(error
));
1356 msyslog(LOG_ERR
, "can't find host %s\n", serv
);
1361 fprintf(stderr
, "host found : %s\n", stohost((sockaddr_u
*)addrResult
->ai_addr
));
1365 /* We must get all returned server in case the first one fails */
1366 for (ptr
= addrResult
; ptr
!= NULL
; ptr
= ptr
->ai_next
) {
1367 if (is_reachable ((sockaddr_u
*)ptr
->ai_addr
)) {
1368 server
= emalloc(sizeof(*server
));
1369 memset(server
, 0, sizeof(*server
));
1371 memcpy(&server
->srcadr
, ptr
->ai_addr
, ptr
->ai_addrlen
);
1372 server
->event_time
= ++sys_numservers
;
1373 if (sys_servers
== NULL
)
1374 sys_servers
= server
;
1378 for (sp
= sys_servers
; sp
->next_server
!= NULL
;
1379 sp
= sp
->next_server
) ;
1380 sp
->next_server
= server
;
1385 freeaddrinfo(addrResult
);
1390 * findserver - find a server in the list given its address
1391 * ***(For now it isn't totally AF-Independant, to check later..)
1393 static struct server
*
1398 struct server
*server
;
1399 struct server
*mc_server
;
1402 if (SRCPORT(addr
) != NTP_PORT
)
1405 for (server
= sys_servers
; server
!= NULL
;
1406 server
= server
->next_server
) {
1407 if (SOCK_EQ(addr
, &server
->srcadr
))
1410 if (AF(addr
) == AF(&server
->srcadr
)) {
1411 if (IS_MCAST(&server
->srcadr
))
1416 if (mc_server
!= NULL
) {
1420 if (mc_server
->event_time
!= 0) {
1421 mc_server
->event_time
= 0;
1425 server
= emalloc(sizeof(*server
));
1426 memset(server
, 0, sizeof(*server
));
1428 server
->srcadr
= *addr
;
1430 server
->event_time
= ++sys_numservers
;
1432 for (sp
= sys_servers
; sp
->next_server
!= NULL
;
1433 sp
= sp
->next_server
) ;
1434 sp
->next_server
= server
;
1442 * timer - process a timer interrupt
1447 struct server
*server
;
1450 * Bump the current idea of the time
1455 * Search through the server list looking for guys
1456 * who's event timers have expired. Give these to
1457 * the transmit routine.
1459 for (server
= sys_servers
; server
!= NULL
;
1460 server
= server
->next_server
) {
1461 if (server
->event_time
!= 0
1462 && server
->event_time
<= current_time
)
1469 * The code duplication in the following subroutine sucks, but
1470 * we need to appease ansi2knr.
1475 * alarming - record the occurance of an alarm interrupt
1486 alarming(UINT uTimerID
, UINT uMsg
, DWORD dwUser
, DWORD dw1
, DWORD dw2
)
1488 UNUSED_ARG(uTimerID
); UNUSED_ARG(uMsg
); UNUSED_ARG(dwUser
);
1489 UNUSED_ARG(dw1
); UNUSED_ARG(dw2
);
1495 callTimeEndPeriod(void)
1497 timeEndPeriod( wTimerRes
);
1500 #endif /* SYS_WINNT */
1504 * init_alarm - set up the timer interrupt
1510 # ifndef HAVE_TIMER_SETTIME
1511 struct itimerval itimer
;
1513 struct itimerspec ntpdate_itimer
;
1518 # endif /* SYS_WINNT */
1519 #if defined SYS_CYGWIN32 || defined SYS_WINNT
1521 TOKEN_PRIVILEGES tkp
;
1523 #endif /* SYS_WINNT */
1528 # if defined(HAVE_TIMER_CREATE) && defined(HAVE_TIMER_SETTIME)
1530 /* this code was put in as setitimer() is non existant this us the
1531 * POSIX "equivalents" setup - casey
1533 /* ntpdate_timerid is global - so we can kill timer later */
1534 if (timer_create (CLOCK_REALTIME
, NULL
, &ntpdate_timerid
) ==
1542 fprintf (stderr
, "init_alarm(): timer_create (...) FAILED\n");
1547 * Set up the alarm interrupt. The first comes 1/(2*TIMER_HZ)
1548 * seconds from now and they continue on every 1/TIMER_HZ seconds.
1550 (void) signal_no_reset(SIGALRM
, alarming
);
1551 ntpdate_itimer
.it_interval
.tv_sec
= ntpdate_itimer
.it_value
.tv_sec
= 0;
1552 ntpdate_itimer
.it_interval
.tv_nsec
= 1000000000/TIMER_HZ
;
1553 ntpdate_itimer
.it_value
.tv_nsec
= 1000000000/(TIMER_HZ
<<1);
1554 timer_settime(ntpdate_timerid
, 0 /* !TIMER_ABSTIME */, &ntpdate_itimer
, NULL
);
1557 * Set up the alarm interrupt. The first comes 1/(2*TIMER_HZ)
1558 * seconds from now and they continue on every 1/TIMER_HZ seconds.
1560 (void) signal_no_reset(SIGALRM
, alarming
);
1561 itimer
.it_interval
.tv_sec
= itimer
.it_value
.tv_sec
= 0;
1562 itimer
.it_interval
.tv_usec
= 1000000/TIMER_HZ
;
1563 itimer
.it_value
.tv_usec
= 1000000/(TIMER_HZ
<<1);
1565 setitimer(ITIMER_REAL
, &itimer
, (struct itimerval
*)0);
1567 #if defined SYS_CYGWIN32
1569 * Get privileges needed for fiddling with the clock
1572 /* get the current process token handle */
1573 if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES
| TOKEN_QUERY
, &hToken
)) {
1574 msyslog(LOG_ERR
, "OpenProcessToken failed: %m");
1577 /* get the LUID for system-time privilege. */
1578 LookupPrivilegeValue(NULL
, SE_SYSTEMTIME_NAME
, &tkp
.Privileges
[0].Luid
);
1579 tkp
.PrivilegeCount
= 1; /* one privilege to set */
1580 tkp
.Privileges
[0].Attributes
= SE_PRIVILEGE_ENABLED
;
1581 /* get set-time privilege for this process. */
1582 AdjustTokenPrivileges(hToken
, FALSE
, &tkp
, 0,(PTOKEN_PRIVILEGES
) NULL
, 0);
1583 /* cannot test return value of AdjustTokenPrivileges. */
1584 if (GetLastError() != ERROR_SUCCESS
)
1585 msyslog(LOG_ERR
, "AdjustTokenPrivileges failed: %m");
1587 #else /* SYS_WINNT */
1591 * Get privileges needed for fiddling with the clock
1594 /* get the current process token handle */
1595 if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES
| TOKEN_QUERY
, &hToken
)) {
1596 msyslog(LOG_ERR
, "OpenProcessToken failed: %m");
1599 /* get the LUID for system-time privilege. */
1600 LookupPrivilegeValue(NULL
, SE_SYSTEMTIME_NAME
, &tkp
.Privileges
[0].Luid
);
1601 tkp
.PrivilegeCount
= 1; /* one privilege to set */
1602 tkp
.Privileges
[0].Attributes
= SE_PRIVILEGE_ENABLED
;
1603 /* get set-time privilege for this process. */
1604 AdjustTokenPrivileges(hToken
, FALSE
, &tkp
, 0,(PTOKEN_PRIVILEGES
) NULL
, 0);
1605 /* cannot test return value of AdjustTokenPrivileges. */
1606 if (GetLastError() != ERROR_SUCCESS
)
1607 msyslog(LOG_ERR
, "AdjustTokenPrivileges failed: %m");
1610 * Set up timer interrupts for every 2**EVENT_TIMEOUT seconds
1611 * Under Win/NT, expiry of timer interval leads to invocation
1612 * of a callback function (on a different thread) rather than
1613 * generating an alarm signal
1616 /* determine max and min resolution supported */
1617 if(timeGetDevCaps(&tc
, sizeof(TIMECAPS
)) != TIMERR_NOERROR
) {
1618 msyslog(LOG_ERR
, "timeGetDevCaps failed: %m");
1621 wTimerRes
= min(max(tc
.wPeriodMin
, TARGET_RESOLUTION
), tc
.wPeriodMax
);
1622 /* establish the minimum timer resolution that we'll use */
1623 timeBeginPeriod(wTimerRes
);
1624 atexit(callTimeEndPeriod
);
1626 /* start the timer event */
1627 wTimerID
= timeSetEvent(
1628 (UINT
) (1000/TIMER_HZ
), /* Delay */
1629 wTimerRes
, /* Resolution */
1630 (LPTIMECALLBACK
) alarming
, /* Callback function */
1631 (DWORD
) dwUser
, /* User data */
1632 TIME_PERIODIC
); /* Event type (periodic) */
1633 if (wTimerID
== 0) {
1634 msyslog(LOG_ERR
, "timeSetEvent failed: %m");
1637 #endif /* SYS_WINNT */
1644 * We do asynchronous input using the SIGIO facility. A number of
1645 * recvbuf buffers are preallocated for input. In the signal
1646 * handler we poll to see if the socket is ready and read the
1647 * packets from it into the recvbuf's along with a time stamp and
1648 * an indication of the source host and the interface it was received
1649 * through. This allows us to get as accurate receive time stamps
1650 * as possible independent of other processing going on.
1652 * We allocate a number of recvbufs equal to the number of servers
1653 * plus 2. This should be plenty.
1658 * init_io - initialize I/O data and open socket
1663 struct addrinfo
*res
, *ressave
;
1664 struct addrinfo hints
;
1667 int check_ntp_port_in_use
= !debug
&& !simple_query
&& !unpriv_port
;
1670 * Init buffer free list and stat counters
1672 init_recvbuff(sys_numservers
+ 2);
1678 strcpy(service
, "ntp");
1681 * Init hints addrinfo structure
1683 memset(&hints
, 0, sizeof(hints
));
1684 hints
.ai_family
= ai_fam_templ
;
1685 hints
.ai_flags
= AI_PASSIVE
;
1686 hints
.ai_socktype
= SOCK_DGRAM
;
1688 if(getaddrinfo(NULL
, service
, &hints
, &res
) != 0) {
1689 msyslog(LOG_ERR
, "getaddrinfo() failed: %m");
1695 if (check_ntp_port_in_use
&& ntp_port_inuse(AF_INET
, NTP_PORT
)){
1696 msyslog(LOG_ERR
, "the NTP socket is in use, exiting: %m");
1701 /* Remember the address of the addrinfo structure chain */
1705 * For each structure returned, open and bind socket
1707 for(nbsock
= 0; (nbsock
< MAX_AF
) && res
; res
= res
->ai_next
) {
1708 /* create a datagram (UDP) socket */
1709 fd
[nbsock
] = socket(res
->ai_family
, res
->ai_socktype
, res
->ai_protocol
);
1710 if (fd
[nbsock
] == SOCKET_ERROR
) {
1712 if (errno
== EPROTONOSUPPORT
|| errno
== EAFNOSUPPORT
||
1713 errno
== EPFNOSUPPORT
)
1715 int err
= WSAGetLastError();
1716 if (err
== WSAEPROTONOSUPPORT
|| err
== WSAEAFNOSUPPORT
||
1717 err
== WSAEPFNOSUPPORT
)
1720 msyslog(LOG_ERR
, "socket() failed: %m");
1724 /* set socket to reuse address */
1725 if (setsockopt(fd
[nbsock
], SOL_SOCKET
, SO_REUSEADDR
, (void*) &optval
, sizeof(optval
)) < 0) {
1726 msyslog(LOG_ERR
, "setsockopt() SO_REUSEADDR failed: %m");
1731 /* Restricts AF_INET6 socket to IPv6 communications (see RFC 2553bis-03) */
1732 if (res
->ai_family
== AF_INET6
)
1733 if (setsockopt(fd
[nbsock
], IPPROTO_IPV6
, IPV6_V6ONLY
, (void*) &optval
, sizeof(optval
)) < 0) {
1734 msyslog(LOG_ERR
, "setsockopt() IPV6_V6ONLY failed: %m");
1740 /* Remember the socket family in fd_family structure */
1741 fd_family
[nbsock
] = res
->ai_family
;
1744 * bind the socket to the NTP port
1746 if (check_ntp_port_in_use
) {
1747 if (bind(fd
[nbsock
], res
->ai_addr
,
1748 SOCKLEN((sockaddr_u
*)res
->ai_addr
)) < 0) {
1750 if (errno
== EADDRINUSE
)
1752 if (WSAGetLastError() == WSAEADDRINUSE
)
1753 #endif /* SYS_WINNT */
1754 msyslog(LOG_ERR
, "the NTP socket is in use, exiting");
1756 msyslog(LOG_ERR
, "bind() fails: %m");
1762 fdmask
[nbsock
].fd
= fd
[nbsock
];
1763 fdmask
[nbsock
].events
= POLLIN
;
1765 FD_SET(fd
[nbsock
], &fdmask
);
1766 if (maxfd
< fd
[nbsock
]+1) {
1767 maxfd
= fd
[nbsock
]+1;
1779 if (ioctl(fd
[nbsock
],FIONBIO
, &on
) == ERROR
) {
1780 msyslog(LOG_ERR
, "ioctl(FIONBIO) fails: %m");
1784 # else /* not SYS_VXWORKS */
1785 # if defined(O_NONBLOCK)
1786 if (fcntl(fd
[nbsock
], F_SETFL
, O_NONBLOCK
) < 0) {
1787 msyslog(LOG_ERR
, "fcntl(FNDELAY|FASYNC) fails: %m");
1791 # else /* not O_NONBLOCK */
1792 # if defined(FNDELAY)
1793 if (fcntl(fd
[nbsock
], F_SETFL
, FNDELAY
) < 0) {
1794 msyslog(LOG_ERR
, "fcntl(FNDELAY|FASYNC) fails: %m");
1798 # else /* FNDELAY */
1799 # include "Bletch: Need non blocking I/O"
1800 # endif /* FNDELAY */
1801 # endif /* not O_NONBLOCK */
1802 # endif /* SYS_VXWORKS */
1803 #else /* SYS_WINNT */
1804 if (ioctlsocket(fd
[nbsock
], FIONBIO
, (u_long
*) &on
) == SOCKET_ERROR
) {
1805 msyslog(LOG_ERR
, "ioctlsocket(FIONBIO) fails: %m");
1808 #endif /* SYS_WINNT */
1811 freeaddrinfo(ressave
);
1815 * sendpkt - send a packet to the specified destination
1826 SOCKET sock
= INVALID_SOCKET
;
1830 #endif /* SYS_WINNT */
1832 /* Find a local family compatible socket to send ntp packet to ntp server */
1833 for(i
= 0; (i
< MAX_AF
); i
++) {
1834 if(AF(dest
) == fd_family
[i
]) {
1840 if (INVALID_SOCKET
== sock
) {
1841 msyslog(LOG_ERR
, "cannot find family compatible socket to send ntp packet");
1846 cc
= sendto(sock
, (char *)pkt
, len
, 0, (struct sockaddr
*)dest
,
1849 if (SOCKET_ERROR
== cc
) {
1851 if (errno
!= EWOULDBLOCK
&& errno
!= ENOBUFS
)
1853 err
= WSAGetLastError();
1854 if (err
!= WSAEWOULDBLOCK
&& err
!= WSAENOBUFS
)
1855 #endif /* SYS_WINNT */
1856 msyslog(LOG_ERR
, "sendto(%s): %m", stohost(dest
));
1862 * input_handler - receive packets asynchronously
1868 register struct recvbuf
*rb
;
1869 struct sock_timeval tvzero
;
1874 struct pollfd fds
[MAX_AF
];
1881 * Do a poll to see if we have data
1884 tvzero
.tv_sec
= tvzero
.tv_usec
= 0;
1886 memcpy(fds
, fdmask
, sizeof(fdmask
));
1887 n
= poll(fds
, (unsigned int)nbsock
, tvzero
.tv_sec
* 1000);
1890 * Determine which socket received data
1893 for(i
=0; i
< nbsock
; i
++) {
1894 if(fds
[i
].revents
& POLLIN
) {
1902 n
= select(maxfd
, &fds
, (fd_set
*)0, (fd_set
*)0, &tvzero
);
1905 * Determine which socket received data
1908 for(i
=0; i
< nbsock
; i
++) {
1909 if(FD_ISSET(fd
[i
], &fds
)) {
1918 * If nothing to do, just return. If an error occurred,
1919 * complain and return. If we've got some, freeze a
1930 "select() error: %m"
1938 * Get a buffer and read the frame. If we
1939 * haven't got a buffer, or this is received
1940 * on the wild card socket, just dump the packet.
1942 if (initializing
|| free_recvbuffs() == 0) {
1947 (void) read(fdc
, buf
, sizeof buf
);
1949 /* NT's _read does not operate on nonblocking sockets
1950 * either recvfrom or ReadFile() has to be used here.
1951 * ReadFile is used in [ntpd]ntp_intres() and ntpdc,
1952 * just to be different use recvfrom() here
1954 recvfrom(fdc
, buf
, sizeof(buf
), 0, (struct sockaddr
*)0, NULL
);
1955 #endif /* SYS_WINNT */
1959 rb
= get_free_recv_buffer();
1961 fromlen
= sizeof(rb
->recv_srcadr
);
1962 rb
->recv_length
= recvfrom(fdc
, (char *)&rb
->recv_pkt
,
1963 sizeof(rb
->recv_pkt
), 0,
1964 (struct sockaddr
*)&rb
->recv_srcadr
, &fromlen
);
1965 if (rb
->recv_length
== -1) {
1971 * Got one. Mark how and when it got here,
1972 * put it on the full list.
1975 add_full_recv_buffer(rb
);
1980 #if !defined SYS_WINNT && !defined SYS_CYGWIN32
1982 * adj_systime - do a big long slew of the system time
1989 struct timeval adjtv
, oadjtv
;
1997 * Take the absolute value of the offset
2000 if (L_ISNEG(&offset
)) {
2007 * Calculate the overshoot. XXX N.B. This code *knows*
2008 * ADJ_OVERSHOOT is 1/2.
2011 L_RSHIFTU(&overshoot
);
2012 if (overshoot
.l_ui
!= 0 || (overshoot
.l_uf
> ADJ_MAXOVERSHOOT
)) {
2014 overshoot
.l_uf
= ADJ_MAXOVERSHOOT
;
2016 L_ADD(&offset
, &overshoot
);
2018 TSTOTV(&offset
, &adjtv
);
2021 adjtv
.tv_sec
= -adjtv
.tv_sec
;
2022 adjtv
.tv_usec
= -adjtv
.tv_usec
;
2025 if (adjtv
.tv_usec
!= 0 && !debug
) {
2026 if (adjtime(&adjtv
, &oadjtv
) < 0) {
2027 msyslog(LOG_ERR
, "Can't adjust the time of day: %m");
2033 #endif /* SYS_WINNT */
2037 * This fuction is not the same as lib/systime step_systime!!!
2052 if (debug
) return 1;
2054 * Take the absolute value of the offset
2057 if (L_ISNEG(&ftmp
)) {
2063 if (ftmp
.l_ui
>= 3) { /* Step it and slew - we might win */
2065 n
= step_systime(dtemp
);
2074 * Just add adjustment into the current offset. The update
2075 * routine will take care of bringing the system clock into
2081 #ifdef FORCE_NTPDATE_STEP
2083 return step_systime(dtemp
);
2088 #else /* SLEWALWAYS */
2092 return step_systime(dtemp
);
2093 #endif /* SLEWALWAYS */
2097 /* XXX ELIMINATE printserver similar in ntptrace.c, ntpdate.c */
2099 * printserver - print detail information for a server
2103 register struct server
*pp
,
2112 (void) fprintf(fp
, "server %s, stratum %d, offset %s, delay %s\n",
2113 stoa(&pp
->srcadr
), pp
->stratum
,
2114 lfptoa(&pp
->offset
, 6), fptoa((s_fp
)pp
->delay
, 5));
2118 (void) fprintf(fp
, "server %s, port %d\n",
2119 stoa(&pp
->srcadr
), ntohs(((struct sockaddr_in
*)&(pp
->srcadr
))->sin_port
));
2121 (void) fprintf(fp
, "stratum %d, precision %d, leap %c%c, trust %03o\n",
2122 pp
->stratum
, pp
->precision
,
2123 pp
->leap
& 0x2 ? '1' : '0',
2124 pp
->leap
& 0x1 ? '1' : '0',
2127 if (pp
->stratum
== 1) {
2129 memmove(junk
, (char *)&pp
->refid
, 4);
2132 str
= stoa(&pp
->srcadr
);
2135 "refid [%s], delay %s, dispersion %s\n",
2136 str
, fptoa((s_fp
)pp
->delay
, 5),
2137 ufptoa(pp
->dispersion
, 5));
2139 (void) fprintf(fp
, "transmitted %d, in filter %d\n",
2140 pp
->xmtcnt
, pp
->filter_nextpt
);
2142 (void) fprintf(fp
, "reference time: %s\n",
2143 prettydate(&pp
->reftime
));
2144 (void) fprintf(fp
, "originate timestamp: %s\n",
2145 prettydate(&pp
->org
));
2146 (void) fprintf(fp
, "transmit timestamp: %s\n",
2147 prettydate(&pp
->xmt
));
2149 (void) fprintf(fp
, "filter delay: ");
2150 for (i
= 0; i
< NTP_SHIFT
; i
++) {
2151 (void) fprintf(fp
, " %-8.8s", fptoa(pp
->filter_delay
[i
], 5));
2152 if (i
== (NTP_SHIFT
>>1)-1)
2153 (void) fprintf(fp
, "\n ");
2155 (void) fprintf(fp
, "\n");
2157 (void) fprintf(fp
, "filter offset:");
2158 for (i
= 0; i
< PEER_SHIFT
; i
++) {
2159 (void) fprintf(fp
, " %-8.8s", lfptoa(&pp
->filter_offset
[i
], 6));
2160 if (i
== (PEER_SHIFT
>>1)-1)
2161 (void) fprintf(fp
, "\n ");
2163 (void) fprintf(fp
, "\n");
2165 (void) fprintf(fp
, "delay %s, dispersion %s\n",
2166 fptoa((s_fp
)pp
->delay
, 5), ufptoa(pp
->dispersion
, 5));
2168 (void) fprintf(fp
, "offset %s\n\n",
2169 lfptoa(&pp
->offset
, 6));
2172 #if !defined(HAVE_VSPRINTF)
2183 f
._flag
= _IOWRT
+_IOSTRG
;
2186 len
= _doprnt(fmt
, ap
, &f
);
2193 /* override function in library since SA_RESTART makes ALL syscalls restart */
2202 struct sigaction vec
;
2204 vec
.sa_handler
= func
;
2205 sigemptyset(&vec
.sa_mask
);
2210 n
= sigaction(sig
, &vec
, NULL
);
2211 if (n
== -1 && errno
== EINTR
)
2217 perror("sigaction");
2225 static ni_namelist
*
2226 getnetinfoservers(void)
2231 ni_namelist
*namelist
= emalloc(sizeof(ni_namelist
));
2233 /* Find a time server in NetInfo */
2234 if ((status
= ni_open(NULL
, ".", &domain
)) != NI_OK
) return NULL
;
2236 while (status
= ni_pathsearch(domain
, &confdir
, NETINFO_CONFIG_DIR
) == NI_NODIR
) {
2238 if (ni_open(domain
, "..", &next_domain
) != NI_OK
) break;
2240 domain
= next_domain
;
2242 if (status
!= NI_OK
) return NULL
;
2245 if (ni_lookupprop(domain
, &confdir
, "server", namelist
) != NI_OK
) {
2246 ni_namelist_free(namelist
);
2256 isc_boolean_t
ntp_port_inuse(int af
, u_short port
)
2259 * Check if NTP socket is already in use on this system
2260 * This is only for Windows Systems, as they tend not to fail on the real bind() below
2264 struct sockaddr_in checkservice
;
2265 checksocket
= socket(af
, SOCK_DGRAM
, 0);
2266 if (checksocket
== INVALID_SOCKET
) {
2270 checkservice
.sin_family
= (short) AF_INET
;
2271 checkservice
.sin_addr
.s_addr
= INADDR_LOOPBACK
;
2272 checkservice
.sin_port
= htons(port
);
2274 if (bind(checksocket
, (struct sockaddr
*)&checkservice
,
2275 sizeof(checkservice
)) == SOCKET_ERROR
) {
2276 if ( WSAGetLastError() == WSAEADDRINUSE
){
2277 closesocket(checksocket
);
2281 closesocket(checksocket
);