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