]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/ntp/ntpd/ntpd.c
Update ntpd to 4.2.8p13 to fix authenticated denial of service.
[FreeBSD/FreeBSD.git] / contrib / ntp / ntpd / ntpd.c
1 /*
2  * ntpd.c - main program for the fixed point NTP daemon
3  */
4
5 #ifdef HAVE_CONFIG_H
6 # include <config.h>
7 #endif
8
9 #include "ntp_machine.h"
10 #include "ntpd.h"
11 #include "ntp_io.h"
12 #include "ntp_stdlib.h"
13 #include <ntp_random.h>
14
15 #include "ntp_config.h"
16 #include "ntp_syslog.h"
17 #include "ntp_assert.h"
18 #include "isc/error.h"
19 #include "isc/strerror.h"
20 #include "isc/formatcheck.h"
21 #include "iosignal.h"
22
23 #ifdef SIM
24 # include "ntpsim.h"
25 #endif
26
27 #include "ntp_libopts.h"
28 #include "ntpd-opts.h"
29
30 /* there's a short treatise below what the thread stuff is for.
31  * [Bug 2954] enable the threading warm-up only for Linux.
32  */
33 #if defined(HAVE_PTHREADS) && HAVE_PTHREADS && !defined(NO_THREADS)
34 # ifdef HAVE_PTHREAD_H
35 #  include <pthread.h>
36 # endif
37 # if defined(linux)
38 #  define NEED_PTHREAD_WARMUP
39 # endif
40 #endif
41
42 #ifdef HAVE_UNISTD_H
43 # include <unistd.h>
44 #endif
45 #ifdef HAVE_SYS_STAT_H
46 # include <sys/stat.h>
47 #endif
48 #include <stdio.h>
49 #ifdef HAVE_SYS_PARAM_H
50 # include <sys/param.h>
51 #endif
52 #ifdef HAVE_SYS_SIGNAL_H
53 # include <sys/signal.h>
54 #else
55 # include <signal.h>
56 #endif
57 #ifdef HAVE_SYS_IOCTL_H
58 # include <sys/ioctl.h>
59 #endif /* HAVE_SYS_IOCTL_H */
60 #if defined(HAVE_RTPRIO)
61 # ifdef HAVE_SYS_LOCK_H
62 #  include <sys/lock.h>
63 # endif
64 # include <sys/rtprio.h>
65 #else
66 # ifdef HAVE_PLOCK
67 #  ifdef HAVE_SYS_LOCK_H
68 #       include <sys/lock.h>
69 #  endif
70 # endif
71 #endif
72 #if defined(HAVE_SCHED_SETSCHEDULER)
73 # ifdef HAVE_SCHED_H
74 #  include <sched.h>
75 # else
76 #  ifdef HAVE_SYS_SCHED_H
77 #   include <sys/sched.h>
78 #  endif
79 # endif
80 #endif
81 #if defined(HAVE_SYS_MMAN_H)
82 # include <sys/mman.h>
83 #endif
84
85 #ifdef HAVE_TERMIOS_H
86 # include <termios.h>
87 #endif
88
89 #ifdef SYS_DOMAINOS
90 # include <apollo/base.h>
91 #endif /* SYS_DOMAINOS */
92
93
94 #include "recvbuff.h"
95 #include "ntp_cmdargs.h"
96
97 #if 0                           /* HMS: I don't think we need this. 961223 */
98 #ifdef LOCK_PROCESS
99 # ifdef SYS_SOLARIS
100 #  include <sys/mman.h>
101 # else
102 #  include <sys/lock.h>
103 # endif
104 #endif
105 #endif
106
107 #ifdef SYS_WINNT
108 # include "ntservice.h"
109 #endif
110
111 #ifdef _AIX
112 # include <ulimit.h>
113 #endif /* _AIX */
114
115 #ifdef SCO5_CLOCK
116 # include <sys/ci/ciioctl.h>
117 #endif
118
119 #ifdef HAVE_DROPROOT
120 # include <ctype.h>
121 # include <grp.h>
122 # include <pwd.h>
123 #ifdef HAVE_LINUX_CAPABILITIES
124 # include <sys/capability.h>
125 # include <sys/prctl.h>
126 #endif /* HAVE_LINUX_CAPABILITIES */
127 #if defined(HAVE_PRIV_H) && defined(HAVE_SOLARIS_PRIVS)
128 # include <priv.h>
129 #endif /* HAVE_PRIV_H */
130 #endif /* HAVE_DROPROOT */
131
132 #if defined (LIBSECCOMP) && (KERN_SECCOMP)
133 /* # include <sys/types.h> */
134 # include <sys/resource.h>
135 # include <seccomp.h>
136 #endif /* LIBSECCOMP and KERN_SECCOMP */
137
138 #ifdef HAVE_DNSREGISTRATION
139 # include <dns_sd.h>
140 DNSServiceRef mdns;
141 #endif
142
143 #ifdef HAVE_SETPGRP_0
144 # define ntp_setpgrp(x, y)      setpgrp()
145 #else
146 # define ntp_setpgrp(x, y)      setpgrp(x, y)
147 #endif
148
149 #ifdef HAVE_SOLARIS_PRIVS
150 # define LOWPRIVS "basic,sys_time,net_privaddr,proc_setid,!proc_info,!proc_session,!proc_exec"
151 static priv_set_t *lowprivs = NULL;
152 static priv_set_t *highprivs = NULL;
153 #endif /* HAVE_SOLARIS_PRIVS */
154 /*
155  * Scheduling priority we run at
156  */
157 #define NTPD_PRIO       (-12)
158
159 int priority_done = 2;          /* 0 - Set priority */
160                                 /* 1 - priority is OK where it is */
161                                 /* 2 - Don't set priority */
162                                 /* 1 and 2 are pretty much the same */
163
164 int listen_to_virtual_ips = TRUE;
165
166 /*
167  * No-fork flag.  If set, we do not become a background daemon.
168  */
169 int nofork;                     /* Fork by default */
170
171 #ifdef HAVE_DNSREGISTRATION
172 /*
173  * mDNS registration flag. If set, we attempt to register with the mDNS system, but only
174  * after we have synched the first time. If the attempt fails, then try again once per 
175  * minute for up to 5 times. After all, we may be starting before mDNS.
176  */
177 int mdnsreg = FALSE;
178 int mdnstries = 5;
179 #endif  /* HAVE_DNSREGISTRATION */
180
181 #ifdef HAVE_DROPROOT
182 int droproot;
183 int root_dropped;
184 char *user;             /* User to switch to */
185 char *group;            /* group to switch to */
186 const char *chrootdir;  /* directory to chroot to */
187 uid_t sw_uid;
188 gid_t sw_gid;
189 struct group *gr;
190 struct passwd *pw;
191 #endif /* HAVE_DROPROOT */
192
193 #ifdef HAVE_WORKING_FORK
194 int     waitsync_fd_to_close = -1;      /* -w/--wait-sync */
195 #endif
196
197 /*
198  * Version declaration
199  */
200 extern const char *Version;
201
202 char const *progname;
203
204 int was_alarmed;
205
206 #ifdef DECL_SYSCALL
207 /*
208  * We put this here, since the argument profile is syscall-specific
209  */
210 extern int syscall      (int, ...);
211 #endif /* DECL_SYSCALL */
212
213
214 #if !defined(SIM) && defined(SIGDIE1)
215 static volatile int signalled   = 0;
216 static volatile int signo       = 0;
217
218 /* In an ideal world, 'finish_safe()' would declared as noreturn... */
219 static  void            finish_safe     (int);
220 static  RETSIGTYPE      finish          (int);
221 #endif
222
223 #if !defined(SIM) && defined(HAVE_WORKING_FORK)
224 static int      wait_child_sync_if      (int, long);
225 #endif
226
227 #if !defined(SIM) && !defined(SYS_WINNT)
228 # ifdef DEBUG
229 static  RETSIGTYPE      moredebug       (int);
230 static  RETSIGTYPE      lessdebug       (int);
231 # else  /* !DEBUG follows */
232 static  RETSIGTYPE      no_debug        (int);
233 # endif /* !DEBUG */
234 #endif  /* !SIM && !SYS_WINNT */
235
236 #ifndef WORK_FORK
237 int     saved_argc;
238 char ** saved_argv;
239 #endif
240
241 #ifndef SIM
242 int             ntpdmain                (int, char **);
243 static void     set_process_priority    (void);
244 static void     assertion_failed        (const char *, int,
245                                          isc_assertiontype_t,
246                                          const char *)
247                         __attribute__   ((__noreturn__));
248 static void     library_fatal_error     (const char *, int, 
249                                          const char *, va_list)
250                                         ISC_FORMAT_PRINTF(3, 0);
251 static void     library_unexpected_error(const char *, int,
252                                          const char *, va_list)
253                                         ISC_FORMAT_PRINTF(3, 0);
254 #endif  /* !SIM */
255
256
257 /* Bug2332 unearthed a problem in the interaction of reduced user
258  * privileges, the limits on memory usage and some versions of the
259  * pthread library on Linux systems. The 'pthread_cancel()' function and
260  * likely some others need to track the stack of the thread involved,
261  * and uses a function that comes from GCC (--> libgcc_s.so) to do
262  * this. Unfortunately the developers of glibc decided to load the
263  * library on demand, which speeds up program start but can cause
264  * trouble here: Due to all the things NTPD does to limit its resource
265  * usage, this deferred load of libgcc_s does not always work once the
266  * restrictions are in effect.
267  *
268  * One way out of this was attempting a forced link against libgcc_s
269  * when possible because it makes the library available immediately
270  * without deferred load. (The symbol resolution would still be dynamic
271  * and on demand, but the code would already be in the process image.)
272  *
273  * This is a tricky thing to do, since it's not necessary everywhere,
274  * not possible everywhere, has shown to break the build of other
275  * programs in the NTP suite and is now generally frowned upon.
276  *
277  * So we take a different approach here: We creat a worker thread that does
278  * actually nothing except waiting for cancellation and cancel it. If
279  * this is done before all the limitations are put in place, the
280  * machinery is pre-heated and all the runtime stuff should be in place
281  * and useable when needed.
282  *
283  * This uses only the standard pthread API and should work with all
284  * implementations of pthreads. It is not necessary everywhere, but it's
285  * cheap enough to go on nearly unnoticed.
286  *
287  * Addendum: Bug 2954 showed that the assumption that this should work
288  * with all OS is wrong -- at least FreeBSD bombs heavily.
289  */
290 #ifdef NEED_PTHREAD_WARMUP
291
292 /* simple thread function: sleep until cancelled, just to exercise
293  * thread cancellation.
294  */
295 static void*
296 my_pthread_warmup_worker(
297         void *thread_args)
298 {
299         (void)thread_args;
300         for (;;)
301                 sleep(10);
302         return NULL;
303 }
304         
305 /* pre-heat threading: create a thread and cancel it, just to exercise
306  * thread cancellation.
307  */
308 static void
309 my_pthread_warmup(void)
310 {
311         pthread_t       thread;
312         pthread_attr_t  thr_attr;
313         int             rc;
314         
315         pthread_attr_init(&thr_attr);
316 #if defined(HAVE_PTHREAD_ATTR_GETSTACKSIZE) && \
317     defined(HAVE_PTHREAD_ATTR_SETSTACKSIZE) && \
318     defined(PTHREAD_STACK_MIN)
319         {
320                 size_t ssmin = 32*1024; /* 32kB should be minimum */
321                 if (ssmin < PTHREAD_STACK_MIN)
322                         ssmin = PTHREAD_STACK_MIN;
323                 rc = pthread_attr_setstacksize(&thr_attr, ssmin);
324                 if (0 != rc)
325                         msyslog(LOG_ERR,
326                                 "my_pthread_warmup: pthread_attr_setstacksize() -> %s",
327                                 strerror(rc));
328         }
329 #endif
330         rc = pthread_create(
331                 &thread, &thr_attr, my_pthread_warmup_worker, NULL);
332         pthread_attr_destroy(&thr_attr);
333         if (0 != rc) {
334                 msyslog(LOG_ERR,
335                         "my_pthread_warmup: pthread_create() -> %s",
336                         strerror(rc));
337         } else {
338                 pthread_cancel(thread);
339                 pthread_join(thread, NULL);
340         }
341 }
342
343 #endif /*defined(NEED_PTHREAD_WARMUP)*/
344
345 #ifdef NEED_EARLY_FORK
346 static void
347 dummy_callback(void) { return; }
348
349 static void
350 fork_nonchroot_worker(void) {
351         getaddrinfo_sometime("localhost", "ntp", NULL, INITIAL_DNS_RETRY,
352                              (gai_sometime_callback)&dummy_callback, NULL);
353 }
354 #endif /* NEED_EARLY_FORK */
355
356 void
357 parse_cmdline_opts(
358         int *   pargc,
359         char ***pargv
360         )
361 {
362         static int      parsed;
363         static int      optct;
364
365         if (!parsed)
366                 optct = ntpOptionProcess(&ntpdOptions, *pargc, *pargv);
367
368         parsed = 1;
369         
370         *pargc -= optct;
371         *pargv += optct;
372 }
373
374
375 #ifdef SIM
376 int
377 main(
378         int argc,
379         char *argv[]
380         )
381 {
382         progname = argv[0];
383         parse_cmdline_opts(&argc, &argv);
384 #ifdef DEBUG
385         debug = OPT_VALUE_SET_DEBUG_LEVEL;
386         DPRINTF(1, ("%s\n", Version));
387 #endif
388
389         return ntpsim(argc, argv);
390 }
391 #else   /* !SIM follows */
392 #ifdef NO_MAIN_ALLOWED
393 CALL(ntpd,"ntpd",ntpdmain);
394 #else   /* !NO_MAIN_ALLOWED follows */
395 #ifndef SYS_WINNT
396 int
397 main(
398         int argc,
399         char *argv[]
400         )
401 {
402         return ntpdmain(argc, argv);
403 }
404 #endif /* !SYS_WINNT */
405 #endif /* !NO_MAIN_ALLOWED */
406 #endif /* !SIM */
407
408 #ifdef _AIX
409 /*
410  * OK. AIX is different than solaris in how it implements plock().
411  * If you do NOT adjust the stack limit, you will get the MAXIMUM
412  * stack size allocated and PINNED with you program. To check the
413  * value, use ulimit -a.
414  *
415  * To fix this, we create an automatic variable and set our stack limit
416  * to that PLUS 32KB of extra space (we need some headroom).
417  *
418  * This subroutine gets the stack address.
419  *
420  * Grover Davidson and Matt Ladendorf
421  *
422  */
423 static char *
424 get_aix_stack(void)
425 {
426         char ch;
427         return (&ch);
428 }
429
430 /*
431  * Signal handler for SIGDANGER.
432  */
433 static void
434 catch_danger(int signo)
435 {
436         msyslog(LOG_INFO, "ntpd: setpgid(): %m");
437         /* Make the system believe we'll free something, but don't do it! */
438         return;
439 }
440 #endif /* _AIX */
441
442 /*
443  * Set the process priority
444  */
445 #ifndef SIM
446 static void
447 set_process_priority(void)
448 {
449
450 # ifdef DEBUG
451         if (debug > 1)
452                 msyslog(LOG_DEBUG, "set_process_priority: %s: priority_done is <%d>",
453                         ((priority_done)
454                          ? "Leave priority alone"
455                          : "Attempt to set priority"
456                                 ),
457                         priority_done);
458 # endif /* DEBUG */
459
460 # if defined(HAVE_SCHED_SETSCHEDULER)
461         if (!priority_done) {
462                 extern int config_priority_override, config_priority;
463                 int pmax, pmin;
464                 struct sched_param sched;
465
466                 pmax = sched_get_priority_max(SCHED_FIFO);
467                 sched.sched_priority = pmax;
468                 if ( config_priority_override ) {
469                         pmin = sched_get_priority_min(SCHED_FIFO);
470                         if ( config_priority > pmax )
471                                 sched.sched_priority = pmax;
472                         else if ( config_priority < pmin )
473                                 sched.sched_priority = pmin;
474                         else
475                                 sched.sched_priority = config_priority;
476                 }
477                 if ( sched_setscheduler(0, SCHED_FIFO, &sched) == -1 )
478                         msyslog(LOG_ERR, "sched_setscheduler(): %m");
479                 else
480                         ++priority_done;
481         }
482 # endif /* HAVE_SCHED_SETSCHEDULER */
483 # ifdef HAVE_RTPRIO
484 #  ifdef RTP_SET
485         if (!priority_done) {
486                 struct rtprio srtp;
487
488                 srtp.type = RTP_PRIO_REALTIME;  /* was: RTP_PRIO_NORMAL */
489                 srtp.prio = 0;          /* 0 (hi) -> RTP_PRIO_MAX (31,lo) */
490
491                 if (rtprio(RTP_SET, getpid(), &srtp) < 0)
492                         msyslog(LOG_ERR, "rtprio() error: %m");
493                 else
494                         ++priority_done;
495         }
496 #  else /* !RTP_SET follows */
497         if (!priority_done) {
498                 if (rtprio(0, 120) < 0)
499                         msyslog(LOG_ERR, "rtprio() error: %m");
500                 else
501                         ++priority_done;
502         }
503 #  endif        /* !RTP_SET */
504 # endif /* HAVE_RTPRIO */
505 # if defined(NTPD_PRIO) && NTPD_PRIO != 0
506 #  ifdef HAVE_ATT_NICE
507         if (!priority_done) {
508                 errno = 0;
509                 if (-1 == nice (NTPD_PRIO) && errno != 0)
510                         msyslog(LOG_ERR, "nice() error: %m");
511                 else
512                         ++priority_done;
513         }
514 #  endif        /* HAVE_ATT_NICE */
515 #  ifdef HAVE_BSD_NICE
516         if (!priority_done) {
517                 if (-1 == setpriority(PRIO_PROCESS, 0, NTPD_PRIO))
518                         msyslog(LOG_ERR, "setpriority() error: %m");
519                 else
520                         ++priority_done;
521         }
522 #  endif        /* HAVE_BSD_NICE */
523 # endif /* NTPD_PRIO && NTPD_PRIO != 0 */
524         if (!priority_done)
525                 msyslog(LOG_ERR, "set_process_priority: No way found to improve our priority");
526 }
527 #endif  /* !SIM */
528
529 #if !defined(SIM) && !defined(SYS_WINNT)
530 /*
531  * Detach from terminal (much like daemon())
532  * Nothe that this function calls exit()
533  */
534 # ifdef HAVE_WORKING_FORK
535 static void
536 detach_from_terminal(
537         int pipe_fds[2],
538         long wait_sync,
539         const char *logfilename
540         )
541 {
542         int rc;
543         int exit_code;
544 #  if !defined(HAVE_SETSID) && !defined (HAVE_SETPGID) && defined(TIOCNOTTY)
545         int             fid;
546 #  endif
547 #  ifdef _AIX
548         struct sigaction sa;
549 #  endif
550
551         rc = fork();
552         if (-1 == rc) {
553                 exit_code = (errno) ? errno : -1;
554                 msyslog(LOG_ERR, "fork: %m");
555                 exit(exit_code);
556         }
557         if (rc > 0) {
558                 /* parent */
559                 exit_code = wait_child_sync_if(pipe_fds[0],
560                                                wait_sync);
561                 exit(exit_code);
562         }
563
564         /*
565          * child/daemon
566          * close all open files excepting waitsync_fd_to_close.
567          * msyslog() unreliable until after init_logging().
568          */
569         closelog();
570         if (syslog_file != NULL) {
571                 fclose(syslog_file);
572                 syslog_file = NULL;
573                 syslogit = TRUE;
574         }
575         close_all_except(waitsync_fd_to_close);
576         INSIST(0 == open("/dev/null", 0) && 1 == dup2(0, 1) \
577                 && 2 == dup2(0, 2));
578
579         init_logging(progname, 0, TRUE);
580         /* we lost our logfile (if any) daemonizing */
581         setup_logfile(logfilename);
582
583 #  ifdef SYS_DOMAINOS
584         {
585                 uid_$t puid;
586                 status_$t st;
587
588                 proc2_$who_am_i(&puid);
589                 proc2_$make_server(&puid, &st);
590         }
591 #  endif        /* SYS_DOMAINOS */
592 #  ifdef HAVE_SETSID
593         if (setsid() == (pid_t)-1)
594                 msyslog(LOG_ERR, "setsid(): %m");
595 #  elif defined(HAVE_SETPGID)
596         if (setpgid(0, 0) == -1)
597                 msyslog(LOG_ERR, "setpgid(): %m");
598 #  else         /* !HAVE_SETSID && !HAVE_SETPGID follows */
599 #   ifdef TIOCNOTTY
600         fid = open("/dev/tty", 2);
601         if (fid >= 0) {
602                 ioctl(fid, (u_long)TIOCNOTTY, NULL);
603                 close(fid);
604         }
605 #   endif       /* TIOCNOTTY */
606         ntp_setpgrp(0, getpid());
607 #  endif        /* !HAVE_SETSID && !HAVE_SETPGID */
608 #  ifdef _AIX
609         /* Don't get killed by low-on-memory signal. */
610         sa.sa_handler = catch_danger;
611         sigemptyset(&sa.sa_mask);
612         sa.sa_flags = SA_RESTART;
613         sigaction(SIGDANGER, &sa, NULL);
614 #  endif        /* _AIX */
615
616         return;
617 }
618 # endif /* HAVE_WORKING_FORK */
619
620 #ifdef HAVE_DROPROOT
621 /*
622  * Map user name/number to user ID
623 */
624 static int
625 map_user(
626         )
627 {
628         char *endp;
629
630         if (isdigit((unsigned char)*user)) {
631                 sw_uid = (uid_t)strtoul(user, &endp, 0);
632                 if (*endp != '\0')
633                         goto getuser;
634
635                 if ((pw = getpwuid(sw_uid)) != NULL) {
636                         free(user);
637                         user = estrdup(pw->pw_name);
638                         sw_gid = pw->pw_gid;
639                 } else {
640                         errno = 0;
641                         msyslog(LOG_ERR, "Cannot find user ID %s", user);
642                         return 0;
643                 }
644
645         } else {
646 getuser:
647                 errno = 0;
648                 if ((pw = getpwnam(user)) != NULL) {
649                         sw_uid = pw->pw_uid;
650                         sw_gid = pw->pw_gid;
651                 } else {
652                         if (errno)
653                                 msyslog(LOG_ERR, "getpwnam(%s) failed: %m", user);
654                         else
655                                 msyslog(LOG_ERR, "Cannot find user `%s'", user);
656                         return 0;
657                 }
658         }
659
660         return 1;
661 }
662
663 /*
664  * Map group name/number to group ID
665 */
666 static int
667 map_group(void)
668 {
669         char *endp;
670
671         if (isdigit((unsigned char)*group)) {
672                 sw_gid = (gid_t)strtoul(group, &endp, 0);
673                 if (*endp != '\0')
674                         goto getgroup;
675         } else {
676 getgroup:
677                 if ((gr = getgrnam(group)) != NULL) {
678                         sw_gid = gr->gr_gid;
679                 } else {
680                         errno = 0;
681                         msyslog(LOG_ERR, "Cannot find group `%s'", group);
682                         return 0;
683                 }
684         }
685
686         return 1;
687 }
688
689 static int
690 set_group_ids(void)
691 {
692         if (user && initgroups(user, sw_gid)) {
693                 msyslog(LOG_ERR, "Cannot initgroups() to user `%s': %m", user);
694                 return 0;
695         }
696         if (group && setgid(sw_gid)) {
697                 msyslog(LOG_ERR, "Cannot setgid() to group `%s': %m", group);
698                 return 0;
699         }
700         if (group && setegid(sw_gid)) {
701                 msyslog(LOG_ERR, "Cannot setegid() to group `%s': %m", group);
702                 return 0;
703         }
704         if (group) {
705                 if (0 != setgroups(1, &sw_gid)) {
706                         msyslog(LOG_ERR, "setgroups(1, %d) failed: %m", sw_gid);
707                         return 0;
708                 }
709         }
710         else if (pw)
711                 if (0 != initgroups(pw->pw_name, pw->pw_gid)) {
712                         msyslog(LOG_ERR, "initgroups(<%s>, %d) filed: %m", pw->pw_name, pw->pw_gid);
713                         return 0;
714                 }
715         return 1;
716 }
717
718 static int
719 set_user_ids(void)
720 {
721         if (user && setuid(sw_uid)) {
722                 msyslog(LOG_ERR, "Cannot setuid() to user `%s': %m", user);
723                 return 0;
724         }
725         if (user && seteuid(sw_uid)) {
726                 msyslog(LOG_ERR, "Cannot seteuid() to user `%s': %m", user);
727                 return 0;
728         }
729         return 1;
730 }
731
732 /*
733  * Change (effective) user and group IDs, also initialize the supplementary group access list
734  */
735 int set_user_group_ids(void);
736 int
737 set_user_group_ids(void)
738 {
739         /* If the the user was already mapped, no need to map it again */
740         if ((NULL != user) && (0 == sw_uid)) {
741                 if (0 == map_user())
742                         exit (-1);
743         }
744         /* same applies for the group */
745         if ((NULL != group) && (0 == sw_gid)) {
746                 if (0 == map_group())
747                         exit (-1);
748         }
749
750         if (getegid() != sw_gid && 0 == set_group_ids())
751                 return 0;
752         if (geteuid() != sw_uid && 0 == set_user_ids())
753                 return 0;
754
755         return 1;
756 }
757 #endif /* HAVE_DROPROOT */
758 #endif /* !SIM */
759
760 /*
761  * Main program.  Initialize us, disconnect us from the tty if necessary,
762  * and loop waiting for I/O and/or timer expiries.
763  */
764 #ifndef SIM
765 int
766 ntpdmain(
767         int argc,
768         char *argv[]
769         )
770 {
771         l_fp            now;
772         struct recvbuf *rbuf;
773         const char *    logfilename;
774 # ifdef HAVE_UMASK
775         mode_t          uv;
776 # endif
777 # if defined(HAVE_GETUID) && !defined(MPE) /* MPE lacks the concept of root */
778         uid_t           uid;
779 # endif
780 # if defined(HAVE_WORKING_FORK)
781         long            wait_sync = 0;
782         int             pipe_fds[2];
783         int             rc;
784         int             exit_code;
785 # endif /* HAVE_WORKING_FORK*/
786 # ifdef SCO5_CLOCK
787         int             fd;
788         int             zero;
789 # endif
790
791 # ifdef NEED_PTHREAD_WARMUP
792         my_pthread_warmup();
793 # endif
794         
795 # ifdef HAVE_UMASK
796         uv = umask(0);
797         if (uv)
798                 umask(uv);
799         else
800                 umask(022);
801 # endif
802         saved_argc = argc;
803         saved_argv = argv;
804         progname = argv[0];
805         initializing = TRUE;            /* mark that we are initializing */
806         parse_cmdline_opts(&argc, &argv);
807 # ifdef DEBUG
808         debug = OPT_VALUE_SET_DEBUG_LEVEL;
809 #  ifdef HAVE_SETLINEBUF
810         setlinebuf(stdout);
811 #  endif
812 # endif
813
814         if (HAVE_OPT(NOFORK) || HAVE_OPT(QUIT)
815 # ifdef DEBUG
816             || debug
817 # endif
818             || HAVE_OPT(SAVECONFIGQUIT))
819                 nofork = TRUE;
820
821         init_logging(progname, NLOG_SYNCMASK, TRUE);
822         /* honor -l/--logfile option to log to a file */
823         if (HAVE_OPT(LOGFILE)) {
824                 logfilename = OPT_ARG(LOGFILE);
825                 syslogit = FALSE;
826                 change_logfile(logfilename, FALSE);
827         } else {
828                 logfilename = NULL;
829                 if (nofork)
830                         msyslog_term = TRUE;
831                 if (HAVE_OPT(SAVECONFIGQUIT))
832                         syslogit = FALSE;
833         }
834         msyslog(LOG_NOTICE, "%s: Starting", Version);
835
836         {
837                 int i;
838                 char buf[1024]; /* Secret knowledge of msyslog buf length */
839                 char *cp = buf;
840
841                 /* Note that every arg has an initial space character */
842                 snprintf(cp, sizeof(buf), "Command line:");
843                 cp += strlen(cp);
844
845                 for (i = 0; i < saved_argc ; ++i) {
846                         snprintf(cp, sizeof(buf) - (cp - buf),
847                                 " %s", saved_argv[i]);
848                         cp += strlen(cp);
849                 }
850                 msyslog(LOG_INFO, "%s", buf);
851         }
852
853         /*
854          * Install trap handlers to log errors and assertion failures.
855          * Default handlers print to stderr which doesn't work if detached.
856          */
857         isc_assertion_setcallback(assertion_failed);
858         isc_error_setfatal(library_fatal_error);
859         isc_error_setunexpected(library_unexpected_error);
860
861         /* MPE lacks the concept of root */
862 # if defined(HAVE_GETUID) && !defined(MPE)
863         uid = getuid();
864         if (uid && !HAVE_OPT( SAVECONFIGQUIT )) {
865                 msyslog_term = TRUE;
866                 msyslog(LOG_ERR,
867                         "must be run as root, not uid %ld", (long)uid);
868                 exit(1);
869         }
870 # endif
871
872 /*
873  * Enable the Multi-Media Timer for Windows?
874  */
875 # ifdef SYS_WINNT
876         if (HAVE_OPT( MODIFYMMTIMER ))
877                 set_mm_timer(MM_TIMER_HIRES);
878 # endif
879
880 #ifdef HAVE_DNSREGISTRATION
881 /*
882  * Enable mDNS registrations?
883  */
884         if (HAVE_OPT( MDNS )) {
885                 mdnsreg = TRUE;
886         }
887 #endif  /* HAVE_DNSREGISTRATION */
888
889         if (HAVE_OPT( NOVIRTUALIPS ))
890                 listen_to_virtual_ips = 0;
891
892         /*
893          * --interface, listen on specified interfaces
894          */
895         if (HAVE_OPT( INTERFACE )) {
896                 int             ifacect = STACKCT_OPT( INTERFACE );
897                 const char**    ifaces  = STACKLST_OPT( INTERFACE );
898                 sockaddr_u      addr;
899
900                 while (ifacect-- > 0) {
901                         add_nic_rule(
902                                 is_ip_address(*ifaces, AF_UNSPEC, &addr)
903                                         ? MATCH_IFADDR
904                                         : MATCH_IFNAME,
905                                 *ifaces, -1, ACTION_LISTEN);
906                         ifaces++;
907                 }
908         }
909
910         if (HAVE_OPT( NICE ))
911                 priority_done = 0;
912
913 # ifdef HAVE_SCHED_SETSCHEDULER
914         if (HAVE_OPT( PRIORITY )) {
915                 config_priority = OPT_VALUE_PRIORITY;
916                 config_priority_override = 1;
917                 priority_done = 0;
918         }
919 # endif
920
921 # ifdef HAVE_WORKING_FORK
922         /* make sure the FDs are initialised */
923         pipe_fds[0] = -1;
924         pipe_fds[1] = -1;
925         do {                                    /* 'loop' once */
926                 if (!HAVE_OPT( WAIT_SYNC ))
927                         break;
928                 wait_sync = OPT_VALUE_WAIT_SYNC;
929                 if (wait_sync <= 0) {
930                         wait_sync = 0;
931                         break;
932                 }
933                 /* -w requires a fork() even with debug > 0 */
934                 nofork = FALSE;
935                 if (pipe(pipe_fds)) {
936                         exit_code = (errno) ? errno : -1;
937                         msyslog(LOG_ERR,
938                                 "Pipe creation failed for --wait-sync: %m");
939                         exit(exit_code);
940                 }
941                 waitsync_fd_to_close = pipe_fds[1];
942         } while (0);                            /* 'loop' once */
943 # endif /* HAVE_WORKING_FORK */
944
945         init_lib();
946 # ifdef SYS_WINNT
947         /*
948          * Make sure the service is initialized before we do anything else
949          */
950         ntservice_init();
951
952         /*
953          * Start interpolation thread, must occur before first
954          * get_systime()
955          */
956         init_winnt_time();
957 # endif
958         /*
959          * Initialize random generator and public key pair
960          */
961         get_systime(&now);
962
963         ntp_srandom((int)(now.l_i * now.l_uf));
964
965         /*
966          * Detach us from the terminal.  May need an #ifndef GIZMO.
967          */
968         if (!nofork) {
969
970 # ifdef HAVE_WORKING_FORK
971                 detach_from_terminal(pipe_fds, wait_sync, logfilename);
972 # endif         /* HAVE_WORKING_FORK */
973         }
974
975 # ifdef SCO5_CLOCK
976         /*
977          * SCO OpenServer's system clock offers much more precise timekeeping
978          * on the base CPU than the other CPUs (for multiprocessor systems),
979          * so we must lock to the base CPU.
980          */
981         fd = open("/dev/at1", O_RDONLY);                
982         if (fd >= 0) {
983                 zero = 0;
984                 if (ioctl(fd, ACPU_LOCK, &zero) < 0)
985                         msyslog(LOG_ERR, "cannot lock to base CPU: %m");
986                 close(fd);
987         }
988 # endif
989
990         /* Setup stack size in preparation for locking pages in memory. */
991 # if defined(HAVE_MLOCKALL)
992 #  ifdef HAVE_SETRLIMIT
993         ntp_rlimit(RLIMIT_STACK, DFLT_RLIMIT_STACK * 4096, 4096, "4k");
994 #   ifdef RLIMIT_MEMLOCK
995         /*
996          * The default RLIMIT_MEMLOCK is very low on Linux systems.
997          * Unless we increase this limit malloc calls are likely to
998          * fail if we drop root privilege.  To be useful the value
999          * has to be larger than the largest ntpd resident set size.
1000          */
1001         ntp_rlimit(RLIMIT_MEMLOCK, DFLT_RLIMIT_MEMLOCK * 1024 * 1024, 1024 * 1024, "MB");
1002 #   endif       /* RLIMIT_MEMLOCK */
1003 #  endif        /* HAVE_SETRLIMIT */
1004 # else  /* !HAVE_MLOCKALL follows */
1005 #  ifdef HAVE_PLOCK
1006 #   ifdef PROCLOCK
1007 #    ifdef _AIX
1008         /*
1009          * set the stack limit for AIX for plock().
1010          * see get_aix_stack() for more info.
1011          */
1012         if (ulimit(SET_STACKLIM, (get_aix_stack() - 8 * 4096)) < 0)
1013                 msyslog(LOG_ERR,
1014                         "Cannot adjust stack limit for plock: %m");
1015 #    endif      /* _AIX */
1016 #   endif       /* PROCLOCK */
1017 #  endif        /* HAVE_PLOCK */
1018 # endif /* !HAVE_MLOCKALL */
1019
1020         /*
1021          * Set up signals we pay attention to locally.
1022          */
1023 # ifdef SIGDIE1
1024         signal_no_reset(SIGDIE1, finish);
1025         signal_no_reset(SIGDIE2, finish);
1026         signal_no_reset(SIGDIE3, finish);
1027         signal_no_reset(SIGDIE4, finish);
1028 # endif
1029 # ifdef SIGBUS
1030         signal_no_reset(SIGBUS, finish);
1031 # endif
1032
1033 # if !defined(SYS_WINNT) && !defined(VMS)
1034 #  ifdef DEBUG
1035         (void) signal_no_reset(MOREDEBUGSIG, moredebug);
1036         (void) signal_no_reset(LESSDEBUGSIG, lessdebug);
1037 #  else
1038         (void) signal_no_reset(MOREDEBUGSIG, no_debug);
1039         (void) signal_no_reset(LESSDEBUGSIG, no_debug);
1040 #  endif        /* DEBUG */
1041 # endif /* !SYS_WINNT && !VMS */
1042
1043         /*
1044          * Set up signals we should never pay attention to.
1045          */
1046 # ifdef SIGPIPE
1047         signal_no_reset(SIGPIPE, SIG_IGN);
1048 # endif
1049
1050         /*
1051          * Call the init_ routines to initialize the data structures.
1052          *
1053          * Exactly what command-line options are we expecting here?
1054          */
1055         INIT_SSL();
1056         init_auth();
1057         init_util();
1058         init_restrict();
1059         init_mon();
1060         init_timer();
1061         init_request();
1062         init_control();
1063         init_peer();
1064 # ifdef REFCLOCK
1065         init_refclock();
1066 # endif
1067         set_process_priority();
1068         init_proto();           /* Call at high priority */
1069         init_io();
1070         init_loopfilter();
1071         mon_start(MON_ON);      /* monitor on by default now      */
1072                                 /* turn off in config if unwanted */
1073
1074         /*
1075          * Get the configuration.  This is done in a separate module
1076          * since this will definitely be different for the gizmo board.
1077          */
1078         getconfig(argc, argv);
1079
1080         if (-1 == cur_memlock) {
1081 # if defined(HAVE_MLOCKALL)
1082                 /*
1083                  * lock the process into memory
1084                  */
1085                 if (   !HAVE_OPT(SAVECONFIGQUIT)
1086 #  ifdef RLIMIT_MEMLOCK
1087                     && -1 != DFLT_RLIMIT_MEMLOCK
1088 #  endif
1089                     && 0 != mlockall(MCL_CURRENT|MCL_FUTURE))
1090                         msyslog(LOG_ERR, "mlockall(): %m");
1091 # else  /* !HAVE_MLOCKALL follows */
1092 #  ifdef HAVE_PLOCK
1093 #   ifdef PROCLOCK
1094                 /*
1095                  * lock the process into memory
1096                  */
1097                 if (!HAVE_OPT(SAVECONFIGQUIT) && 0 != plock(PROCLOCK))
1098                         msyslog(LOG_ERR, "plock(PROCLOCK): %m");
1099 #   else        /* !PROCLOCK follows  */
1100 #    ifdef TXTLOCK
1101                 /*
1102                  * Lock text into ram
1103                  */
1104                 if (!HAVE_OPT(SAVECONFIGQUIT) && 0 != plock(TXTLOCK))
1105                         msyslog(LOG_ERR, "plock(TXTLOCK) error: %m");
1106 #    else       /* !TXTLOCK follows */
1107                 msyslog(LOG_ERR, "plock() - don't know what to lock!");
1108 #    endif      /* !TXTLOCK */
1109 #   endif       /* !PROCLOCK */
1110 #  endif        /* HAVE_PLOCK */
1111 # endif /* !HAVE_MLOCKALL */
1112         }
1113
1114         loop_config(LOOP_DRIFTINIT, 0);
1115         report_event(EVNT_SYSRESTART, NULL, NULL);
1116         initializing = FALSE;
1117
1118 # ifdef HAVE_DROPROOT
1119         if (droproot) {
1120
1121 #ifdef NEED_EARLY_FORK
1122                 fork_nonchroot_worker();
1123 #endif
1124
1125                 /* Drop super-user privileges and chroot now if the OS supports this */
1126
1127 #  ifdef HAVE_LINUX_CAPABILITIES
1128                 /* set flag: keep privileges accross setuid() call (we only really need cap_sys_time): */
1129                 if (prctl( PR_SET_KEEPCAPS, 1L, 0L, 0L, 0L ) == -1) {
1130                         msyslog( LOG_ERR, "prctl( PR_SET_KEEPCAPS, 1L ) failed: %m" );
1131                         exit(-1);
1132                 }
1133 #  elif HAVE_SOLARIS_PRIVS
1134                 /* Nothing to do here */
1135 #  else
1136                 /* we need a user to switch to */
1137                 if (user == NULL) {
1138                         msyslog(LOG_ERR, "Need user name to drop root privileges (see -u flag!)" );
1139                         exit(-1);
1140                 }
1141 #  endif        /* HAVE_LINUX_CAPABILITIES || HAVE_SOLARIS_PRIVS */
1142
1143                 if (user != NULL) {
1144                         if (0 == map_user())
1145                                 exit (-1);
1146                 }
1147                 if (group != NULL) {
1148                         if (0 == map_group())
1149                                 exit (-1);
1150                 }
1151
1152                 if (chrootdir ) {
1153                         /* make sure cwd is inside the jail: */
1154                         if (chdir(chrootdir)) {
1155                                 msyslog(LOG_ERR, "Cannot chdir() to `%s': %m", chrootdir);
1156                                 exit (-1);
1157                         }
1158                         if (chroot(chrootdir)) {
1159                                 msyslog(LOG_ERR, "Cannot chroot() to `%s': %m", chrootdir);
1160                                 exit (-1);
1161                         }
1162                         if (chdir("/")) {
1163                                 msyslog(LOG_ERR, "Cannot chdir() to`root after chroot(): %m");
1164                                 exit (-1);
1165                         }
1166                 }
1167 #  ifdef HAVE_SOLARIS_PRIVS
1168                 if ((lowprivs = priv_str_to_set(LOWPRIVS, ",", NULL)) == NULL) {
1169                         msyslog(LOG_ERR, "priv_str_to_set() failed:%m");
1170                         exit(-1);
1171                 }
1172                 if ((highprivs = priv_allocset()) == NULL) {
1173                         msyslog(LOG_ERR, "priv_allocset() failed:%m");
1174                         exit(-1);
1175                 }
1176                 (void) getppriv(PRIV_PERMITTED, highprivs);
1177                 (void) priv_intersect(highprivs, lowprivs);
1178                 if (setppriv(PRIV_SET, PRIV_PERMITTED, lowprivs) == -1) {
1179                         msyslog(LOG_ERR, "setppriv() failed:%m");
1180                         exit(-1);
1181                 }
1182 #  endif /* HAVE_SOLARIS_PRIVS */
1183                 if (0 == set_user_group_ids())
1184                         exit(-1);
1185
1186 #  if !defined(HAVE_LINUX_CAPABILITIES) && !defined(HAVE_SOLARIS_PRIVS)
1187                 /*
1188                  * for now assume that the privilege to bind to privileged ports
1189                  * is associated with running with uid 0 - should be refined on
1190                  * ports that allow binding to NTP_PORT with uid != 0
1191                  */
1192                 disable_dynamic_updates |= (sw_uid != 0);  /* also notifies routing message listener */
1193 #  endif /* !HAVE_LINUX_CAPABILITIES && !HAVE_SOLARIS_PRIVS */
1194
1195                 if (disable_dynamic_updates && interface_interval) {
1196                         interface_interval = 0;
1197                         msyslog(LOG_INFO, "running as non-root disables dynamic interface tracking");
1198                 }
1199
1200 #  ifdef HAVE_LINUX_CAPABILITIES
1201                 {
1202                         /*
1203                          *  We may be running under non-root uid now, but we still hold full root privileges!
1204                          *  We drop all of them, except for the crucial one or two: cap_sys_time and
1205                          *  cap_net_bind_service if doing dynamic interface tracking.
1206                          */
1207                         cap_t caps;
1208                         char *captext;
1209                         
1210                         captext = (0 != interface_interval)
1211                                       ? "cap_sys_time,cap_net_bind_service=pe"
1212                                       : "cap_sys_time=pe";
1213                         caps = cap_from_text(captext);
1214                         if (!caps) {
1215                                 msyslog(LOG_ERR,
1216                                         "cap_from_text(%s) failed: %m",
1217                                         captext);
1218                                 exit(-1);
1219                         }
1220                         if (-1 == cap_set_proc(caps)) {
1221                                 msyslog(LOG_ERR,
1222                                         "cap_set_proc() failed to drop root privs: %m");
1223                                 exit(-1);
1224                         }
1225                         cap_free(caps);
1226                 }
1227 #  endif        /* HAVE_LINUX_CAPABILITIES */
1228 #  ifdef HAVE_SOLARIS_PRIVS
1229                 if (priv_delset(lowprivs, "proc_setid") == -1) {
1230                         msyslog(LOG_ERR, "priv_delset() failed:%m");
1231                         exit(-1);
1232                 }
1233                 if (setppriv(PRIV_SET, PRIV_PERMITTED, lowprivs) == -1) {
1234                         msyslog(LOG_ERR, "setppriv() failed:%m");
1235                         exit(-1);
1236                 }
1237                 priv_freeset(lowprivs);
1238                 priv_freeset(highprivs);
1239 #  endif /* HAVE_SOLARIS_PRIVS */
1240                 root_dropped = TRUE;
1241                 fork_deferred_worker();
1242         }       /* if (droproot) */
1243 # endif /* HAVE_DROPROOT */
1244
1245 /* libssecomp sandboxing */
1246 #if defined (LIBSECCOMP) && (KERN_SECCOMP)
1247         scmp_filter_ctx ctx;
1248
1249         if ((ctx = seccomp_init(SCMP_ACT_KILL)) < 0)
1250                 msyslog(LOG_ERR, "%s: seccomp_init(SCMP_ACT_KILL) failed: %m", __func__);
1251         else {
1252                 msyslog(LOG_DEBUG, "%s: seccomp_init(SCMP_ACT_KILL) succeeded", __func__);
1253         }
1254
1255 #ifdef __x86_64__
1256 int scmp_sc[] = {
1257         SCMP_SYS(adjtimex),
1258         SCMP_SYS(bind),
1259         SCMP_SYS(brk),
1260         SCMP_SYS(chdir),
1261         SCMP_SYS(clock_gettime),
1262         SCMP_SYS(clock_settime),
1263         SCMP_SYS(close),
1264         SCMP_SYS(connect),
1265         SCMP_SYS(exit_group),
1266         SCMP_SYS(fstat),
1267         SCMP_SYS(fsync),
1268         SCMP_SYS(futex),
1269         SCMP_SYS(getitimer),
1270         SCMP_SYS(getsockname),
1271         SCMP_SYS(ioctl),
1272         SCMP_SYS(lseek),
1273         SCMP_SYS(madvise),
1274         SCMP_SYS(mmap),
1275         SCMP_SYS(munmap),
1276         SCMP_SYS(open),
1277         SCMP_SYS(poll),
1278         SCMP_SYS(read),
1279         SCMP_SYS(recvmsg),
1280         SCMP_SYS(rename),
1281         SCMP_SYS(rt_sigaction),
1282         SCMP_SYS(rt_sigprocmask),
1283         SCMP_SYS(rt_sigreturn),
1284         SCMP_SYS(select),
1285         SCMP_SYS(sendto),
1286         SCMP_SYS(setitimer),
1287         SCMP_SYS(setsid),
1288         SCMP_SYS(socket),
1289         SCMP_SYS(stat),
1290         SCMP_SYS(time),
1291         SCMP_SYS(write),
1292 };
1293 #endif
1294 #ifdef __i386__
1295 int scmp_sc[] = {
1296         SCMP_SYS(_newselect),
1297         SCMP_SYS(adjtimex),
1298         SCMP_SYS(brk),
1299         SCMP_SYS(chdir),
1300         SCMP_SYS(clock_gettime),
1301         SCMP_SYS(clock_settime),
1302         SCMP_SYS(close),
1303         SCMP_SYS(exit_group),
1304         SCMP_SYS(fsync),
1305         SCMP_SYS(futex),
1306         SCMP_SYS(getitimer),
1307         SCMP_SYS(madvise),
1308         SCMP_SYS(mmap),
1309         SCMP_SYS(mmap2),
1310         SCMP_SYS(munmap),
1311         SCMP_SYS(open),
1312         SCMP_SYS(poll),
1313         SCMP_SYS(read),
1314         SCMP_SYS(rename),
1315         SCMP_SYS(rt_sigaction),
1316         SCMP_SYS(rt_sigprocmask),
1317         SCMP_SYS(select),
1318         SCMP_SYS(setitimer),
1319         SCMP_SYS(setsid),
1320         SCMP_SYS(sigprocmask),
1321         SCMP_SYS(sigreturn),
1322         SCMP_SYS(socketcall),
1323         SCMP_SYS(stat64),
1324         SCMP_SYS(time),
1325         SCMP_SYS(write),
1326 };
1327 #endif
1328         {
1329                 int i;
1330
1331                 for (i = 0; i < COUNTOF(scmp_sc); i++) {
1332                         if (seccomp_rule_add(ctx,
1333                             SCMP_ACT_ALLOW, scmp_sc[i], 0) < 0) {
1334                                 msyslog(LOG_ERR,
1335                                     "%s: seccomp_rule_add() failed: %m",
1336                                     __func__);
1337                         }
1338                 }
1339         }
1340
1341         if (seccomp_load(ctx) < 0)
1342                 msyslog(LOG_ERR, "%s: seccomp_load() failed: %m",
1343                     __func__);  
1344         else {
1345                 msyslog(LOG_DEBUG, "%s: seccomp_load() succeeded", __func__);
1346         }
1347 #endif /* LIBSECCOMP and KERN_SECCOMP */
1348
1349 #ifdef SYS_WINNT
1350         ntservice_isup();
1351 #endif
1352
1353 # ifdef HAVE_IO_COMPLETION_PORT
1354
1355         for (;;) {
1356 #if !defined(SIM) && defined(SIGDIE1)
1357                 if (signalled)
1358                         finish_safe(signo);
1359 #endif
1360                 GetReceivedBuffers();
1361 # else /* normal I/O */
1362
1363         BLOCK_IO_AND_ALARM();
1364         was_alarmed = FALSE;
1365
1366         for (;;) {
1367 #if !defined(SIM) && defined(SIGDIE1)
1368                 if (signalled)
1369                         finish_safe(signo);
1370 #endif          
1371                 if (alarm_flag) {       /* alarmed? */
1372                         was_alarmed = TRUE;
1373                         alarm_flag = FALSE;
1374                 }
1375
1376                 /* collect async name/addr results */
1377                 if (!was_alarmed)
1378                     harvest_blocking_responses();
1379                 
1380                 if (!was_alarmed && !has_full_recv_buffer()) {
1381                         /*
1382                          * Nothing to do.  Wait for something.
1383                          */
1384                         io_handler();
1385                 }
1386
1387                 if (alarm_flag) {       /* alarmed? */
1388                         was_alarmed = TRUE;
1389                         alarm_flag = FALSE;
1390                 }
1391
1392                 if (was_alarmed) {
1393                         UNBLOCK_IO_AND_ALARM();
1394                         /*
1395                          * Out here, signals are unblocked.  Call timer routine
1396                          * to process expiry.
1397                          */
1398                         timer();
1399                         was_alarmed = FALSE;
1400                         BLOCK_IO_AND_ALARM();
1401                 }
1402
1403 # endif         /* !HAVE_IO_COMPLETION_PORT */
1404
1405 # ifdef DEBUG_TIMING
1406                 {
1407                         l_fp pts;
1408                         l_fp tsa, tsb;
1409                         int bufcount = 0;
1410
1411                         get_systime(&pts);
1412                         tsa = pts;
1413 # endif
1414                         rbuf = get_full_recv_buffer();
1415                         while (rbuf != NULL) {
1416                                 if (alarm_flag) {
1417                                         was_alarmed = TRUE;
1418                                         alarm_flag = FALSE;
1419                                 }
1420                                 UNBLOCK_IO_AND_ALARM();
1421
1422                                 if (was_alarmed) {
1423                                         /* avoid timer starvation during lengthy I/O handling */
1424                                         timer();
1425                                         was_alarmed = FALSE;
1426                                 }
1427
1428                                 /*
1429                                  * Call the data procedure to handle each received
1430                                  * packet.
1431                                  */
1432                                 if (rbuf->receiver != NULL) {
1433 # ifdef DEBUG_TIMING
1434                                         l_fp dts = pts;
1435
1436                                         L_SUB(&dts, &rbuf->recv_time);
1437                                         DPRINTF(2, ("processing timestamp delta %s (with prec. fuzz)\n", lfptoa(&dts, 9)));
1438                                         collect_timing(rbuf, "buffer processing delay", 1, &dts);
1439                                         bufcount++;
1440 # endif
1441                                         (*rbuf->receiver)(rbuf);
1442                                 } else {
1443                                         msyslog(LOG_ERR, "fatal: receive buffer callback NULL");
1444                                         abort();
1445                                 }
1446
1447                                 BLOCK_IO_AND_ALARM();
1448                                 freerecvbuf(rbuf);
1449                                 rbuf = get_full_recv_buffer();
1450                         }
1451 # ifdef DEBUG_TIMING
1452                         get_systime(&tsb);
1453                         L_SUB(&tsb, &tsa);
1454                         if (bufcount) {
1455                                 collect_timing(NULL, "processing", bufcount, &tsb);
1456                                 DPRINTF(2, ("processing time for %d buffers %s\n", bufcount, lfptoa(&tsb, 9)));
1457                         }
1458                 }
1459 # endif
1460
1461                 /*
1462                  * Go around again
1463                  */
1464
1465 # ifdef HAVE_DNSREGISTRATION
1466                 if (mdnsreg && (current_time - mdnsreg ) > 60 && mdnstries && sys_leap != LEAP_NOTINSYNC) {
1467                         mdnsreg = current_time;
1468                         msyslog(LOG_INFO, "Attempting to register mDNS");
1469                         if ( DNSServiceRegister (&mdns, 0, 0, NULL, "_ntp._udp", NULL, NULL, 
1470                             htons(NTP_PORT), 0, NULL, NULL, NULL) != kDNSServiceErr_NoError ) {
1471                                 if (!--mdnstries) {
1472                                         msyslog(LOG_ERR, "Unable to register mDNS, giving up.");
1473                                 } else {        
1474                                         msyslog(LOG_INFO, "Unable to register mDNS, will try later.");
1475                                 }
1476                         } else {
1477                                 msyslog(LOG_INFO, "mDNS service registered.");
1478                                 mdnsreg = FALSE;
1479                         }
1480                 }
1481 # endif /* HAVE_DNSREGISTRATION */
1482
1483         }
1484         UNBLOCK_IO_AND_ALARM();
1485         return 1;
1486 }
1487 #endif  /* !SIM */
1488
1489
1490 #if !defined(SIM) && defined(SIGDIE1)
1491 /*
1492  * finish - exit gracefully
1493  */
1494 static void
1495 finish_safe(
1496         int     sig
1497         )
1498 {
1499         const char *sig_desc;
1500
1501         sig_desc = NULL;
1502 #ifdef HAVE_STRSIGNAL
1503         sig_desc = strsignal(sig);
1504 #endif
1505         if (sig_desc == NULL)
1506                 sig_desc = "";
1507         msyslog(LOG_NOTICE, "%s exiting on signal %d (%s)", progname,
1508                 sig, sig_desc);
1509         /* See Bug 2513 and Bug 2522 re the unlink of PIDFILE */
1510 # ifdef HAVE_DNSREGISTRATION
1511         if (mdns != NULL)
1512                 DNSServiceRefDeallocate(mdns);
1513 # endif
1514         peer_cleanup();
1515         exit(0);
1516 }
1517
1518 static RETSIGTYPE
1519 finish(
1520         int     sig
1521         )
1522 {
1523         signalled = 1;
1524         signo = sig;
1525 }
1526
1527 #endif  /* !SIM && SIGDIE1 */
1528
1529
1530 #ifndef SIM
1531 /*
1532  * wait_child_sync_if - implements parent side of -w/--wait-sync
1533  */
1534 # ifdef HAVE_WORKING_FORK
1535 static int
1536 wait_child_sync_if(
1537         int     pipe_read_fd,
1538         long    wait_sync
1539         )
1540 {
1541         int     rc;
1542         int     exit_code;
1543         time_t  wait_end_time;
1544         time_t  cur_time;
1545         time_t  wait_rem;
1546         fd_set  readset;
1547         struct timeval wtimeout;
1548
1549         if (0 == wait_sync) 
1550                 return 0;
1551
1552         /* waitsync_fd_to_close used solely by child */
1553         close(waitsync_fd_to_close);
1554         wait_end_time = time(NULL) + wait_sync;
1555         do {
1556                 cur_time = time(NULL);
1557                 wait_rem = (wait_end_time > cur_time)
1558                                 ? (wait_end_time - cur_time)
1559                                 : 0;
1560                 wtimeout.tv_sec = wait_rem;
1561                 wtimeout.tv_usec = 0;
1562                 FD_ZERO(&readset);
1563                 FD_SET(pipe_read_fd, &readset);
1564                 rc = select(pipe_read_fd + 1, &readset, NULL, NULL,
1565                             &wtimeout);
1566                 if (-1 == rc) {
1567                         if (EINTR == errno)
1568                                 continue;
1569                         exit_code = (errno) ? errno : -1;
1570                         msyslog(LOG_ERR,
1571                                 "--wait-sync select failed: %m");
1572                         return exit_code;
1573                 }
1574                 if (0 == rc) {
1575                         /*
1576                          * select() indicated a timeout, but in case
1577                          * its timeouts are affected by a step of the
1578                          * system clock, select() again with a zero 
1579                          * timeout to confirm.
1580                          */
1581                         FD_ZERO(&readset);
1582                         FD_SET(pipe_read_fd, &readset);
1583                         wtimeout.tv_sec = 0;
1584                         wtimeout.tv_usec = 0;
1585                         rc = select(pipe_read_fd + 1, &readset, NULL,
1586                                     NULL, &wtimeout);
1587                         if (0 == rc)    /* select() timeout */
1588                                 break;
1589                         else            /* readable */
1590                                 return 0;
1591                 } else                  /* readable */
1592                         return 0;
1593         } while (wait_rem > 0);
1594
1595         fprintf(stderr, "%s: -w/--wait-sync %ld timed out.\n",
1596                 progname, wait_sync);
1597         return ETIMEDOUT;
1598 }
1599 # endif /* HAVE_WORKING_FORK */
1600
1601
1602 /*
1603  * assertion_failed - Redirect assertion failures to msyslog().
1604  */
1605 static void
1606 assertion_failed(
1607         const char *file,
1608         int line,
1609         isc_assertiontype_t type,
1610         const char *cond
1611         )
1612 {
1613         isc_assertion_setcallback(NULL);    /* Avoid recursion */
1614
1615         msyslog(LOG_ERR, "%s:%d: %s(%s) failed",
1616                 file, line, isc_assertion_typetotext(type), cond);
1617         msyslog(LOG_ERR, "exiting (due to assertion failure)");
1618
1619 #if defined(DEBUG) && defined(SYS_WINNT)
1620         if (debug)
1621                 DebugBreak();
1622 #endif
1623
1624         abort();
1625 }
1626
1627
1628 /*
1629  * library_fatal_error - Handle fatal errors from our libraries.
1630  */
1631 static void
1632 library_fatal_error(
1633         const char *file,
1634         int line,
1635         const char *format,
1636         va_list args
1637         )
1638 {
1639         char errbuf[256];
1640
1641         isc_error_setfatal(NULL);  /* Avoid recursion */
1642
1643         msyslog(LOG_ERR, "%s:%d: fatal error:", file, line);
1644         vsnprintf(errbuf, sizeof(errbuf), format, args);
1645         msyslog(LOG_ERR, "%s", errbuf);
1646         msyslog(LOG_ERR, "exiting (due to fatal error in library)");
1647
1648 #if defined(DEBUG) && defined(SYS_WINNT)
1649         if (debug)
1650                 DebugBreak();
1651 #endif
1652
1653         abort();
1654 }
1655
1656
1657 /*
1658  * library_unexpected_error - Handle non fatal errors from our libraries.
1659  */
1660 # define MAX_UNEXPECTED_ERRORS 100
1661 int unexpected_error_cnt = 0;
1662 static void
1663 library_unexpected_error(
1664         const char *file,
1665         int line,
1666         const char *format,
1667         va_list args
1668         )
1669 {
1670         char errbuf[256];
1671
1672         if (unexpected_error_cnt >= MAX_UNEXPECTED_ERRORS)
1673                 return; /* avoid clutter in log */
1674
1675         msyslog(LOG_ERR, "%s:%d: unexpected error:", file, line);
1676         vsnprintf(errbuf, sizeof(errbuf), format, args);
1677         msyslog(LOG_ERR, "%s", errbuf);
1678
1679         if (++unexpected_error_cnt == MAX_UNEXPECTED_ERRORS)
1680                 msyslog(LOG_ERR, "Too many errors.  Shutting up.");
1681
1682 }
1683 #endif  /* !SIM */
1684
1685 #if !defined(SIM) && !defined(SYS_WINNT)
1686 # ifdef DEBUG
1687
1688 /*
1689  * moredebug - increase debugging verbosity
1690  */
1691 static RETSIGTYPE
1692 moredebug(
1693         int sig
1694         )
1695 {
1696         int saved_errno = errno;
1697
1698         if (debug < 255)
1699         {
1700                 debug++;
1701                 msyslog(LOG_DEBUG, "debug raised to %d", debug);
1702         }
1703         errno = saved_errno;
1704 }
1705
1706
1707 /*
1708  * lessdebug - decrease debugging verbosity
1709  */
1710 static RETSIGTYPE
1711 lessdebug(
1712         int sig
1713         )
1714 {
1715         int saved_errno = errno;
1716
1717         if (debug > 0)
1718         {
1719                 debug--;
1720                 msyslog(LOG_DEBUG, "debug lowered to %d", debug);
1721         }
1722         errno = saved_errno;
1723 }
1724
1725 # else  /* !DEBUG follows */
1726
1727
1728 /*
1729  * no_debug - We don't do the debug here.
1730  */
1731 static RETSIGTYPE
1732 no_debug(
1733         int sig
1734         )
1735 {
1736         int saved_errno = errno;
1737
1738         msyslog(LOG_DEBUG, "ntpd not compiled for debugging (signal %d)", sig);
1739         errno = saved_errno;
1740 }
1741 # endif /* !DEBUG */
1742 #endif  /* !SIM && !SYS_WINNT */