1/*	$KAME: rtsold.c,v 1.67 2003/05/17 18:16:15 itojun Exp $	*/
2
3/*-
4 * SPDX-License-Identifier: BSD-3-Clause
5 *
6 * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
7 * All rights reserved.
8 *
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
11 * are met:
12 * 1. Redistributions of source code must retain the above copyright
13 *    notice, this list of conditions and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the above copyright
15 *    notice, this list of conditions and the following disclaimer in the
16 *    documentation and/or other materials provided with the distribution.
17 * 3. Neither the name of the project nor the names of its contributors
18 *    may be used to endorse or promote products derived from this software
19 *    without specific prior written permission.
20 *
21 * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
22 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24 * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
25 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31 * SUCH DAMAGE.
32 *
33 * $FreeBSD$
34 */
35
36#include <sys/param.h>
37#include <sys/capsicum.h>
38#include <sys/event.h>
39#include <sys/ioctl.h>
40#include <sys/socket.h>
41
42#include <net/if.h>
43#include <net/if_dl.h>
44
45#include <netinet/in.h>
46#include <netinet/icmp6.h>
47#include <netinet/in_var.h>
48#include <arpa/inet.h>
49
50#include <netinet6/nd6.h>
51
52#include <capsicum_helpers.h>
53#include <err.h>
54#include <errno.h>
55#include <ifaddrs.h>
56#include <libgen.h>
57#include <signal.h>
58#include <stdarg.h>
59#include <stdio.h>
60#include <stdlib.h>
61#include <string.h>
62#include <syslog.h>
63#include <time.h>
64#include <unistd.h>
65
66#include <libcasper.h>
67#include <casper/cap_syslog.h>
68#include <libutil.h>
69
70#include "rtsold.h"
71
72#define RTSOL_DUMPFILE	"/var/run/rtsold.dump"
73
74struct timespec tm_max;
75static int log_upto = 999;
76static int fflag = 0;
77
78int Fflag = 0;	/* force setting sysctl parameters */
79int aflag = 0;
80int dflag = 0;
81int uflag = 0;
82
83const char *managedconf_script;
84const char *otherconf_script;
85const char *resolvconf_script = "/sbin/resolvconf";
86
87cap_channel_t *capllflags, *capscript, *capsendmsg, *capsyslog;
88
89/* protocol constants */
90#define MAX_RTR_SOLICITATION_DELAY	1 /* second */
91#define RTR_SOLICITATION_INTERVAL	4 /* seconds */
92#define MAX_RTR_SOLICITATIONS		3 /* times */
93
94/*
95 * implementation dependent constants in seconds
96 * XXX: should be configurable
97 */
98#define PROBE_INTERVAL 60
99
100/* static variables and functions */
101static int mobile_node = 0;
102
103static sig_atomic_t do_dump, do_exit;
104static struct pidfh *pfh;
105
106static char **autoifprobe(void);
107static int ifconfig(char *ifname);
108static int init_capabilities(void);
109static int make_packet(struct ifinfo *);
110static struct timespec *rtsol_check_timer(void);
111
112static void set_dumpfile(int);
113static void set_exit(int);
114static void usage(const char *progname);
115
116int
117main(int argc, char **argv)
118{
119	struct kevent events[2];
120	FILE *dumpfp;
121	struct ifinfo *ifi;
122	struct timespec *timeout;
123	const char *opts, *pidfilepath, *progname;
124	int ch, error, kq, once, rcvsock, rtsock;
125
126	progname = basename(argv[0]);
127	if (strcmp(progname, "rtsold") == 0) {
128		opts = "adDfFm1M:O:p:R:u";
129		once = 0;
130		pidfilepath = NULL;
131	} else {
132		opts = "adDFM:O:R:u";
133		fflag = 1;
134		once = 1;
135	}
136
137	while ((ch = getopt(argc, argv, opts)) != -1) {
138		switch (ch) {
139		case 'a':
140			aflag = 1;
141			break;
142		case 'd':
143			dflag += 1;
144			break;
145		case 'D':
146			dflag += 2;
147			break;
148		case 'f':
149			fflag = 1;
150			break;
151		case 'F':
152			Fflag = 1;
153			break;
154		case 'm':
155			mobile_node = 1;
156			break;
157		case '1':
158			once = 1;
159			break;
160		case 'M':
161			managedconf_script = optarg;
162			break;
163		case 'O':
164			otherconf_script = optarg;
165			break;
166		case 'p':
167			pidfilepath = optarg;
168			break;
169		case 'R':
170			resolvconf_script = optarg;
171			break;
172		case 'u':
173			uflag = 1;
174			break;
175		default:
176			usage(progname);
177		}
178	}
179	argc -= optind;
180	argv += optind;
181
182	if ((!aflag && argc == 0) || (aflag && argc != 0))
183		usage(progname);
184
185	/* Generate maximum time in timespec. */
186	tm_max.tv_sec = (-1) & ~((time_t)1 << ((sizeof(tm_max.tv_sec) * 8) - 1));
187	tm_max.tv_nsec = (-1) & ~((long)1 << ((sizeof(tm_max.tv_nsec) * 8) - 1));
188
189	/* set log level */
190	if (dflag > 1)
191		log_upto = LOG_DEBUG;
192	else if (dflag > 0)
193		log_upto = LOG_INFO;
194	else
195		log_upto = LOG_NOTICE;
196
197	if (managedconf_script != NULL && *managedconf_script != '/')
198		errx(1, "configuration script (%s) must be an absolute path",
199		    managedconf_script);
200	if (otherconf_script != NULL && *otherconf_script != '/')
201		errx(1, "configuration script (%s) must be an absolute path",
202		    otherconf_script);
203	if (*resolvconf_script != '/')
204		errx(1, "configuration script (%s) must be an absolute path",
205		    resolvconf_script);
206
207	if (!fflag) {
208		pfh = pidfile_open(pidfilepath, 0644, NULL);
209		if (pfh == NULL)
210			errx(1, "failed to open pidfile: %s", strerror(errno));
211		if (daemon(0, 0) != 0)
212			errx(1, "failed to daemonize");
213	}
214
215	if ((error = init_capabilities()) != 0)
216		err(1, "failed to initialize capabilities");
217
218	if (!fflag) {
219		cap_openlog(capsyslog, progname, LOG_NDELAY | LOG_PID,
220		    LOG_DAEMON);
221		if (log_upto >= 0)
222			(void)cap_setlogmask(capsyslog, LOG_UPTO(log_upto));
223		(void)signal(SIGTERM, set_exit);
224		(void)signal(SIGINT, set_exit);
225		(void)signal(SIGUSR1, set_dumpfile);
226		dumpfp = rtsold_init_dumpfile(RTSOL_DUMPFILE);
227	} else
228		dumpfp = NULL;
229
230	kq = kqueue();
231	if (kq < 0) {
232		warnmsg(LOG_ERR, __func__, "failed to create a kqueue: %s",
233		    strerror(errno));
234		exit(1);
235	}
236
237	/* Open global sockets and register for read events. */
238	if ((rtsock = rtsock_open()) < 0) {
239		warnmsg(LOG_ERR, __func__, "failed to open routing socket");
240		exit(1);
241	}
242	if ((rcvsock = recvsockopen()) < 0) {
243		warnmsg(LOG_ERR, __func__, "failed to open receive socket");
244		exit(1);
245	}
246	EV_SET(&events[0], rtsock, EVFILT_READ, EV_ADD, 0, 0, NULL);
247	EV_SET(&events[1], rcvsock, EVFILT_READ, EV_ADD, 0, 0, NULL);
248	if (kevent(kq, events, 2, NULL, 0, NULL) < 0) {
249		warnmsg(LOG_ERR, __func__, "kevent(): %s", strerror(errno));
250		exit(1);
251	}
252
253	/* Probe network interfaces and set up tracking info. */
254	if (ifinit() != 0) {
255		warnmsg(LOG_ERR, __func__, "failed to initialize interfaces");
256		exit(1);
257	}
258	if (aflag)
259		argv = autoifprobe();
260	while (argv && *argv) {
261		if (ifconfig(*argv)) {
262			warnmsg(LOG_ERR, __func__,
263			    "failed to initialize %s", *argv);
264			exit(1);
265		}
266		argv++;
267	}
268
269	/* Write to our pidfile. */
270	if (pfh != NULL && pidfile_write(pfh) != 0) {
271		warnmsg(LOG_ERR, __func__,
272		    "failed to open pidfile: %s", strerror(errno));
273		exit(1);
274	}
275
276	/* Enter capability mode. */
277	caph_cache_catpages();
278	if (caph_enter_casper() != 0) {
279		warnmsg(LOG_ERR, __func__, "caph_enter(): %s", strerror(errno));
280		exit(1);
281	}
282
283	for (;;) {
284		if (do_exit) {
285			/* Handle SIGTERM, SIGINT. */
286			if (pfh != NULL)
287				pidfile_remove(pfh);
288			break;
289		}
290		if (do_dump) {
291			/* Handle SIGUSR1. */
292			do_dump = 0;
293			if (dumpfp != NULL)
294				rtsold_dump(dumpfp);
295		}
296
297		timeout = rtsol_check_timer();
298
299		if (once) {
300			/* if we have no timeout, we are done (or failed) */
301			if (timeout == NULL)
302				break;
303
304			/* if all interfaces have got RA packet, we are done */
305			TAILQ_FOREACH(ifi, &ifinfo_head, ifi_next) {
306				if (ifi->state != IFS_DOWN && ifi->racnt == 0)
307					break;
308			}
309			if (ifi == NULL)
310				break;
311		}
312
313		error = kevent(kq, NULL, 0, &events[0], 1, timeout);
314		if (error < 1) {
315			if (error < 0 && errno != EINTR)
316				warnmsg(LOG_ERR, __func__, "kevent(): %s",
317				    strerror(errno));
318			continue;
319		}
320
321		if (events[0].ident == (uintptr_t)rtsock)
322			rtsock_input(rtsock);
323		else
324			rtsol_input(rcvsock);
325	}
326
327	return (0);
328}
329
330static int
331init_capabilities(void)
332{
333#ifdef WITH_CASPER
334	const char *const scripts[] =
335	    { resolvconf_script, managedconf_script, otherconf_script };
336	const char *scripts_set[nitems(scripts)];
337	cap_channel_t *capcasper;
338	nvlist_t *limits;
339	int count;
340
341	capcasper = cap_init();
342	if (capcasper == NULL)
343		return (-1);
344
345	capllflags = cap_service_open(capcasper, "rtsold.llflags");
346	if (capllflags == NULL)
347		return (-1);
348
349	capscript = cap_service_open(capcasper, "rtsold.script");
350	if (capscript == NULL)
351		return (-1);
352	count = 0;
353	for (size_t i = 0; i < nitems(scripts); i++)
354		if (scripts[i] != NULL)
355			scripts_set[count++] = scripts[i];
356	limits = nvlist_create(0);
357	nvlist_add_string_array(limits, "scripts", scripts_set, count);
358	if (cap_limit_set(capscript, limits) != 0)
359		return (-1);
360
361	capsendmsg = cap_service_open(capcasper, "rtsold.sendmsg");
362	if (capsendmsg == NULL)
363		return (-1);
364
365	if (!fflag) {
366		capsyslog = cap_service_open(capcasper, "system.syslog");
367		if (capsyslog == NULL)
368			return (-1);
369	}
370
371	cap_close(capcasper);
372#endif /* WITH_CASPER */
373	return (0);
374}
375
376static int
377ifconfig(char *ifname)
378{
379	struct ifinfo *ifi;
380	struct sockaddr_dl *sdl;
381	int flags;
382
383	ifi = NULL;
384	if ((sdl = if_nametosdl(ifname)) == NULL) {
385		warnmsg(LOG_ERR, __func__,
386		    "failed to get link layer information for %s", ifname);
387		goto bad;
388	}
389	if (find_ifinfo(sdl->sdl_index)) {
390		warnmsg(LOG_ERR, __func__,
391		    "interface %s was already configured", ifname);
392		goto bad;
393	}
394
395	if (Fflag) {
396		struct in6_ndireq nd;
397		int s;
398
399		if ((s = socket(AF_INET6, SOCK_DGRAM, 0)) < 0) {
400			warnmsg(LOG_ERR, __func__, "socket() failed.");
401			goto bad;
402		}
403		memset(&nd, 0, sizeof(nd));
404		strlcpy(nd.ifname, ifname, sizeof(nd.ifname));
405		if (ioctl(s, SIOCGIFINFO_IN6, (caddr_t)&nd) < 0) {
406			warnmsg(LOG_ERR, __func__,
407			    "cannot get accept_rtadv flag");
408			(void)close(s);
409			goto bad;
410		}
411		nd.ndi.flags |= ND6_IFF_ACCEPT_RTADV;
412		if (ioctl(s, SIOCSIFINFO_IN6, (caddr_t)&nd) < 0) {
413			warnmsg(LOG_ERR, __func__,
414			    "cannot set accept_rtadv flag");
415			(void)close(s);
416			goto bad;
417		}
418		(void)close(s);
419	}
420
421	if ((ifi = malloc(sizeof(*ifi))) == NULL) {
422		warnmsg(LOG_ERR, __func__, "memory allocation failed");
423		goto bad;
424	}
425	memset(ifi, 0, sizeof(*ifi));
426	ifi->sdl = sdl;
427	ifi->ifi_rdnss = IFI_DNSOPT_STATE_NOINFO;
428	ifi->ifi_dnssl = IFI_DNSOPT_STATE_NOINFO;
429	TAILQ_INIT(&ifi->ifi_rainfo);
430	strlcpy(ifi->ifname, ifname, sizeof(ifi->ifname));
431
432	/* construct a router solicitation message */
433	if (make_packet(ifi))
434		goto bad;
435
436	/* set link ID of this interface. */
437#ifdef HAVE_SCOPELIB
438	if (inet_zoneid(AF_INET6, 2, ifname, &ifi->linkid))
439		goto bad;
440#else
441	/* XXX: assume interface IDs as link IDs */
442	ifi->linkid = ifi->sdl->sdl_index;
443#endif
444
445	/*
446	 * check if the interface is available.
447	 * also check if SIOCGIFMEDIA ioctl is OK on the interface.
448	 */
449	ifi->mediareqok = 1;
450	ifi->active = interface_status(ifi);
451	if (!ifi->mediareqok) {
452		/*
453		 * probe routers periodically even if the link status
454		 * does not change.
455		 */
456		ifi->probeinterval = PROBE_INTERVAL;
457	}
458
459	/* activate interface: interface_up returns 0 on success */
460	flags = interface_up(ifi->ifname);
461	if (flags == 0)
462		ifi->state = IFS_DELAY;
463	else if (flags == IFS_TENTATIVE)
464		ifi->state = IFS_TENTATIVE;
465	else
466		ifi->state = IFS_DOWN;
467
468	rtsol_timer_update(ifi);
469
470	TAILQ_INSERT_TAIL(&ifinfo_head, ifi, ifi_next);
471	return (0);
472
473bad:
474	free(sdl);
475	free(ifi);
476	return (-1);
477}
478
479struct rainfo *
480find_rainfo(struct ifinfo *ifi, struct sockaddr_in6 *sin6)
481{
482	struct rainfo *rai;
483
484	TAILQ_FOREACH(rai, &ifi->ifi_rainfo, rai_next)
485		if (memcmp(&rai->rai_saddr.sin6_addr, &sin6->sin6_addr,
486		    sizeof(rai->rai_saddr.sin6_addr)) == 0)
487			return (rai);
488
489	return (NULL);
490}
491
492struct ifinfo *
493find_ifinfo(int ifindex)
494{
495	struct ifinfo *ifi;
496
497	TAILQ_FOREACH(ifi, &ifinfo_head, ifi_next) {
498		if (ifi->sdl->sdl_index == ifindex)
499			return (ifi);
500	}
501	return (NULL);
502}
503
504static int
505make_packet(struct ifinfo *ifi)
506{
507	size_t packlen = sizeof(struct nd_router_solicit), lladdroptlen = 0;
508	struct nd_router_solicit *rs;
509	char *buf;
510
511	if ((lladdroptlen = lladdropt_length(ifi->sdl)) == 0) {
512		warnmsg(LOG_INFO, __func__,
513		    "link-layer address option has null length"
514		    " on %s. Treat as not included.", ifi->ifname);
515	}
516	packlen += lladdroptlen;
517	ifi->rs_datalen = packlen;
518
519	/* allocate buffer */
520	if ((buf = malloc(packlen)) == NULL) {
521		warnmsg(LOG_ERR, __func__,
522		    "memory allocation failed for %s", ifi->ifname);
523		return (-1);
524	}
525	ifi->rs_data = buf;
526
527	/* fill in the message */
528	rs = (struct nd_router_solicit *)buf;
529	rs->nd_rs_type = ND_ROUTER_SOLICIT;
530	rs->nd_rs_code = 0;
531	rs->nd_rs_cksum = 0;
532	rs->nd_rs_reserved = 0;
533	buf += sizeof(*rs);
534
535	/* fill in source link-layer address option */
536	if (lladdroptlen)
537		lladdropt_fill(ifi->sdl, (struct nd_opt_hdr *)buf);
538
539	return (0);
540}
541
542static struct timespec *
543rtsol_check_timer(void)
544{
545	static struct timespec returnval;
546	struct timespec now, rtsol_timer;
547	struct ifinfo *ifi;
548	struct rainfo *rai;
549	struct ra_opt *rao, *raotmp;
550	int error, flags;
551
552	clock_gettime(CLOCK_MONOTONIC_FAST, &now);
553
554	rtsol_timer = tm_max;
555
556	TAILQ_FOREACH(ifi, &ifinfo_head, ifi_next) {
557		if (TS_CMP(&ifi->expire, &now, <=)) {
558			warnmsg(LOG_DEBUG, __func__, "timer expiration on %s, "
559			    "state = %d", ifi->ifname, ifi->state);
560
561			while((rai = TAILQ_FIRST(&ifi->ifi_rainfo)) != NULL) {
562				/* Remove all RA options. */
563				TAILQ_REMOVE(&ifi->ifi_rainfo, rai, rai_next);
564				while ((rao = TAILQ_FIRST(&rai->rai_ra_opt)) !=
565				    NULL) {
566					TAILQ_REMOVE(&rai->rai_ra_opt, rao,
567					    rao_next);
568					if (rao->rao_msg != NULL)
569						free(rao->rao_msg);
570					free(rao);
571				}
572				free(rai);
573			}
574			switch (ifi->state) {
575			case IFS_DOWN:
576			case IFS_TENTATIVE:
577				/* interface_up returns 0 on success */
578				flags = interface_up(ifi->ifname);
579				if (flags == 0)
580					ifi->state = IFS_DELAY;
581				else if (flags == IFS_TENTATIVE)
582					ifi->state = IFS_TENTATIVE;
583				else
584					ifi->state = IFS_DOWN;
585				break;
586			case IFS_IDLE:
587			{
588				int oldstatus = ifi->active;
589				int probe = 0;
590
591				ifi->active = interface_status(ifi);
592
593				if (oldstatus != ifi->active) {
594					warnmsg(LOG_DEBUG, __func__,
595					    "%s status is changed"
596					    " from %d to %d",
597					    ifi->ifname,
598					    oldstatus, ifi->active);
599					probe = 1;
600					ifi->state = IFS_DELAY;
601				} else if (ifi->probeinterval &&
602				    (ifi->probetimer -=
603				    ifi->timer.tv_sec) <= 0) {
604					/* probe timer expired */
605					ifi->probetimer =
606					    ifi->probeinterval;
607					probe = 1;
608					ifi->state = IFS_PROBE;
609				}
610
611				/*
612				 * If we need a probe, clear the previous
613				 * status wrt the "managed/other" configuration.
614				 */
615				if (probe) {
616					ifi->managedconfig = 0;
617					ifi->otherconfig = 0;
618				}
619				if (probe && mobile_node) {
620					error = cap_probe_defrouters(capsendmsg,
621					    ifi);
622					if (error != 0)
623						warnmsg(LOG_DEBUG, __func__,
624					    "failed to probe routers: %d",
625						    error);
626				}
627				break;
628			}
629			case IFS_DELAY:
630				ifi->state = IFS_PROBE;
631				(void)cap_rssend(capsendmsg, ifi);
632				break;
633			case IFS_PROBE:
634				if (ifi->probes < MAX_RTR_SOLICITATIONS)
635					(void)cap_rssend(capsendmsg, ifi);
636				else {
637					warnmsg(LOG_INFO, __func__,
638					    "No answer after sending %d RSs",
639					    ifi->probes);
640					ifi->probes = 0;
641					ifi->state = IFS_IDLE;
642				}
643				break;
644			}
645			rtsol_timer_update(ifi);
646		} else {
647			/* Expiration check for RA options. */
648			int expire = 0;
649
650			TAILQ_FOREACH(rai, &ifi->ifi_rainfo, rai_next) {
651				TAILQ_FOREACH_SAFE(rao, &rai->rai_ra_opt,
652				    rao_next, raotmp) {
653					warnmsg(LOG_DEBUG, __func__,
654					    "RA expiration timer: "
655					    "type=%d, msg=%s, expire=%s",
656					    rao->rao_type, (char *)rao->rao_msg,
657						sec2str(&rao->rao_expire));
658					if (TS_CMP(&now, &rao->rao_expire,
659					    >=)) {
660						warnmsg(LOG_DEBUG, __func__,
661						    "RA expiration timer: "
662						    "expired.");
663						TAILQ_REMOVE(&rai->rai_ra_opt,
664						    rao, rao_next);
665						if (rao->rao_msg != NULL)
666							free(rao->rao_msg);
667						free(rao);
668						expire = 1;
669					}
670				}
671			}
672			if (expire)
673				ra_opt_handler(ifi);
674		}
675		if (TS_CMP(&ifi->expire, &rtsol_timer, <))
676			rtsol_timer = ifi->expire;
677	}
678
679	if (TS_CMP(&rtsol_timer, &tm_max, ==)) {
680		warnmsg(LOG_DEBUG, __func__, "there is no timer");
681		return (NULL);
682	} else if (TS_CMP(&rtsol_timer, &now, <))
683		/* this may occur when the interval is too small */
684		returnval.tv_sec = returnval.tv_nsec = 0;
685	else
686		TS_SUB(&rtsol_timer, &now, &returnval);
687
688	now.tv_sec += returnval.tv_sec;
689	now.tv_nsec += returnval.tv_nsec;
690	warnmsg(LOG_DEBUG, __func__, "New timer is %s",
691	    sec2str(&now));
692
693	return (&returnval);
694}
695
696void
697rtsol_timer_update(struct ifinfo *ifi)
698{
699#define MILLION 1000000
700#define DADRETRY 10		/* XXX: adhoc */
701	long interval;
702	struct timespec now;
703
704	bzero(&ifi->timer, sizeof(ifi->timer));
705
706	switch (ifi->state) {
707	case IFS_DOWN:
708	case IFS_TENTATIVE:
709		if (++ifi->dadcount > DADRETRY) {
710			ifi->dadcount = 0;
711			ifi->timer.tv_sec = PROBE_INTERVAL;
712		} else
713			ifi->timer.tv_sec = 1;
714		break;
715	case IFS_IDLE:
716		if (mobile_node)
717			/* XXX should be configurable */
718			ifi->timer.tv_sec = 3;
719		else
720			ifi->timer = tm_max;	/* stop timer(valid?) */
721		break;
722	case IFS_DELAY:
723		interval = arc4random_uniform(MAX_RTR_SOLICITATION_DELAY * MILLION);
724		ifi->timer.tv_sec = interval / MILLION;
725		ifi->timer.tv_nsec = (interval % MILLION) * 1000;
726		break;
727	case IFS_PROBE:
728		if (ifi->probes < MAX_RTR_SOLICITATIONS)
729			ifi->timer.tv_sec = RTR_SOLICITATION_INTERVAL;
730		else
731			/*
732			 * After sending MAX_RTR_SOLICITATIONS solicitations,
733			 * we're just waiting for possible replies; there
734			 * will be no more solicitation.  Thus, we change
735			 * the timer value to MAX_RTR_SOLICITATION_DELAY based
736			 * on RFC 2461, Section 6.3.7.
737			 */
738			ifi->timer.tv_sec = MAX_RTR_SOLICITATION_DELAY;
739		break;
740	default:
741		warnmsg(LOG_ERR, __func__,
742		    "illegal interface state(%d) on %s",
743		    ifi->state, ifi->ifname);
744		return;
745	}
746
747	/* reset the timer */
748	if (TS_CMP(&ifi->timer, &tm_max, ==)) {
749		ifi->expire = tm_max;
750		warnmsg(LOG_DEBUG, __func__,
751		    "stop timer for %s", ifi->ifname);
752	} else {
753		clock_gettime(CLOCK_MONOTONIC_FAST, &now);
754		TS_ADD(&now, &ifi->timer, &ifi->expire);
755
756		now.tv_sec += ifi->timer.tv_sec;
757		now.tv_nsec += ifi->timer.tv_nsec;
758		warnmsg(LOG_DEBUG, __func__, "set timer for %s to %s",
759		    ifi->ifname, sec2str(&now));
760	}
761
762#undef MILLION
763}
764
765static void
766set_dumpfile(int sig __unused)
767{
768
769	do_dump = 1;
770}
771
772static void
773set_exit(int sig __unused)
774{
775
776	do_exit = 1;
777}
778
779static void
780usage(const char *progname)
781{
782
783	if (strcmp(progname, "rtsold") == 0) {
784		fprintf(stderr, "usage: rtsold [-dDfFm1] [-O script-name] "
785		    "[-p pidfile] [-R script-name] interface ...\n");
786		fprintf(stderr, "usage: rtsold [-dDfFm1] [-O script-name] "
787		    "[-p pidfile] [-R script-name] -a\n");
788	} else {
789		fprintf(stderr, "usage: rtsol [-dDF] [-O script-name] "
790		    "[-p pidfile] [-R script-name] interface ...\n");
791		fprintf(stderr, "usage: rtsol [-dDF] [-O script-name] "
792		    "[-p pidfile] [-R script-name] -a\n");
793	}
794	exit(1);
795}
796
797void
798warnmsg(int priority, const char *func, const char *msg, ...)
799{
800	va_list ap;
801	char buf[BUFSIZ];
802
803	va_start(ap, msg);
804	if (fflag) {
805		if (priority <= log_upto)
806			vwarnx(msg, ap);
807	} else {
808		snprintf(buf, sizeof(buf), "<%s> %s", func, msg);
809		msg = buf;
810		cap_vsyslog(capsyslog, priority, msg, ap);
811	}
812	va_end(ap);
813}
814
815/*
816 * return a list of interfaces which is suitable to sending an RS.
817 */
818static char **
819autoifprobe(void)
820{
821	static char **argv = NULL;
822	static int n = 0;
823	char **a;
824	int s = 0, i, found;
825	struct ifaddrs *ifap, *ifa;
826	struct in6_ndireq nd;
827
828	/* initialize */
829	while (n--)
830		free(argv[n]);
831	if (argv) {
832		free(argv);
833		argv = NULL;
834	}
835	n = 0;
836
837	if (getifaddrs(&ifap) != 0)
838		return (NULL);
839
840	if (!Fflag && (s = socket(AF_INET6, SOCK_DGRAM, 0)) < 0) {
841		warnmsg(LOG_ERR, __func__, "socket");
842		exit(1);
843	}
844
845	/* find an ethernet */
846	for (ifa = ifap; ifa; ifa = ifa->ifa_next) {
847		if ((ifa->ifa_flags & IFF_UP) == 0)
848			continue;
849		if ((ifa->ifa_flags & IFF_POINTOPOINT) != 0)
850			continue;
851		if ((ifa->ifa_flags & IFF_LOOPBACK) != 0)
852			continue;
853		if ((ifa->ifa_flags & IFF_MULTICAST) == 0)
854			continue;
855
856		if (ifa->ifa_addr->sa_family != AF_INET6)
857			continue;
858
859		found = 0;
860		for (i = 0; i < n; i++) {
861			if (strcmp(argv[i], ifa->ifa_name) == 0) {
862				found++;
863				break;
864			}
865		}
866		if (found)
867			continue;
868
869		/*
870		 * Skip the interfaces which IPv6 and/or accepting RA
871		 * is disabled.
872		 */
873		if (!Fflag) {
874			memset(&nd, 0, sizeof(nd));
875			strlcpy(nd.ifname, ifa->ifa_name, sizeof(nd.ifname));
876			if (ioctl(s, SIOCGIFINFO_IN6, (caddr_t)&nd) < 0) {
877				warnmsg(LOG_ERR, __func__,
878					"ioctl(SIOCGIFINFO_IN6)");
879				exit(1);
880			}
881			if ((nd.ndi.flags & ND6_IFF_IFDISABLED))
882				continue;
883			if (!(nd.ndi.flags & ND6_IFF_ACCEPT_RTADV))
884				continue;
885		}
886
887		/* if we find multiple candidates, just warn. */
888		if (n != 0 && dflag > 1)
889			warnmsg(LOG_WARNING, __func__,
890				"multiple interfaces found");
891
892		a = realloc(argv, (n + 1) * sizeof(char *));
893		if (a == NULL) {
894			warnmsg(LOG_ERR, __func__, "realloc");
895			exit(1);
896		}
897		argv = a;
898		argv[n] = strdup(ifa->ifa_name);
899		if (!argv[n]) {
900			warnmsg(LOG_ERR, __func__, "malloc");
901			exit(1);
902		}
903		n++;
904	}
905
906	if (n) {
907		a = realloc(argv, (n + 1) * sizeof(char *));
908		if (a == NULL) {
909			warnmsg(LOG_ERR, __func__, "realloc");
910			exit(1);
911		}
912		argv = a;
913		argv[n] = NULL;
914
915		if (dflag > 0) {
916			for (i = 0; i < n; i++)
917				warnmsg(LOG_WARNING, __func__, "probing %s",
918					argv[i]);
919		}
920	}
921	if (!Fflag)
922		close(s);
923	freeifaddrs(ifap);
924	return (argv);
925}
926