Home | History | Annotate | Line # | Download | only in sntp
main.c revision 1.16
      1  1.15  christos /*	$NetBSD: main.c,v 1.16 2018/04/07 00:19:53 christos Exp $	*/
      2   1.1    kardel 
      3   1.3    kardel #include <config.h>
      4   1.1    kardel 
      5   1.8  christos #include <event2/util.h>
      6   1.8  christos #include <event2/event.h>
      7   1.8  christos 
      8   1.8  christos #include "ntp_workimpl.h"
      9   1.8  christos #ifdef WORK_THREAD
     10   1.8  christos # include <event2/thread.h>
     11   1.8  christos #endif
     12   1.8  christos 
     13   1.3    kardel #include "main.h"
     14   1.8  christos #include "ntp_libopts.h"
     15   1.1    kardel #include "kod_management.h"
     16   1.1    kardel #include "networking.h"
     17   1.1    kardel #include "utilities.h"
     18   1.1    kardel #include "log.h"
     19   1.8  christos #include "libntp.h"
     20   1.1    kardel 
     21   1.8  christos 
     22   1.8  christos int shutting_down;
     23   1.8  christos int time_derived;
     24   1.8  christos int time_adjusted;
     25   1.8  christos int n_pending_dns = 0;
     26   1.8  christos int n_pending_ntp = 0;
     27   1.1    kardel int ai_fam_pref = AF_UNSPEC;
     28   1.8  christos int ntpver = 4;
     29   1.8  christos double steplimit = -1;
     30   1.8  christos SOCKET sock4 = -1;		/* Socket for IPv4 */
     31   1.8  christos SOCKET sock6 = -1;		/* Socket for IPv6 */
     32   1.8  christos /*
     33   1.8  christos ** BCAST *must* listen on port 123 (by default), so we can only
     34   1.8  christos ** use the UCST sockets (above) if they too are using port 123
     35   1.8  christos */
     36   1.8  christos SOCKET bsock4 = -1;		/* Broadcast Socket for IPv4 */
     37   1.8  christos SOCKET bsock6 = -1;		/* Broadcast Socket for IPv6 */
     38   1.8  christos struct event_base *base;
     39   1.8  christos struct event *ev_sock4;
     40   1.8  christos struct event *ev_sock6;
     41   1.8  christos struct event *ev_worker_timeout;
     42   1.8  christos struct event *ev_xmt_timer;
     43   1.8  christos 
     44   1.8  christos struct dns_ctx {
     45   1.8  christos 	const char *	name;
     46   1.8  christos 	int		flags;
     47   1.8  christos #define CTX_BCST	0x0001
     48   1.8  christos #define CTX_UCST	0x0002
     49   1.8  christos #define CTX_xCST	0x0003
     50   1.8  christos #define CTX_CONC	0x0004
     51   1.8  christos #define CTX_unused	0xfffd
     52   1.8  christos 	int		key_id;
     53   1.8  christos 	struct timeval	timeout;
     54   1.8  christos 	struct key *	key;
     55   1.8  christos };
     56   1.8  christos 
     57   1.8  christos typedef struct sent_pkt_tag sent_pkt;
     58   1.8  christos struct sent_pkt_tag {
     59   1.8  christos 	sent_pkt *		link;
     60   1.8  christos 	struct dns_ctx *	dctx;
     61   1.8  christos 	sockaddr_u		addr;
     62   1.8  christos 	time_t			stime;
     63   1.8  christos 	int			done;
     64   1.8  christos 	struct pkt		x_pkt;
     65   1.8  christos };
     66   1.8  christos 
     67   1.8  christos typedef struct xmt_ctx_tag xmt_ctx;
     68   1.8  christos struct xmt_ctx_tag {
     69   1.8  christos 	xmt_ctx *		link;
     70   1.8  christos 	SOCKET			sock;
     71   1.8  christos 	time_t			sched;
     72   1.8  christos 	sent_pkt *		spkt;
     73   1.8  christos };
     74   1.8  christos 
     75   1.8  christos struct timeval	gap;
     76   1.8  christos xmt_ctx *	xmt_q;
     77   1.8  christos struct key *	keys = NULL;
     78   1.8  christos int		response_timeout;
     79   1.8  christos struct timeval	response_tv;
     80   1.8  christos struct timeval	start_tv;
     81   1.8  christos /* check the timeout at least once per second */
     82   1.8  christos struct timeval	wakeup_tv = { 0, 888888 };
     83   1.8  christos 
     84   1.8  christos sent_pkt *	fam_listheads[2];
     85   1.8  christos #define v4_pkts_list	(fam_listheads[0])
     86   1.8  christos #define v6_pkts_list	(fam_listheads[1])
     87   1.8  christos 
     88   1.8  christos static union {
     89   1.8  christos 	struct pkt pkt;
     90  1.11  christos 	char   buf[LEN_PKT_NOMAC + NTP_MAXEXTEN + MAX_MAC_LEN];
     91   1.8  christos } rbuf;
     92   1.8  christos 
     93   1.8  christos #define r_pkt  rbuf.pkt
     94   1.1    kardel 
     95   1.8  christos #ifdef HAVE_DROPROOT
     96   1.8  christos int droproot;			/* intres imports these */
     97   1.8  christos int root_dropped;
     98   1.8  christos #endif
     99   1.8  christos u_long current_time;		/* libntp/authkeys.c */
    100   1.1    kardel 
    101   1.8  christos void open_sockets(void);
    102   1.8  christos void handle_lookup(const char *name, int flags);
    103   1.8  christos void sntp_addremove_fd(int fd, int is_pipe, int remove_it);
    104   1.8  christos void worker_timeout(evutil_socket_t, short, void *);
    105   1.8  christos void worker_resp_cb(evutil_socket_t, short, void *);
    106   1.8  christos void sntp_name_resolved(int, int, void *, const char *, const char *,
    107   1.8  christos 			const struct addrinfo *,
    108   1.8  christos 			const struct addrinfo *);
    109   1.8  christos void queue_xmt(SOCKET sock, struct dns_ctx *dctx, sent_pkt *spkt,
    110   1.8  christos 	       u_int xmt_delay);
    111   1.8  christos void xmt_timer_cb(evutil_socket_t, short, void *ptr);
    112   1.8  christos void xmt(xmt_ctx *xctx);
    113   1.8  christos int  check_kod(const struct addrinfo *ai);
    114   1.8  christos void timeout_query(sent_pkt *);
    115   1.8  christos void timeout_queries(void);
    116   1.8  christos void sock_cb(evutil_socket_t, short, void *);
    117   1.8  christos void check_exit_conditions(void);
    118   1.8  christos void sntp_libevent_log_cb(int, const char *);
    119   1.8  christos void set_li_vn_mode(struct pkt *spkt, char leap, char version, char mode);
    120   1.8  christos int  set_time(double offset);
    121   1.8  christos void dec_pending_ntp(const char *, sockaddr_u *);
    122   1.8  christos int  libevent_version_ok(void);
    123   1.8  christos int  gettimeofday_cached(struct event_base *b, struct timeval *tv);
    124   1.1    kardel 
    125   1.1    kardel 
    126   1.1    kardel /*
    127   1.1    kardel  * The actual main function.
    128   1.1    kardel  */
    129   1.8  christos int
    130   1.1    kardel sntp_main (
    131   1.8  christos 	int argc,
    132   1.8  christos 	char **argv,
    133   1.8  christos 	const char *sntpVersion
    134   1.8  christos 	)
    135   1.8  christos {
    136   1.8  christos 	int			i;
    137   1.8  christos 	int			exitcode;
    138   1.8  christos 	int			optct;
    139   1.8  christos 	struct event_config *	evcfg;
    140   1.8  christos 
    141   1.8  christos 	/* Initialize logging system - sets up progname */
    142   1.8  christos 	sntp_init_logging(argv[0]);
    143   1.8  christos 
    144   1.8  christos 	if (!libevent_version_ok())
    145   1.8  christos 		exit(EX_SOFTWARE);
    146   1.8  christos 
    147   1.8  christos 	init_lib();
    148   1.8  christos 	init_auth();
    149   1.1    kardel 
    150   1.8  christos 	optct = ntpOptionProcess(&sntpOptions, argc, argv);
    151   1.3    kardel 	argc -= optct;
    152   1.8  christos 	argv += optct;
    153   1.8  christos 
    154   1.8  christos 
    155   1.8  christos 	debug = OPT_VALUE_SET_DEBUG_LEVEL;
    156   1.8  christos 
    157   1.8  christos 	TRACE(2, ("init_lib() done, %s%s\n",
    158   1.8  christos 		  (ipv4_works)
    159   1.8  christos 		      ? "ipv4_works "
    160   1.8  christos 		      : "",
    161   1.8  christos 		  (ipv6_works)
    162   1.8  christos 		      ? "ipv6_works "
    163   1.8  christos 		      : ""));
    164   1.8  christos 	ntpver = OPT_VALUE_NTPVERSION;
    165   1.8  christos 	steplimit = OPT_VALUE_STEPLIMIT / 1e3;
    166   1.8  christos 	gap.tv_usec = max(0, OPT_VALUE_GAP * 1000);
    167   1.8  christos 	gap.tv_usec = min(gap.tv_usec, 999999);
    168   1.3    kardel 
    169   1.3    kardel 	if (HAVE_OPT(LOGFILE))
    170   1.3    kardel 		open_logfile(OPT_ARG(LOGFILE));
    171   1.3    kardel 
    172   1.8  christos 	msyslog(LOG_INFO, "%s", sntpVersion);
    173   1.8  christos 
    174   1.8  christos 	if (0 == argc && !HAVE_OPT(BROADCAST) && !HAVE_OPT(CONCURRENT)) {
    175   1.8  christos 		printf("%s: Must supply at least one of -b hostname, -c hostname, or hostname.\n",
    176   1.8  christos 		       progname);
    177   1.8  christos 		exit(EX_USAGE);
    178   1.8  christos 	}
    179   1.8  christos 
    180   1.8  christos 
    181   1.8  christos 	/*
    182   1.8  christos 	** Eventually, we probably want:
    183   1.8  christos 	** - separate bcst and ucst timeouts (why?)
    184   1.8  christos 	** - multiple --timeout values in the commandline
    185   1.8  christos 	*/
    186   1.8  christos 
    187   1.8  christos 	response_timeout = OPT_VALUE_TIMEOUT;
    188   1.8  christos 	response_tv.tv_sec = response_timeout;
    189   1.8  christos 	response_tv.tv_usec = 0;
    190   1.3    kardel 
    191   1.1    kardel 	/* IPv6 available? */
    192   1.1    kardel 	if (isc_net_probeipv6() != ISC_R_SUCCESS) {
    193   1.1    kardel 		ai_fam_pref = AF_INET;
    194   1.8  christos 		TRACE(1, ("No ipv6 support available, forcing ipv4\n"));
    195   1.3    kardel 	} else {
    196   1.1    kardel 		/* Check for options -4 and -6 */
    197   1.1    kardel 		if (HAVE_OPT(IPV4))
    198   1.1    kardel 			ai_fam_pref = AF_INET;
    199   1.1    kardel 		else if (HAVE_OPT(IPV6))
    200   1.1    kardel 			ai_fam_pref = AF_INET6;
    201   1.1    kardel 	}
    202   1.1    kardel 
    203   1.8  christos 	/* TODO: Parse config file if declared */
    204   1.1    kardel 
    205   1.8  christos 	/*
    206   1.8  christos 	** Init the KOD system.
    207   1.8  christos 	** For embedded systems with no writable filesystem,
    208   1.8  christos 	** -K /dev/null can be used to disable KoD storage.
    209   1.8  christos 	*/
    210   1.8  christos 	kod_init_kod_db(OPT_ARG(KOD), FALSE);
    211   1.1    kardel 
    212  1.16  christos 	/* HMS: Check and see what happens if KEYFILE doesn't exist */
    213  1.16  christos 	auth_init(OPT_ARG(KEYFILE), &keys);
    214   1.1    kardel 
    215   1.8  christos 	/*
    216   1.8  christos 	** Considering employing a variable that prevents functions of doing
    217   1.8  christos 	** anything until everything is initialized properly
    218   1.8  christos 	**
    219   1.8  christos 	** HMS: What exactly does the above mean?
    220   1.8  christos 	*/
    221   1.8  christos 	event_set_log_callback(&sntp_libevent_log_cb);
    222   1.8  christos 	if (debug > 0)
    223   1.8  christos 		event_enable_debug_mode();
    224   1.8  christos #ifdef WORK_THREAD
    225   1.8  christos 	evthread_use_pthreads();
    226   1.8  christos 	/* we use libevent from main thread only, locks should be academic */
    227   1.8  christos 	if (debug > 0)
    228   1.8  christos 		evthread_enable_lock_debuging();
    229   1.8  christos #endif
    230   1.8  christos 	evcfg = event_config_new();
    231   1.8  christos 	if (NULL == evcfg) {
    232   1.8  christos 		printf("%s: event_config_new() failed!\n", progname);
    233   1.8  christos 		return -1;
    234   1.8  christos 	}
    235   1.8  christos #ifndef HAVE_SOCKETPAIR
    236   1.8  christos 	event_config_require_features(evcfg, EV_FEATURE_FDS);
    237   1.8  christos #endif
    238   1.8  christos 	/* all libevent calls are from main thread */
    239   1.8  christos 	/* event_config_set_flag(evcfg, EVENT_BASE_FLAG_NOLOCK); */
    240   1.8  christos 	base = event_base_new_with_config(evcfg);
    241   1.8  christos 	event_config_free(evcfg);
    242   1.8  christos 	if (NULL == base) {
    243   1.8  christos 		printf("%s: event_base_new() failed!\n", progname);
    244   1.8  christos 		return -1;
    245   1.8  christos 	}
    246   1.8  christos 
    247   1.8  christos 	/* wire into intres resolver */
    248   1.8  christos 	worker_per_query = TRUE;
    249   1.8  christos 	addremove_io_fd = &sntp_addremove_fd;
    250   1.8  christos 
    251   1.8  christos 	open_sockets();
    252   1.8  christos 
    253   1.8  christos 	if (HAVE_OPT(BROADCAST)) {
    254   1.8  christos 		int		cn = STACKCT_OPT(  BROADCAST );
    255   1.8  christos 		const char **	cp = STACKLST_OPT( BROADCAST );
    256   1.8  christos 
    257   1.8  christos 		while (cn-- > 0) {
    258   1.8  christos 			handle_lookup(*cp, CTX_BCST);
    259   1.8  christos 			cp++;
    260   1.8  christos 		}
    261   1.8  christos 	}
    262   1.8  christos 
    263   1.8  christos 	if (HAVE_OPT(CONCURRENT)) {
    264   1.8  christos 		int		cn = STACKCT_OPT( CONCURRENT );
    265   1.8  christos 		const char **	cp = STACKLST_OPT( CONCURRENT );
    266   1.8  christos 
    267   1.8  christos 		while (cn-- > 0) {
    268   1.8  christos 			handle_lookup(*cp, CTX_UCST | CTX_CONC);
    269   1.8  christos 			cp++;
    270   1.8  christos 		}
    271   1.8  christos 	}
    272   1.8  christos 
    273   1.8  christos 	for (i = 0; i < argc; ++i)
    274   1.8  christos 		handle_lookup(argv[i], CTX_UCST);
    275   1.8  christos 
    276   1.8  christos 	gettimeofday_cached(base, &start_tv);
    277   1.8  christos 	event_base_dispatch(base);
    278   1.8  christos 	event_base_free(base);
    279   1.8  christos 
    280   1.8  christos 	if (!time_adjusted &&
    281   1.8  christos 	    (ENABLED_OPT(STEP) || ENABLED_OPT(SLEW)))
    282   1.8  christos 		exitcode = 1;
    283   1.1    kardel 	else
    284   1.8  christos 		exitcode = 0;
    285   1.8  christos 
    286   1.8  christos 	return exitcode;
    287   1.8  christos }
    288   1.8  christos 
    289   1.8  christos 
    290   1.8  christos /*
    291   1.8  christos ** open sockets and make them non-blocking
    292   1.8  christos */
    293   1.8  christos void
    294   1.8  christos open_sockets(
    295   1.8  christos 	void
    296   1.8  christos 	)
    297   1.8  christos {
    298   1.8  christos 	sockaddr_u	name;
    299   1.8  christos 
    300   1.8  christos 	if (-1 == sock4) {
    301   1.8  christos 		sock4 = socket(PF_INET, SOCK_DGRAM, 0);
    302   1.8  christos 		if (-1 == sock4) {
    303   1.8  christos 			/* error getting a socket */
    304   1.8  christos 			msyslog(LOG_ERR, "open_sockets: socket(PF_INET) failed: %m");
    305   1.8  christos 			exit(1);
    306   1.8  christos 		}
    307   1.8  christos 		/* Make it non-blocking */
    308   1.8  christos 		make_socket_nonblocking(sock4);
    309   1.8  christos 
    310   1.8  christos 		/* Let's try using a wildcard... */
    311   1.8  christos 		ZERO(name);
    312   1.8  christos 		AF(&name) = AF_INET;
    313   1.8  christos 		SET_ADDR4N(&name, INADDR_ANY);
    314   1.8  christos 		SET_PORT(&name, (HAVE_OPT(USERESERVEDPORT) ? 123 : 0));
    315   1.8  christos 
    316   1.8  christos 		if (-1 == bind(sock4, &name.sa,
    317   1.8  christos 			       SOCKLEN(&name))) {
    318   1.8  christos 			msyslog(LOG_ERR, "open_sockets: bind(sock4) failed: %m");
    319   1.8  christos 			exit(1);
    320   1.8  christos 		}
    321   1.8  christos 
    322   1.8  christos 		/* Register an NTP callback for recv/timeout */
    323   1.8  christos 		ev_sock4 = event_new(base, sock4,
    324   1.8  christos 				     EV_TIMEOUT | EV_READ | EV_PERSIST,
    325   1.8  christos 				     &sock_cb, NULL);
    326   1.8  christos 		if (NULL == ev_sock4) {
    327   1.8  christos 			msyslog(LOG_ERR,
    328   1.8  christos 				"open_sockets: event_new(base, sock4) failed!");
    329   1.8  christos 		} else {
    330   1.8  christos 			event_add(ev_sock4, &wakeup_tv);
    331   1.8  christos 		}
    332   1.8  christos 	}
    333   1.8  christos 
    334   1.8  christos 	/* We may not always have IPv6... */
    335   1.8  christos 	if (-1 == sock6 && ipv6_works) {
    336   1.8  christos 		sock6 = socket(PF_INET6, SOCK_DGRAM, 0);
    337   1.8  christos 		if (-1 == sock6 && ipv6_works) {
    338   1.8  christos 			/* error getting a socket */
    339   1.8  christos 			msyslog(LOG_ERR, "open_sockets: socket(PF_INET6) failed: %m");
    340   1.8  christos 			exit(1);
    341   1.8  christos 		}
    342   1.8  christos 		/* Make it non-blocking */
    343   1.8  christos 		make_socket_nonblocking(sock6);
    344   1.8  christos 
    345   1.8  christos 		/* Let's try using a wildcard... */
    346   1.8  christos 		ZERO(name);
    347   1.8  christos 		AF(&name) = AF_INET6;
    348   1.8  christos 		SET_ADDR6N(&name, in6addr_any);
    349   1.8  christos 		SET_PORT(&name, (HAVE_OPT(USERESERVEDPORT) ? 123 : 0));
    350   1.8  christos 
    351   1.8  christos 		if (-1 == bind(sock6, &name.sa,
    352   1.8  christos 			       SOCKLEN(&name))) {
    353   1.8  christos 			msyslog(LOG_ERR, "open_sockets: bind(sock6) failed: %m");
    354   1.8  christos 			exit(1);
    355   1.8  christos 		}
    356   1.8  christos 		/* Register an NTP callback for recv/timeout */
    357   1.8  christos 		ev_sock6 = event_new(base, sock6,
    358   1.8  christos 				     EV_TIMEOUT | EV_READ | EV_PERSIST,
    359   1.8  christos 				     &sock_cb, NULL);
    360   1.8  christos 		if (NULL == ev_sock6) {
    361   1.8  christos 			msyslog(LOG_ERR,
    362   1.8  christos 				"open_sockets: event_new(base, sock6) failed!");
    363   1.8  christos 		} else {
    364   1.8  christos 			event_add(ev_sock6, &wakeup_tv);
    365   1.8  christos 		}
    366   1.8  christos 	}
    367   1.8  christos 
    368   1.8  christos 	return;
    369   1.8  christos }
    370   1.8  christos 
    371   1.8  christos 
    372   1.8  christos /*
    373   1.8  christos ** handle_lookup
    374   1.8  christos */
    375   1.8  christos void
    376   1.8  christos handle_lookup(
    377   1.8  christos 	const char *name,
    378   1.8  christos 	int flags
    379   1.8  christos 	)
    380   1.8  christos {
    381   1.8  christos 	struct addrinfo	hints;	/* Local copy is OK */
    382   1.8  christos 	struct dns_ctx *ctx;
    383   1.8  christos 	char *		name_copy;
    384   1.8  christos 	size_t		name_sz;
    385   1.8  christos 	size_t		octets;
    386   1.8  christos 
    387   1.8  christos 	TRACE(1, ("handle_lookup(%s,%#x)\n", name, flags));
    388   1.8  christos 
    389   1.8  christos 	ZERO(hints);
    390   1.8  christos 	hints.ai_family = ai_fam_pref;
    391   1.8  christos 	hints.ai_flags = AI_CANONNAME | Z_AI_NUMERICSERV;
    392   1.8  christos 	/*
    393   1.8  christos 	** Unless we specify a socktype, we'll get at least two
    394   1.8  christos 	** entries for each address: one for TCP and one for
    395   1.8  christos 	** UDP. That's not what we want.
    396   1.8  christos 	*/
    397   1.8  christos 	hints.ai_socktype = SOCK_DGRAM;
    398   1.8  christos 	hints.ai_protocol = IPPROTO_UDP;
    399   1.8  christos 
    400   1.8  christos 	name_sz = 1 + strlen(name);
    401   1.8  christos 	octets = sizeof(*ctx) + name_sz;	// Space for a ctx and the name
    402   1.8  christos 	ctx = emalloc_zero(octets);		// ctx at ctx[0]
    403   1.8  christos 	name_copy = (char *)(ctx + 1);		// Put the name at ctx[1]
    404   1.8  christos 	memcpy(name_copy, name, name_sz);	// copy the name to ctx[1]
    405   1.8  christos 	ctx->name = name_copy;			// point to it...
    406   1.8  christos 	ctx->flags = flags;
    407   1.8  christos 	ctx->timeout = response_tv;
    408  1.16  christos 	ctx->key = NULL;
    409   1.8  christos 
    410   1.8  christos 	/* The following should arguably be passed in... */
    411  1.16  christos 	if (ENABLED_OPT(AUTHENTICATION)) {
    412  1.16  christos 		ctx->key_id = OPT_VALUE_AUTHENTICATION;
    413   1.8  christos 		get_key(ctx->key_id, &ctx->key);
    414  1.16  christos 		if (NULL == ctx->key) {
    415  1.16  christos 			fprintf(stderr, "%s: Authentication with keyID %d requested, but no matching keyID found in <%s>!\n",
    416  1.16  christos 				progname, ctx->key_id, OPT_ARG(KEYFILE));
    417  1.16  christos 			exit(1);
    418  1.16  christos 		}
    419   1.8  christos 	} else {
    420   1.8  christos 		ctx->key_id = -1;
    421   1.8  christos 	}
    422   1.8  christos 
    423   1.8  christos 	++n_pending_dns;
    424   1.8  christos 	getaddrinfo_sometime(name, "123", &hints, 0,
    425   1.8  christos 			     &sntp_name_resolved, ctx);
    426   1.8  christos }
    427   1.8  christos 
    428   1.8  christos 
    429   1.8  christos /*
    430   1.8  christos ** DNS Callback:
    431   1.8  christos ** - For each IP:
    432   1.8  christos ** - - open a socket
    433   1.8  christos ** - - increment n_pending_ntp
    434   1.8  christos ** - - send a request if this is a Unicast callback
    435   1.8  christos ** - - queue wait for response
    436   1.8  christos ** - decrement n_pending_dns
    437   1.8  christos */
    438   1.8  christos void
    439   1.8  christos sntp_name_resolved(
    440   1.8  christos 	int			rescode,
    441   1.8  christos 	int			gai_errno,
    442   1.8  christos 	void *			context,
    443   1.8  christos 	const char *		name,
    444   1.8  christos 	const char *		service,
    445   1.8  christos 	const struct addrinfo *	hints,
    446   1.8  christos 	const struct addrinfo *	addr
    447   1.8  christos 	)
    448   1.8  christos {
    449   1.8  christos 	struct dns_ctx *	dctx;
    450   1.8  christos 	sent_pkt *		spkt;
    451   1.8  christos 	const struct addrinfo *	ai;
    452   1.8  christos 	SOCKET			sock;
    453   1.8  christos 	u_int			xmt_delay_v4;
    454   1.8  christos 	u_int			xmt_delay_v6;
    455   1.8  christos 	u_int			xmt_delay;
    456   1.8  christos 	size_t			octets;
    457   1.8  christos 
    458   1.8  christos 	xmt_delay_v4 = 0;
    459   1.8  christos 	xmt_delay_v6 = 0;
    460   1.8  christos 	dctx = context;
    461   1.8  christos 	if (rescode) {
    462   1.8  christos #ifdef EAI_SYSTEM
    463   1.8  christos 		if (EAI_SYSTEM == rescode) {
    464   1.8  christos 			errno = gai_errno;
    465   1.8  christos 			mfprintf(stderr, "%s lookup error %m\n",
    466   1.8  christos 				 dctx->name);
    467   1.8  christos 		} else
    468   1.1    kardel #endif
    469   1.8  christos 			fprintf(stderr, "%s lookup error %s\n",
    470   1.8  christos 				dctx->name, gai_strerror(rescode));
    471   1.8  christos 	} else {
    472   1.8  christos 		TRACE(3, ("%s [%s]\n", dctx->name,
    473   1.8  christos 			  (addr->ai_canonname != NULL)
    474   1.8  christos 			      ? addr->ai_canonname
    475   1.8  christos 			      : ""));
    476   1.8  christos 
    477   1.8  christos 		for (ai = addr; ai != NULL; ai = ai->ai_next) {
    478   1.8  christos 
    479   1.8  christos 			if (check_kod(ai))
    480   1.8  christos 				continue;
    481   1.8  christos 
    482   1.8  christos 			switch (ai->ai_family) {
    483   1.8  christos 
    484   1.8  christos 			case AF_INET:
    485   1.8  christos 				sock = sock4;
    486   1.8  christos 				xmt_delay = xmt_delay_v4;
    487   1.8  christos 				xmt_delay_v4++;
    488   1.8  christos 				break;
    489   1.8  christos 
    490   1.8  christos 			case AF_INET6:
    491   1.8  christos 				if (!ipv6_works)
    492   1.8  christos 					continue;
    493   1.8  christos 
    494   1.8  christos 				sock = sock6;
    495   1.8  christos 				xmt_delay = xmt_delay_v6;
    496   1.8  christos 				xmt_delay_v6++;
    497   1.8  christos 				break;
    498   1.8  christos 
    499   1.8  christos 			default:
    500   1.8  christos 				msyslog(LOG_ERR, "sntp_name_resolved: unexpected ai_family: %d",
    501   1.8  christos 					ai->ai_family);
    502   1.8  christos 				exit(1);
    503   1.8  christos 				break;
    504   1.8  christos 			}
    505   1.1    kardel 
    506   1.8  christos 			/*
    507   1.8  christos 			** We're waiting for a response for either unicast
    508   1.8  christos 			** or broadcast, so...
    509   1.8  christos 			*/
    510   1.8  christos 			++n_pending_ntp;
    511   1.8  christos 
    512   1.8  christos 			/* If this is for a unicast IP, queue a request */
    513   1.8  christos 			if (dctx->flags & CTX_UCST) {
    514   1.8  christos 				spkt = emalloc_zero(sizeof(*spkt));
    515   1.8  christos 				spkt->dctx = dctx;
    516   1.8  christos 				octets = min(ai->ai_addrlen, sizeof(spkt->addr));
    517   1.8  christos 				memcpy(&spkt->addr, ai->ai_addr, octets);
    518   1.8  christos 				queue_xmt(sock, dctx, spkt, xmt_delay);
    519   1.8  christos 			}
    520   1.8  christos 		}
    521   1.8  christos 	}
    522   1.8  christos 	/* n_pending_dns really should be >0 here... */
    523   1.8  christos 	--n_pending_dns;
    524   1.8  christos 	check_exit_conditions();
    525   1.8  christos }
    526   1.8  christos 
    527   1.8  christos 
    528   1.8  christos /*
    529   1.8  christos ** queue_xmt
    530   1.8  christos */
    531   1.8  christos void
    532   1.8  christos queue_xmt(
    533   1.8  christos 	SOCKET			sock,
    534   1.8  christos 	struct dns_ctx *	dctx,
    535   1.8  christos 	sent_pkt *		spkt,
    536   1.8  christos 	u_int			xmt_delay
    537   1.8  christos 	)
    538   1.8  christos {
    539   1.8  christos 	sockaddr_u *	dest;
    540   1.8  christos 	sent_pkt **	pkt_listp;
    541   1.8  christos 	sent_pkt *	match;
    542   1.8  christos 	xmt_ctx *	xctx;
    543   1.8  christos 	struct timeval	start_cb;
    544   1.8  christos 	struct timeval	delay;
    545   1.8  christos 
    546   1.8  christos 	dest = &spkt->addr;
    547   1.8  christos 	if (IS_IPV6(dest))
    548   1.8  christos 		pkt_listp = &v6_pkts_list;
    549   1.8  christos 	else
    550   1.8  christos 		pkt_listp = &v4_pkts_list;
    551   1.8  christos 
    552   1.8  christos 	/* reject attempts to add address already listed */
    553   1.8  christos 	for (match = *pkt_listp; match != NULL; match = match->link) {
    554   1.8  christos 		if (ADDR_PORT_EQ(&spkt->addr, &match->addr)) {
    555   1.8  christos 			if (strcasecmp(spkt->dctx->name,
    556   1.8  christos 				       match->dctx->name))
    557   1.8  christos 				printf("%s %s duplicate address from %s ignored.\n",
    558   1.8  christos 				       sptoa(&match->addr),
    559   1.8  christos 				       match->dctx->name,
    560   1.8  christos 				       spkt->dctx->name);
    561   1.8  christos 			else
    562   1.8  christos 				printf("%s %s, duplicate address ignored.\n",
    563   1.8  christos 				       sptoa(&match->addr),
    564   1.8  christos 				       match->dctx->name);
    565   1.8  christos 			dec_pending_ntp(spkt->dctx->name, &spkt->addr);
    566   1.8  christos 			free(spkt);
    567   1.8  christos 			return;
    568   1.8  christos 		}
    569   1.8  christos 	}
    570   1.8  christos 
    571   1.8  christos 	LINK_SLIST(*pkt_listp, spkt, link);
    572   1.8  christos 
    573   1.8  christos 	xctx = emalloc_zero(sizeof(*xctx));
    574   1.8  christos 	xctx->sock = sock;
    575   1.8  christos 	xctx->spkt = spkt;
    576   1.8  christos 	gettimeofday_cached(base, &start_cb);
    577   1.8  christos 	xctx->sched = start_cb.tv_sec + (2 * xmt_delay);
    578   1.8  christos 
    579   1.8  christos 	LINK_SORT_SLIST(xmt_q, xctx, (xctx->sched < L_S_S_CUR()->sched),
    580   1.8  christos 			link, xmt_ctx);
    581   1.8  christos 	if (xmt_q == xctx) {
    582   1.8  christos 		/*
    583   1.8  christos 		 * The new entry is the first scheduled.  The timer is
    584   1.8  christos 		 * either not active or is set for the second xmt
    585   1.8  christos 		 * context in xmt_q.
    586   1.8  christos 		 */
    587   1.8  christos 		if (NULL == ev_xmt_timer)
    588   1.8  christos 			ev_xmt_timer = event_new(base, INVALID_SOCKET,
    589   1.8  christos 						 EV_TIMEOUT,
    590   1.8  christos 						 &xmt_timer_cb, NULL);
    591   1.8  christos 		if (NULL == ev_xmt_timer) {
    592   1.8  christos 			msyslog(LOG_ERR,
    593   1.8  christos 				"queue_xmt: event_new(base, -1, EV_TIMEOUT) failed!");
    594   1.8  christos 			exit(1);
    595   1.8  christos 		}
    596   1.8  christos 		ZERO(delay);
    597   1.8  christos 		if (xctx->sched > start_cb.tv_sec)
    598   1.8  christos 			delay.tv_sec = xctx->sched - start_cb.tv_sec;
    599   1.8  christos 		event_add(ev_xmt_timer, &delay);
    600   1.8  christos 		TRACE(2, ("queue_xmt: xmt timer for %u usec\n",
    601   1.8  christos 			  (u_int)delay.tv_usec));
    602   1.8  christos 	}
    603   1.8  christos }
    604   1.8  christos 
    605   1.8  christos 
    606   1.8  christos /*
    607   1.8  christos ** xmt_timer_cb
    608   1.8  christos */
    609   1.8  christos void
    610   1.8  christos xmt_timer_cb(
    611   1.8  christos 	evutil_socket_t	fd,
    612   1.8  christos 	short		what,
    613   1.8  christos 	void *		ctx
    614   1.8  christos 	)
    615   1.8  christos {
    616   1.8  christos 	struct timeval	start_cb;
    617   1.8  christos 	struct timeval	delay;
    618   1.8  christos 	xmt_ctx *	x;
    619   1.8  christos 
    620   1.8  christos 	UNUSED_ARG(fd);
    621   1.8  christos 	UNUSED_ARG(ctx);
    622   1.8  christos 	DEBUG_INSIST(EV_TIMEOUT == what);
    623   1.8  christos 
    624   1.8  christos 	if (NULL == xmt_q || shutting_down)
    625   1.8  christos 		return;
    626   1.8  christos 	gettimeofday_cached(base, &start_cb);
    627   1.8  christos 	if (xmt_q->sched <= start_cb.tv_sec) {
    628   1.8  christos 		UNLINK_HEAD_SLIST(x, xmt_q, link);
    629   1.8  christos 		TRACE(2, ("xmt_timer_cb: at .%6.6u -> %s\n",
    630   1.8  christos 			  (u_int)start_cb.tv_usec, stoa(&x->spkt->addr)));
    631   1.8  christos 		xmt(x);
    632   1.8  christos 		free(x);
    633   1.8  christos 		if (NULL == xmt_q)
    634   1.8  christos 			return;
    635   1.8  christos 	}
    636   1.8  christos 	if (xmt_q->sched <= start_cb.tv_sec) {
    637   1.8  christos 		event_add(ev_xmt_timer, &gap);
    638   1.8  christos 		TRACE(2, ("xmt_timer_cb: at .%6.6u gap %6.6u\n",
    639   1.8  christos 			  (u_int)start_cb.tv_usec,
    640   1.8  christos 			  (u_int)gap.tv_usec));
    641   1.8  christos 	} else {
    642   1.8  christos 		delay.tv_sec = xmt_q->sched - start_cb.tv_sec;
    643   1.8  christos 		delay.tv_usec = 0;
    644   1.8  christos 		event_add(ev_xmt_timer, &delay);
    645   1.8  christos 		TRACE(2, ("xmt_timer_cb: at .%6.6u next %ld seconds\n",
    646   1.8  christos 			  (u_int)start_cb.tv_usec,
    647   1.8  christos 			  (long)delay.tv_sec));
    648   1.8  christos 	}
    649   1.8  christos }
    650   1.8  christos 
    651   1.8  christos 
    652   1.8  christos /*
    653   1.8  christos ** xmt()
    654   1.8  christos */
    655   1.8  christos void
    656   1.8  christos xmt(
    657   1.8  christos 	xmt_ctx *	xctx
    658   1.8  christos 	)
    659   1.8  christos {
    660   1.8  christos 	SOCKET		sock = xctx->sock;
    661   1.8  christos 	struct dns_ctx *dctx = xctx->spkt->dctx;
    662   1.8  christos 	sent_pkt *	spkt = xctx->spkt;
    663   1.8  christos 	sockaddr_u *	dst = &spkt->addr;
    664   1.8  christos 	struct timeval	tv_xmt;
    665   1.8  christos 	struct pkt	x_pkt;
    666   1.8  christos 	size_t		pkt_len;
    667   1.8  christos 	int		sent;
    668   1.8  christos 
    669   1.8  christos 	if (0 != gettimeofday(&tv_xmt, NULL)) {
    670   1.8  christos 		msyslog(LOG_ERR,
    671   1.8  christos 			"xmt: gettimeofday() failed: %m");
    672   1.8  christos 		exit(1);
    673   1.8  christos 	}
    674   1.8  christos 	tv_xmt.tv_sec += JAN_1970;
    675   1.8  christos 
    676   1.8  christos 	pkt_len = generate_pkt(&x_pkt, &tv_xmt, dctx->key_id,
    677   1.8  christos 			       dctx->key);
    678   1.8  christos 
    679   1.8  christos 	sent = sendpkt(sock, dst, &x_pkt, pkt_len);
    680   1.8  christos 	if (sent) {
    681   1.8  christos 		/* Save the packet we sent... */
    682   1.8  christos 		memcpy(&spkt->x_pkt, &x_pkt, min(sizeof(spkt->x_pkt),
    683   1.8  christos 		       pkt_len));
    684   1.8  christos 		spkt->stime = tv_xmt.tv_sec - JAN_1970;
    685   1.8  christos 
    686   1.8  christos 		TRACE(2, ("xmt: %lx.%6.6u %s %s\n", (u_long)tv_xmt.tv_sec,
    687   1.8  christos 			  (u_int)tv_xmt.tv_usec, dctx->name, stoa(dst)));
    688   1.8  christos 	} else {
    689   1.8  christos 		dec_pending_ntp(dctx->name, dst);
    690   1.1    kardel 	}
    691   1.8  christos 
    692   1.8  christos 	return;
    693   1.8  christos }
    694   1.8  christos 
    695   1.8  christos 
    696   1.8  christos /*
    697   1.8  christos  * timeout_queries() -- give up on unrequited NTP queries
    698   1.8  christos  */
    699   1.8  christos void
    700   1.8  christos timeout_queries(void)
    701   1.8  christos {
    702   1.8  christos 	struct timeval	start_cb;
    703   1.8  christos 	u_int		idx;
    704   1.8  christos 	sent_pkt *	head;
    705   1.8  christos 	sent_pkt *	spkt;
    706   1.8  christos 	sent_pkt *	spkt_next;
    707   1.8  christos 	long		age;
    708   1.8  christos 	int didsomething = 0;
    709   1.8  christos 
    710   1.8  christos 	TRACE(3, ("timeout_queries: called to check %u items\n",
    711   1.8  christos 		  (unsigned)COUNTOF(fam_listheads)));
    712   1.8  christos 
    713   1.8  christos 	gettimeofday_cached(base, &start_cb);
    714   1.8  christos 	for (idx = 0; idx < COUNTOF(fam_listheads); idx++) {
    715   1.8  christos 		head = fam_listheads[idx];
    716   1.8  christos 		for (spkt = head; spkt != NULL; spkt = spkt_next) {
    717   1.8  christos 			char xcst;
    718   1.8  christos 
    719   1.8  christos 			didsomething = 1;
    720   1.8  christos 			switch (spkt->dctx->flags & CTX_xCST) {
    721   1.8  christos 			    case CTX_BCST:
    722   1.8  christos 				xcst = 'B';
    723   1.8  christos 				break;
    724   1.8  christos 
    725   1.8  christos 			    case CTX_UCST:
    726   1.8  christos 				xcst = 'U';
    727   1.8  christos 				break;
    728   1.8  christos 
    729   1.8  christos 			    default:
    730   1.8  christos 				INSIST(!"spkt->dctx->flags neither UCST nor BCST");
    731   1.8  christos 				break;
    732   1.1    kardel 			}
    733   1.8  christos 
    734   1.8  christos 			spkt_next = spkt->link;
    735   1.8  christos 			if (0 == spkt->stime || spkt->done)
    736   1.8  christos 				continue;
    737   1.8  christos 			age = start_cb.tv_sec - spkt->stime;
    738   1.8  christos 			TRACE(3, ("%s %s %cCST age %ld\n",
    739   1.8  christos 				  stoa(&spkt->addr),
    740   1.8  christos 				  spkt->dctx->name, xcst, age));
    741   1.8  christos 			if (age > response_timeout)
    742   1.8  christos 				timeout_query(spkt);
    743   1.8  christos 		}
    744   1.8  christos 	}
    745   1.8  christos 	// Do we care about didsomething?
    746   1.8  christos 	TRACE(3, ("timeout_queries: didsomething is %d, age is %ld\n",
    747   1.8  christos 		  didsomething, (long) (start_cb.tv_sec - start_tv.tv_sec)));
    748   1.8  christos 	if (start_cb.tv_sec - start_tv.tv_sec > response_timeout) {
    749   1.8  christos 		TRACE(3, ("timeout_queries: bail!\n"));
    750   1.8  christos 		event_base_loopexit(base, NULL);
    751   1.8  christos 		shutting_down = TRUE;
    752   1.8  christos 	}
    753   1.8  christos }
    754   1.8  christos 
    755   1.8  christos 
    756   1.8  christos void dec_pending_ntp(
    757   1.8  christos 	const char *	name,
    758   1.8  christos 	sockaddr_u *	server
    759   1.8  christos 	)
    760   1.8  christos {
    761   1.8  christos 	if (n_pending_ntp > 0) {
    762   1.8  christos 		--n_pending_ntp;
    763   1.8  christos 		check_exit_conditions();
    764   1.8  christos 	} else {
    765   1.8  christos 		INSIST(0 == n_pending_ntp);
    766   1.8  christos 		TRACE(1, ("n_pending_ntp was zero before decrement for %s\n",
    767   1.8  christos 			  hostnameaddr(name, server)));
    768   1.1    kardel 	}
    769   1.8  christos }
    770   1.8  christos 
    771   1.8  christos 
    772   1.8  christos void timeout_query(
    773   1.8  christos 	sent_pkt *	spkt
    774   1.8  christos 	)
    775   1.8  christos {
    776   1.8  christos 	sockaddr_u *	server;
    777   1.8  christos 	char		xcst;
    778   1.8  christos 
    779   1.8  christos 
    780   1.8  christos 	switch (spkt->dctx->flags & CTX_xCST) {
    781   1.8  christos 	    case CTX_BCST:
    782   1.8  christos 		xcst = 'B';
    783   1.8  christos 		break;
    784   1.8  christos 
    785   1.8  christos 	    case CTX_UCST:
    786   1.8  christos 		xcst = 'U';
    787   1.8  christos 		break;
    788   1.8  christos 
    789   1.8  christos 	    default:
    790   1.8  christos 		INSIST(!"spkt->dctx->flags neither UCST nor BCST");
    791   1.8  christos 		break;
    792   1.8  christos 	}
    793   1.8  christos 	spkt->done = TRUE;
    794   1.8  christos 	server = &spkt->addr;
    795   1.8  christos 	msyslog(LOG_INFO, "%s no %cCST response after %d seconds",
    796   1.8  christos 		hostnameaddr(spkt->dctx->name, server), xcst,
    797   1.8  christos 		response_timeout);
    798   1.8  christos 	dec_pending_ntp(spkt->dctx->name, server);
    799   1.8  christos 	return;
    800   1.8  christos }
    801   1.8  christos 
    802   1.8  christos 
    803   1.8  christos /*
    804   1.8  christos ** check_kod
    805   1.8  christos */
    806   1.8  christos int
    807   1.8  christos check_kod(
    808   1.8  christos 	const struct addrinfo *	ai
    809   1.8  christos 	)
    810   1.8  christos {
    811   1.8  christos 	char *hostname;
    812   1.8  christos 	struct kod_entry *reason;
    813   1.8  christos 
    814   1.8  christos 	/* Is there a KoD on file for this address? */
    815   1.8  christos 	hostname = addrinfo_to_str(ai);
    816   1.8  christos 	TRACE(2, ("check_kod: checking <%s>\n", hostname));
    817   1.8  christos 	if (search_entry(hostname, &reason)) {
    818   1.8  christos 		printf("prior KoD for %s, skipping.\n",
    819   1.8  christos 			hostname);
    820   1.8  christos 		free(reason);
    821   1.8  christos 		free(hostname);
    822   1.1    kardel 
    823   1.3    kardel 		return 1;
    824   1.8  christos 	}
    825   1.8  christos 	free(hostname);
    826   1.8  christos 
    827   1.1    kardel 	return 0;
    828   1.1    kardel }
    829   1.1    kardel 
    830   1.3    kardel 
    831   1.8  christos /*
    832   1.8  christos ** Socket readable/timeout Callback:
    833   1.8  christos ** Read in the packet
    834   1.8  christos ** Unicast:
    835   1.8  christos ** - close socket
    836   1.8  christos ** - decrement n_pending_ntp
    837   1.8  christos ** - If packet is good, set the time and "exit"
    838   1.8  christos ** Broadcast:
    839   1.8  christos ** - If packet is good, set the time and "exit"
    840   1.8  christos */
    841   1.8  christos void
    842   1.8  christos sock_cb(
    843   1.8  christos 	evutil_socket_t fd,
    844   1.8  christos 	short what,
    845   1.8  christos 	void *ptr
    846   1.8  christos 	)
    847   1.8  christos {
    848   1.8  christos 	sockaddr_u	sender;
    849   1.8  christos 	sockaddr_u *	psau;
    850   1.8  christos 	sent_pkt **	p_pktlist;
    851   1.8  christos 	sent_pkt *	spkt;
    852   1.8  christos 	int		rpktl;
    853   1.8  christos 	int		rc;
    854   1.8  christos 
    855   1.8  christos 	INSIST(sock4 == fd || sock6 == fd);
    856   1.8  christos 
    857   1.8  christos 	TRACE(3, ("sock_cb: event on sock%s:%s%s%s%s\n",
    858   1.8  christos 		  (fd == sock6)
    859   1.8  christos 		      ? "6"
    860   1.8  christos 		      : "4",
    861   1.8  christos 		  (what & EV_TIMEOUT) ? " timeout" : "",
    862   1.8  christos 		  (what & EV_READ)    ? " read" : "",
    863   1.8  christos 		  (what & EV_WRITE)   ? " write" : "",
    864   1.8  christos 		  (what & EV_SIGNAL)  ? " signal" : ""));
    865   1.8  christos 
    866   1.8  christos 	if (!(EV_READ & what)) {
    867   1.8  christos 		if (EV_TIMEOUT & what)
    868   1.8  christos 			timeout_queries();
    869   1.8  christos 
    870   1.8  christos 		return;
    871   1.8  christos 	}
    872   1.8  christos 
    873   1.8  christos 	/* Read in the packet */
    874   1.8  christos 	rpktl = recvdata(fd, &sender, &rbuf, sizeof(rbuf));
    875   1.8  christos 	if (rpktl < 0) {
    876   1.8  christos 		msyslog(LOG_DEBUG, "recvfrom error %m");
    877   1.8  christos 		return;
    878   1.8  christos 	}
    879   1.8  christos 
    880   1.8  christos 	if (sock6 == fd)
    881   1.8  christos 		p_pktlist = &v6_pkts_list;
    882   1.8  christos 	else
    883   1.8  christos 		p_pktlist = &v4_pkts_list;
    884   1.8  christos 
    885   1.8  christos 	for (spkt = *p_pktlist; spkt != NULL; spkt = spkt->link) {
    886   1.8  christos 		psau = &spkt->addr;
    887   1.8  christos 		if (SOCK_EQ(&sender, psau))
    888   1.8  christos 			break;
    889   1.8  christos 	}
    890   1.8  christos 	if (NULL == spkt) {
    891   1.8  christos 		msyslog(LOG_WARNING,
    892   1.8  christos 			"Packet from unexpected source %s dropped",
    893   1.8  christos 			sptoa(&sender));
    894   1.8  christos 		return;
    895   1.8  christos 	}
    896   1.8  christos 
    897   1.8  christos 	TRACE(1, ("sock_cb: %s %s\n", spkt->dctx->name,
    898   1.8  christos 		  sptoa(&sender)));
    899   1.8  christos 
    900   1.8  christos 	rpktl = process_pkt(&r_pkt, &sender, rpktl, MODE_SERVER,
    901   1.8  christos 			    &spkt->x_pkt, "sock_cb");
    902   1.8  christos 
    903   1.8  christos 	TRACE(2, ("sock_cb: process_pkt returned %d\n", rpktl));
    904   1.8  christos 
    905   1.8  christos 	/* If this is a Unicast packet, one down ... */
    906   1.8  christos 	if (!spkt->done && (CTX_UCST & spkt->dctx->flags)) {
    907   1.8  christos 		dec_pending_ntp(spkt->dctx->name, &spkt->addr);
    908   1.8  christos 		spkt->done = TRUE;
    909   1.8  christos 	}
    910   1.8  christos 
    911   1.8  christos 
    912   1.8  christos 	/* If the packet is good, set the time and we're all done */
    913   1.8  christos 	rc = handle_pkt(rpktl, &r_pkt, &spkt->addr, spkt->dctx->name);
    914   1.8  christos 	if (0 != rc)
    915   1.8  christos 		TRACE(1, ("sock_cb: handle_pkt() returned %d\n", rc));
    916   1.8  christos 	check_exit_conditions();
    917   1.8  christos }
    918   1.8  christos 
    919   1.8  christos 
    920   1.8  christos /*
    921   1.8  christos  * check_exit_conditions()
    922   1.8  christos  *
    923   1.8  christos  * If sntp has a reply, ask the event loop to stop after this round of
    924   1.8  christos  * callbacks, unless --wait was used.
    925   1.8  christos  */
    926   1.8  christos void
    927   1.8  christos check_exit_conditions(void)
    928   1.8  christos {
    929   1.8  christos 	if ((0 == n_pending_ntp && 0 == n_pending_dns) ||
    930   1.8  christos 	    (time_derived && !HAVE_OPT(WAIT))) {
    931   1.8  christos 		event_base_loopexit(base, NULL);
    932   1.8  christos 		shutting_down = TRUE;
    933   1.8  christos 	} else {
    934   1.8  christos 		TRACE(2, ("%d NTP and %d name queries pending\n",
    935   1.8  christos 			  n_pending_ntp, n_pending_dns));
    936   1.8  christos 	}
    937   1.8  christos }
    938   1.8  christos 
    939   1.8  christos 
    940   1.8  christos /*
    941   1.8  christos  * sntp_addremove_fd() is invoked by the intres blocking worker code
    942   1.8  christos  * to read from a pipe, or to stop same.
    943   1.8  christos  */
    944   1.8  christos void sntp_addremove_fd(
    945   1.8  christos 	int	fd,
    946   1.8  christos 	int	is_pipe,
    947   1.8  christos 	int	remove_it
    948   1.8  christos 	)
    949   1.8  christos {
    950   1.8  christos 	u_int		idx;
    951   1.8  christos 	blocking_child *c;
    952   1.8  christos 	struct event *	ev;
    953   1.8  christos 
    954   1.8  christos #ifdef HAVE_SOCKETPAIR
    955   1.8  christos 	if (is_pipe) {
    956   1.8  christos 		/* sntp only asks for EV_FEATURE_FDS without HAVE_SOCKETPAIR */
    957   1.8  christos 		msyslog(LOG_ERR, "fatal: pipes not supported on systems with socketpair()");
    958   1.8  christos 		exit(1);
    959   1.8  christos 	}
    960   1.8  christos #endif
    961   1.8  christos 
    962   1.8  christos 	c = NULL;
    963   1.8  christos 	for (idx = 0; idx < blocking_children_alloc; idx++) {
    964   1.8  christos 		c = blocking_children[idx];
    965   1.8  christos 		if (NULL == c)
    966   1.8  christos 			continue;
    967   1.8  christos 		if (fd == c->resp_read_pipe)
    968   1.8  christos 			break;
    969   1.8  christos 	}
    970   1.8  christos 	if (idx == blocking_children_alloc)
    971   1.8  christos 		return;
    972   1.8  christos 
    973   1.8  christos 	if (remove_it) {
    974   1.8  christos 		ev = c->resp_read_ctx;
    975   1.8  christos 		c->resp_read_ctx = NULL;
    976   1.8  christos 		event_del(ev);
    977   1.8  christos 		event_free(ev);
    978   1.8  christos 
    979   1.8  christos 		return;
    980   1.8  christos 	}
    981   1.8  christos 
    982   1.8  christos 	ev = event_new(base, fd, EV_READ | EV_PERSIST,
    983   1.8  christos 		       &worker_resp_cb, c);
    984   1.8  christos 	if (NULL == ev) {
    985   1.8  christos 		msyslog(LOG_ERR,
    986   1.8  christos 			"sntp_addremove_fd: event_new(base, fd) failed!");
    987   1.8  christos 		return;
    988   1.8  christos 	}
    989   1.8  christos 	c->resp_read_ctx = ev;
    990   1.8  christos 	event_add(ev, NULL);
    991   1.8  christos }
    992   1.8  christos 
    993   1.8  christos 
    994   1.8  christos /* called by forked intres child to close open descriptors */
    995   1.8  christos #ifdef WORK_FORK
    996   1.8  christos void
    997   1.8  christos kill_asyncio(
    998   1.8  christos 	int	startfd
    999   1.8  christos 	)
   1000   1.8  christos {
   1001   1.8  christos 	if (INVALID_SOCKET != sock4) {
   1002   1.8  christos 		closesocket(sock4);
   1003   1.8  christos 		sock4 = INVALID_SOCKET;
   1004   1.8  christos 	}
   1005   1.8  christos 	if (INVALID_SOCKET != sock6) {
   1006   1.8  christos 		closesocket(sock6);
   1007   1.8  christos 		sock6 = INVALID_SOCKET;
   1008   1.8  christos 	}
   1009   1.8  christos 	if (INVALID_SOCKET != bsock4) {
   1010   1.8  christos 		closesocket(sock4);
   1011   1.8  christos 		sock4 = INVALID_SOCKET;
   1012   1.8  christos 	}
   1013   1.8  christos 	if (INVALID_SOCKET != bsock6) {
   1014   1.8  christos 		closesocket(sock6);
   1015   1.8  christos 		sock6 = INVALID_SOCKET;
   1016   1.8  christos 	}
   1017   1.8  christos }
   1018   1.8  christos #endif
   1019   1.8  christos 
   1020   1.8  christos 
   1021   1.8  christos /*
   1022   1.8  christos  * worker_resp_cb() is invoked when resp_read_pipe is readable.
   1023   1.8  christos  */
   1024   1.8  christos void
   1025   1.8  christos worker_resp_cb(
   1026   1.8  christos 	evutil_socket_t	fd,
   1027   1.8  christos 	short		what,
   1028   1.8  christos 	void *		ctx	/* blocking_child * */
   1029   1.8  christos 	)
   1030   1.8  christos {
   1031   1.8  christos 	blocking_child *	c;
   1032   1.8  christos 
   1033   1.8  christos 	DEBUG_INSIST(EV_READ & what);
   1034   1.8  christos 	c = ctx;
   1035   1.8  christos 	DEBUG_INSIST(fd == c->resp_read_pipe);
   1036   1.8  christos 	process_blocking_resp(c);
   1037   1.8  christos }
   1038   1.8  christos 
   1039   1.8  christos 
   1040   1.8  christos /*
   1041   1.8  christos  * intres_timeout_req(s) is invoked in the parent to schedule an idle
   1042   1.8  christos  * timeout to fire in s seconds, if not reset earlier by a call to
   1043   1.8  christos  * intres_timeout_req(0), which clears any pending timeout.  When the
   1044   1.8  christos  * timeout expires, worker_idle_timer_fired() is invoked (again, in the
   1045   1.8  christos  * parent).
   1046   1.8  christos  *
   1047   1.8  christos  * sntp and ntpd each provide implementations adapted to their timers.
   1048   1.8  christos  */
   1049   1.8  christos void
   1050   1.8  christos intres_timeout_req(
   1051   1.8  christos 	u_int	seconds		/* 0 cancels */
   1052   1.8  christos 	)
   1053   1.8  christos {
   1054   1.8  christos 	struct timeval	tv_to;
   1055   1.8  christos 
   1056   1.8  christos 	if (NULL == ev_worker_timeout) {
   1057   1.8  christos 		ev_worker_timeout = event_new(base, -1,
   1058   1.8  christos 					      EV_TIMEOUT | EV_PERSIST,
   1059   1.8  christos 					      &worker_timeout, NULL);
   1060   1.8  christos 		DEBUG_INSIST(NULL != ev_worker_timeout);
   1061   1.8  christos 	} else {
   1062   1.8  christos 		event_del(ev_worker_timeout);
   1063   1.8  christos 	}
   1064   1.8  christos 	if (0 == seconds)
   1065   1.8  christos 		return;
   1066   1.8  christos 	tv_to.tv_sec = seconds;
   1067   1.8  christos 	tv_to.tv_usec = 0;
   1068   1.8  christos 	event_add(ev_worker_timeout, &tv_to);
   1069   1.8  christos }
   1070   1.8  christos 
   1071   1.8  christos 
   1072   1.8  christos void
   1073   1.8  christos worker_timeout(
   1074   1.8  christos 	evutil_socket_t	fd,
   1075   1.8  christos 	short		what,
   1076   1.8  christos 	void *		ctx
   1077   1.8  christos 	)
   1078   1.8  christos {
   1079   1.8  christos 	UNUSED_ARG(fd);
   1080   1.8  christos 	UNUSED_ARG(ctx);
   1081   1.8  christos 
   1082   1.8  christos 	DEBUG_REQUIRE(EV_TIMEOUT & what);
   1083   1.8  christos 	worker_idle_timer_fired();
   1084   1.8  christos }
   1085   1.8  christos 
   1086   1.8  christos 
   1087   1.8  christos void
   1088   1.8  christos sntp_libevent_log_cb(
   1089   1.8  christos 	int		severity,
   1090   1.8  christos 	const char *	msg
   1091   1.8  christos 	)
   1092   1.8  christos {
   1093   1.8  christos 	int		level;
   1094   1.8  christos 
   1095   1.8  christos 	switch (severity) {
   1096   1.8  christos 
   1097   1.8  christos 	default:
   1098   1.8  christos 	case _EVENT_LOG_DEBUG:
   1099   1.8  christos 		level = LOG_DEBUG;
   1100   1.8  christos 		break;
   1101   1.8  christos 
   1102   1.8  christos 	case _EVENT_LOG_MSG:
   1103   1.8  christos 		level = LOG_NOTICE;
   1104   1.8  christos 		break;
   1105   1.8  christos 
   1106   1.8  christos 	case _EVENT_LOG_WARN:
   1107   1.8  christos 		level = LOG_WARNING;
   1108   1.8  christos 		break;
   1109   1.8  christos 
   1110   1.8  christos 	case _EVENT_LOG_ERR:
   1111   1.8  christos 		level = LOG_ERR;
   1112   1.8  christos 		break;
   1113   1.8  christos 	}
   1114   1.8  christos 
   1115   1.8  christos 	msyslog(level, "%s", msg);
   1116   1.8  christos }
   1117   1.8  christos 
   1118   1.3    kardel 
   1119   1.3    kardel int
   1120   1.3    kardel generate_pkt (
   1121   1.3    kardel 	struct pkt *x_pkt,
   1122   1.3    kardel 	const struct timeval *tv_xmt,
   1123   1.3    kardel 	int key_id,
   1124   1.3    kardel 	struct key *pkt_key
   1125   1.3    kardel 	)
   1126   1.3    kardel {
   1127   1.8  christos 	l_fp	xmt_fp;
   1128   1.8  christos 	int	pkt_len;
   1129   1.8  christos 	int	mac_size;
   1130   1.8  christos 
   1131   1.8  christos 	pkt_len = LEN_PKT_NOMAC;
   1132   1.8  christos 	ZERO(*x_pkt);
   1133   1.8  christos 	TVTOTS(tv_xmt, &xmt_fp);
   1134   1.8  christos 	HTONL_FP(&xmt_fp, &x_pkt->xmt);
   1135   1.3    kardel 	x_pkt->stratum = STRATUM_TO_PKT(STRATUM_UNSPEC);
   1136   1.3    kardel 	x_pkt->ppoll = 8;
   1137   1.3    kardel 	/* FIXME! Modus broadcast + adr. check -> bdr. pkt */
   1138   1.8  christos 	set_li_vn_mode(x_pkt, LEAP_NOTINSYNC, ntpver, 3);
   1139  1.16  christos 	if (debug > 0) {
   1140  1.16  christos 		printf("generate_pkt: key_id %d, key pointer %p\n", key_id, pkt_key);
   1141  1.16  christos 	}
   1142   1.3    kardel 	if (pkt_key != NULL) {
   1143   1.3    kardel 		x_pkt->exten[0] = htonl(key_id);
   1144  1.16  christos 		mac_size = make_mac(x_pkt, pkt_len, MAX_MDG_LEN,
   1145   1.8  christos 				    pkt_key, (char *)&x_pkt->exten[1]);
   1146   1.8  christos 		if (mac_size > 0)
   1147  1.16  christos 			pkt_len += mac_size + KEY_MAC_LEN;
   1148  1.16  christos #ifdef DEBUG
   1149  1.16  christos 		if (debug > 0) {
   1150  1.16  christos 			printf("generate_pkt: mac_size is %d\n", mac_size);
   1151  1.16  christos 		}
   1152  1.16  christos #endif
   1153  1.16  christos 
   1154   1.3    kardel 	}
   1155   1.3    kardel 	return pkt_len;
   1156   1.3    kardel }
   1157   1.3    kardel 
   1158   1.8  christos 
   1159   1.1    kardel int
   1160   1.8  christos handle_pkt(
   1161   1.8  christos 	int		rpktl,
   1162   1.8  christos 	struct pkt *	rpkt,
   1163   1.8  christos 	sockaddr_u *	host,
   1164   1.8  christos 	const char *	hostname
   1165   1.3    kardel 	)
   1166   1.1    kardel {
   1167   1.8  christos 	char		disptxt[32];
   1168   1.8  christos 	const char *	addrtxt;
   1169   1.8  christos 	struct timeval	tv_dst;
   1170   1.8  christos 	int		cnt;
   1171   1.8  christos 	int		sw_case;
   1172   1.8  christos 	int		digits;
   1173   1.8  christos 	int		stratum;
   1174   1.8  christos 	char *		ref;
   1175   1.8  christos 	char *		ts_str;
   1176  1.12  christos 	const char *	leaptxt;
   1177   1.8  christos 	double		offset;
   1178   1.8  christos 	double		precision;
   1179   1.8  christos 	double		synch_distance;
   1180   1.8  christos 	char *		p_SNTP_PRETEND_TIME;
   1181   1.8  christos 	time_t		pretend_time;
   1182   1.8  christos #if SIZEOF_TIME_T == 8
   1183   1.8  christos 	long long	ll;
   1184   1.8  christos #else
   1185   1.8  christos 	long		l;
   1186   1.8  christos #endif
   1187   1.8  christos 
   1188   1.8  christos 	ts_str = NULL;
   1189   1.1    kardel 
   1190   1.8  christos 	if (rpktl > 0)
   1191   1.3    kardel 		sw_case = 1;
   1192   1.3    kardel 	else
   1193   1.3    kardel 		sw_case = rpktl;
   1194   1.1    kardel 
   1195   1.8  christos 	switch (sw_case) {
   1196   1.8  christos 
   1197   1.3    kardel 	case SERVER_UNUSEABLE:
   1198   1.3    kardel 		return -1;
   1199   1.3    kardel 		break;
   1200   1.1    kardel 
   1201   1.3    kardel 	case PACKET_UNUSEABLE:
   1202   1.3    kardel 		break;
   1203   1.8  christos 
   1204   1.3    kardel 	case SERVER_AUTH_FAIL:
   1205   1.3    kardel 		break;
   1206   1.3    kardel 
   1207   1.3    kardel 	case KOD_DEMOBILIZE:
   1208   1.3    kardel 		/* Received a DENY or RESTR KOD packet */
   1209   1.8  christos 		addrtxt = stoa(host);
   1210   1.3    kardel 		ref = (char *)&rpkt->refid;
   1211   1.8  christos 		add_entry(addrtxt, ref);
   1212   1.8  christos 		msyslog(LOG_WARNING, "KOD code %c%c%c%c from %s %s",
   1213   1.8  christos 			ref[0], ref[1], ref[2], ref[3], addrtxt, hostname);
   1214   1.3    kardel 		break;
   1215   1.3    kardel 
   1216   1.3    kardel 	case KOD_RATE:
   1217   1.8  christos 		/*
   1218   1.8  christos 		** Hmm...
   1219   1.8  christos 		** We should probably call add_entry() with an
   1220   1.8  christos 		** expiration timestamp of several seconds in the future,
   1221   1.8  christos 		** and back-off even more if we get more RATE responses.
   1222   1.8  christos 		*/
   1223   1.3    kardel 		break;
   1224   1.3    kardel 
   1225   1.3    kardel 	case 1:
   1226   1.8  christos 		TRACE(3, ("handle_pkt: %d bytes from %s %s\n",
   1227   1.8  christos 			  rpktl, stoa(host), hostname));
   1228   1.1    kardel 
   1229   1.8  christos 		gettimeofday_cached(base, &tv_dst);
   1230   1.1    kardel 
   1231   1.3    kardel 		p_SNTP_PRETEND_TIME = getenv("SNTP_PRETEND_TIME");
   1232   1.3    kardel 		if (p_SNTP_PRETEND_TIME) {
   1233   1.8  christos 			pretend_time = 0;
   1234   1.8  christos #if SIZEOF_TIME_T == 4
   1235   1.8  christos 			if (1 == sscanf(p_SNTP_PRETEND_TIME, "%ld", &l))
   1236   1.8  christos 				pretend_time = (time_t)l;
   1237   1.8  christos #elif SIZEOF_TIME_T == 8
   1238   1.8  christos 			if (1 == sscanf(p_SNTP_PRETEND_TIME, "%lld", &ll))
   1239   1.8  christos 				pretend_time = (time_t)ll;
   1240   1.8  christos #else
   1241   1.8  christos # include "GRONK: unexpected value for SIZEOF_TIME_T"
   1242   1.8  christos #endif
   1243   1.8  christos 			if (0 != pretend_time)
   1244   1.8  christos 				tv_dst.tv_sec = pretend_time;
   1245   1.3    kardel 		}
   1246   1.1    kardel 
   1247   1.3    kardel 		offset_calculation(rpkt, rpktl, &tv_dst, &offset,
   1248   1.8  christos 				   &precision, &synch_distance);
   1249   1.8  christos 		time_derived = TRUE;
   1250   1.1    kardel 
   1251   1.3    kardel 		for (digits = 0; (precision *= 10.) < 1.; ++digits)
   1252   1.3    kardel 			/* empty */ ;
   1253   1.3    kardel 		if (digits > 6)
   1254   1.3    kardel 			digits = 6;
   1255   1.3    kardel 
   1256   1.3    kardel 		ts_str = tv_to_str(&tv_dst);
   1257   1.8  christos 		stratum = rpkt->stratum;
   1258   1.8  christos 		if (0 == stratum)
   1259   1.8  christos 				stratum = 16;
   1260   1.8  christos 
   1261   1.8  christos 		if (synch_distance > 0.) {
   1262   1.8  christos 			cnt = snprintf(disptxt, sizeof(disptxt),
   1263   1.8  christos 				       " +/- %f", synch_distance);
   1264   1.8  christos 			if ((size_t)cnt >= sizeof(disptxt))
   1265   1.8  christos 				snprintf(disptxt, sizeof(disptxt),
   1266   1.8  christos 					 "ERROR %d >= %d", cnt,
   1267   1.8  christos 					 (int)sizeof(disptxt));
   1268   1.8  christos 		} else {
   1269   1.8  christos 			disptxt[0] = '\0';
   1270   1.8  christos 		}
   1271   1.8  christos 
   1272  1.12  christos 		switch (PKT_LEAP(rpkt->li_vn_mode)) {
   1273  1.12  christos 		    case LEAP_NOWARNING:
   1274  1.12  christos 		    	leaptxt = "no-leap";
   1275  1.12  christos 			break;
   1276  1.12  christos 		    case LEAP_ADDSECOND:
   1277  1.12  christos 		    	leaptxt = "add-leap";
   1278  1.12  christos 			break;
   1279  1.12  christos 		    case LEAP_DELSECOND:
   1280  1.12  christos 		    	leaptxt = "del-leap";
   1281  1.12  christos 			break;
   1282  1.12  christos 		    case LEAP_NOTINSYNC:
   1283  1.12  christos 		    	leaptxt = "unsync";
   1284  1.12  christos 			break;
   1285  1.12  christos 		    default:
   1286  1.12  christos 		    	leaptxt = "LEAP-ERROR";
   1287  1.12  christos 			break;
   1288  1.12  christos 		}
   1289  1.12  christos 
   1290  1.12  christos 		msyslog(LOG_INFO, "%s %+.*f%s %s s%d %s%s", ts_str,
   1291   1.8  christos 			digits, offset, disptxt,
   1292   1.8  christos 			hostnameaddr(hostname, host), stratum,
   1293  1.12  christos 			leaptxt,
   1294   1.8  christos 			(time_adjusted)
   1295   1.8  christos 			    ? " [excess]"
   1296   1.8  christos 			    : "");
   1297   1.3    kardel 		free(ts_str);
   1298   1.1    kardel 
   1299   1.3    kardel 		if (p_SNTP_PRETEND_TIME)
   1300   1.3    kardel 			return 0;
   1301   1.3    kardel 
   1302   1.8  christos 		if (!time_adjusted &&
   1303   1.8  christos 		    (ENABLED_OPT(STEP) || ENABLED_OPT(SLEW)))
   1304   1.8  christos 			return set_time(offset);
   1305   1.3    kardel 
   1306   1.8  christos 		return EX_OK;
   1307   1.3    kardel 	}
   1308   1.3    kardel 
   1309   1.3    kardel 	return 1;
   1310   1.3    kardel }
   1311   1.3    kardel 
   1312   1.8  christos 
   1313   1.3    kardel void
   1314   1.8  christos offset_calculation(
   1315   1.3    kardel 	struct pkt *rpkt,
   1316   1.3    kardel 	int rpktl,
   1317   1.3    kardel 	struct timeval *tv_dst,
   1318   1.3    kardel 	double *offset,
   1319   1.3    kardel 	double *precision,
   1320   1.8  christos 	double *synch_distance
   1321   1.3    kardel 	)
   1322   1.3    kardel {
   1323   1.3    kardel 	l_fp p_rec, p_xmt, p_ref, p_org, tmp, dst;
   1324   1.3    kardel 	u_fp p_rdly, p_rdsp;
   1325   1.3    kardel 	double t21, t34, delta;
   1326   1.3    kardel 
   1327   1.3    kardel 	/* Convert timestamps from network to host byte order */
   1328   1.3    kardel 	p_rdly = NTOHS_FP(rpkt->rootdelay);
   1329   1.3    kardel 	p_rdsp = NTOHS_FP(rpkt->rootdisp);
   1330   1.3    kardel 	NTOHL_FP(&rpkt->reftime, &p_ref);
   1331   1.3    kardel 	NTOHL_FP(&rpkt->org, &p_org);
   1332   1.3    kardel 	NTOHL_FP(&rpkt->rec, &p_rec);
   1333   1.3    kardel 	NTOHL_FP(&rpkt->xmt, &p_xmt);
   1334   1.1    kardel 
   1335   1.3    kardel 	*precision = LOGTOD(rpkt->precision);
   1336   1.1    kardel 
   1337   1.8  christos 	TRACE(3, ("offset_calculation: LOGTOD(rpkt->precision): %f\n", *precision));
   1338   1.1    kardel 
   1339   1.3    kardel 	/* Compute offset etc. */
   1340   1.3    kardel 	tmp = p_rec;
   1341   1.3    kardel 	L_SUB(&tmp, &p_org);
   1342   1.3    kardel 	LFPTOD(&tmp, t21);
   1343   1.3    kardel 	TVTOTS(tv_dst, &dst);
   1344   1.3    kardel 	dst.l_ui += JAN_1970;
   1345   1.3    kardel 	tmp = p_xmt;
   1346   1.3    kardel 	L_SUB(&tmp, &dst);
   1347   1.3    kardel 	LFPTOD(&tmp, t34);
   1348   1.3    kardel 	*offset = (t21 + t34) / 2.;
   1349   1.3    kardel 	delta = t21 - t34;
   1350   1.1    kardel 
   1351   1.8  christos 	// synch_distance is:
   1352   1.8  christos 	// (peer->delay + peer->rootdelay) / 2 + peer->disp
   1353   1.8  christos 	// + peer->rootdisp + clock_phi * (current_time - peer->update)
   1354   1.8  christos 	// + peer->jitter;
   1355   1.8  christos 	//
   1356   1.8  christos 	// and peer->delay = fabs(peer->offset - p_offset) * 2;
   1357   1.8  christos 	// and peer->offset needs history, so we're left with
   1358   1.8  christos 	// p_offset = (t21 + t34) / 2.;
   1359   1.8  christos 	// peer->disp = 0; (we have no history to augment this)
   1360   1.8  christos 	// clock_phi = 15e-6;
   1361   1.8  christos 	// peer->jitter = LOGTOD(sys_precision); (we have no history to augment this)
   1362   1.8  christos 	// and ntp_proto.c:set_sys_tick_precision() should get us sys_precision.
   1363   1.8  christos 	//
   1364   1.8  christos 	// so our answer seems to be:
   1365   1.8  christos 	//
   1366   1.8  christos 	// (fabs(t21 + t34) + peer->rootdelay) / 3.
   1367   1.8  christos 	// + 0 (peer->disp)
   1368   1.8  christos 	// + peer->rootdisp
   1369   1.8  christos 	// + 15e-6 (clock_phi)
   1370   1.8  christos 	// + LOGTOD(sys_precision)
   1371   1.8  christos 
   1372   1.8  christos 	INSIST( FPTOD(p_rdly) >= 0. );
   1373   1.8  christos #if 1
   1374   1.8  christos 	*synch_distance = (fabs(t21 + t34) + FPTOD(p_rdly)) / 3.
   1375   1.8  christos 		+ 0.
   1376   1.8  christos 		+ FPTOD(p_rdsp)
   1377   1.8  christos 		+ 15e-6
   1378   1.8  christos 		+ 0.	/* LOGTOD(sys_precision) when we can get it */
   1379   1.8  christos 		;
   1380   1.8  christos 	INSIST( *synch_distance >= 0. );
   1381   1.8  christos #else
   1382   1.8  christos 	*synch_distance = (FPTOD(p_rdly) + FPTOD(p_rdsp))/2.0;
   1383   1.8  christos #endif
   1384   1.1    kardel 
   1385   1.3    kardel #ifdef DEBUG
   1386   1.8  christos 	if (debug > 3) {
   1387   1.8  christos 		printf("sntp rootdelay: %f\n", FPTOD(p_rdly));
   1388   1.8  christos 		printf("sntp rootdisp: %f\n", FPTOD(p_rdsp));
   1389   1.8  christos 		printf("sntp syncdist: %f\n", *synch_distance);
   1390   1.8  christos 
   1391   1.8  christos 		pkt_output(rpkt, rpktl, stdout);
   1392   1.8  christos 
   1393   1.8  christos 		printf("sntp offset_calculation: rpkt->reftime:\n");
   1394   1.8  christos 		l_fp_output(&p_ref, stdout);
   1395   1.8  christos 		printf("sntp offset_calculation: rpkt->org:\n");
   1396   1.8  christos 		l_fp_output(&p_org, stdout);
   1397   1.8  christos 		printf("sntp offset_calculation: rpkt->rec:\n");
   1398   1.8  christos 		l_fp_output(&p_rec, stdout);
   1399   1.8  christos 		printf("sntp offset_calculation: rpkt->xmt:\n");
   1400   1.8  christos 		l_fp_output(&p_xmt, stdout);
   1401   1.8  christos 	}
   1402   1.3    kardel #endif
   1403   1.1    kardel 
   1404   1.8  christos 	TRACE(3, ("sntp offset_calculation:\trec - org t21: %.6f\n"
   1405   1.8  christos 		  "\txmt - dst t34: %.6f\tdelta: %.6f\toffset: %.6f\n",
   1406   1.8  christos 		  t21, t34, delta, *offset));
   1407   1.3    kardel 
   1408   1.8  christos 	return;
   1409   1.8  christos }
   1410   1.1    kardel 
   1411   1.1    kardel 
   1412   1.1    kardel 
   1413   1.1    kardel /* Compute the 8 bits for li_vn_mode */
   1414   1.1    kardel void
   1415   1.1    kardel set_li_vn_mode (
   1416   1.3    kardel 	struct pkt *spkt,
   1417   1.3    kardel 	char leap,
   1418   1.3    kardel 	char version,
   1419   1.3    kardel 	char mode
   1420   1.8  christos 	)
   1421   1.1    kardel {
   1422   1.3    kardel 	if (leap > 3) {
   1423   1.8  christos 		msyslog(LOG_DEBUG, "set_li_vn_mode: leap > 3, using max. 3");
   1424   1.1    kardel 		leap = 3;
   1425   1.1    kardel 	}
   1426   1.1    kardel 
   1427   1.9  christos 	if ((unsigned char)version > 7) {
   1428   1.8  christos 		msyslog(LOG_DEBUG, "set_li_vn_mode: version < 0 or > 7, using 4");
   1429   1.8  christos 		version = 4;
   1430   1.8  christos 	}
   1431   1.8  christos 
   1432   1.3    kardel 	if (mode > 7) {
   1433   1.3    kardel 		msyslog(LOG_DEBUG, "set_li_vn_mode: mode > 7, using client mode 3");
   1434   1.1    kardel 		mode = 3;
   1435   1.1    kardel 	}
   1436   1.1    kardel 
   1437   1.1    kardel 	spkt->li_vn_mode  = leap << 6;
   1438   1.1    kardel 	spkt->li_vn_mode |= version << 3;
   1439   1.1    kardel 	spkt->li_vn_mode |= mode;
   1440   1.1    kardel }
   1441   1.1    kardel 
   1442   1.8  christos 
   1443   1.8  christos /*
   1444   1.8  christos ** set_time applies 'offset' to the local clock.
   1445   1.8  christos */
   1446   1.1    kardel int
   1447   1.3    kardel set_time(
   1448   1.3    kardel 	double offset
   1449   1.3    kardel 	)
   1450   1.1    kardel {
   1451   1.8  christos 	int rc;
   1452   1.8  christos 
   1453   1.8  christos 	if (time_adjusted)
   1454   1.8  christos 		return EX_OK;
   1455   1.1    kardel 
   1456   1.8  christos 	/*
   1457   1.8  christos 	** If we can step but we cannot slew, then step.
   1458   1.8  christos 	** If we can step or slew and and |offset| > steplimit, then step.
   1459   1.8  christos 	*/
   1460   1.8  christos 	if (ENABLED_OPT(STEP) &&
   1461   1.8  christos 	    (   !ENABLED_OPT(SLEW)
   1462   1.8  christos 	     || (ENABLED_OPT(SLEW) && (fabs(offset) > steplimit))
   1463   1.8  christos 	    )) {
   1464   1.8  christos 		rc = step_systime(offset);
   1465   1.8  christos 
   1466   1.8  christos 		/* If there was a problem, can we rely on errno? */
   1467   1.8  christos 		if (1 == rc)
   1468   1.8  christos 			time_adjusted = TRUE;
   1469   1.8  christos 		return (time_adjusted)
   1470   1.8  christos 			   ? EX_OK
   1471   1.8  christos 			   : 1;
   1472   1.8  christos 		/*
   1473   1.8  christos 		** In case of error, what should we use?
   1474   1.8  christos 		** EX_UNAVAILABLE?
   1475   1.8  christos 		** EX_OSERR?
   1476   1.8  christos 		** EX_NOPERM?
   1477   1.8  christos 		*/
   1478   1.8  christos 	}
   1479   1.8  christos 
   1480   1.8  christos 	if (ENABLED_OPT(SLEW)) {
   1481   1.8  christos 		rc = adj_systime(offset);
   1482   1.1    kardel 
   1483   1.8  christos 		/* If there was a problem, can we rely on errno? */
   1484   1.8  christos 		if (1 == rc)
   1485   1.8  christos 			time_adjusted = TRUE;
   1486   1.8  christos 		return (time_adjusted)
   1487   1.8  christos 			   ? EX_OK
   1488   1.8  christos 			   : 1;
   1489   1.8  christos 		/*
   1490   1.8  christos 		** In case of error, what should we use?
   1491   1.8  christos 		** EX_UNAVAILABLE?
   1492   1.8  christos 		** EX_OSERR?
   1493   1.8  christos 		** EX_NOPERM?
   1494   1.8  christos 		*/
   1495   1.8  christos 	}
   1496   1.8  christos 
   1497   1.8  christos 	return EX_SOFTWARE;
   1498   1.8  christos }
   1499   1.8  christos 
   1500   1.8  christos 
   1501   1.8  christos int
   1502   1.8  christos libevent_version_ok(void)
   1503   1.8  christos {
   1504   1.8  christos 	ev_uint32_t v_compile_maj;
   1505   1.8  christos 	ev_uint32_t v_run_maj;
   1506   1.8  christos 
   1507   1.8  christos 	v_compile_maj = LIBEVENT_VERSION_NUMBER & 0xffff0000;
   1508   1.8  christos 	v_run_maj = event_get_version_number() & 0xffff0000;
   1509   1.8  christos 	if (v_compile_maj != v_run_maj) {
   1510   1.8  christos 		fprintf(stderr,
   1511   1.8  christos 			"Incompatible libevent versions: have %s, built with %s\n",
   1512   1.8  christos 			event_get_version(),
   1513   1.8  christos 			LIBEVENT_VERSION);
   1514   1.3    kardel 		return 0;
   1515   1.1    kardel 	}
   1516   1.8  christos 	return 1;
   1517   1.8  christos }
   1518   1.3    kardel 
   1519   1.8  christos /*
   1520   1.8  christos  * gettimeofday_cached()
   1521   1.8  christos  *
   1522   1.8  christos  * Clones the event_base_gettimeofday_cached() interface but ensures the
   1523   1.8  christos  * times are always on the gettimeofday() 1970 scale.  Older libevent 2
   1524   1.8  christos  * sometimes used gettimeofday(), sometimes the since-system-start
   1525   1.8  christos  * clock_gettime(CLOCK_MONOTONIC), depending on the platform.
   1526   1.8  christos  *
   1527   1.8  christos  * It is not cleanly possible to tell which timescale older libevent is
   1528   1.8  christos  * using.
   1529   1.8  christos  *
   1530   1.8  christos  * The strategy involves 1 hour thresholds chosen to be far longer than
   1531   1.8  christos  * the duration of a round of libevent callbacks, which share a cached
   1532   1.8  christos  * start-of-round time.  First compare the last cached time with the
   1533   1.8  christos  * current gettimeofday() time.  If they are within one hour, libevent
   1534   1.8  christos  * is using the proper timescale so leave the offset 0.  Otherwise,
   1535   1.8  christos  * compare libevent's cached time and the current time on the monotonic
   1536   1.8  christos  * scale.  If they are within an hour, libevent is using the monotonic
   1537   1.8  christos  * scale so calculate the offset to add to such times to bring them to
   1538   1.8  christos  * gettimeofday()'s scale.
   1539   1.8  christos  */
   1540   1.8  christos int
   1541   1.8  christos gettimeofday_cached(
   1542   1.8  christos 	struct event_base *	b,
   1543   1.8  christos 	struct timeval *	caller_tv
   1544   1.8  christos 	)
   1545   1.8  christos {
   1546   1.8  christos #if defined(_EVENT_HAVE_CLOCK_GETTIME) && defined(CLOCK_MONOTONIC)
   1547   1.8  christos 	static struct event_base *	cached_b;
   1548   1.8  christos 	static struct timeval		cached;
   1549   1.8  christos 	static struct timeval		adj_cached;
   1550   1.8  christos 	static struct timeval		offset;
   1551   1.8  christos 	static int			offset_ready;
   1552   1.8  christos 	struct timeval			latest;
   1553   1.8  christos 	struct timeval			systemt;
   1554   1.8  christos 	struct timespec			ts;
   1555   1.8  christos 	struct timeval			mono;
   1556   1.8  christos 	struct timeval			diff;
   1557   1.8  christos 	int				cgt_rc;
   1558   1.8  christos 	int				gtod_rc;
   1559   1.8  christos 
   1560   1.8  christos 	event_base_gettimeofday_cached(b, &latest);
   1561   1.8  christos 	if (b == cached_b &&
   1562   1.8  christos 	    !memcmp(&latest, &cached, sizeof(latest))) {
   1563   1.8  christos 		*caller_tv = adj_cached;
   1564   1.8  christos 		return 0;
   1565   1.8  christos 	}
   1566   1.8  christos 	cached = latest;
   1567   1.8  christos 	cached_b = b;
   1568   1.8  christos 	if (!offset_ready) {
   1569   1.8  christos 		cgt_rc = clock_gettime(CLOCK_MONOTONIC, &ts);
   1570   1.8  christos 		gtod_rc = gettimeofday(&systemt, NULL);
   1571   1.8  christos 		if (0 != gtod_rc) {
   1572   1.8  christos 			msyslog(LOG_ERR,
   1573   1.8  christos 				"%s: gettimeofday() error %m",
   1574   1.8  christos 				progname);
   1575   1.8  christos 			exit(1);
   1576   1.8  christos 		}
   1577   1.8  christos 		diff = sub_tval(systemt, latest);
   1578   1.8  christos 		if (debug > 1)
   1579   1.8  christos 			printf("system minus cached %+ld.%06ld\n",
   1580   1.8  christos 			       (long)diff.tv_sec, (long)diff.tv_usec);
   1581   1.8  christos 		if (0 != cgt_rc || labs((long)diff.tv_sec) < 3600) {
   1582   1.8  christos 			/*
   1583   1.8  christos 			 * Either use_monotonic == 0, or this libevent
   1584   1.8  christos 			 * has been repaired.  Leave offset at zero.
   1585   1.8  christos 			 */
   1586   1.8  christos 		} else {
   1587   1.8  christos 			mono.tv_sec = ts.tv_sec;
   1588   1.8  christos 			mono.tv_usec = ts.tv_nsec / 1000;
   1589   1.8  christos 			diff = sub_tval(latest, mono);
   1590   1.8  christos 			if (debug > 1)
   1591   1.8  christos 				printf("cached minus monotonic %+ld.%06ld\n",
   1592   1.8  christos 				       (long)diff.tv_sec, (long)diff.tv_usec);
   1593   1.8  christos 			if (labs((long)diff.tv_sec) < 3600) {
   1594   1.8  christos 				/* older libevent2 using monotonic */
   1595   1.8  christos 				offset = sub_tval(systemt, mono);
   1596   1.8  christos 				TRACE(1, ("%s: Offsetting libevent CLOCK_MONOTONIC times  by %+ld.%06ld\n",
   1597   1.8  christos 					 "gettimeofday_cached",
   1598   1.8  christos 					 (long)offset.tv_sec,
   1599   1.8  christos 					 (long)offset.tv_usec));
   1600   1.8  christos 			}
   1601   1.8  christos 		}
   1602   1.8  christos 		offset_ready = TRUE;
   1603   1.8  christos 	}
   1604   1.8  christos 	adj_cached = add_tval(cached, offset);
   1605   1.8  christos 	*caller_tv = adj_cached;
   1606   1.3    kardel 
   1607   1.3    kardel 	return 0;
   1608   1.8  christos #else
   1609   1.8  christos 	return event_base_gettimeofday_cached(b, caller_tv);
   1610   1.8  christos #endif
   1611   1.1    kardel }
   1612   1.8  christos 
   1613