1 /*        $NetBSD: ntpdate.c,v 1.15 2022/10/09 21:41:04 christos Exp $          */
2 
3 /*
4  * ntpdate - set the time of day by polling one or more NTP servers
5  */
6 
7 #ifdef HAVE_CONFIG_H
8 # include <config.h>
9 #endif
10 
11 #ifdef HAVE_NETINFO
12 #include <netinfo/ni.h>
13 #endif
14 
15 #include "ntp_machine.h"
16 #include "ntp_fp.h"
17 #include "ntp.h"
18 #include "ntp_io.h"
19 #include "timevalops.h"
20 #include "ntpdate.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>
26 
27 #include "isc/net.h"
28 #include "isc/result.h"
29 #include "isc/sockaddr.h"
30 
31 #ifdef HAVE_UNISTD_H
32 # include <unistd.h>
33 #endif
34 
35 #include <stdio.h>
36 #include <signal.h>
37 #include <ctype.h>
38 #ifdef HAVE_POLL_H
39 # include <poll.h>
40 #endif
41 #ifdef HAVE_SYS_SIGNAL_H
42 # include <sys/signal.h>
43 #endif
44 #ifdef HAVE_SYS_IOCTL_H
45 # include <sys/ioctl.h>
46 #endif
47 #ifdef HAVE_SYS_RESOURCE_H
48 # include <sys/resource.h>
49 #endif
50 
51 #include <arpa/inet.h>
52 
53 #ifdef SYS_VXWORKS
54 # include "ioLib.h"
55 # include "sockLib.h"
56 # include "timers.h"
57 
58 /* select wants a zero structure ... */
59 struct timeval timeout = {0,0};
60 #elif defined(SYS_WINNT)
61 /*
62  * Windows does not abort a select select call if SIGALRM goes off
63  * so a 200 ms timeout is needed (TIMER_HZ is 5).
64  */
65 struct sock_timeval timeout = {0,1000000/TIMER_HZ};
66 #else
67 struct timeval timeout = {60,0};
68 #endif
69 
70 #ifdef HAVE_NETINFO
71 #include <netinfo/ni.h>
72 #endif
73 
74 #include "recvbuff.h"
75 
76 #ifdef SYS_WINNT
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);
81 UINT wTimerRes;
82 #endif /* SYS_WINNT */
83 
84 /*
85  * Scheduling priority we run at
86  */
87 #ifndef SYS_VXWORKS
88 # define  NTPDATE_PRIO        (-12)
89 #else
90 # define  NTPDATE_PRIO        (100)
91 #endif
92 
93 #ifdef HAVE_TIMER_CREATE
94 /* POSIX TIMERS - vxWorks doesn't have itimer - casey */
95 static timer_t ntpdate_timerid;
96 #endif
97 
98 /*
99  * Compatibility stuff for Version 2
100  */
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 */
108 
109 /*
110  * for get_systime()
111  */
112 s_char    sys_precision;                /* local clock precision (log2 s) */
113 
114 /*
115  * File descriptor masks etc. for call to select
116  */
117 
118 int ai_fam_templ;
119 int nbsock;                             /* the number of sockets used */
120 SOCKET fd[MAX_AF];
121 int fd_family[MAX_AF];                  /* to remember the socket family */
122 #ifdef HAVE_POLL_H
123 struct pollfd fdmask[MAX_AF];
124 #else
125 fd_set fdmask;
126 SOCKET maxfd;
127 #endif
128 int polltest = 0;
129 
130 /*
131  * Initializing flag.  All async routines watch this and only do their
132  * thing when it is clear.
133  */
134 int initializing = 1;
135 
136 /*
137  * Alarm flag.      Set when an alarm occurs
138  */
139 volatile int alarm_flag = 0;
140 
141 /*
142  * Simple query flag.
143  */
144 int simple_query = 0;
145 
146 /*
147  * Unprivileged port flag.
148  */
149 int unpriv_port = 0;
150 
151 /*
152  * Program name.
153  */
154 char const *progname;
155 
156 /*
157  * Systemwide parameters and flags
158  */
159 int sys_samples = 0;                    /* number of samples/server, will be modified later */
160 u_long sys_timeout = DEFTIMEOUT; /* timeout time, in TIMER_HZ units */
161 struct server *sys_servers;   /* the server list */
162 int sys_numservers = 0;       /* number of servers to poll */
163 int sys_authenticate = 0;     /* true when authenticating */
164 u_int32 sys_authkey = 0;      /* set to authentication key in use */
165 u_long sys_authdelay = 0;     /* authentication delay */
166 int sys_version = NTP_VERSION;          /* version to poll with */
167 
168 /*
169  * The current internal time
170  */
171 u_long current_time = 0;
172 
173 /*
174  * Counter for keeping track of completed servers
175  */
176 int complete_servers = 0;
177 
178 /*
179  * File of encryption keys
180  */
181 
182 #ifndef KEYFILE
183 # ifndef SYS_WINNT
184 #define KEYFILE     "/etc/ntp.keys"
185 # else
186 #define KEYFILE     "%windir%\\ntp.keys"
187 # endif /* SYS_WINNT */
188 #endif /* KEYFILE */
189 
190 #ifndef SYS_WINNT
191 const char *key_file = KEYFILE;
192 #else
193 char key_file_storage[MAX_PATH+1], *key_file ;
194 #endif     /* SYS_WINNT */
195 
196 /*
197  * Miscellaneous flags
198  */
199 int verbose = 0;
200 int always_step = 0;
201 int never_step = 0;
202 
203 int       ntpdatemain (int, char **);
204 
205 static    void      transmit  (struct server *);
206 static    void      receive   (struct recvbuf *);
207 static    void      server_data (struct server *, s_fp, l_fp *, u_fp);
208 static    void      clock_filter        (struct server *);
209 static    struct server *clock_select (void);
210 static    int clock_adjust    (void);
211 static    void      addserver (char *);
212 static    struct server *findserver (sockaddr_u *);
213                     void      timer               (void);
214 static    void      init_alarm          (void);
215 #ifndef SYS_WINNT
216 static    RETSIGTYPE alarming (int);
217 #endif /* SYS_WINNT */
218 static    void      init_io   (void);
219 static    void      sendpkt   (sockaddr_u *, struct pkt *, int);
220 void      input_handler       (void);
221 
222 static    int l_adj_systime   (l_fp *);
223 static    int l_step_systime  (l_fp *);
224 
225 static    void      print_server (struct server *, FILE *);
226 
227 #ifdef SYS_WINNT
228 int       on = 1;
229 WORD      wVersionRequested;
230 WSADATA   wsaData;
231 #endif /* SYS_WINNT */
232 
233 #ifdef NO_MAIN_ALLOWED
234 CALL(ntpdate,"ntpdate",ntpdatemain);
235 
clear_globals()236 void clear_globals()
237 {
238   /*
239    * Debugging flag
240    */
241   debug = 0;
242 
243   ntp_optind = 0;
244   /*
245    * Initializing flag.  All async routines watch this and only do their
246    * thing when it is clear.
247    */
248   initializing = 1;
249 
250   /*
251    * Alarm flag.  Set when an alarm occurs
252    */
253   alarm_flag = 0;
254 
255   /*
256    * Simple query flag.
257    */
258   simple_query = 0;
259 
260   /*
261    * Unprivileged port flag.
262    */
263   unpriv_port = 0;
264 
265   /*
266    * Systemwide parameters and flags
267    */
268   sys_numservers = 0;           /* number of servers to poll */
269   sys_authenticate = 0;   /* true when authenticating */
270   sys_authkey = 0;     /* set to authentication key in use */
271   sys_authdelay = 0;   /* authentication delay */
272   sys_version = NTP_VERSION;  /* version to poll with */
273 
274   /*
275    * The current internal time
276    */
277   current_time = 0;
278 
279   /*
280    * Counter for keeping track of completed servers
281    */
282   complete_servers = 0;
283   verbose = 0;
284   always_step = 0;
285   never_step = 0;
286 }
287 #endif
288 
289 #ifdef HAVE_NETINFO
290 static ni_namelist *getnetinfoservers (void);
291 #endif
292 
293 /*
294  * Main program.  Initialize us and loop waiting for I/O and/or
295  * timer expiries.
296  */
297 #ifndef NO_MAIN_ALLOWED
298 int
main(int argc,char * argv[])299 main(
300           int argc,
301           char *argv[]
302           )
303 {
304           return ntpdatemain (argc, argv);
305 }
306 #endif /* NO_MAIN_ALLOWED */
307 
308 int
ntpdatemain(int argc,char * argv[])309 ntpdatemain (
310           int argc,
311           char *argv[]
312           )
313 {
314           int was_alarmed;
315           int tot_recvbufs;
316           struct recvbuf *rbuf;
317           l_fp tmp;
318           int errflg;
319           int c;
320           int nfound;
321 
322 #ifdef HAVE_NETINFO
323           ni_namelist *netinfoservers;
324 #endif
325 #ifdef SYS_WINNT
326           key_file = key_file_storage;
327 
328           if (!ExpandEnvironmentStrings(KEYFILE, key_file, MAX_PATH))
329                     msyslog(LOG_ERR, "ExpandEnvironmentStrings(KEYFILE) failed: %m");
330 
331           ssl_applink();
332 #endif /* SYS_WINNT */
333 
334 #ifdef NO_MAIN_ALLOWED
335           clear_globals();
336 #endif
337 
338           init_lib();         /* sets up ipv4_works, ipv6_works */
339 
340           /* Check to see if we have IPv6. Otherwise default to IPv4 */
341           if (!ipv6_works)
342                     ai_fam_templ = AF_INET;
343 
344 #ifdef HAVE_NETINFO
345           errflg = 0;                   /* servers can come from netinfo */
346 #else
347           errflg = (argc < 2);          /* need at least server on cmdline */
348 #endif
349           progname = argv[0];
350           syslogit = 0;
351 
352           /*
353            * Decode argument list
354            */
355           while ((c = ntp_getopt(argc, argv, "46a:bBde:k:o:p:qst:uv")) != EOF)
356                     switch (c)
357                     {
358                     case '4':
359                               ai_fam_templ = AF_INET;
360                               break;
361                     case '6':
362                               ai_fam_templ = AF_INET6;
363                               break;
364                     case 'a':
365                               c = atoi(ntp_optarg);
366                               sys_authenticate = 1;
367                               sys_authkey = c;
368                               break;
369                     case 'b':
370                               always_step++;
371                               never_step = 0;
372                               break;
373                     case 'B':
374                               never_step++;
375                               always_step = 0;
376                               break;
377                     case 'd':
378                               ++debug;
379                               break;
380                     case 'e':
381                               if (!atolfp(ntp_optarg, &tmp)
382                               || tmp.l_ui != 0) {
383                                         (void) fprintf(stderr,
384                                                      "%s: encryption delay %s is unlikely\n",
385                                                      progname, ntp_optarg);
386                                         errflg++;
387                               } else {
388                                         sys_authdelay = tmp.l_uf;
389                               }
390                               break;
391                     case 'k':
392                               key_file = ntp_optarg;
393                               break;
394                     case 'o':
395                               sys_version = atoi(ntp_optarg);
396                               break;
397                     case 'p':
398                               c = atoi(ntp_optarg);
399                               if (c <= 0 || c > NTP_SHIFT) {
400                                         (void) fprintf(stderr,
401                                                      "%s: number of samples (%d) is invalid\n",
402                                                      progname, c);
403                                         errflg++;
404                               } else {
405                                         sys_samples = c;
406                               }
407                               break;
408                     case 'q':
409                               simple_query = 1;
410                               break;
411                     case 's':
412                               syslogit = 1;
413                               break;
414                     case 't':
415                               if (!atolfp(ntp_optarg, &tmp)) {
416                                         (void) fprintf(stderr,
417                                                      "%s: timeout %s is undecodeable\n",
418                                                      progname, ntp_optarg);
419                                         errflg++;
420                               } else {
421                                         sys_timeout = ((LFPTOFP(&tmp) * TIMER_HZ)
422                                                      + 0x8000) >> 16;
423                                         sys_timeout = max(sys_timeout, MINTIMEOUT);
424                               }
425                               break;
426                     case 'v':
427                               verbose = 1;
428                               break;
429                     case 'u':
430                               unpriv_port = 1;
431                               break;
432                     case '?':
433                               ++errflg;
434                               break;
435                     default:
436                               break;
437               }
438 
439           if (errflg) {
440 usage:
441                     (void) fprintf(stderr,
442                         "usage: %s [-46bBdqsuv] [-a key#] [-e delay] [-k file] [-p samples] [-o version#] [-t timeo] server ...\n",
443                         progname);
444                     exit(2);
445           }
446 
447           /*
448            * If number of Samples (-p) not specified by user:
449            * - if a simple_query (-q) just ONE will do
450            * - otherwise the normal is DEFSAMPLES
451            */
452           if (sys_samples == 0)
453                      sys_samples = (simple_query ? 1 : DEFSAMPLES);
454 
455           if (debug || simple_query) {
456 #ifdef HAVE_SETVBUF
457                     static char buf[BUFSIZ];
458                     setvbuf(stdout, buf, _IOLBF, BUFSIZ);
459 #else
460                     setlinebuf(stdout);
461 #endif
462           }
463 
464           /*
465            * Logging.  Open the syslog if we have to
466            */
467           if (syslogit) {
468 #if !defined (SYS_WINNT) && !defined (SYS_VXWORKS) && !defined SYS_CYGWIN32
469 # ifndef  LOG_DAEMON
470                     openlog("ntpdate", LOG_PID);
471 # else
472 
473 #  ifndef LOG_NTP
474 #         define    LOG_NTP LOG_DAEMON
475 #  endif
476                     openlog("ntpdate", LOG_PID | LOG_NDELAY, LOG_NTP);
477                     if (debug)
478                               setlogmask(LOG_UPTO(LOG_DEBUG));
479                     else
480                               setlogmask(LOG_UPTO(LOG_INFO));
481 # endif /* LOG_DAEMON */
482 #endif    /* SYS_WINNT */
483           }
484 
485           if (debug || verbose)
486                     msyslog(LOG_NOTICE, "%s", Version);
487 
488           /*
489            * Add servers we are going to be polling
490            */
491 #ifdef HAVE_NETINFO
492           netinfoservers = getnetinfoservers();
493 #endif
494 
495           for ( ; ntp_optind < argc; ntp_optind++)
496                     addserver(argv[ntp_optind]);
497 
498 #ifdef HAVE_NETINFO
499           if (netinfoservers) {
500                     if ( netinfoservers->ni_namelist_len &&
501                         *netinfoservers->ni_namelist_val ) {
502                               u_int servercount = 0;
503                               while (servercount < netinfoservers->ni_namelist_len) {
504                                         if (debug) msyslog(LOG_DEBUG,
505                                                                "Adding time server %s from NetInfo configuration.",
506                                                                netinfoservers->ni_namelist_val[servercount]);
507                                         addserver(netinfoservers->ni_namelist_val[servercount++]);
508                               }
509                     }
510                     ni_namelist_free(netinfoservers);
511                     free(netinfoservers);
512           }
513 #endif
514 
515           if (sys_numservers == 0) {
516                     msyslog(LOG_ERR, "no servers can be used, exiting");
517                     goto usage;
518           }
519 
520           /*
521            * Initialize the time of day routines and the I/O subsystem
522            */
523           if (sys_authenticate) {
524                     init_auth();
525                     if (!authreadkeys(key_file)) {
526                               msyslog(LOG_ERR, "no key file <%s>, exiting", key_file);
527                               exit(1);
528                     }
529                     authtrust(sys_authkey, 1);
530                     if (!authistrusted(sys_authkey)) {
531                               msyslog(LOG_ERR, "authentication key %lu unknown",
532                                         (unsigned long) sys_authkey);
533                               exit(1);
534                     }
535           }
536           init_io();
537           init_alarm();
538 
539           /*
540            * Set the priority.
541            */
542 #ifdef SYS_VXWORKS
543           taskPrioritySet( taskIdSelf(), NTPDATE_PRIO);
544 #endif
545 #if defined(HAVE_ATT_NICE)
546           nice (NTPDATE_PRIO);
547 #endif
548 #if defined(HAVE_BSD_NICE)
549           (void) setpriority(PRIO_PROCESS, 0, NTPDATE_PRIO);
550 #endif
551 
552 
553           initializing = 0;
554           was_alarmed = 0;
555 
556           while (complete_servers < sys_numservers) {
557 #ifdef HAVE_POLL_H
558                     struct pollfd* rdfdes;
559                     rdfdes = fdmask;
560 #else
561                     fd_set rdfdes;
562                     rdfdes = fdmask;
563 #endif
564 
565                     if (alarm_flag) {             /* alarmed? */
566                               was_alarmed = 1;
567                               alarm_flag = 0;
568                     }
569                     tot_recvbufs = full_recvbuffs();        /* get received buffers */
570 
571                     if (!was_alarmed && tot_recvbufs == 0) {
572                               /*
573                                * Nothing to do.    Wait for something.
574                                */
575 #ifdef HAVE_POLL_H
576                               nfound = poll(rdfdes, (unsigned int)nbsock, timeout.tv_sec * 1000);
577 
578 #else
579                               nfound = select(maxfd, &rdfdes, NULL, NULL,
580                                                   &timeout);
581 #endif
582                               if (nfound > 0)
583                                         input_handler();
584                               else if (nfound == SOCKET_ERROR)
585                               {
586 #ifndef SYS_WINNT
587                                         if (errno != EINTR)
588 #else
589                                         if (WSAGetLastError() != WSAEINTR)
590 #endif
591                                                   msyslog(LOG_ERR,
592 #ifdef HAVE_POLL_H
593                                                             "poll() error: %m"
594 #else
595                                                             "select() error: %m"
596 #endif
597                                                             );
598                               } else if (errno != 0) {
599 #ifndef SYS_VXWORKS
600                                         msyslog(LOG_DEBUG,
601 #ifdef HAVE_POLL_H
602                                                   "poll(): nfound = %d, error: %m",
603 #else
604                                                   "select(): nfound = %d, error: %m",
605 #endif
606                                                   nfound);
607 #endif
608                               }
609                               if (alarm_flag) {             /* alarmed? */
610                                         was_alarmed = 1;
611                                         alarm_flag = 0;
612                               }
613                               tot_recvbufs = full_recvbuffs();        /* get received buffers */
614                     }
615 
616                     /*
617                      * Out here, signals are unblocked.  Call receive
618                      * procedure for each incoming packet.
619                      */
620                     rbuf = get_full_recv_buffer();
621                     while (rbuf != NULL)
622                     {
623                               receive(rbuf);
624                               freerecvbuf(rbuf);
625                               rbuf = get_full_recv_buffer();
626                     }
627 
628                     /*
629                      * Call timer to process any timeouts
630                      */
631                     if (was_alarmed) {
632                               timer();
633                               was_alarmed = 0;
634                     }
635 
636                     /*
637                      * Go around again
638                      */
639           }
640 
641           /*
642            * When we get here we've completed the polling of all servers.
643            * Adjust the clock, then exit.
644            */
645 #ifdef SYS_WINNT
646           WSACleanup();
647 #endif
648 #ifdef SYS_VXWORKS
649           close (fd);
650           timer_delete(ntpdate_timerid);
651 #endif
652 
653           return clock_adjust();
654 }
655 
656 
657 /*
658  * transmit - transmit a packet to the given server, or mark it completed.
659  *                  This is called by the timeout routine and by the receive
660  *                  procedure.
661  */
662 static void
transmit(register struct server * server)663 transmit(
664           register struct server *server
665           )
666 {
667           struct pkt xpkt;
668 
669           if (server->filter_nextpt < server->xmtcnt) {
670                     l_fp ts;
671                     /*
672                      * Last message to this server timed out.  Shift
673                      * zeros into the filter.
674                      */
675                     L_CLR(&ts);
676                     server_data(server, 0, &ts, 0);
677           }
678 
679           if ((int)server->filter_nextpt >= sys_samples) {
680                     /*
681                      * Got all the data we need.  Mark this guy
682                      * completed and return.
683                      */
684                     server->event_time = 0;
685                     complete_servers++;
686                     return;
687           }
688 
689           if (debug)
690                     printf("transmit(%s)\n", stoa(&server->srcadr));
691 
692           /*
693            * If we're here, send another message to the server.  Fill in
694            * the packet and let 'er rip.
695            */
696           xpkt.li_vn_mode = PKT_LI_VN_MODE(LEAP_NOTINSYNC,
697                                                    sys_version, MODE_CLIENT);
698           xpkt.stratum = STRATUM_TO_PKT(STRATUM_UNSPEC);
699           xpkt.ppoll = NTP_MINPOLL;
700           xpkt.precision = NTPDATE_PRECISION;
701           xpkt.rootdelay = htonl(NTPDATE_DISTANCE);
702           xpkt.rootdisp = htonl(NTPDATE_DISP);
703           xpkt.refid = htonl(NTPDATE_REFID);
704           L_CLR(&xpkt.reftime);
705           L_CLR(&xpkt.org);
706           L_CLR(&xpkt.rec);
707 
708           /*
709            * Determine whether to authenticate or not.      If so,
710            * fill in the extended part of the packet and do it.
711            * If not, just timestamp it and send it away.
712            */
713           if (sys_authenticate) {
714                     size_t len;
715 
716                     xpkt.exten[0] = htonl(sys_authkey);
717                     get_systime(&server->xmt);
718                     L_ADDUF(&server->xmt, sys_authdelay);
719                     HTONL_FP(&server->xmt, &xpkt.xmt);
720                     len = authencrypt(sys_authkey, (u_int32 *)&xpkt, LEN_PKT_NOMAC);
721                     sendpkt(&server->srcadr, &xpkt, (int)(LEN_PKT_NOMAC + len));
722 
723                     if (debug > 1)
724                               printf("transmit auth to %s\n",
725                                  stoa(&server->srcadr));
726           } else {
727                     get_systime(&(server->xmt));
728                     HTONL_FP(&server->xmt, &xpkt.xmt);
729                     sendpkt(&server->srcadr, &xpkt, LEN_PKT_NOMAC);
730 
731                     if (debug > 1)
732                               printf("transmit to %s\n", stoa(&server->srcadr));
733           }
734 
735           /*
736            * Update the server timeout and transmit count
737            */
738           server->event_time = current_time + sys_timeout;
739           server->xmtcnt++;
740 }
741 
742 
743 /*
744  * receive - receive and process an incoming frame
745  */
746 static void
receive(struct recvbuf * rbufp)747 receive(
748           struct recvbuf *rbufp
749           )
750 {
751           register struct pkt *rpkt;
752           register struct server *server;
753           register s_fp di;
754           l_fp t10, t23, tmp;
755           l_fp org;
756           l_fp rec;
757           l_fp ci;
758           int has_mac;
759           int is_authentic;
760 
761           if (debug)
762                     printf("receive(%s)\n", stoa(&rbufp->recv_srcadr));
763           /*
764            * Check to see if the packet basically looks like something
765            * intended for us.
766            */
767           if (rbufp->recv_length == LEN_PKT_NOMAC)
768                     has_mac = 0;
769           else if (rbufp->recv_length >= (int)LEN_PKT_NOMAC)
770                     has_mac = 1;
771           else {
772                     if (debug)
773                               printf("receive: packet length %d\n",
774                                  rbufp->recv_length);
775                     return;             /* funny length packet */
776           }
777 
778           rpkt = &(rbufp->recv_pkt);
779           if (PKT_VERSION(rpkt->li_vn_mode) < NTP_OLDVERSION ||
780                     PKT_VERSION(rpkt->li_vn_mode) > NTP_VERSION) {
781                     return;
782           }
783 
784           if ((PKT_MODE(rpkt->li_vn_mode) != MODE_SERVER
785                      && PKT_MODE(rpkt->li_vn_mode) != MODE_PASSIVE)
786                     || rpkt->stratum >= STRATUM_UNSPEC) {
787                     if (debug)
788                               printf("receive: mode %d stratum %d\n",
789                                  PKT_MODE(rpkt->li_vn_mode), rpkt->stratum);
790                     return;
791           }
792 
793           /*
794            * So far, so good.  See if this is from a server we know.
795            */
796           server = findserver(&(rbufp->recv_srcadr));
797           if (server == NULL) {
798                     if (debug)
799                               printf("receive: server not found\n");
800                     return;
801           }
802 
803           /*
804            * Decode the org timestamp and make sure we're getting a response
805            * to our last request.
806            */
807           NTOHL_FP(&rpkt->org, &org);
808           if (!L_ISEQU(&org, &server->xmt)) {
809                     if (debug)
810                               printf("receive: pkt.org and peer.xmt differ\n");
811                     return;
812           }
813 
814           /*
815            * Check out the authenticity if we're doing that.
816            */
817           if (!sys_authenticate)
818                     is_authentic = 1;
819           else {
820                     is_authentic = 0;
821 
822                     if (debug > 3)
823                               printf("receive: rpkt keyid=%ld sys_authkey=%ld decrypt=%ld\n",
824                                  (long int)ntohl(rpkt->exten[0]), (long int)sys_authkey,
825                                  (long int)authdecrypt(sys_authkey, (u_int32 *)rpkt,
826                                         LEN_PKT_NOMAC, (size_t)(rbufp->recv_length - LEN_PKT_NOMAC)));
827 
828                     if (has_mac && ntohl(rpkt->exten[0]) == sys_authkey &&
829                               authdecrypt(sys_authkey, (u_int32 *)rpkt, LEN_PKT_NOMAC,
830                               (size_t)(rbufp->recv_length - LEN_PKT_NOMAC)))
831                               is_authentic = 1;
832                     if (debug)
833                               printf("receive: authentication %s\n",
834                                  is_authentic ? "passed" : "failed");
835           }
836           server->trust <<= 1;
837           if (!is_authentic)
838                     server->trust |= 1;
839 
840           /*
841            * Check for a KoD (rate limiting) response, cease and decist.
842            */
843           if (LEAP_NOTINSYNC == PKT_LEAP(rpkt->li_vn_mode) &&
844               STRATUM_PKT_UNSPEC == rpkt->stratum &&
845               !memcmp("RATE", &rpkt->refid, 4)) {
846                     msyslog(LOG_ERR, "%s rate limit response from server.",
847                               stoa(&rbufp->recv_srcadr));
848                     server->event_time = 0;
849                     complete_servers++;
850                     return;
851           }
852 
853           /*
854            * Looks good.      Record info from the packet.
855            */
856           server->leap = PKT_LEAP(rpkt->li_vn_mode);
857           server->stratum = PKT_TO_STRATUM(rpkt->stratum);
858           server->precision = rpkt->precision;
859           server->rootdelay = ntohl(rpkt->rootdelay);
860           server->rootdisp = ntohl(rpkt->rootdisp);
861           server->refid = rpkt->refid;
862           NTOHL_FP(&rpkt->reftime, &server->reftime);
863           NTOHL_FP(&rpkt->rec, &rec);
864           NTOHL_FP(&rpkt->xmt, &server->org);
865 
866           /*
867            * Make sure the server is at least somewhat sane. If not, try
868            * again.
869            */
870           if (L_ISZERO(&rec) || !L_ISHIS(&server->org, &rec)) {
871                     server->event_time = current_time + sys_timeout;
872                     return;
873           }
874 
875           /*
876            * Calculate the round trip delay (di) and the clock offset (ci).
877            * We use the equations (reordered from those in the spec):
878            *
879            * d = (t2 - t3) - (t1 - t0)
880            * c = ((t2 - t3) + (t1 - t0)) / 2
881            */
882           t10 = server->org;            /* pkt.xmt == t1 */
883           L_SUB(&t10, &rbufp->recv_time); /* recv_time == t0*/
884 
885           t23 = rec;                              /* pkt.rec == t2 */
886           L_SUB(&t23, &org);            /* pkt->org == t3 */
887 
888           /* now have (t2 - t3) and (t0 - t1).    Calculate (ci) and (di) */
889           /*
890            * Calculate (ci) = ((t1 - t0) / 2) + ((t2 - t3) / 2)
891            * For large offsets this may prevent an overflow on '+'
892            */
893           ci = t10;
894           L_RSHIFT(&ci);
895           tmp = t23;
896           L_RSHIFT(&tmp);
897           L_ADD(&ci, &tmp);
898 
899           /*
900            * Calculate di in t23 in full precision, then truncate
901            * to an s_fp.
902            */
903           L_SUB(&t23, &t10);
904           di = LFPTOFP(&t23);
905 
906           if (debug > 3)
907                     printf("offset: %s, delay %s\n", lfptoa(&ci, 6), fptoa(di, 5));
908 
909           di += (FP_SECOND >> (-(int)NTPDATE_PRECISION))
910                     + (FP_SECOND >> (-(int)server->precision)) + NTP_MAXSKW;
911 
912           if (di <= 0) {                /* value still too raunchy to use? */
913                     L_CLR(&ci);
914                     di = 0;
915           } else {
916                     di = max(di, NTP_MINDIST);
917           }
918 
919           /*
920            * Shift this data in, then schedule another transmit.
921            */
922           server_data(server, (s_fp) di, &ci, 0);
923 
924           if ((int)server->filter_nextpt >= sys_samples) {
925                     /*
926                      * Got all the data we need.  Mark this guy
927                      * completed and return.
928                      */
929                     server->event_time = 0;
930                     complete_servers++;
931                     return;
932           }
933 
934           server->event_time = current_time + sys_timeout;
935 }
936 
937 
938 /*
939  * server_data - add a sample to the server's filter registers
940  */
941 static void
server_data(register struct server * server,s_fp d,l_fp * c,u_fp e)942 server_data(
943           register struct server *server,
944           s_fp d,
945           l_fp *c,
946           u_fp e
947           )
948 {
949           u_short i;
950 
951           i = server->filter_nextpt;
952           if (i < NTP_SHIFT) {
953                     server->filter_delay[i] = d;
954                     server->filter_offset[i] = *c;
955                     server->filter_soffset[i] = LFPTOFP(c);
956                     server->filter_error[i] = e;
957                     server->filter_nextpt = (u_short)(i + 1);
958           }
959 }
960 
961 
962 /*
963  * clock_filter - determine a server's delay, dispersion and offset
964  */
965 static void
clock_filter(register struct server * server)966 clock_filter(
967           register struct server *server
968           )
969 {
970           register int i, j;
971           int ord[NTP_SHIFT];
972 
973           INSIST((0 < sys_samples) && (sys_samples <= NTP_SHIFT));
974 
975           /*
976            * Sort indices into increasing delay order
977            */
978           for (i = 0; i < sys_samples; i++)
979                     ord[i] = i;
980 
981           for (i = 0; i < (sys_samples-1); i++) {
982                     for (j = i+1; j < sys_samples; j++) {
983                               if (server->filter_delay[ord[j]] == 0)
984                                         continue;
985                               if (server->filter_delay[ord[i]] == 0
986                                         || (server->filter_delay[ord[i]]
987                                         > server->filter_delay[ord[j]])) {
988                                         register int tmp;
989 
990                                         tmp = ord[i];
991                                         ord[i] = ord[j];
992                                         ord[j] = tmp;
993                               }
994                     }
995           }
996 
997           /*
998            * Now compute the dispersion, and assign values to delay and
999            * offset.          If there are no samples in the register, delay and
1000            * offset go to zero and dispersion is set to the maximum.
1001            */
1002           if (server->filter_delay[ord[0]] == 0) {
1003                     server->delay = 0;
1004                     L_CLR(&server->offset);
1005                     server->soffset = 0;
1006                     server->dispersion = PEER_MAXDISP;
1007           } else {
1008                     register s_fp d;
1009 
1010                     server->delay = server->filter_delay[ord[0]];
1011                     server->offset = server->filter_offset[ord[0]];
1012                     server->soffset = LFPTOFP(&server->offset);
1013                     server->dispersion = 0;
1014                     for (i = 1; i < sys_samples; i++) {
1015                               if (server->filter_delay[ord[i]] == 0)
1016                                         d = PEER_MAXDISP;
1017                               else {
1018                                         d = server->filter_soffset[ord[i]]
1019                                                   - server->filter_soffset[ord[0]];
1020                                         if (d < 0)
1021                                                   d = -d;
1022                                         if (d > PEER_MAXDISP)
1023                                                   d = PEER_MAXDISP;
1024                               }
1025                               /*
1026                                * XXX This *knows* PEER_FILTER is 1/2
1027                                */
1028                               server->dispersion += (u_fp)(d) >> i;
1029                     }
1030           }
1031           /*
1032            * We're done
1033            */
1034 }
1035 
1036 
1037 /*
1038  * clock_select - select the pick-of-the-litter clock from the samples
1039  *                    we've got.
1040  */
1041 static struct server *
clock_select(void)1042 clock_select(void)
1043 {
1044           struct server *server;
1045           u_int nlist;
1046           s_fp d;
1047           u_int count;
1048           u_int i;
1049           u_int j;
1050           u_int k;
1051           int n;
1052           s_fp local_threshold;
1053           struct server *server_list[NTP_MAXCLOCK];
1054           u_fp server_badness[NTP_MAXCLOCK];
1055           struct server *sys_server;
1056 
1057           /*
1058            * This first chunk of code is supposed to go through all
1059            * servers we know about to find the NTP_MAXLIST servers which
1060            * are most likely to succeed. We run through the list
1061            * doing the sanity checks and trying to insert anyone who
1062            * looks okay. We are at all times aware that we should
1063            * only keep samples from the top two strata and we only need
1064            * NTP_MAXLIST of them.
1065            */
1066           nlist = 0;          /* none yet */
1067           for (server = sys_servers; server != NULL; server = server->next_server) {
1068                     if (server->stratum == 0) {
1069                               if (debug)
1070                                         printf("%s: Server dropped: no data\n", ntoa(&server->srcadr));
1071                               continue; /* no data */
1072                     }
1073                     if (server->stratum > NTP_INFIN) {
1074                               if (debug)
1075                                         printf("%s: Server dropped: strata too high\n", ntoa(&server->srcadr));
1076                               continue; /* stratum no good */
1077                     }
1078                     if (server->delay > NTP_MAXWGT) {
1079                               if (debug)
1080                                         printf("%s: Server dropped: server too far away\n",
1081                                                   ntoa(&server->srcadr));
1082                               continue; /* too far away */
1083                     }
1084                     if (server->leap == LEAP_NOTINSYNC) {
1085                               if (debug)
1086                                         printf("%s: Server dropped: leap not in sync\n", ntoa(&server->srcadr));
1087                               continue; /* he's in trouble */
1088                     }
1089                     if (!L_ISHIS(&server->org, &server->reftime)) {
1090                               if (debug)
1091                                         printf("%s: Server dropped: server is very broken\n",
1092                                                ntoa(&server->srcadr));
1093                               continue; /* very broken host */
1094                     }
1095                     if ((server->org.l_ui - server->reftime.l_ui)
1096                         >= NTP_MAXAGE) {
1097                               if (debug)
1098                                         printf("%s: Server dropped: server has gone too long without sync\n",
1099                                                ntoa(&server->srcadr));
1100                               continue; /* too long without sync */
1101                     }
1102                     if (server->trust != 0) {
1103                               if (debug)
1104                                         printf("%s: Server dropped: Server is untrusted\n",
1105                                                ntoa(&server->srcadr));
1106                               continue;
1107                     }
1108 
1109                     /*
1110                      * This one seems sane.  Find where he belongs
1111                      * on the list.
1112                      */
1113                     d = server->dispersion + server->dispersion;
1114                     for (i = 0; i < nlist; i++)
1115                               if (server->stratum <= server_list[i]->stratum)
1116                               break;
1117                     for ( ; i < nlist; i++) {
1118                               if (server->stratum < server_list[i]->stratum)
1119                                         break;
1120                               if (d < (s_fp) server_badness[i])
1121                                         break;
1122                     }
1123 
1124                     /*
1125                      * If i points past the end of the list, this
1126                      * guy is a loser, else stick him in.
1127                      */
1128                     if (i >= NTP_MAXLIST)
1129                               continue;
1130                     for (j = nlist; j > i; j--)
1131                               if (j < NTP_MAXLIST) {
1132                                         server_list[j] = server_list[j-1];
1133                                         server_badness[j]
1134                                                   = server_badness[j-1];
1135                               }
1136 
1137                     server_list[i] = server;
1138                     server_badness[i] = d;
1139                     if (nlist < NTP_MAXLIST)
1140                               nlist++;
1141           }
1142 
1143           /*
1144            * Got the five-or-less best.  Cut the list where the number of
1145            * strata exceeds two.
1146            */
1147           count = 0;
1148           for (i = 1; i < nlist; i++)
1149                     if (server_list[i]->stratum > server_list[i-1]->stratum) {
1150                               count++;
1151                               if (2 == count) {
1152                                         nlist = i;
1153                                         break;
1154                               }
1155                     }
1156 
1157           /*
1158            * Whew!  What we should have by now is 0 to 5 candidates for
1159            * the job of syncing us.  If we have none, we're out of luck.
1160            * If we have one, he's a winner.  If we have more, do falseticker
1161            * detection.
1162            */
1163 
1164           if (0 == nlist)
1165                     sys_server = NULL;
1166           else if (1 == nlist) {
1167                     sys_server = server_list[0];
1168           } else {
1169                     /*
1170                      * Re-sort by stratum, bdelay estimate quality and
1171                      * server.delay.
1172                      */
1173                     for (i = 0; i < nlist-1; i++)
1174                               for (j = i+1; j < nlist; j++) {
1175                                         if (server_list[i]->stratum <
1176                                             server_list[j]->stratum)
1177                                                   /* already sorted by stratum */
1178                                                   break;
1179                                         if (server_list[i]->delay <
1180                                             server_list[j]->delay)
1181                                                   continue;
1182                                         server = server_list[i];
1183                                         server_list[i] = server_list[j];
1184                                         server_list[j] = server;
1185                               }
1186 
1187                     /*
1188                      * Calculate the fixed part of the dispersion limit
1189                      */
1190                     local_threshold = (FP_SECOND >> (-(int)NTPDATE_PRECISION))
1191                               + NTP_MAXSKW;
1192 
1193                     /*
1194                      * Now drop samples until we're down to one.
1195                      */
1196                     while (nlist > 1) {
1197                               for (k = 0; k < nlist; k++) {
1198                                         server_badness[k] = 0;
1199                                         for (j = 0; j < nlist; j++) {
1200                                                   if (j == k) /* with self? */
1201                                                             continue;
1202                                                   d = server_list[j]->soffset -
1203                                                       server_list[k]->soffset;
1204                                                   if (d < 0)          /* abs value */
1205                                                             d = -d;
1206                                                   /*
1207                                                    * XXX This code *knows* that
1208                                                    * NTP_SELECT is 3/4
1209                                                    */
1210                                                   for (i = 0; i < j; i++)
1211                                                             d = (d>>1) + (d>>2);
1212                                                   server_badness[k] += d;
1213                                         }
1214                               }
1215 
1216                               /*
1217                                * We now have an array of nlist badness
1218                                * coefficients.    Find the badest.  Find
1219                                * the minimum precision while we're at
1220                                * it.
1221                                */
1222                               i = 0;
1223                               n = server_list[0]->precision;;
1224                               for (j = 1; j < nlist; j++) {
1225                                         if (server_badness[j] >= server_badness[i])
1226                                                   i = j;
1227                                         if (n > server_list[j]->precision)
1228                                                   n = server_list[j]->precision;
1229                               }
1230 
1231                               /*
1232                                * i is the index of the server with the worst
1233                                * dispersion.      If his dispersion is less than
1234                                * the threshold, stop now, else delete him and
1235                                * continue around again.
1236                                */
1237                               if ( (s_fp) server_badness[i] < (local_threshold
1238                                                                        + (FP_SECOND >> (-n))))
1239                                         break;
1240                               for (j = i + 1; j < nlist; j++)
1241                                         server_list[j-1] = server_list[j];
1242                               nlist--;
1243                     }
1244 
1245                     /*
1246                      * What remains is a list of less than 5 servers.  Take
1247                      * the best.
1248                      */
1249                     sys_server = server_list[0];
1250           }
1251 
1252           /*
1253            * That's it.  Return our server.
1254            */
1255           return sys_server;
1256 }
1257 
1258 
1259 /*
1260  * clock_adjust - process what we've received, and adjust the time
1261  *                   if we got anything decent.
1262  */
1263 static int
clock_adjust(void)1264 clock_adjust(void)
1265 {
1266           register struct server *sp, *server;
1267           int dostep;
1268 
1269           for (sp = sys_servers; sp != NULL; sp = sp->next_server)
1270                     clock_filter(sp);
1271           server = clock_select();
1272 
1273           if (debug || simple_query) {
1274                     if (debug)
1275                               printf ("\n");
1276                     for (sp = sys_servers; sp != NULL; sp = sp->next_server)
1277                               print_server(sp, stdout);
1278           }
1279 
1280           if (server == 0) {
1281                     msyslog(LOG_ERR,
1282                               "no server suitable for synchronization found");
1283                     return(1);
1284           }
1285 
1286           if (always_step) {
1287                     dostep = 1;
1288           } else if (never_step) {
1289                     dostep = 0;
1290           } else {
1291                     /* [Bug 3023] get absolute difference, avoiding signed
1292                      * integer overflow like hell.
1293                      */
1294                     u_fp absoffset;
1295                     if (server->soffset < 0)
1296                               absoffset = 1u + (u_fp)(-(server->soffset + 1));
1297                     else
1298                               absoffset = (u_fp)server->soffset;
1299                     dostep = (absoffset >= NTPDATE_THRESHOLD);
1300           }
1301 
1302           if (dostep) {
1303                     if (simple_query || l_step_systime(&server->offset)){
1304                               msyslog(LOG_NOTICE, "step time server %s offset %s sec",
1305                                         stoa(&server->srcadr),
1306                                         lfptoa(&server->offset, 6));
1307                     }
1308           } else {
1309                     if (simple_query || l_adj_systime(&server->offset)) {
1310                               msyslog(LOG_NOTICE, "adjust time server %s offset %s sec",
1311                                         stoa(&server->srcadr),
1312                                         lfptoa(&server->offset, 6));
1313                     }
1314           }
1315           return(0);
1316 }
1317 
1318 
1319 /*
1320  * is_unreachable - check to see if we have a route to given destination
1321  *                      (non-blocking).
1322  */
1323 static int
is_reachable(sockaddr_u * dst)1324 is_reachable (sockaddr_u *dst)
1325 {
1326           SOCKET sockfd;
1327 
1328           sockfd = socket(AF(dst), SOCK_DGRAM, 0);
1329           if (sockfd == -1) {
1330                     return 0;
1331           }
1332 
1333           if (connect(sockfd, &dst->sa, SOCKLEN(dst))) {
1334                     closesocket(sockfd);
1335                     return 0;
1336           }
1337           closesocket(sockfd);
1338           return 1;
1339 }
1340 
1341 
1342 
1343 /* XXX ELIMINATE: merge BIG slew into adj_systime in lib/systime.c */
1344 /*
1345  * addserver - determine a server's address and allocate a new structure
1346  *                  for it.
1347  */
1348 static void
addserver(char * serv)1349 addserver(
1350           char *serv
1351           )
1352 {
1353           register struct server *server;
1354           /* Address infos structure to store result of getaddrinfo */
1355           struct addrinfo *addrResult, *ptr;
1356           /* Address infos structure to store hints for getaddrinfo */
1357           struct addrinfo hints;
1358           /* Error variable for getaddrinfo */
1359           int error;
1360           /* Service name */
1361           char service[5];
1362           sockaddr_u addr;
1363 
1364           strlcpy(service, "ntp", sizeof(service));
1365 
1366           /* Get host address. Looking for UDP datagram connection. */
1367           ZERO(hints);
1368           hints.ai_family = ai_fam_templ;
1369           hints.ai_socktype = SOCK_DGRAM;
1370 
1371 #ifdef DEBUG
1372           if (debug)
1373                     printf("Looking for host %s and service %s\n", serv, service);
1374 #endif
1375 
1376           error = getaddrinfo(serv, service, &hints, &addrResult);
1377           if (error == EAI_SERVICE) {
1378                     strlcpy(service, "123", sizeof(service));
1379                     error = getaddrinfo(serv, service, &hints, &addrResult);
1380           }
1381           if (error != 0) {
1382                     /* Conduct more refined error analysis */
1383                     if (error == EAI_FAIL || error == EAI_AGAIN){
1384                               /* Name server is unusable. Exit after failing on the
1385                                  first server, in order to shorten the timeout caused
1386                                  by waiting for resolution of several servers */
1387                               fprintf(stderr, "Exiting, name server cannot be used: %s (%d)",
1388                                         gai_strerror(error), error);
1389                               msyslog(LOG_ERR, "name server cannot be used: %s (%d)",
1390                                         gai_strerror(error), error);
1391                               exit(1);
1392                     }
1393                     fprintf(stderr, "Error resolving %s: %s (%d)\n", serv,
1394                               gai_strerror(error), error);
1395                     msyslog(LOG_ERR, "Can't find host %s: %s (%d)", serv,
1396                               gai_strerror(error), error);
1397                     return;
1398           }
1399 #ifdef DEBUG
1400           if (debug) {
1401                     ZERO(addr);
1402                     INSIST(addrResult->ai_addrlen <= sizeof(addr));
1403                     memcpy(&addr, addrResult->ai_addr, addrResult->ai_addrlen);
1404                     fprintf(stderr, "host found : %s\n", stohost(&addr));
1405           }
1406 #endif
1407 
1408           /* We must get all returned server in case the first one fails */
1409           for (ptr = addrResult; ptr != NULL; ptr = ptr->ai_next) {
1410                     ZERO(addr);
1411                     INSIST(ptr->ai_addrlen <= sizeof(addr));
1412                     memcpy(&addr, ptr->ai_addr, ptr->ai_addrlen);
1413                     if (is_reachable(&addr)) {
1414                               server = emalloc_zero(sizeof(*server));
1415                               memcpy(&server->srcadr, ptr->ai_addr, ptr->ai_addrlen);
1416                               server->event_time = ++sys_numservers;
1417                               if (sys_servers == NULL)
1418                                         sys_servers = server;
1419                               else {
1420                                         struct server *sp;
1421 
1422                                         for (sp = sys_servers; sp->next_server != NULL;
1423                                              sp = sp->next_server)
1424                                                   /* empty */;
1425                                         sp->next_server = server;
1426                               }
1427                     }
1428           }
1429 
1430           freeaddrinfo(addrResult);
1431 }
1432 
1433 
1434 /*
1435  * findserver - find a server in the list given its address
1436  * ***(For now it isn't totally AF-Independant, to check later..)
1437  */
1438 static struct server *
findserver(sockaddr_u * addr)1439 findserver(
1440           sockaddr_u *addr
1441           )
1442 {
1443           struct server *server;
1444           struct server *mc_server;
1445 
1446           mc_server = NULL;
1447           if (SRCPORT(addr) != NTP_PORT)
1448                     return 0;
1449 
1450           for (server = sys_servers; server != NULL;
1451                server = server->next_server) {
1452                     if (SOCK_EQ(addr, &server->srcadr))
1453                               return server;
1454 
1455                     if (AF(addr) == AF(&server->srcadr)) {
1456                               if (IS_MCAST(&server->srcadr))
1457                                         mc_server = server;
1458                     }
1459           }
1460 
1461           if (mc_server != NULL) {
1462 
1463                     struct server *sp;
1464 
1465                     if (mc_server->event_time != 0) {
1466                               mc_server->event_time = 0;
1467                               complete_servers++;
1468                     }
1469 
1470                     server = emalloc_zero(sizeof(*server));
1471 
1472                     server->srcadr = *addr;
1473 
1474                     server->event_time = ++sys_numservers;
1475 
1476                     for (sp = sys_servers; sp->next_server != NULL;
1477                          sp = sp->next_server)
1478                               /* empty */;
1479                     sp->next_server = server;
1480                     transmit(server);
1481           }
1482           return NULL;
1483 }
1484 
1485 
1486 /*
1487  * timer - process a timer interrupt
1488  */
1489 void
timer(void)1490 timer(void)
1491 {
1492           struct server *server;
1493 
1494           /*
1495            * Bump the current idea of the time
1496            */
1497           current_time++;
1498 
1499           /*
1500            * Search through the server list looking for guys
1501            * who's event timers have expired.  Give these to
1502            * the transmit routine.
1503            */
1504           for (server = sys_servers; server != NULL;
1505                server = server->next_server) {
1506                     if (server->event_time != 0
1507                         && server->event_time <= current_time)
1508                               transmit(server);
1509           }
1510 }
1511 
1512 
1513 /*
1514  * The code duplication in the following subroutine sucks, but
1515  * we need to appease ansi2knr.
1516  */
1517 
1518 #ifndef SYS_WINNT
1519 /*
1520  * alarming - record the occurance of an alarm interrupt
1521  */
1522 static RETSIGTYPE
alarming(int sig)1523 alarming(
1524           int sig
1525           )
1526 {
1527           alarm_flag++;
1528 }
1529 #else     /* SYS_WINNT follows */
1530 void CALLBACK
alarming(UINT uTimerID,UINT uMsg,DWORD dwUser,DWORD dw1,DWORD dw2)1531 alarming(UINT uTimerID, UINT uMsg, DWORD dwUser, DWORD dw1, DWORD dw2)
1532 {
1533           UNUSED_ARG(uTimerID); UNUSED_ARG(uMsg); UNUSED_ARG(dwUser);
1534           UNUSED_ARG(dw1); UNUSED_ARG(dw2);
1535 
1536           alarm_flag++;
1537 }
1538 
1539 static void
callTimeEndPeriod(void)1540 callTimeEndPeriod(void)
1541 {
1542           timeEndPeriod( wTimerRes );
1543           wTimerRes = 0;
1544 }
1545 #endif /* SYS_WINNT */
1546 
1547 
1548 /*
1549  * init_alarm - set up the timer interrupt
1550  */
1551 static void
init_alarm(void)1552 init_alarm(void)
1553 {
1554 #ifndef SYS_WINNT
1555 # ifdef HAVE_TIMER_CREATE
1556           struct itimerspec its;
1557 # else
1558           struct itimerval itv;
1559 # endif
1560 #else     /* SYS_WINNT follows */
1561           TIMECAPS tc;
1562           UINT wTimerID;
1563           HANDLE hToken;
1564           TOKEN_PRIVILEGES tkp;
1565           DWORD dwUser = 0;
1566 #endif /* SYS_WINNT */
1567 
1568           alarm_flag = 0;
1569 
1570 #ifndef SYS_WINNT
1571 # ifdef HAVE_TIMER_CREATE
1572           alarm_flag = 0;
1573           /* this code was put in as setitimer() is non existant this us the
1574            * POSIX "equivalents" setup - casey
1575            */
1576           /* ntpdate_timerid is global - so we can kill timer later */
1577           if (timer_create (CLOCK_REALTIME, NULL, &ntpdate_timerid) ==
1578 #  ifdef SYS_VXWORKS
1579                     ERROR
1580 #  else
1581                     -1
1582 #  endif
1583                     )
1584           {
1585                     fprintf (stderr, "init_alarm(): timer_create (...) FAILED\n");
1586                     return;
1587           }
1588 
1589           /*        TIMER_HZ = (5)
1590            * Set up the alarm interrupt.          The first comes 1/(2*TIMER_HZ)
1591            * seconds from now and they continue on every 1/TIMER_HZ seconds.
1592            */
1593           signal_no_reset(SIGALRM, alarming);
1594           its.it_interval.tv_sec = 0;
1595           its.it_value.tv_sec = 0;
1596           its.it_interval.tv_nsec = 1000000000/TIMER_HZ;
1597           its.it_value.tv_nsec = 1000000000/(TIMER_HZ<<1);
1598           timer_settime(ntpdate_timerid, 0 /* !TIMER_ABSTIME */, &its, NULL);
1599 # else    /* !HAVE_TIMER_CREATE follows */
1600           /*
1601            * Set up the alarm interrupt.          The first comes 1/(2*TIMER_HZ)
1602            * seconds from now and they continue on every 1/TIMER_HZ seconds.
1603            */
1604           signal_no_reset(SIGALRM, alarming);
1605           itv.it_interval.tv_sec = 0;
1606           itv.it_value.tv_sec = 0;
1607           itv.it_interval.tv_usec = 1000000/TIMER_HZ;
1608           itv.it_value.tv_usec = 1000000/(TIMER_HZ<<1);
1609 
1610           setitimer(ITIMER_REAL, &itv, NULL);
1611 # endif   /* !HAVE_TIMER_CREATE */
1612 #else     /* SYS_WINNT follows */
1613           _tzset();
1614 
1615           if (!simple_query && !debug) {
1616                     /*
1617                      * Get privileges needed for fiddling with the clock
1618                      */
1619 
1620                     /* get the current process token handle */
1621                     if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken)) {
1622                               msyslog(LOG_ERR, "OpenProcessToken failed: %m");
1623                               exit(1);
1624                     }
1625                     /* get the LUID for system-time privilege. */
1626                     LookupPrivilegeValue(NULL, SE_SYSTEMTIME_NAME, &tkp.Privileges[0].Luid);
1627                     tkp.PrivilegeCount = 1;                 /* one privilege to set */
1628                     tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
1629                     /* get set-time privilege for this process. */
1630                     AdjustTokenPrivileges(hToken, FALSE, &tkp, 0,(PTOKEN_PRIVILEGES) NULL, 0);
1631                     /* cannot test return value of AdjustTokenPrivileges. */
1632                     if (GetLastError() != ERROR_SUCCESS)
1633                               msyslog(LOG_ERR, "AdjustTokenPrivileges failed: %m");
1634           }
1635 
1636           /*
1637            * Set up timer interrupts for every 2**EVENT_TIMEOUT seconds
1638            * Under Win/NT, expiry of timer interval leads to invocation
1639            * of a callback function (on a different thread) rather than
1640            * generating an alarm signal
1641            */
1642 
1643           /* determine max and min resolution supported */
1644           if(timeGetDevCaps(&tc, sizeof(TIMECAPS)) != TIMERR_NOERROR) {
1645                     msyslog(LOG_ERR, "timeGetDevCaps failed: %m");
1646                     exit(1);
1647           }
1648           wTimerRes = min(max(tc.wPeriodMin, TARGET_RESOLUTION), tc.wPeriodMax);
1649           /* establish the minimum timer resolution that we'll use */
1650           timeBeginPeriod(wTimerRes);
1651           atexit(callTimeEndPeriod);
1652 
1653           /* start the timer event */
1654           wTimerID = timeSetEvent(
1655                     (UINT) (1000/TIMER_HZ),                 /* Delay */
1656                     wTimerRes,                              /* Resolution */
1657                     (LPTIMECALLBACK) alarming,    /* Callback function */
1658                     (DWORD) dwUser,                         /* User data */
1659                     TIME_PERIODIC);                         /* Event type (periodic) */
1660           if (wTimerID == 0) {
1661                     msyslog(LOG_ERR, "timeSetEvent failed: %m");
1662                     exit(1);
1663           }
1664 #endif /* SYS_WINNT */
1665 }
1666 
1667 
1668 
1669 
1670 /*
1671  * We do asynchronous input using the SIGIO facility.  A number of
1672  * recvbuf buffers are preallocated for input.    In the signal
1673  * handler we poll to see if the socket is ready and read the
1674  * packets from it into the recvbuf's along with a time stamp and
1675  * an indication of the source host and the interface it was received
1676  * through.  This allows us to get as accurate receive time stamps
1677  * as possible independent of other processing going on.
1678  *
1679  * We allocate a number of recvbufs equal to the number of servers
1680  * plus 2.          This should be plenty.
1681  */
1682 
1683 
1684 /*
1685  * init_io - initialize I/O data and open socket
1686  */
1687 static void
init_io(void)1688 init_io(void)
1689 {
1690           struct addrinfo *res, *ressave;
1691           struct addrinfo hints;
1692           sockaddr_u addr;
1693           char service[5];
1694           int rc;
1695           int optval = 1;
1696           int check_ntp_port_in_use = !debug && !simple_query && !unpriv_port;
1697 
1698           /*
1699            * Init buffer free list and stat counters
1700            */
1701           init_recvbuff(sys_numservers + 2);
1702 
1703           /*
1704            * Open the socket
1705            */
1706 
1707           strlcpy(service, "ntp", sizeof(service));
1708 
1709           /*
1710            * Init hints addrinfo structure
1711            */
1712           ZERO(hints);
1713           hints.ai_family = ai_fam_templ;
1714           hints.ai_flags = AI_PASSIVE;
1715           hints.ai_socktype = SOCK_DGRAM;
1716 
1717           rc = getaddrinfo(NULL, service, &hints, &res);
1718           if (rc == EAI_SERVICE) {
1719                     strlcpy(service, "123", sizeof(service));
1720                     rc = getaddrinfo(NULL, service, &hints, &res);
1721           }
1722           if (rc != 0) {
1723                     msyslog(LOG_ERR, "getaddrinfo() failed: %m");
1724                     exit(1);
1725                     /*NOTREACHED*/
1726           }
1727 
1728 #ifdef SYS_WINNT
1729           if (check_ntp_port_in_use && ntp_port_inuse(AF_INET, NTP_PORT)){
1730                     msyslog(LOG_ERR, "the NTP socket is in use, exiting: %m");
1731                     exit(1);
1732           }
1733 #endif
1734 
1735           /* Remember the address of the addrinfo structure chain */
1736           ressave = res;
1737 
1738           /*
1739            * For each structure returned, open and bind socket
1740            */
1741           for(nbsock = 0; (nbsock < MAX_AF) && res ; res = res->ai_next) {
1742           /* create a datagram (UDP) socket */
1743                     fd[nbsock] = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
1744                     if (fd[nbsock] == SOCKET_ERROR) {
1745 #ifndef SYS_WINNT
1746                     if (errno == EPROTONOSUPPORT || errno == EAFNOSUPPORT ||
1747                         errno == EPFNOSUPPORT)
1748 #else
1749                     int err = WSAGetLastError();
1750                     if (err == WSAEPROTONOSUPPORT || err == WSAEAFNOSUPPORT ||
1751                         err == WSAEPFNOSUPPORT)
1752 #endif
1753                               continue;
1754                     msyslog(LOG_ERR, "socket() failed: %m");
1755                     exit(1);
1756                     /*NOTREACHED*/
1757                     }
1758                     /* set socket to reuse address */
1759                     if (setsockopt(fd[nbsock], SOL_SOCKET, SO_REUSEADDR, (void*) &optval, sizeof(optval)) < 0) {
1760                                         msyslog(LOG_ERR, "setsockopt() SO_REUSEADDR failed: %m");
1761                                         exit(1);
1762                                         /*NOTREACHED*/
1763                     }
1764 #ifdef IPV6_V6ONLY
1765                     /* Restricts AF_INET6 socket to IPv6 communications (see RFC 2553bis-03) */
1766                     if (res->ai_family == AF_INET6)
1767                               if (setsockopt(fd[nbsock], IPPROTO_IPV6, IPV6_V6ONLY, (void*) &optval, sizeof(optval)) < 0) {
1768                                         msyslog(LOG_ERR, "setsockopt() IPV6_V6ONLY failed: %m");
1769                     }
1770 #endif
1771 
1772                     /* Remember the socket family in fd_family structure */
1773                     fd_family[nbsock] = res->ai_family;
1774 
1775                     /*
1776                      * bind the socket to the NTP port
1777                      */
1778                     if (check_ntp_port_in_use) {
1779                               ZERO(addr);
1780                               INSIST(res->ai_addrlen <= sizeof(addr));
1781                               memcpy(&addr, res->ai_addr, res->ai_addrlen);
1782                               rc = bind(fd[nbsock], &addr.sa, SOCKLEN(&addr));
1783                               if (rc < 0) {
1784                                         if (EADDRINUSE == socket_errno())
1785                                                   msyslog(LOG_ERR, "the NTP socket is in use, exiting");
1786                                         else
1787                                                   msyslog(LOG_ERR, "bind() fails: %m");
1788                                         exit(1);
1789                               }
1790                     }
1791 
1792 #ifdef HAVE_POLL_H
1793                     fdmask[nbsock].fd = fd[nbsock];
1794                     fdmask[nbsock].events = POLLIN;
1795 #else
1796                     FD_SET(fd[nbsock], &fdmask);
1797                     if (maxfd < fd[nbsock]+1) {
1798                               maxfd = fd[nbsock]+1;
1799                     }
1800 #endif
1801 
1802                     /*
1803                      * set non-blocking,
1804                      */
1805 #ifndef SYS_WINNT
1806 # ifdef SYS_VXWORKS
1807                     {
1808                               int on = TRUE;
1809 
1810                               if (ioctl(fd[nbsock],FIONBIO, &on) == ERROR) {
1811                                         msyslog(LOG_ERR, "ioctl(FIONBIO) fails: %m");
1812                                         exit(1);
1813                               }
1814                     }
1815 # else /* not SYS_VXWORKS */
1816 #  if defined(O_NONBLOCK)
1817                     if (fcntl(fd[nbsock], F_SETFL, O_NONBLOCK) < 0) {
1818                               msyslog(LOG_ERR, "fcntl(FNDELAY|FASYNC) fails: %m");
1819                               exit(1);
1820                               /*NOTREACHED*/
1821                     }
1822 #  else /* not O_NONBLOCK */
1823 #         if defined(FNDELAY)
1824                     if (fcntl(fd[nbsock], F_SETFL, FNDELAY) < 0) {
1825                               msyslog(LOG_ERR, "fcntl(FNDELAY|FASYNC) fails: %m");
1826                               exit(1);
1827                               /*NOTREACHED*/
1828                     }
1829 #         else /* FNDELAY */
1830 #          include "Bletch: Need non blocking I/O"
1831 #         endif /* FNDELAY */
1832 #  endif /* not O_NONBLOCK */
1833 # endif /* SYS_VXWORKS */
1834 #else /* SYS_WINNT */
1835                     if (ioctlsocket(fd[nbsock], FIONBIO, (u_long *) &on) == SOCKET_ERROR) {
1836                               msyslog(LOG_ERR, "ioctlsocket(FIONBIO) fails: %m");
1837                               exit(1);
1838                     }
1839 #endif /* SYS_WINNT */
1840                     nbsock++;
1841           }
1842           freeaddrinfo(ressave);
1843 }
1844 
1845 /*
1846  * sendpkt - send a packet to the specified destination
1847  */
1848 static void
sendpkt(sockaddr_u * dest,struct pkt * pkt,int len)1849 sendpkt(
1850           sockaddr_u *dest,
1851           struct pkt *pkt,
1852           int len
1853           )
1854 {
1855           int i;
1856           int cc;
1857           SOCKET sock = INVALID_SOCKET;
1858 
1859 #ifdef SYS_WINNT
1860           DWORD err;
1861 #endif /* SYS_WINNT */
1862 
1863           /* Find a local family compatible socket to send ntp packet to ntp server */
1864           for(i = 0; (i < MAX_AF); i++) {
1865                     if(AF(dest) == fd_family[i]) {
1866                               sock = fd[i];
1867                     break;
1868                     }
1869           }
1870 
1871           if (INVALID_SOCKET == sock) {
1872                     msyslog(LOG_ERR, "cannot find family compatible socket to send ntp packet");
1873                     exit(1);
1874                     /*NOTREACHED*/
1875           }
1876 
1877           cc = sendto(sock, (char *)pkt, len, 0, (struct sockaddr *)dest,
1878                               SOCKLEN(dest));
1879 
1880           if (SOCKET_ERROR == cc) {
1881 #ifndef SYS_WINNT
1882                     if (errno != EWOULDBLOCK && errno != ENOBUFS)
1883 #else
1884                     err = WSAGetLastError();
1885                     if (err != WSAEWOULDBLOCK && err != WSAENOBUFS)
1886 #endif /* SYS_WINNT */
1887                               msyslog(LOG_ERR, "sendto(%s): %m", stohost(dest));
1888           }
1889 }
1890 
1891 
1892 /*
1893  * input_handler - receive packets asynchronously
1894  */
1895 void
input_handler(void)1896 input_handler(void)
1897 {
1898           register int n;
1899           register struct recvbuf *rb;
1900           struct sock_timeval tvzero;
1901           GETSOCKNAME_SOCKLEN_TYPE fromlen;
1902           l_fp ts;
1903           int i;
1904 #ifdef HAVE_POLL_H
1905           struct pollfd fds[MAX_AF];
1906 #else
1907           fd_set fds;
1908 #endif
1909           SOCKET fdc = 0;
1910 
1911           /*
1912            * Do a poll to see if we have data
1913            */
1914           for (;;) {
1915                     tvzero.tv_sec = tvzero.tv_usec = 0;
1916 #ifdef HAVE_POLL_H
1917                     memcpy(fds, fdmask, sizeof(fdmask));
1918                     n = poll(fds, (unsigned int)nbsock, tvzero.tv_sec * 1000);
1919 
1920                     /*
1921                      * Determine which socket received data
1922                      */
1923 
1924                     for(i=0; i < nbsock; i++) {
1925                               if(fds[i].revents & POLLIN) {
1926                                         fdc = fd[i];
1927                                         break;
1928                               }
1929                     }
1930 
1931 #else
1932                     fds = fdmask;
1933                     n = select(maxfd, &fds, NULL, NULL, &tvzero);
1934 
1935                     /*
1936                      * Determine which socket received data
1937                      */
1938 
1939                     for(i=0; i < nbsock; i++) {
1940                               if(FD_ISSET(fd[i], &fds)) {
1941                                          fdc = fd[i];
1942                                          break;
1943                               }
1944                     }
1945 
1946 #endif
1947 
1948                     /*
1949                      * If nothing to do, just return.  If an error occurred,
1950                      * complain and return.  If we've got some, freeze a
1951                      * timestamp.
1952                      */
1953                     if (n == 0)
1954                               return;
1955                     else if (n == -1) {
1956                               if (errno != EINTR)
1957                                         msyslog(LOG_ERR,
1958 #ifdef HAVE_POLL_H
1959                                                   "poll() error: %m"
1960 #else
1961                                                   "select() error: %m"
1962 #endif
1963                                                   );
1964                               return;
1965                     }
1966                     get_systime(&ts);
1967 
1968                     /*
1969                      * Get a buffer and read the frame.  If we
1970                      * haven't got a buffer, or this is received
1971                      * on the wild card socket, just dump the packet.
1972                      */
1973                     if (initializing || free_recvbuffs() == 0) {
1974                               char buf[100];
1975 
1976 
1977 #ifndef SYS_WINNT
1978                               (void) read(fdc, buf, sizeof buf);
1979 #else
1980                               /* NT's _read does not operate on nonblocking sockets
1981                                * either recvfrom or ReadFile() has to be used here.
1982                                * ReadFile is used in [ntpd]ntp_intres() and ntpdc,
1983                                * just to be different use recvfrom() here
1984                                */
1985                               recvfrom(fdc, buf, sizeof(buf), 0, (struct sockaddr *)0, NULL);
1986 #endif /* SYS_WINNT */
1987                               continue;
1988                     }
1989 
1990                     rb = get_free_recv_buffer(TRUE);
1991 
1992                     fromlen = sizeof(rb->recv_srcadr);
1993                     rb->recv_length = recvfrom(fdc, (char *)&rb->recv_pkt,
1994                        sizeof(rb->recv_pkt), 0,
1995                        (struct sockaddr *)&rb->recv_srcadr, &fromlen);
1996                     if (rb->recv_length == -1) {
1997                               freerecvbuf(rb);
1998                               continue;
1999                     }
2000 
2001                     /*
2002                      * Got one.  Mark how and when it got here,
2003                      * put it on the full list.
2004                      */
2005                     rb->recv_time = ts;
2006                     add_full_recv_buffer(rb);
2007           }
2008 }
2009 
2010 
2011 /*
2012  * adj_systime - do a big long slew of the system time
2013  */
2014 static int
l_adj_systime(l_fp * ts)2015 l_adj_systime(
2016           l_fp *ts
2017           )
2018 {
2019           struct timeval adjtv;
2020           int isneg = 0;
2021           l_fp offset;
2022 #ifndef STEP_SLEW
2023           l_fp overshoot;
2024 #endif
2025 
2026           /*
2027            * Take the absolute value of the offset
2028            */
2029           offset = *ts;
2030           if (L_ISNEG(&offset)) {
2031                     isneg = 1;
2032                     L_NEG(&offset);
2033           }
2034 
2035 #ifndef STEP_SLEW
2036           /*
2037            * Calculate the overshoot.  XXX N.B. This code *knows*
2038            * ADJ_OVERSHOOT is 1/2.
2039            */
2040           overshoot = offset;
2041           L_RSHIFTU(&overshoot);
2042           if (overshoot.l_ui != 0 || (overshoot.l_uf > ADJ_MAXOVERSHOOT)) {
2043                     overshoot.l_ui = 0;
2044                     overshoot.l_uf = ADJ_MAXOVERSHOOT;
2045           }
2046           L_ADD(&offset, &overshoot);
2047 #endif
2048           TSTOTV(&offset, &adjtv);
2049 
2050           if (isneg) {
2051                     adjtv.tv_sec = -adjtv.tv_sec;
2052                     adjtv.tv_usec = -adjtv.tv_usec;
2053           }
2054 
2055           if (!debug && (adjtv.tv_usec != 0)) {
2056                     /* A time correction needs to be applied. */
2057 #if !defined SYS_WINNT && !defined SYS_CYGWIN32
2058                     /* Slew the time on systems that support this. */
2059                     struct timeval oadjtv;
2060                     if (adjtime(&adjtv, &oadjtv) < 0) {
2061                               msyslog(LOG_ERR, "Can't adjust the time of day: %m");
2062                               exit(1);
2063                     }
2064 #else     /* SYS_WINNT or SYS_CYGWIN32 is defined */
2065                     /*
2066                      * The NT SetSystemTimeAdjustment() call achieves slewing by
2067                      * changing the clock frequency. This means that we cannot specify
2068                      * it to slew the clock by a definite amount and then stop like
2069                      * the Unix adjtime() routine. We can technically adjust the clock
2070                      * frequency, have ntpdate sleep for a while, and then wake
2071                      * up and reset the clock frequency, but this might cause some
2072                      * grief if the user attempts to run ntpd immediately after
2073                      * ntpdate and the socket is in use.
2074                      */
2075                     printf("\nSlewing the system time is not supported on Windows. Use the -b option to step the time.\n");
2076 #endif    /* defined SYS_WINNT || defined SYS_CYGWIN32 */
2077           }
2078           return 1;
2079 }
2080 
2081 
2082 /*
2083  * This fuction is not the same as lib/systime step_systime!!!
2084  */
2085 static int
l_step_systime(l_fp * ts)2086 l_step_systime(
2087           l_fp *ts
2088           )
2089 {
2090           double dtemp;
2091 
2092 #ifdef SLEWALWAYS
2093 #ifdef STEP_SLEW
2094           l_fp ftmp;
2095           int isneg;
2096           int n;
2097 
2098           if (debug)
2099                     return 1;
2100 
2101           /*
2102            * Take the absolute value of the offset
2103            */
2104           ftmp = *ts;
2105 
2106           if (L_ISNEG(&ftmp)) {
2107                     L_NEG(&ftmp);
2108                     isneg = 1;
2109           } else
2110                     isneg = 0;
2111 
2112           if (ftmp.l_ui >= 3) {                   /* Step it and slew - we might win */
2113                     LFPTOD(ts, dtemp);
2114                     n = step_systime(dtemp);
2115                     if (n == 0)
2116                               return 0;
2117                     if (isneg)                    /* WTF! */
2118                               ts->l_ui = ~0;
2119                     else
2120                               ts->l_ui = ~0;
2121           }
2122           /*
2123            * Just add adjustment into the current offset.  The update
2124            * routine will take care of bringing the system clock into
2125            * line.
2126            */
2127 #endif
2128           if (debug)
2129                     return 1;
2130 #ifdef FORCE_NTPDATE_STEP
2131           LFPTOD(ts, dtemp);
2132           return step_systime(dtemp);
2133 #else
2134           l_adj_systime(ts);
2135           return 1;
2136 #endif
2137 #else /* SLEWALWAYS */
2138           if (debug)
2139                     return 1;
2140           LFPTOD(ts, dtemp);
2141           return step_systime(dtemp);
2142 #endif    /* SLEWALWAYS */
2143 }
2144 
2145 
2146 /* XXX ELIMINATE print_server similar in ntptrace.c, ntpdate.c */
2147 /*
2148  * print_server - print detail information for a server
2149  */
2150 static void
print_server(register struct server * pp,FILE * fp)2151 print_server(
2152           register struct server *pp,
2153           FILE *fp
2154           )
2155 {
2156           register int i;
2157           char junk[5];
2158           const char *str;
2159 
2160           if (pp->stratum == 0)                   /* Nothing received => nothing to print */
2161                     return;
2162 
2163           if (!debug) {
2164                     (void) fprintf(fp, "server %s, stratum %d, offset %s, delay %s\n",
2165                                            stoa(&pp->srcadr), pp->stratum,
2166                                            lfptoa(&pp->offset, 6), fptoa((s_fp)pp->delay, 5));
2167                     return;
2168           }
2169 
2170           (void) fprintf(fp, "server %s, port %d\n",
2171                                  stoa(&pp->srcadr), ntohs(((struct sockaddr_in*)&(pp->srcadr))->sin_port));
2172 
2173           (void) fprintf(fp, "stratum %d, precision %d, leap %c%c, trust %03o\n",
2174                                  pp->stratum, pp->precision,
2175                                  pp->leap & 0x2 ? '1' : '0',
2176                                  pp->leap & 0x1 ? '1' : '0',
2177                                  pp->trust);
2178 
2179           if (REFID_ISTEXT(pp->stratum)) {
2180                     str = (char *) &pp->refid;
2181                     for (i=0; i<4 && str[i]; i++) {
2182                               junk[i] = (isprint((unsigned char)str[i]) ? str[i] : '.');
2183                     }
2184                     junk[i] = 0; // force terminating 0
2185                     str = junk;
2186           } else {
2187                     str = numtoa(pp->refid);
2188           }
2189           (void) fprintf(fp,
2190                               "refid [%s], root delay %s, root dispersion %s\n",
2191                               str, fptoa((s_fp)pp->rootdelay, 6),
2192                               ufptoa(pp->rootdisp, 6));
2193 
2194           if (pp->xmtcnt != pp->filter_nextpt)
2195                     (void) fprintf(fp, "transmitted %d, in filter %d\n",
2196                                  pp->xmtcnt, pp->filter_nextpt);
2197 
2198           (void) fprintf(fp, "reference time:      %s\n",
2199                                  prettydate(&pp->reftime));
2200           (void) fprintf(fp, "originate timestamp: %s\n",
2201                                  prettydate(&pp->org));
2202           (void) fprintf(fp, "transmit timestamp:  %s\n",
2203                                  prettydate(&pp->xmt));
2204 
2205           if (sys_samples > 1) {
2206                     (void) fprintf(fp, "filter delay: ");
2207                     for (i = 0; i < NTP_SHIFT; i++) {
2208                               if (i == (NTP_SHIFT>>1))
2209                                         (void) fprintf(fp, "\n              ");
2210                               (void) fprintf(fp, " %-10.10s",
2211                                         (i<sys_samples ? fptoa(pp->filter_delay[i], 5) : "----"));
2212                     }
2213                     (void) fprintf(fp, "\n");
2214 
2215                     (void) fprintf(fp, "filter offset:");
2216                     for (i = 0; i < PEER_SHIFT; i++) {
2217                               if (i == (PEER_SHIFT>>1))
2218                                         (void) fprintf(fp, "\n              ");
2219                               (void) fprintf(fp, " %-10.10s",
2220                                         (i<sys_samples ? lfptoa(&pp->filter_offset[i], 6): "----"));
2221                     }
2222                     (void) fprintf(fp, "\n");
2223           }
2224 
2225           (void) fprintf(fp, "delay %s, dispersion %s, ",
2226                                  fptoa((s_fp)pp->delay, 5), ufptoa(pp->dispersion, 5));
2227 
2228           (void) fprintf(fp, "offset %s\n\n",
2229                                  lfptoa(&pp->offset, 6));
2230 }
2231 
2232 
2233 #ifdef HAVE_NETINFO
2234 static ni_namelist *
getnetinfoservers(void)2235 getnetinfoservers(void)
2236 {
2237           ni_status status;
2238           void *domain;
2239           ni_id confdir;
2240           ni_namelist *namelist = emalloc(sizeof(ni_namelist));
2241 
2242           /* Find a time server in NetInfo */
2243           if ((status = ni_open(NULL, ".", &domain)) != NI_OK) return NULL;
2244 
2245           while (status = ni_pathsearch(domain, &confdir, NETINFO_CONFIG_DIR) == NI_NODIR) {
2246                     void *next_domain;
2247                     if (ni_open(domain, "..", &next_domain) != NI_OK) break;
2248                     ni_free(domain);
2249                     domain = next_domain;
2250           }
2251           if (status != NI_OK) return NULL;
2252 
2253           NI_INIT(namelist);
2254           if (ni_lookupprop(domain, &confdir, "server", namelist) != NI_OK) {
2255                     ni_namelist_free(namelist);
2256                     free(namelist);
2257                     return NULL;
2258           }
2259 
2260           return(namelist);
2261 }
2262 #endif
2263 
2264 #ifdef SYS_WINNT
ntp_port_inuse(int af,u_short port)2265 isc_boolean_t ntp_port_inuse(int af, u_short port)
2266 {
2267           /*
2268            * Check if NTP socket is already in use on this system
2269            * This is only for Windows Systems, as they tend not to fail on the real bind() below
2270            */
2271 
2272           SOCKET checksocket;
2273           struct sockaddr_in checkservice;
2274           checksocket = socket(af, SOCK_DGRAM, 0);
2275           if (checksocket == INVALID_SOCKET) {
2276                     return (ISC_TRUE);
2277           }
2278 
2279           checkservice.sin_family = (short) AF_INET;
2280           checkservice.sin_addr.s_addr = INADDR_LOOPBACK;
2281           checkservice.sin_port = htons(port);
2282 
2283           if (bind(checksocket, (struct sockaddr *)&checkservice,
2284                     sizeof(checkservice)) == SOCKET_ERROR) {
2285                     if ( WSAGetLastError() == WSAEADDRINUSE ){
2286                               closesocket(checksocket);
2287                               return (ISC_TRUE);
2288                     }
2289           }
2290           closesocket(checksocket);
2291           return (ISC_FALSE);
2292 }
2293 #endif
2294