1 /* $NetBSD: ntpdate.c,v 1.8 2007/06/24 16:55:14 kardel Exp $ */
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"
26 /* Don't include ISC's version of IPv6 variables and structures */
29 #include "isc/result.h"
30 #include "isc/sockaddr.h"
43 # ifdef HAVE_SYS_SIGNAL_H
44 # include <sys/signal.h>
48 # ifdef HAVE_SYS_IOCTL_H
49 # include <sys/ioctl.h>
51 #endif /* SYS_WINNT */
52 #ifdef HAVE_SYS_RESOURCE_H
53 # include <sys/resource.h>
54 #endif /* HAVE_SYS_RESOURCE_H */
56 #include <arpa/inet.h>
63 /* select wants a zero structure ... */
64 struct timeval timeout
= {0,0};
65 #elif defined(SYS_WINNT)
67 * Windows does not abort a select select call if SIGALRM goes off
68 * so a 200 ms timeout is needed
70 struct timeval timeout
= {0,1000000/TIMER_HZ
};
72 struct timeval timeout
= {60,0};
76 #include <netinfo/ni.h>
82 #define EPROTONOSUPPORT WSAEPROTONOSUPPORT
83 #define EAFNOSUPPORT WSAEAFNOSUPPORT
84 #define EPFNOSUPPORT WSAEPFNOSUPPORT
85 #define TARGET_RESOLUTION 1 /* Try for 1-millisecond accuracy
86 on Windows NT timers. */
87 #pragma comment(lib, "winmm")
88 isc_boolean_t
ntp_port_inuse(int af
, u_short port
);
90 #endif /* SYS_WINNT */
93 * Scheduling priority we run at
96 # define NTPDATE_PRIO (-12)
98 # define NTPDATE_PRIO (100)
101 #if defined(HAVE_TIMER_SETTIME) || defined (HAVE_TIMER_CREATE)
102 /* POSIX TIMERS - vxWorks doesn't have itimer - casey */
103 static timer_t ntpdate_timerid
;
107 * Compatibility stuff for Version 2
109 #define NTP_MAXSKW 0x28f /* 0.01 sec in fp format */
110 #define NTP_MINDIST 0x51f /* 0.02 sec in fp format */
111 #define PEER_MAXDISP (64*FP_SECOND) /* maximum dispersion (fp 64) */
112 #define NTP_INFIN 15 /* max stratum, infinity a la Bellman-Ford */
113 #define NTP_MAXWGT (8*FP_SECOND) /* maximum select weight 8 seconds */
114 #define NTP_MAXLIST 5 /* maximum select list size */
115 #define PEER_SHIFT 8 /* 8 suitable for crystal time base */
120 s_char sys_precision
; /* local clock precision (log2 s) */
125 volatile int debug
= 0;
128 * File descriptor masks etc. for call to select
132 int nbsock
; /* the number of sockets used */
134 int fd_family
[MAX_AF
]; /* to remember the socket family */
136 struct pollfd fdmask
[MAX_AF
];
144 * Initializing flag. All async routines watch this and only do their
145 * thing when it is clear.
147 int initializing
= 1;
150 * Alarm flag. Set when an alarm occurs
152 volatile int alarm_flag
= 0;
157 int simple_query
= 0;
160 * Unprivileged port flag.
170 * Systemwide parameters and flags
172 int sys_samples
= DEFSAMPLES
; /* number of samples/server */
173 u_long sys_timeout
= DEFTIMEOUT
; /* timeout time, in TIMER_HZ units */
174 struct server
*sys_servers
; /* the server list */
175 int sys_numservers
= 0; /* number of servers to poll */
176 int sys_authenticate
= 0; /* true when authenticating */
177 u_int32 sys_authkey
= 0; /* set to authentication key in use */
178 u_long sys_authdelay
= 0; /* authentication delay */
179 int sys_version
= NTP_VERSION
; /* version to poll with */
182 * The current internal time
184 u_long current_time
= 0;
187 * Counter for keeping track of completed servers
189 int complete_servers
= 0;
192 * File of encryption keys
197 #define KEYFILE "/etc/ntp.keys"
199 #define KEYFILE "%windir%\\ntp.keys"
200 # endif /* SYS_WINNT */
204 const char *key_file
= KEYFILE
;
206 char key_file_storage
[MAX_PATH
+1], *key_file
;
207 #endif /* SYS_WINNT */
210 * Miscellaneous flags
216 int ntpdatemain
P((int, char **));
218 static void transmit
P((struct server
*));
219 static void receive
P((struct recvbuf
*));
220 static void server_data
P((struct server
*, s_fp
, l_fp
*, u_fp
));
221 static void clock_filter
P((struct server
*));
222 static struct server
*clock_select
P((void));
223 static int clock_adjust
P((void));
224 static void addserver
P((char *));
225 static struct server
*findserver
P((struct sockaddr_storage
*));
226 void timer
P((void));
227 static void init_alarm
P((void));
229 static RETSIGTYPE alarming
P((int));
230 #endif /* SYS_WINNT */
231 static void init_io
P((void));
232 static void sendpkt
P((struct sockaddr_storage
*, struct pkt
*, int));
233 void input_handler
P((void));
235 static int l_adj_systime
P((l_fp
*));
236 static int l_step_systime
P((l_fp
*));
238 static void printserver
P((struct server
*, FILE *));
242 WORD wVersionRequested
;
244 HANDLE TimerThreadHandle
= NULL
;
245 #endif /* SYS_WINNT */
247 #ifdef NO_MAIN_ALLOWED
248 CALL(ntpdate
,"ntpdate",ntpdatemain
);
259 * Initializing flag. All async routines watch this and only do their
260 * thing when it is clear.
265 * Alarm flag. Set when an alarm occurs
275 * Unprivileged port flag.
280 * Systemwide parameters and flags
282 sys_numservers
= 0; /* number of servers to poll */
283 sys_authenticate
= 0; /* true when authenticating */
284 sys_authkey
= 0; /* set to authentication key in use */
285 sys_authdelay
= 0; /* authentication delay */
286 sys_version
= NTP_VERSION
; /* version to poll with */
289 * The current internal time
294 * Counter for keeping track of completed servers
296 complete_servers
= 0;
304 static ni_namelist
*getnetinfoservers
P((void));
308 * Main program. Initialize us and loop waiting for I/O and/or
311 #ifndef NO_MAIN_ALLOWED
318 return ntpdatemain (argc
, argv
);
320 #endif /* NO_MAIN_ALLOWED */
330 struct recvbuf
*rbuf
;
337 ni_namelist
*netinfoservers
;
340 HANDLE process_handle
;
342 wVersionRequested
= MAKEWORD(1,1);
343 if (WSAStartup(wVersionRequested
, &wsaData
)) {
344 netsyslog(LOG_ERR
, "No useable winsock.dll: %m");
348 key_file
= key_file_storage
;
350 if (!ExpandEnvironmentStrings(KEYFILE
, key_file
, MAX_PATH
))
352 msyslog(LOG_ERR
, "ExpandEnvironmentStrings(KEYFILE) failed: %m\n");
354 #endif /* SYS_WINNT */
356 #ifdef NO_MAIN_ALLOWED
361 /* Check to see if we have IPv6. Otherwise force the -4 flag */
362 if (isc_net_probeipv6() != ISC_R_SUCCESS
) {
363 ai_fam_templ
= AF_INET
;
371 * Decode argument list
373 while ((c
= ntp_getopt(argc
, argv
, "46a:bBde:k:o:p:qst:uv")) != EOF
)
377 ai_fam_templ
= AF_INET
;
380 ai_fam_templ
= AF_INET6
;
383 c
= atoi(ntp_optarg
);
384 sys_authenticate
= 1;
399 if (!atolfp(ntp_optarg
, &tmp
)
401 (void) fprintf(stderr
,
402 "%s: encryption delay %s is unlikely\n",
403 progname
, ntp_optarg
);
406 sys_authdelay
= tmp
.l_uf
;
410 key_file
= ntp_optarg
;
413 sys_version
= atoi(ntp_optarg
);
416 c
= atoi(ntp_optarg
);
417 if (c
<= 0 || c
> NTP_SHIFT
) {
418 (void) fprintf(stderr
,
419 "%s: number of samples (%d) is invalid\n",
433 if (!atolfp(ntp_optarg
, &tmp
)) {
434 (void) fprintf(stderr
,
435 "%s: timeout %s is undecodeable\n",
436 progname
, ntp_optarg
);
439 sys_timeout
= ((LFPTOFP(&tmp
) * TIMER_HZ
)
441 if (sys_timeout
== 0)
459 (void) fprintf(stderr
,
460 "usage: %s [-46bBdqsuv] [-a key#] [-e delay] [-k file] [-p samples] [-o version#] [-t timeo] server ...\n",
465 if (debug
|| simple_query
) {
467 static char buf
[BUFSIZ
];
469 /* Win32 does not implement line buffering */
470 setvbuf(stdout
, NULL
, _IONBF
, BUFSIZ
);
472 setvbuf(stdout
, buf
, _IOLBF
, BUFSIZ
);
473 #endif /* SYS_WINNT */
480 * Logging. Open the syslog if we have to
483 #if !defined (SYS_WINNT) && !defined (SYS_VXWORKS) && !defined SYS_CYGWIN32
485 openlog("ntpdate", LOG_PID
);
489 # define LOG_NTP LOG_DAEMON
491 openlog("ntpdate", LOG_PID
| LOG_NDELAY
, LOG_NTP
);
493 setlogmask(LOG_UPTO(LOG_DEBUG
));
495 setlogmask(LOG_UPTO(LOG_INFO
));
496 # endif /* LOG_DAEMON */
497 #endif /* SYS_WINNT */
500 if (debug
|| verbose
)
501 msyslog(LOG_NOTICE
, "%s", Version
);
504 * Add servers we are going to be polling
507 netinfoservers
= getnetinfoservers();
510 for ( ; ntp_optind
< argc
; ntp_optind
++)
511 addserver(argv
[ntp_optind
]);
514 if (netinfoservers
) {
515 if ( netinfoservers
->ni_namelist_len
&&
516 *netinfoservers
->ni_namelist_val
) {
517 u_int servercount
= 0;
518 while (servercount
< netinfoservers
->ni_namelist_len
) {
519 if (debug
) msyslog(LOG_DEBUG
,
520 "Adding time server %s from NetInfo configuration.",
521 netinfoservers
->ni_namelist_val
[servercount
]);
522 addserver(netinfoservers
->ni_namelist_val
[servercount
++]);
525 ni_namelist_free(netinfoservers
);
526 free(netinfoservers
);
530 if (sys_numservers
== 0) {
531 msyslog(LOG_ERR
, "no servers can be used, exiting");
536 * Initialize the time of day routines and the I/O subsystem
538 if (sys_authenticate
) {
540 if (!authreadkeys(key_file
)) {
541 msyslog(LOG_ERR
, "no key file <%s>, exiting", key_file
);
544 authtrust(sys_authkey
, 1);
545 if (!authistrusted(sys_authkey
)) {
546 msyslog(LOG_ERR
, "authentication key %lu unknown",
547 (unsigned long) sys_authkey
);
558 taskPrioritySet( taskIdSelf(), NTPDATE_PRIO
);
560 #if defined(HAVE_ATT_NICE)
563 #if defined(HAVE_BSD_NICE)
564 (void) setpriority(PRIO_PROCESS
, 0, NTPDATE_PRIO
);
567 process_handle
= GetCurrentProcess();
568 if (!SetPriorityClass(process_handle
, (DWORD
) REALTIME_PRIORITY_CLASS
)) {
569 msyslog(LOG_ERR
, "SetPriorityClass failed: %m");
571 #endif /* SYS_WINNT */
578 while (complete_servers
< sys_numservers
) {
580 struct pollfd
* rdfdes
;
587 if (alarm_flag
) { /* alarmed? */
591 tot_recvbufs
= full_recvbuffs(); /* get received buffers */
593 if (!was_alarmed
&& tot_recvbufs
== 0) {
595 * Nothing to do. Wait for something.
598 nfound
= poll(rdfdes
, (unsigned int)nbsock
, timeout
.tv_sec
* 1000);
601 nfound
= select(maxfd
, &rdfdes
, (fd_set
*)0,
602 (fd_set
*)0, &timeout
);
606 else if (nfound
== SOCKET_ERROR
)
611 if (WSAGetLastError() != WSAEINTR
)
620 } else if (errno
!= 0) {
624 "poll(): nfound = %d, error: %m",
626 "select(): nfound = %d, error: %m",
631 if (alarm_flag
) { /* alarmed? */
635 tot_recvbufs
= full_recvbuffs(); /* get received buffers */
639 * Out here, signals are unblocked. Call receive
640 * procedure for each incoming packet.
642 rbuf
= get_full_recv_buffer();
647 rbuf
= get_full_recv_buffer();
651 * Call timer to process any timeouts
664 * When we get here we've completed the polling of all servers.
665 * Adjust the clock, then exit.
672 timer_delete(ntpdate_timerid
);
675 return clock_adjust();
680 * transmit - transmit a packet to the given server, or mark it completed.
681 * This is called by the timeout routine and by the receive
686 register struct server
*server
692 printf("transmit(%s)\n", stoa(&(server
->srcadr
)));
694 if (server
->filter_nextpt
< server
->xmtcnt
) {
697 * Last message to this server timed out. Shift
698 * zeros into the filter.
701 server_data(server
, 0, &ts
, 0);
704 if ((int)server
->filter_nextpt
>= sys_samples
) {
706 * Got all the data we need. Mark this guy
707 * completed and return.
709 server
->event_time
= 0;
715 * If we're here, send another message to the server. Fill in
716 * the packet and let 'er rip.
718 xpkt
.li_vn_mode
= PKT_LI_VN_MODE(LEAP_NOTINSYNC
,
719 sys_version
, MODE_CLIENT
);
720 xpkt
.stratum
= STRATUM_TO_PKT(STRATUM_UNSPEC
);
721 xpkt
.ppoll
= NTP_MINPOLL
;
722 xpkt
.precision
= NTPDATE_PRECISION
;
723 xpkt
.rootdelay
= htonl(NTPDATE_DISTANCE
);
724 xpkt
.rootdispersion
= htonl(NTPDATE_DISP
);
725 xpkt
.refid
= htonl(NTPDATE_REFID
);
726 L_CLR(&xpkt
.reftime
);
731 * Determine whether to authenticate or not. If so,
732 * fill in the extended part of the packet and do it.
733 * If not, just timestamp it and send it away.
735 if (sys_authenticate
) {
738 xpkt
.exten
[0] = htonl(sys_authkey
);
739 get_systime(&server
->xmt
);
740 L_ADDUF(&server
->xmt
, sys_authdelay
);
741 HTONL_FP(&server
->xmt
, &xpkt
.xmt
);
742 len
= authencrypt(sys_authkey
, (u_int32
*)&xpkt
, LEN_PKT_NOMAC
);
743 sendpkt(&(server
->srcadr
), &xpkt
, (int)(LEN_PKT_NOMAC
+ len
));
746 printf("transmit auth to %s\n",
747 stoa(&(server
->srcadr
)));
749 get_systime(&(server
->xmt
));
750 HTONL_FP(&server
->xmt
, &xpkt
.xmt
);
751 sendpkt(&(server
->srcadr
), &xpkt
, LEN_PKT_NOMAC
);
754 printf("transmit to %s\n", stoa(&(server
->srcadr
)));
758 * Update the server timeout and transmit count
760 server
->event_time
= current_time
+ sys_timeout
;
766 * receive - receive and process an incoming frame
770 struct recvbuf
*rbufp
773 register struct pkt
*rpkt
;
774 register struct server
*server
;
784 printf("receive(%s)\n", stoa(&rbufp
->recv_srcadr
));
786 * Check to see if the packet basically looks like something
789 if (rbufp
->recv_length
== LEN_PKT_NOMAC
)
791 else if (rbufp
->recv_length
>= LEN_PKT_NOMAC
)
795 printf("receive: packet length %d\n",
797 return; /* funny length packet */
800 rpkt
= &(rbufp
->recv_pkt
);
801 if (PKT_VERSION(rpkt
->li_vn_mode
) < NTP_OLDVERSION
||
802 PKT_VERSION(rpkt
->li_vn_mode
) > NTP_VERSION
) {
806 if ((PKT_MODE(rpkt
->li_vn_mode
) != MODE_SERVER
807 && PKT_MODE(rpkt
->li_vn_mode
) != MODE_PASSIVE
)
808 || rpkt
->stratum
>= STRATUM_UNSPEC
) {
810 printf("receive: mode %d stratum %d\n",
811 PKT_MODE(rpkt
->li_vn_mode
), rpkt
->stratum
);
816 * So far, so good. See if this is from a server we know.
818 server
= findserver(&(rbufp
->recv_srcadr
));
819 if (server
== NULL
) {
821 printf("receive: server not found\n");
826 * Decode the org timestamp and make sure we're getting a response
827 * to our last request.
829 NTOHL_FP(&rpkt
->org
, &org
);
830 if (!L_ISEQU(&org
, &server
->xmt
)) {
832 printf("receive: pkt.org and peer.xmt differ\n");
837 * Check out the authenticity if we're doing that.
839 if (!sys_authenticate
)
845 printf("receive: rpkt keyid=%ld sys_authkey=%ld decrypt=%ld\n",
846 (long int)ntohl(rpkt
->exten
[0]), (long int)sys_authkey
,
847 (long int)authdecrypt(sys_authkey
, (u_int32
*)rpkt
,
848 LEN_PKT_NOMAC
, (int)(rbufp
->recv_length
- LEN_PKT_NOMAC
)));
850 if (has_mac
&& ntohl(rpkt
->exten
[0]) == sys_authkey
&&
851 authdecrypt(sys_authkey
, (u_int32
*)rpkt
, LEN_PKT_NOMAC
,
852 (int)(rbufp
->recv_length
- LEN_PKT_NOMAC
)))
855 printf("receive: authentication %s\n",
856 is_authentic
? "passed" : "failed");
863 * Looks good. Record info from the packet.
865 server
->leap
= PKT_LEAP(rpkt
->li_vn_mode
);
866 server
->stratum
= PKT_TO_STRATUM(rpkt
->stratum
);
867 server
->precision
= rpkt
->precision
;
868 server
->rootdelay
= ntohl(rpkt
->rootdelay
);
869 server
->rootdispersion
= ntohl(rpkt
->rootdispersion
);
870 server
->refid
= rpkt
->refid
;
871 NTOHL_FP(&rpkt
->reftime
, &server
->reftime
);
872 NTOHL_FP(&rpkt
->rec
, &rec
);
873 NTOHL_FP(&rpkt
->xmt
, &server
->org
);
876 * Make sure the server is at least somewhat sane. If not, try
879 if (L_ISZERO(&rec
) || !L_ISHIS(&server
->org
, &rec
)) {
885 * Calculate the round trip delay (di) and the clock offset (ci).
886 * We use the equations (reordered from those in the spec):
888 * d = (t2 - t3) - (t1 - t0)
889 * c = ((t2 - t3) + (t1 - t0)) / 2
891 t10
= server
->org
; /* pkt.xmt == t1 */
892 L_SUB(&t10
, &rbufp
->recv_time
); /* recv_time == t0*/
894 t23
= rec
; /* pkt.rec == t2 */
895 L_SUB(&t23
, &org
); /* pkt->org == t3 */
897 /* now have (t2 - t3) and (t0 - t1). Calculate (ci) and (di) */
899 * Calculate (ci) = ((t1 - t0) / 2) + ((t2 - t3) / 2)
900 * For large offsets this may prevent an overflow on '+'
909 * Calculate di in t23 in full precision, then truncate
916 printf("offset: %s, delay %s\n", lfptoa(&ci
, 6), fptoa(di
, 5));
918 di
+= (FP_SECOND
>> (-(int)NTPDATE_PRECISION
))
919 + (FP_SECOND
>> (-(int)server
->precision
)) + NTP_MAXSKW
;
921 if (di
<= 0) { /* value still too raunchy to use? */
925 di
= max(di
, NTP_MINDIST
);
929 * Shift this data in, then transmit again.
931 server_data(server
, (s_fp
) di
, &ci
, 0);
937 * server_data - add a sample to the server's filter registers
941 register struct server
*server
,
949 i
= server
->filter_nextpt
;
951 server
->filter_delay
[i
] = d
;
952 server
->filter_offset
[i
] = *c
;
953 server
->filter_soffset
[i
] = LFPTOFP(c
);
954 server
->filter_error
[i
] = e
;
955 server
->filter_nextpt
= (u_short
)(i
+ 1);
961 * clock_filter - determine a server's delay, dispersion and offset
965 register struct server
*server
972 * Sort indices into increasing delay order
974 for (i
= 0; i
< sys_samples
; i
++)
977 for (i
= 0; i
< (sys_samples
-1); i
++) {
978 for (j
= i
+1; j
< sys_samples
; j
++) {
979 if (server
->filter_delay
[ord
[j
]] == 0)
981 if (server
->filter_delay
[ord
[i
]] == 0
982 || (server
->filter_delay
[ord
[i
]]
983 > server
->filter_delay
[ord
[j
]])) {
994 * Now compute the dispersion, and assign values to delay and
995 * offset. If there are no samples in the register, delay and
996 * offset go to zero and dispersion is set to the maximum.
998 if (server
->filter_delay
[ord
[0]] == 0) {
1000 L_CLR(&server
->offset
);
1001 server
->soffset
= 0;
1002 server
->dispersion
= PEER_MAXDISP
;
1006 server
->delay
= server
->filter_delay
[ord
[0]];
1007 server
->offset
= server
->filter_offset
[ord
[0]];
1008 server
->soffset
= LFPTOFP(&server
->offset
);
1009 server
->dispersion
= 0;
1010 for (i
= 1; i
< sys_samples
; i
++) {
1011 if (server
->filter_delay
[ord
[i
]] == 0)
1014 d
= server
->filter_soffset
[ord
[i
]]
1015 - server
->filter_soffset
[ord
[0]];
1018 if (d
> PEER_MAXDISP
)
1022 * XXX This *knows* PEER_FILTER is 1/2
1024 server
->dispersion
+= (u_fp
)(d
) >> i
;
1034 * clock_select - select the pick-of-the-litter clock from the samples
1037 static struct server
*
1040 register struct server
*server
;
1046 s_fp local_threshold
;
1047 struct server
*server_list
[NTP_MAXCLOCK
];
1048 u_fp server_badness
[NTP_MAXCLOCK
];
1049 struct server
*sys_server
;
1052 * This first chunk of code is supposed to go through all
1053 * servers we know about to find the NTP_MAXLIST servers which
1054 * are most likely to succeed. We run through the list
1055 * doing the sanity checks and trying to insert anyone who
1056 * looks okay. We are at all times aware that we should
1057 * only keep samples from the top two strata and we only need
1058 * NTP_MAXLIST of them.
1060 nlist
= 0; /* none yet */
1061 for (server
= sys_servers
; server
!= NULL
; server
= server
->next_server
) {
1062 if (server
->delay
== 0) {
1064 printf("%s: Server dropped: no data\n", ntoa(&server
->srcadr
));
1065 continue; /* no data */
1067 if (server
->stratum
> NTP_INFIN
) {
1069 printf("%s: Server dropped: strata too high\n", ntoa(&server
->srcadr
));
1070 continue; /* stratum no good */
1072 if (server
->delay
> NTP_MAXWGT
) {
1074 printf("%s: Server dropped: server too far away\n",
1075 ntoa(&server
->srcadr
));
1076 continue; /* too far away */
1078 if (server
->leap
== LEAP_NOTINSYNC
) {
1080 printf("%s: Server dropped: Leap not in sync\n", ntoa(&server
->srcadr
));
1081 continue; /* he's in trouble */
1083 if (!L_ISHIS(&server
->org
, &server
->reftime
)) {
1085 printf("%s: Server dropped: server is very broken\n",
1086 ntoa(&server
->srcadr
));
1087 continue; /* very broken host */
1089 if ((server
->org
.l_ui
- server
->reftime
.l_ui
)
1092 printf("%s: Server dropped: Server has gone too long without sync\n",
1093 ntoa(&server
->srcadr
));
1094 continue; /* too long without sync */
1096 if (server
->trust
!= 0) {
1098 printf("%s: Server dropped: Server is untrusted\n",
1099 ntoa(&server
->srcadr
));
1104 * This one seems sane. Find where he belongs
1107 d
= server
->dispersion
+ server
->dispersion
;
1108 for (i
= 0; i
< nlist
; i
++)
1109 if (server
->stratum
<= server_list
[i
]->stratum
)
1111 for ( ; i
< nlist
; i
++) {
1112 if (server
->stratum
< server_list
[i
]->stratum
)
1114 if (d
< (s_fp
) server_badness
[i
])
1119 * If i points past the end of the list, this
1120 * guy is a loser, else stick him in.
1122 if (i
>= NTP_MAXLIST
)
1124 for (j
= nlist
; j
> i
; j
--)
1125 if (j
< NTP_MAXLIST
) {
1126 server_list
[j
] = server_list
[j
-1];
1128 = server_badness
[j
-1];
1131 server_list
[i
] = server
;
1132 server_badness
[i
] = d
;
1133 if (nlist
< NTP_MAXLIST
)
1138 * Got the five-or-less best. Cut the list where the number of
1139 * strata exceeds two.
1142 for (i
= 1; i
< nlist
; i
++)
1143 if (server_list
[i
]->stratum
> server_list
[i
-1]->stratum
)
1150 * Whew! What we should have by now is 0 to 5 candidates for
1151 * the job of syncing us. If we have none, we're out of luck.
1152 * If we have one, he's a winner. If we have more, do falseticker
1158 else if (nlist
== 1) {
1159 sys_server
= server_list
[0];
1162 * Re-sort by stratum, bdelay estimate quality and
1165 for (i
= 0; i
< nlist
-1; i
++)
1166 for (j
= i
+1; j
< nlist
; j
++) {
1167 if (server_list
[i
]->stratum
1168 < server_list
[j
]->stratum
)
1169 break; /* already sorted by stratum */
1170 if (server_list
[i
]->delay
1171 < server_list
[j
]->delay
)
1173 server
= server_list
[i
];
1174 server_list
[i
] = server_list
[j
];
1175 server_list
[j
] = server
;
1179 * Calculate the fixed part of the dispersion limit
1181 local_threshold
= (FP_SECOND
>> (-(int)NTPDATE_PRECISION
))
1185 * Now drop samples until we're down to one.
1188 for (n
= 0; n
< nlist
; n
++) {
1189 server_badness
[n
] = 0;
1190 for (j
= 0; j
< nlist
; j
++) {
1191 if (j
== n
) /* with self? */
1193 d
= server_list
[j
]->soffset
1194 - server_list
[n
]->soffset
;
1195 if (d
< 0) /* absolute value */
1198 * XXX This code *knows* that
1201 for (i
= 0; i
< j
; i
++)
1202 d
= (d
>>1) + (d
>>2);
1203 server_badness
[n
] += d
;
1208 * We now have an array of nlist badness
1209 * coefficients. Find the badest. Find
1210 * the minimum precision while we're at
1214 n
= server_list
[0]->precision
;;
1215 for (j
= 1; j
< nlist
; j
++) {
1216 if (server_badness
[j
] >= server_badness
[i
])
1218 if (n
> server_list
[j
]->precision
)
1219 n
= server_list
[j
]->precision
;
1223 * i is the index of the server with the worst
1224 * dispersion. If his dispersion is less than
1225 * the threshold, stop now, else delete him and
1226 * continue around again.
1228 if ( (s_fp
) server_badness
[i
] < (local_threshold
1229 + (FP_SECOND
>> (-n
))))
1231 for (j
= i
+ 1; j
< nlist
; j
++)
1232 server_list
[j
-1] = server_list
[j
];
1237 * What remains is a list of less than 5 servers. Take
1240 sys_server
= server_list
[0];
1244 * That's it. Return our server.
1251 * clock_adjust - process what we've received, and adjust the time
1252 * if we got anything decent.
1257 register struct server
*sp
, *server
;
1261 for (sp
= sys_servers
; sp
!= NULL
; sp
= sp
->next_server
)
1263 server
= clock_select();
1265 if (debug
|| simple_query
) {
1266 for (sp
= sys_servers
; sp
!= NULL
; sp
= sp
->next_server
)
1267 printserver(sp
, stdout
);
1272 "no server suitable for synchronization found");
1278 } else if (never_step
) {
1281 absoffset
= server
->soffset
;
1283 absoffset
= -absoffset
;
1284 dostep
= (absoffset
>= NTPDATE_THRESHOLD
|| absoffset
< 0);
1288 if (simple_query
|| debug
|| l_step_systime(&server
->offset
)){
1289 msyslog(LOG_NOTICE
, "step time server %s offset %s sec",
1290 stoa(&server
->srcadr
),
1291 lfptoa(&server
->offset
, 6));
1294 #if !defined SYS_WINNT && !defined SYS_CYGWIN32
1295 if (simple_query
|| l_adj_systime(&server
->offset
)) {
1296 msyslog(LOG_NOTICE
, "adjust time server %s offset %s sec",
1297 stoa(&server
->srcadr
),
1298 lfptoa(&server
->offset
, 6));
1301 /* The NT SetSystemTimeAdjustment() call achieves slewing by
1302 * changing the clock frequency. This means that we cannot specify
1303 * it to slew the clock by a definite amount and then stop like
1304 * the Unix adjtime() routine. We can technically adjust the clock
1305 * frequency, have ntpdate sleep for a while, and then wake
1306 * up and reset the clock frequency, but this might cause some
1307 * grief if the user attempts to run ntpd immediately after
1308 * ntpdate and the socket is in use.
1310 printf("\nThe -b option is required by ntpdate on Windows NT platforms\n");
1312 #endif /* SYS_WINNT */
1319 * is_unreachable - check to see if we have a route to given destination
1323 is_reachable (struct sockaddr_storage
*dst
)
1327 sockfd
= socket(dst
->ss_family
, SOCK_DGRAM
, 0);
1332 if(connect(sockfd
, (struct sockaddr
*)dst
, SOCKLEN(dst
))) {
1333 closesocket(sockfd
);
1336 closesocket(sockfd
);
1342 /* XXX ELIMINATE: merge BIG slew into adj_systime in lib/systime.c */
1344 * addserver - determine a server's address and allocate a new structure
1352 register struct server
*server
;
1353 /* Address infos structure to store result of getaddrinfo */
1354 struct addrinfo
*addrResult
, *ptr
;
1355 /* Address infos structure to store hints for getaddrinfo */
1356 struct addrinfo hints
;
1357 /* Error variable for getaddrinfo */
1361 strcpy(service
, "ntp");
1363 /* Get host address. Looking for UDP datagram connection. */
1364 memset(&hints
, 0, sizeof(hints
));
1365 hints
.ai_family
= ai_fam_templ
;
1366 hints
.ai_socktype
= SOCK_DGRAM
;
1370 printf("Looking for host %s and service %s\n", serv
, service
);
1373 error
= getaddrinfo(serv
, service
, &hints
, &addrResult
);
1375 /* Conduct more refined error analysis */
1376 if (error
== EAI_FAIL
|| error
== EAI_AGAIN
){
1377 /* Name server is unusable. Exit after failing on the
1378 first server, in order to shorten the timeout caused
1379 by waiting for resolution of several servers */
1380 fprintf(stderr
, "Name server cannot be used, exiting");
1381 msyslog(LOG_ERR
, "name server cannot be used, reason: %s\n", gai_strerror(error
));
1384 fprintf(stderr
, "Error : %s\n", gai_strerror(error
));
1385 msyslog(LOG_ERR
, "can't find host %s\n", serv
);
1390 fprintf(stderr
, "host found : %s\n", stohost((struct sockaddr_storage
*)addrResult
->ai_addr
));
1394 /* We must get all returned server in case the first one fails */
1395 for (ptr
= addrResult
; ptr
!= NULL
; ptr
= ptr
->ai_next
) {
1396 if (is_reachable ((struct sockaddr_storage
*)ptr
->ai_addr
)) {
1397 server
= (struct server
*)emalloc(sizeof(struct server
));
1398 memset((char *)server
, 0, sizeof(struct server
));
1400 memset(&(server
->srcadr
), 0, sizeof(struct sockaddr_storage
));
1401 memcpy(&(server
->srcadr
), ptr
->ai_addr
, ptr
->ai_addrlen
);
1402 server
->event_time
= ++sys_numservers
;
1403 if (sys_servers
== NULL
)
1404 sys_servers
= server
;
1408 for (sp
= sys_servers
; sp
->next_server
!= NULL
;
1409 sp
= sp
->next_server
) ;
1410 sp
->next_server
= server
;
1415 freeaddrinfo(addrResult
);
1420 * findserver - find a server in the list given its address
1421 * ***(For now it isn't totally AF-Independant, to check later..)
1423 static struct server
*
1425 struct sockaddr_storage
*addr
1428 struct server
*server
;
1429 struct server
*mc_server
;
1430 isc_sockaddr_t laddr
;
1431 isc_sockaddr_t saddr
;
1433 if(addr
->ss_family
== AF_INET
) {
1434 isc_sockaddr_fromin( &laddr
, &((struct sockaddr_in
*)addr
)->sin_addr
, 0);
1437 isc_sockaddr_fromin6(&laddr
, &((struct sockaddr_in6
*)addr
)->sin6_addr
, 0);
1442 if (htons(((struct sockaddr_in
*)addr
)->sin_port
) != NTP_PORT
)
1445 for (server
= sys_servers
; server
!= NULL
;
1446 server
= server
->next_server
) {
1448 if(server
->srcadr
.ss_family
== AF_INET
) {
1449 isc_sockaddr_fromin(&saddr
, &((struct sockaddr_in
*)&server
->srcadr
)->sin_addr
, 0);
1452 isc_sockaddr_fromin6(&saddr
, &((struct sockaddr_in6
*)&server
->srcadr
)->sin6_addr
, 0);
1454 if (isc_sockaddr_eqaddr(&laddr
, &saddr
) == ISC_TRUE
)
1457 if(addr
->ss_family
== server
->srcadr
.ss_family
) {
1458 if (isc_sockaddr_ismulticast(&saddr
) == ISC_TRUE
)
1463 if (mc_server
!= NULL
) {
1467 if (mc_server
->event_time
!= 0) {
1468 mc_server
->event_time
= 0;
1472 server
= (struct server
*)emalloc(sizeof(struct server
));
1473 memset((char *)server
, 0, sizeof(struct server
));
1475 memcpy(&server
->srcadr
, addr
, sizeof(struct sockaddr_storage
));
1477 server
->event_time
= ++sys_numservers
;
1479 for (sp
= sys_servers
; sp
->next_server
!= NULL
;
1480 sp
= sp
->next_server
) ;
1481 sp
->next_server
= server
;
1489 * timer - process a timer interrupt
1494 struct server
*server
;
1497 * Bump the current idea of the time
1502 * Search through the server list looking for guys
1503 * who's event timers have expired. Give these to
1504 * the transmit routine.
1506 for (server
= sys_servers
; server
!= NULL
;
1507 server
= server
->next_server
) {
1508 if (server
->event_time
!= 0
1509 && server
->event_time
<= current_time
)
1516 * The code duplication in the following subroutine sucks, but
1517 * we need to appease ansi2knr.
1522 * alarming - record the occurance of an alarm interrupt
1533 alarming(UINT uTimerID
, UINT uMsg
, DWORD dwUser
, DWORD dw1
, DWORD dw2
)
1537 #endif /* SYS_WINNT */
1542 callTimeEndPeriod(void)
1544 timeEndPeriod( wTimerRes
);
1547 #endif /* SYS_WINNT */
1551 * init_alarm - set up the timer interrupt
1557 # ifndef HAVE_TIMER_SETTIME
1558 struct itimerval itimer
;
1560 struct itimerspec ntpdate_itimer
;
1565 # endif /* SYS_WINNT */
1566 #if defined SYS_CYGWIN32 || defined SYS_WINNT
1568 TOKEN_PRIVILEGES tkp
;
1570 #endif /* SYS_WINNT */
1575 # if defined(HAVE_TIMER_CREATE) && defined(HAVE_TIMER_SETTIME)
1577 /* this code was put in as setitimer() is non existant this us the
1578 * POSIX "equivalents" setup - casey
1580 /* ntpdate_timerid is global - so we can kill timer later */
1581 if (timer_create (CLOCK_REALTIME
, NULL
, &ntpdate_timerid
) ==
1589 fprintf (stderr
, "init_alarm(): timer_create (...) FAILED\n");
1594 * Set up the alarm interrupt. The first comes 1/(2*TIMER_HZ)
1595 * seconds from now and they continue on every 1/TIMER_HZ seconds.
1597 (void) signal_no_reset(SIGALRM
, alarming
);
1598 ntpdate_itimer
.it_interval
.tv_sec
= ntpdate_itimer
.it_value
.tv_sec
= 0;
1599 ntpdate_itimer
.it_interval
.tv_nsec
= 1000000000/TIMER_HZ
;
1600 ntpdate_itimer
.it_value
.tv_nsec
= 1000000000/(TIMER_HZ
<<1);
1601 timer_settime(ntpdate_timerid
, 0 /* !TIMER_ABSTIME */, &ntpdate_itimer
, NULL
);
1604 * Set up the alarm interrupt. The first comes 1/(2*TIMER_HZ)
1605 * seconds from now and they continue on every 1/TIMER_HZ seconds.
1607 (void) signal_no_reset(SIGALRM
, alarming
);
1608 itimer
.it_interval
.tv_sec
= itimer
.it_value
.tv_sec
= 0;
1609 itimer
.it_interval
.tv_usec
= 1000000/TIMER_HZ
;
1610 itimer
.it_value
.tv_usec
= 1000000/(TIMER_HZ
<<1);
1612 setitimer(ITIMER_REAL
, &itimer
, (struct itimerval
*)0);
1614 #if defined SYS_CYGWIN32
1616 * Get privileges needed for fiddling with the clock
1619 /* get the current process token handle */
1620 if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES
| TOKEN_QUERY
, &hToken
)) {
1621 msyslog(LOG_ERR
, "OpenProcessToken failed: %m");
1624 /* get the LUID for system-time privilege. */
1625 LookupPrivilegeValue(NULL
, SE_SYSTEMTIME_NAME
, &tkp
.Privileges
[0].Luid
);
1626 tkp
.PrivilegeCount
= 1; /* one privilege to set */
1627 tkp
.Privileges
[0].Attributes
= SE_PRIVILEGE_ENABLED
;
1628 /* get set-time privilege for this process. */
1629 AdjustTokenPrivileges(hToken
, FALSE
, &tkp
, 0,(PTOKEN_PRIVILEGES
) NULL
, 0);
1630 /* cannot test return value of AdjustTokenPrivileges. */
1631 if (GetLastError() != ERROR_SUCCESS
)
1632 msyslog(LOG_ERR
, "AdjustTokenPrivileges failed: %m");
1634 #else /* SYS_WINNT */
1638 * Get privileges needed for fiddling with the clock
1641 /* get the current process token handle */
1642 if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES
| TOKEN_QUERY
, &hToken
)) {
1643 msyslog(LOG_ERR
, "OpenProcessToken failed: %m");
1646 /* get the LUID for system-time privilege. */
1647 LookupPrivilegeValue(NULL
, SE_SYSTEMTIME_NAME
, &tkp
.Privileges
[0].Luid
);
1648 tkp
.PrivilegeCount
= 1; /* one privilege to set */
1649 tkp
.Privileges
[0].Attributes
= SE_PRIVILEGE_ENABLED
;
1650 /* get set-time privilege for this process. */
1651 AdjustTokenPrivileges(hToken
, FALSE
, &tkp
, 0,(PTOKEN_PRIVILEGES
) NULL
, 0);
1652 /* cannot test return value of AdjustTokenPrivileges. */
1653 if (GetLastError() != ERROR_SUCCESS
)
1654 msyslog(LOG_ERR
, "AdjustTokenPrivileges failed: %m");
1657 * Set up timer interrupts for every 2**EVENT_TIMEOUT seconds
1658 * Under Win/NT, expiry of timer interval leads to invocation
1659 * of a callback function (on a different thread) rather than
1660 * generating an alarm signal
1663 /* determine max and min resolution supported */
1664 if(timeGetDevCaps(&tc
, sizeof(TIMECAPS
)) != TIMERR_NOERROR
) {
1665 msyslog(LOG_ERR
, "timeGetDevCaps failed: %m");
1668 wTimerRes
= min(max(tc
.wPeriodMin
, TARGET_RESOLUTION
), tc
.wPeriodMax
);
1669 /* establish the minimum timer resolution that we'll use */
1670 timeBeginPeriod(wTimerRes
);
1671 atexit(callTimeEndPeriod
);
1673 /* start the timer event */
1674 wTimerID
= timeSetEvent(
1675 (UINT
) (1000/TIMER_HZ
), /* Delay */
1676 wTimerRes
, /* Resolution */
1677 (LPTIMECALLBACK
) alarming
, /* Callback function */
1678 (DWORD
) dwUser
, /* User data */
1679 TIME_PERIODIC
); /* Event type (periodic) */
1680 if (wTimerID
== 0) {
1681 msyslog(LOG_ERR
, "timeSetEvent failed: %m");
1684 #endif /* SYS_WINNT */
1691 * We do asynchronous input using the SIGIO facility. A number of
1692 * recvbuf buffers are preallocated for input. In the signal
1693 * handler we poll to see if the socket is ready and read the
1694 * packets from it into the recvbuf's along with a time stamp and
1695 * an indication of the source host and the interface it was received
1696 * through. This allows us to get as accurate receive time stamps
1697 * as possible independent of other processing going on.
1699 * We allocate a number of recvbufs equal to the number of servers
1700 * plus 2. This should be plenty.
1705 * init_io - initialize I/O data and open socket
1710 struct addrinfo
*res
, *ressave
;
1711 struct addrinfo hints
;
1714 int check_ntp_port_in_use
= !debug
&& !simple_query
&& !unpriv_port
;
1717 * Init buffer free list and stat counters
1719 init_recvbuff(sys_numservers
+ 2);
1725 strcpy(service
, "ntp");
1728 * Init hints addrinfo structure
1730 memset(&hints
, 0, sizeof(hints
));
1731 hints
.ai_family
= ai_fam_templ
;
1732 hints
.ai_flags
= AI_PASSIVE
;
1733 hints
.ai_socktype
= SOCK_DGRAM
;
1735 if(getaddrinfo(NULL
, service
, &hints
, &res
) != 0) {
1736 msyslog(LOG_ERR
, "getaddrinfo() failed: %m");
1742 if (check_ntp_port_in_use
&& ntp_port_inuse(AF_INET
, NTP_PORT
)){
1743 netsyslog(LOG_ERR
, "the NTP socket is in use, exiting: %m");
1748 /* Remember the address of the addrinfo structure chain */
1752 * For each structure returned, open and bind socket
1754 for(nbsock
= 0; (nbsock
< MAX_AF
) && res
; res
= res
->ai_next
) {
1755 /* create a datagram (UDP) socket */
1756 fd
[nbsock
] = socket(res
->ai_family
, res
->ai_socktype
, res
->ai_protocol
);
1757 if (fd
[nbsock
] == SOCKET_ERROR
) {
1759 if (errno
== EPROTONOSUPPORT
|| errno
== EAFNOSUPPORT
||
1760 errno
== EPFNOSUPPORT
)
1762 int err
= WSAGetLastError();
1763 if (err
== WSAEPROTONOSUPPORT
|| err
== WSAEAFNOSUPPORT
||
1764 err
== WSAEPFNOSUPPORT
)
1767 netsyslog(LOG_ERR
, "socket() failed: %m");
1771 /* set socket to reuse address */
1772 if (setsockopt(fd
[nbsock
], SOL_SOCKET
, SO_REUSEADDR
, (void*) &optval
, sizeof(optval
)) < 0) {
1773 netsyslog(LOG_ERR
, "setsockopt() SO_REUSEADDR failed: %m");
1778 /* Restricts AF_INET6 socket to IPv6 communications (see RFC 2553bis-03) */
1779 if (res
->ai_family
== AF_INET6
)
1780 if (setsockopt(fd
[nbsock
], IPPROTO_IPV6
, IPV6_V6ONLY
, (void*) &optval
, sizeof(optval
)) < 0) {
1781 netsyslog(LOG_ERR
, "setsockopt() IPV6_V6ONLY failed: %m");
1787 /* Remember the socket family in fd_family structure */
1788 fd_family
[nbsock
] = res
->ai_family
;
1791 * bind the socket to the NTP port
1793 if (check_ntp_port_in_use
) {
1794 if (bind(fd
[nbsock
], res
->ai_addr
, SOCKLEN(res
->ai_addr
)) < 0) {
1796 if (errno
== EADDRINUSE
)
1798 if (WSAGetLastError() == WSAEADDRINUSE
)
1799 #endif /* SYS_WINNT */
1800 netsyslog(LOG_ERR
, "the NTP socket is in use, exiting");
1802 netsyslog(LOG_ERR
, "bind() fails: %m");
1808 fdmask
[nbsock
].fd
= fd
[nbsock
];
1809 fdmask
[nbsock
].events
= POLLIN
;
1811 FD_SET(fd
[nbsock
], &fdmask
);
1812 if (maxfd
< fd
[nbsock
]+1) {
1813 maxfd
= fd
[nbsock
]+1;
1825 if (ioctl(fd
[nbsock
],FIONBIO
, &on
) == ERROR
) {
1826 netsyslog(LOG_ERR
, "ioctl(FIONBIO) fails: %m");
1830 # else /* not SYS_VXWORKS */
1831 # if defined(O_NONBLOCK)
1832 if (fcntl(fd
[nbsock
], F_SETFL
, O_NONBLOCK
) < 0) {
1833 netsyslog(LOG_ERR
, "fcntl(FNDELAY|FASYNC) fails: %m");
1837 # else /* not O_NONBLOCK */
1838 # if defined(FNDELAY)
1839 if (fcntl(fd
[nbsock
], F_SETFL
, FNDELAY
) < 0) {
1840 netsyslog(LOG_ERR
, "fcntl(FNDELAY|FASYNC) fails: %m");
1844 # else /* FNDELAY */
1845 # include "Bletch: Need non blocking I/O"
1846 # endif /* FNDELAY */
1847 # endif /* not O_NONBLOCK */
1848 # endif /* SYS_VXWORKS */
1849 #else /* SYS_WINNT */
1850 if (ioctlsocket(fd
[nbsock
], FIONBIO
, (u_long
*) &on
) == SOCKET_ERROR
) {
1851 netsyslog(LOG_ERR
, "ioctlsocket(FIONBIO) fails: %m");
1854 #endif /* SYS_WINNT */
1857 freeaddrinfo(ressave
);
1861 * sendpkt - send a packet to the specified destination
1865 struct sockaddr_storage
*dest
,
1872 SOCKET sock
= INVALID_SOCKET
;
1876 #endif /* SYS_WINNT */
1878 /* Find a local family compatible socket to send ntp packet to ntp server */
1879 for(i
= 0; (i
< MAX_AF
); i
++) {
1880 if(dest
->ss_family
== fd_family
[i
]) {
1886 if ( sock
== INVALID_SOCKET
) {
1887 netsyslog(LOG_ERR
, "cannot find family compatible socket to send ntp packet");
1892 cc
= sendto(sock
, (char *)pkt
, len
, 0, (struct sockaddr
*)dest
,
1895 if (cc
== SOCKET_ERROR
) {
1897 if (errno
!= EWOULDBLOCK
&& errno
!= ENOBUFS
)
1899 err
= WSAGetLastError();
1900 if (err
!= WSAEWOULDBLOCK
&& err
!= WSAENOBUFS
)
1901 #endif /* SYS_WINNT */
1902 netsyslog(LOG_ERR
, "sendto(%s): %m", stohost(dest
));
1908 * input_handler - receive packets asynchronously
1914 register struct recvbuf
*rb
;
1915 struct timeval tvzero
;
1920 struct pollfd fds
[MAX_AF
];
1927 * Do a poll to see if we have data
1930 tvzero
.tv_sec
= tvzero
.tv_usec
= 0;
1932 memcpy(fds
, fdmask
, sizeof(fdmask
));
1933 n
= poll(fds
, (unsigned int)nbsock
, tvzero
.tv_sec
* 1000);
1936 * Determine which socket received data
1939 for(i
=0; i
< nbsock
; i
++) {
1940 if(fds
[i
].revents
& POLLIN
) {
1948 n
= select(maxfd
, &fds
, (fd_set
*)0, (fd_set
*)0, &tvzero
);
1951 * Determine which socket received data
1954 for(i
=0; i
< nbsock
; i
++) {
1955 if(FD_ISSET(fd
[i
], &fds
)) {
1964 * If nothing to do, just return. If an error occurred,
1965 * complain and return. If we've got some, freeze a
1976 "select() error: %m"
1984 * Get a buffer and read the frame. If we
1985 * haven't got a buffer, or this is received
1986 * on the wild card socket, just dump the packet.
1988 if (initializing
|| free_recvbuffs() == 0) {
1993 (void) read(fdc
, buf
, sizeof buf
);
1995 /* NT's _read does not operate on nonblocking sockets
1996 * either recvfrom or ReadFile() has to be used here.
1997 * ReadFile is used in [ntpd]ntp_intres() and ntpdc,
1998 * just to be different use recvfrom() here
2000 recvfrom(fdc
, buf
, sizeof(buf
), 0, (struct sockaddr
*)0, NULL
);
2001 #endif /* SYS_WINNT */
2005 rb
= get_free_recv_buffer();
2007 fromlen
= sizeof(struct sockaddr_storage
);
2008 rb
->recv_length
= recvfrom(fdc
, (char *)&rb
->recv_pkt
,
2009 sizeof(rb
->recv_pkt
), 0,
2010 (struct sockaddr
*)&rb
->recv_srcadr
, &fromlen
);
2011 if (rb
->recv_length
== -1) {
2017 * Got one. Mark how and when it got here,
2018 * put it on the full list.
2021 add_full_recv_buffer(rb
);
2026 #if !defined SYS_WINNT && !defined SYS_CYGWIN32
2028 * adj_systime - do a big long slew of the system time
2035 struct timeval adjtv
, oadjtv
;
2043 * Take the absolute value of the offset
2046 if (L_ISNEG(&offset
)) {
2053 * Calculate the overshoot. XXX N.B. This code *knows*
2054 * ADJ_OVERSHOOT is 1/2.
2057 L_RSHIFTU(&overshoot
);
2058 if (overshoot
.l_ui
!= 0 || (overshoot
.l_uf
> ADJ_MAXOVERSHOOT
)) {
2060 overshoot
.l_uf
= ADJ_MAXOVERSHOOT
;
2062 L_ADD(&offset
, &overshoot
);
2064 TSTOTV(&offset
, &adjtv
);
2067 adjtv
.tv_sec
= -adjtv
.tv_sec
;
2068 adjtv
.tv_usec
= -adjtv
.tv_usec
;
2071 if (adjtv
.tv_usec
!= 0 && !debug
) {
2072 if (adjtime(&adjtv
, &oadjtv
) < 0) {
2073 msyslog(LOG_ERR
, "Can't adjust the time of day: %m");
2079 #endif /* SYS_WINNT */
2083 * This fuction is not the same as lib/systime step_systime!!!
2098 if (debug
) return 1;
2100 * Take the absolute value of the offset
2103 if (L_ISNEG(&ftmp
)) {
2109 if (ftmp
.l_ui
>= 3) { /* Step it and slew - we might win */
2111 n
= step_systime(dtemp
);
2120 * Just add adjustment into the current offset. The update
2121 * routine will take care of bringing the system clock into
2127 #ifdef FORCE_NTPDATE_STEP
2129 return step_systime(dtemp
);
2134 #else /* SLEWALWAYS */
2138 return step_systime(dtemp
);
2139 #endif /* SLEWALWAYS */
2143 /* XXX ELIMINATE printserver similar in ntptrace.c, ntpdate.c */
2145 * printserver - print detail information for a server
2149 register struct server
*pp
,
2158 (void) fprintf(fp
, "server %s, stratum %d, offset %s, delay %s\n",
2159 stoa(&pp
->srcadr
), pp
->stratum
,
2160 lfptoa(&pp
->offset
, 6), fptoa((s_fp
)pp
->delay
, 5));
2164 (void) fprintf(fp
, "server %s, port %d\n",
2165 stoa(&pp
->srcadr
), ntohs(((struct sockaddr_in
*)&(pp
->srcadr
))->sin_port
));
2167 (void) fprintf(fp
, "stratum %d, precision %d, leap %c%c, trust %03o\n",
2168 pp
->stratum
, pp
->precision
,
2169 pp
->leap
& 0x2 ? '1' : '0',
2170 pp
->leap
& 0x1 ? '1' : '0',
2173 if (pp
->stratum
== 1) {
2175 memmove(junk
, (char *)&pp
->refid
, 4);
2178 str
= stoa(&pp
->srcadr
);
2181 "refid [%s], delay %s, dispersion %s\n",
2182 str
, fptoa((s_fp
)pp
->delay
, 5),
2183 ufptoa(pp
->dispersion
, 5));
2185 (void) fprintf(fp
, "transmitted %d, in filter %d\n",
2186 pp
->xmtcnt
, pp
->filter_nextpt
);
2188 (void) fprintf(fp
, "reference time: %s\n",
2189 prettydate(&pp
->reftime
));
2190 (void) fprintf(fp
, "originate timestamp: %s\n",
2191 prettydate(&pp
->org
));
2192 (void) fprintf(fp
, "transmit timestamp: %s\n",
2193 prettydate(&pp
->xmt
));
2195 (void) fprintf(fp
, "filter delay: ");
2196 for (i
= 0; i
< NTP_SHIFT
; i
++) {
2197 (void) fprintf(fp
, " %-8.8s", fptoa(pp
->filter_delay
[i
], 5));
2198 if (i
== (NTP_SHIFT
>>1)-1)
2199 (void) fprintf(fp
, "\n ");
2201 (void) fprintf(fp
, "\n");
2203 (void) fprintf(fp
, "filter offset:");
2204 for (i
= 0; i
< PEER_SHIFT
; i
++) {
2205 (void) fprintf(fp
, " %-8.8s", lfptoa(&pp
->filter_offset
[i
], 6));
2206 if (i
== (PEER_SHIFT
>>1)-1)
2207 (void) fprintf(fp
, "\n ");
2209 (void) fprintf(fp
, "\n");
2211 (void) fprintf(fp
, "delay %s, dispersion %s\n",
2212 fptoa((s_fp
)pp
->delay
, 5), ufptoa(pp
->dispersion
, 5));
2214 (void) fprintf(fp
, "offset %s\n\n",
2215 lfptoa(&pp
->offset
, 6));
2218 #if !defined(HAVE_VSPRINTF)
2229 f
._flag
= _IOWRT
+_IOSTRG
;
2232 len
= _doprnt(fmt
, ap
, &f
);
2239 /* override function in library since SA_RESTART makes ALL syscalls restart */
2248 struct sigaction vec
;
2250 vec
.sa_handler
= func
;
2251 sigemptyset(&vec
.sa_mask
);
2256 n
= sigaction(sig
, &vec
, NULL
);
2257 if (n
== -1 && errno
== EINTR
)
2263 perror("sigaction");
2271 static ni_namelist
*
2272 getnetinfoservers(void)
2277 ni_namelist
*namelist
= (ni_namelist
*)malloc(sizeof(ni_namelist
));
2279 /* Find a time server in NetInfo */
2280 if ((status
= ni_open(NULL
, ".", &domain
)) != NI_OK
) return NULL
;
2282 while (status
= ni_pathsearch(domain
, &confdir
, NETINFO_CONFIG_DIR
) == NI_NODIR
) {
2284 if (ni_open(domain
, "..", &next_domain
) != NI_OK
) break;
2286 domain
= next_domain
;
2288 if (status
!= NI_OK
) return NULL
;
2291 if (ni_lookupprop(domain
, &confdir
, "server", namelist
) != NI_OK
) {
2292 ni_namelist_free(namelist
);
2302 isc_boolean_t
ntp_port_inuse(int af
, u_short port
)
2305 * Check if NTP socket is already in use on this system
2306 * This is only for Windows Systems, as they tend not to fail on the real bind() below
2310 struct sockaddr_in checkservice
;
2311 checksocket
= socket(af
, SOCK_DGRAM
, 0);
2312 if (checksocket
== INVALID_SOCKET
) {
2316 checkservice
.sin_family
= (short) AF_INET
;
2317 checkservice
.sin_addr
.s_addr
= INADDR_LOOPBACK
;
2318 checkservice
.sin_port
= htons(port
);
2320 if (bind(checksocket
, (struct sockaddr
*)&checkservice
,
2321 sizeof(checkservice
)) == SOCKET_ERROR
) {
2322 if ( WSAGetLastError() == WSAEADDRINUSE
){
2323 closesocket(checksocket
);
2327 closesocket(checksocket
);