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