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