xref: /freebsd/usr.sbin/rtsold/rtsold.c (revision 79ac3c12a714bcd3f2354c52d948aed9575c46d6)
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 
74 struct timespec tm_max;
75 static int log_upto = 999;
76 static int fflag = 0;
77 
78 int Fflag = 0;	/* force setting sysctl parameters */
79 int aflag = 0;
80 int dflag = 0;
81 int uflag = 0;
82 
83 const char *managedconf_script;
84 const char *otherconf_script;
85 const char *resolvconf_script = "/sbin/resolvconf";
86 
87 cap_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 */
101 static int mobile_node = 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 = "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 
330 static int
331 init_capabilities(void)
332 {
333 #ifdef WITH_CASPER
334 	const char *const scripts[] =
335 	    { resolvconf_script, managedconf_script, otherconf_script };
336 	cap_channel_t *capcasper;
337 	nvlist_t *limits;
338 
339 	capcasper = cap_init();
340 	if (capcasper == NULL)
341 		return (-1);
342 
343 	capllflags = cap_service_open(capcasper, "rtsold.llflags");
344 	if (capllflags == NULL)
345 		return (-1);
346 
347 	capscript = cap_service_open(capcasper, "rtsold.script");
348 	if (capscript == NULL)
349 		return (-1);
350 	limits = nvlist_create(0);
351 	for (size_t i = 0; i < nitems(scripts); i++)
352 		if (scripts[i] != NULL)
353 			nvlist_append_string_array(limits, "scripts",
354 			    scripts[i]);
355 	if (cap_limit_set(capscript, limits) != 0)
356 		return (-1);
357 
358 	capsendmsg = cap_service_open(capcasper, "rtsold.sendmsg");
359 	if (capsendmsg == NULL)
360 		return (-1);
361 
362 	if (!fflag) {
363 		capsyslog = cap_service_open(capcasper, "system.syslog");
364 		if (capsyslog == NULL)
365 			return (-1);
366 	}
367 
368 	cap_close(capcasper);
369 #endif /* WITH_CASPER */
370 	return (0);
371 }
372 
373 static int
374 ifconfig(char *ifname)
375 {
376 	struct ifinfo *ifi;
377 	struct sockaddr_dl *sdl;
378 	int flags;
379 
380 	ifi = NULL;
381 	if ((sdl = if_nametosdl(ifname)) == NULL) {
382 		warnmsg(LOG_ERR, __func__,
383 		    "failed to get link layer information for %s", ifname);
384 		goto bad;
385 	}
386 	if (find_ifinfo(sdl->sdl_index)) {
387 		warnmsg(LOG_ERR, __func__,
388 		    "interface %s was already configured", ifname);
389 		goto bad;
390 	}
391 
392 	if (Fflag) {
393 		struct in6_ndireq nd;
394 		int s;
395 
396 		if ((s = socket(AF_INET6, SOCK_DGRAM, 0)) < 0) {
397 			warnmsg(LOG_ERR, __func__, "socket() failed.");
398 			goto bad;
399 		}
400 		memset(&nd, 0, sizeof(nd));
401 		strlcpy(nd.ifname, ifname, sizeof(nd.ifname));
402 		if (ioctl(s, SIOCGIFINFO_IN6, (caddr_t)&nd) < 0) {
403 			warnmsg(LOG_ERR, __func__,
404 			    "cannot get accept_rtadv flag");
405 			(void)close(s);
406 			goto bad;
407 		}
408 		nd.ndi.flags |= ND6_IFF_ACCEPT_RTADV;
409 		if (ioctl(s, SIOCSIFINFO_IN6, (caddr_t)&nd) < 0) {
410 			warnmsg(LOG_ERR, __func__,
411 			    "cannot set accept_rtadv flag");
412 			(void)close(s);
413 			goto bad;
414 		}
415 		(void)close(s);
416 	}
417 
418 	if ((ifi = malloc(sizeof(*ifi))) == NULL) {
419 		warnmsg(LOG_ERR, __func__, "memory allocation failed");
420 		goto bad;
421 	}
422 	memset(ifi, 0, sizeof(*ifi));
423 	ifi->sdl = sdl;
424 	ifi->ifi_rdnss = IFI_DNSOPT_STATE_NOINFO;
425 	ifi->ifi_dnssl = IFI_DNSOPT_STATE_NOINFO;
426 	TAILQ_INIT(&ifi->ifi_rainfo);
427 	strlcpy(ifi->ifname, ifname, sizeof(ifi->ifname));
428 
429 	/* construct a router solicitation message */
430 	if (make_packet(ifi))
431 		goto bad;
432 
433 	/* set link ID of this interface. */
434 #ifdef HAVE_SCOPELIB
435 	if (inet_zoneid(AF_INET6, 2, ifname, &ifi->linkid))
436 		goto bad;
437 #else
438 	/* XXX: assume interface IDs as link IDs */
439 	ifi->linkid = ifi->sdl->sdl_index;
440 #endif
441 
442 	/*
443 	 * check if the interface is available.
444 	 * also check if SIOCGIFMEDIA ioctl is OK on the interface.
445 	 */
446 	ifi->mediareqok = 1;
447 	ifi->active = interface_status(ifi);
448 	if (!ifi->mediareqok) {
449 		/*
450 		 * probe routers periodically even if the link status
451 		 * does not change.
452 		 */
453 		ifi->probeinterval = PROBE_INTERVAL;
454 	}
455 
456 	/* activate interface: interface_up returns 0 on success */
457 	flags = interface_up(ifi->ifname);
458 	if (flags == 0)
459 		ifi->state = IFS_DELAY;
460 	else if (flags == IFS_TENTATIVE)
461 		ifi->state = IFS_TENTATIVE;
462 	else
463 		ifi->state = IFS_DOWN;
464 
465 	rtsol_timer_update(ifi);
466 
467 	TAILQ_INSERT_TAIL(&ifinfo_head, ifi, ifi_next);
468 	return (0);
469 
470 bad:
471 	free(sdl);
472 	free(ifi);
473 	return (-1);
474 }
475 
476 struct rainfo *
477 find_rainfo(struct ifinfo *ifi, struct sockaddr_in6 *sin6)
478 {
479 	struct rainfo *rai;
480 
481 	TAILQ_FOREACH(rai, &ifi->ifi_rainfo, rai_next)
482 		if (memcmp(&rai->rai_saddr.sin6_addr, &sin6->sin6_addr,
483 		    sizeof(rai->rai_saddr.sin6_addr)) == 0)
484 			return (rai);
485 
486 	return (NULL);
487 }
488 
489 struct ifinfo *
490 find_ifinfo(int ifindex)
491 {
492 	struct ifinfo *ifi;
493 
494 	TAILQ_FOREACH(ifi, &ifinfo_head, ifi_next) {
495 		if (ifi->sdl->sdl_index == ifindex)
496 			return (ifi);
497 	}
498 	return (NULL);
499 }
500 
501 static int
502 make_packet(struct ifinfo *ifi)
503 {
504 	size_t packlen = sizeof(struct nd_router_solicit), lladdroptlen = 0;
505 	struct nd_router_solicit *rs;
506 	char *buf;
507 
508 	if ((lladdroptlen = lladdropt_length(ifi->sdl)) == 0) {
509 		warnmsg(LOG_INFO, __func__,
510 		    "link-layer address option has null length"
511 		    " on %s. Treat as not included.", ifi->ifname);
512 	}
513 	packlen += lladdroptlen;
514 	ifi->rs_datalen = packlen;
515 
516 	/* allocate buffer */
517 	if ((buf = malloc(packlen)) == NULL) {
518 		warnmsg(LOG_ERR, __func__,
519 		    "memory allocation failed for %s", ifi->ifname);
520 		return (-1);
521 	}
522 	ifi->rs_data = buf;
523 
524 	/* fill in the message */
525 	rs = (struct nd_router_solicit *)buf;
526 	rs->nd_rs_type = ND_ROUTER_SOLICIT;
527 	rs->nd_rs_code = 0;
528 	rs->nd_rs_cksum = 0;
529 	rs->nd_rs_reserved = 0;
530 	buf += sizeof(*rs);
531 
532 	/* fill in source link-layer address option */
533 	if (lladdroptlen)
534 		lladdropt_fill(ifi->sdl, (struct nd_opt_hdr *)buf);
535 
536 	return (0);
537 }
538 
539 static struct timespec *
540 rtsol_check_timer(void)
541 {
542 	static struct timespec returnval;
543 	struct timespec now, rtsol_timer;
544 	struct ifinfo *ifi;
545 	struct rainfo *rai;
546 	struct ra_opt *rao, *raotmp;
547 	int error, flags;
548 
549 	clock_gettime(CLOCK_MONOTONIC_FAST, &now);
550 
551 	rtsol_timer = tm_max;
552 
553 	TAILQ_FOREACH(ifi, &ifinfo_head, ifi_next) {
554 		if (TS_CMP(&ifi->expire, &now, <=)) {
555 			warnmsg(LOG_DEBUG, __func__, "timer expiration on %s, "
556 			    "state = %d", ifi->ifname, ifi->state);
557 
558 			while((rai = TAILQ_FIRST(&ifi->ifi_rainfo)) != NULL) {
559 				/* Remove all RA options. */
560 				TAILQ_REMOVE(&ifi->ifi_rainfo, rai, rai_next);
561 				while ((rao = TAILQ_FIRST(&rai->rai_ra_opt)) !=
562 				    NULL) {
563 					TAILQ_REMOVE(&rai->rai_ra_opt, rao,
564 					    rao_next);
565 					if (rao->rao_msg != NULL)
566 						free(rao->rao_msg);
567 					free(rao);
568 				}
569 				free(rai);
570 			}
571 			switch (ifi->state) {
572 			case IFS_DOWN:
573 			case IFS_TENTATIVE:
574 				/* interface_up returns 0 on success */
575 				flags = interface_up(ifi->ifname);
576 				if (flags == 0)
577 					ifi->state = IFS_DELAY;
578 				else if (flags == IFS_TENTATIVE)
579 					ifi->state = IFS_TENTATIVE;
580 				else
581 					ifi->state = IFS_DOWN;
582 				break;
583 			case IFS_IDLE:
584 			{
585 				int oldstatus = ifi->active;
586 				int probe = 0;
587 
588 				ifi->active = interface_status(ifi);
589 
590 				if (oldstatus != ifi->active) {
591 					warnmsg(LOG_DEBUG, __func__,
592 					    "%s status is changed"
593 					    " from %d to %d",
594 					    ifi->ifname,
595 					    oldstatus, ifi->active);
596 					probe = 1;
597 					ifi->state = IFS_DELAY;
598 				} else if (ifi->probeinterval &&
599 				    (ifi->probetimer -=
600 				    ifi->timer.tv_sec) <= 0) {
601 					/* probe timer expired */
602 					ifi->probetimer =
603 					    ifi->probeinterval;
604 					probe = 1;
605 					ifi->state = IFS_PROBE;
606 				}
607 
608 				/*
609 				 * If we need a probe, clear the previous
610 				 * status wrt the "managed/other" configuration.
611 				 */
612 				if (probe) {
613 					ifi->managedconfig = 0;
614 					ifi->otherconfig = 0;
615 				}
616 				if (probe && mobile_node) {
617 					error = cap_probe_defrouters(capsendmsg,
618 					    ifi);
619 					if (error != 0)
620 						warnmsg(LOG_DEBUG, __func__,
621 					    "failed to probe routers: %d",
622 						    error);
623 				}
624 				break;
625 			}
626 			case IFS_DELAY:
627 				ifi->state = IFS_PROBE;
628 				(void)cap_rssend(capsendmsg, ifi);
629 				break;
630 			case IFS_PROBE:
631 				if (ifi->probes < MAX_RTR_SOLICITATIONS)
632 					(void)cap_rssend(capsendmsg, ifi);
633 				else {
634 					warnmsg(LOG_INFO, __func__,
635 					    "No answer after sending %d RSs",
636 					    ifi->probes);
637 					ifi->probes = 0;
638 					ifi->state = IFS_IDLE;
639 				}
640 				break;
641 			}
642 			rtsol_timer_update(ifi);
643 		} else {
644 			/* Expiration check for RA options. */
645 			int expire = 0;
646 
647 			TAILQ_FOREACH(rai, &ifi->ifi_rainfo, rai_next) {
648 				TAILQ_FOREACH_SAFE(rao, &rai->rai_ra_opt,
649 				    rao_next, raotmp) {
650 					warnmsg(LOG_DEBUG, __func__,
651 					    "RA expiration timer: "
652 					    "type=%d, msg=%s, expire=%s",
653 					    rao->rao_type, (char *)rao->rao_msg,
654 						sec2str(&rao->rao_expire));
655 					if (TS_CMP(&now, &rao->rao_expire,
656 					    >=)) {
657 						warnmsg(LOG_DEBUG, __func__,
658 						    "RA expiration timer: "
659 						    "expired.");
660 						TAILQ_REMOVE(&rai->rai_ra_opt,
661 						    rao, rao_next);
662 						if (rao->rao_msg != NULL)
663 							free(rao->rao_msg);
664 						free(rao);
665 						expire = 1;
666 					}
667 				}
668 			}
669 			if (expire)
670 				ra_opt_handler(ifi);
671 		}
672 		if (TS_CMP(&ifi->expire, &rtsol_timer, <))
673 			rtsol_timer = ifi->expire;
674 	}
675 
676 	if (TS_CMP(&rtsol_timer, &tm_max, ==)) {
677 		warnmsg(LOG_DEBUG, __func__, "there is no timer");
678 		return (NULL);
679 	} else if (TS_CMP(&rtsol_timer, &now, <))
680 		/* this may occur when the interval is too small */
681 		returnval.tv_sec = returnval.tv_nsec = 0;
682 	else
683 		TS_SUB(&rtsol_timer, &now, &returnval);
684 
685 	now.tv_sec += returnval.tv_sec;
686 	now.tv_nsec += returnval.tv_nsec;
687 	warnmsg(LOG_DEBUG, __func__, "New timer is %s",
688 	    sec2str(&now));
689 
690 	return (&returnval);
691 }
692 
693 void
694 rtsol_timer_update(struct ifinfo *ifi)
695 {
696 #define MILLION 1000000
697 #define DADRETRY 10		/* XXX: adhoc */
698 	long interval;
699 	struct timespec now;
700 
701 	bzero(&ifi->timer, sizeof(ifi->timer));
702 
703 	switch (ifi->state) {
704 	case IFS_DOWN:
705 	case IFS_TENTATIVE:
706 		if (++ifi->dadcount > DADRETRY) {
707 			ifi->dadcount = 0;
708 			ifi->timer.tv_sec = PROBE_INTERVAL;
709 		} else
710 			ifi->timer.tv_sec = 1;
711 		break;
712 	case IFS_IDLE:
713 		if (mobile_node)
714 			/* XXX should be configurable */
715 			ifi->timer.tv_sec = 3;
716 		else
717 			ifi->timer = tm_max;	/* stop timer(valid?) */
718 		break;
719 	case IFS_DELAY:
720 		interval = arc4random_uniform(MAX_RTR_SOLICITATION_DELAY * MILLION);
721 		ifi->timer.tv_sec = interval / MILLION;
722 		ifi->timer.tv_nsec = (interval % MILLION) * 1000;
723 		break;
724 	case IFS_PROBE:
725 		if (ifi->probes < MAX_RTR_SOLICITATIONS)
726 			ifi->timer.tv_sec = RTR_SOLICITATION_INTERVAL;
727 		else
728 			/*
729 			 * After sending MAX_RTR_SOLICITATIONS solicitations,
730 			 * we're just waiting for possible replies; there
731 			 * will be no more solicitation.  Thus, we change
732 			 * the timer value to MAX_RTR_SOLICITATION_DELAY based
733 			 * on RFC 2461, Section 6.3.7.
734 			 */
735 			ifi->timer.tv_sec = MAX_RTR_SOLICITATION_DELAY;
736 		break;
737 	default:
738 		warnmsg(LOG_ERR, __func__,
739 		    "illegal interface state(%d) on %s",
740 		    ifi->state, ifi->ifname);
741 		return;
742 	}
743 
744 	/* reset the timer */
745 	if (TS_CMP(&ifi->timer, &tm_max, ==)) {
746 		ifi->expire = tm_max;
747 		warnmsg(LOG_DEBUG, __func__,
748 		    "stop timer for %s", ifi->ifname);
749 	} else {
750 		clock_gettime(CLOCK_MONOTONIC_FAST, &now);
751 		TS_ADD(&now, &ifi->timer, &ifi->expire);
752 
753 		now.tv_sec += ifi->timer.tv_sec;
754 		now.tv_nsec += ifi->timer.tv_nsec;
755 		warnmsg(LOG_DEBUG, __func__, "set timer for %s to %s",
756 		    ifi->ifname, sec2str(&now));
757 	}
758 
759 #undef MILLION
760 }
761 
762 static void
763 set_dumpfile(int sig __unused)
764 {
765 
766 	do_dump = 1;
767 }
768 
769 static void
770 set_exit(int sig __unused)
771 {
772 
773 	do_exit = 1;
774 }
775 
776 static void
777 usage(const char *progname)
778 {
779 
780 	if (strcmp(progname, "rtsold") == 0) {
781 		fprintf(stderr, "usage: rtsold [-dDfFm1] [-O script-name] "
782 		    "[-p pidfile] [-R script-name] interface ...\n");
783 		fprintf(stderr, "usage: rtsold [-dDfFm1] [-O script-name] "
784 		    "[-p pidfile] [-R script-name] -a\n");
785 	} else {
786 		fprintf(stderr, "usage: rtsol [-dDF] [-O script-name] "
787 		    "[-p pidfile] [-R script-name] interface ...\n");
788 		fprintf(stderr, "usage: rtsol [-dDF] [-O script-name] "
789 		    "[-p pidfile] [-R script-name] -a\n");
790 	}
791 	exit(1);
792 }
793 
794 void
795 warnmsg(int priority, const char *func, const char *msg, ...)
796 {
797 	va_list ap;
798 	char buf[BUFSIZ];
799 
800 	va_start(ap, msg);
801 	if (fflag) {
802 		if (priority <= log_upto)
803 			vwarnx(msg, ap);
804 	} else {
805 		snprintf(buf, sizeof(buf), "<%s> %s", func, msg);
806 		msg = buf;
807 		cap_vsyslog(capsyslog, priority, msg, ap);
808 	}
809 	va_end(ap);
810 }
811 
812 /*
813  * return a list of interfaces which is suitable to sending an RS.
814  */
815 static char **
816 autoifprobe(void)
817 {
818 	static char **argv = NULL;
819 	static int n = 0;
820 	char **a;
821 	int s = 0, i, found;
822 	struct ifaddrs *ifap, *ifa;
823 	struct in6_ndireq nd;
824 
825 	/* initialize */
826 	while (n--)
827 		free(argv[n]);
828 	if (argv) {
829 		free(argv);
830 		argv = NULL;
831 	}
832 	n = 0;
833 
834 	if (getifaddrs(&ifap) != 0)
835 		return (NULL);
836 
837 	if (!Fflag && (s = socket(AF_INET6, SOCK_DGRAM, 0)) < 0) {
838 		warnmsg(LOG_ERR, __func__, "socket");
839 		exit(1);
840 	}
841 
842 	/* find an ethernet */
843 	for (ifa = ifap; ifa; ifa = ifa->ifa_next) {
844 		if ((ifa->ifa_flags & IFF_UP) == 0)
845 			continue;
846 		if ((ifa->ifa_flags & IFF_POINTOPOINT) != 0)
847 			continue;
848 		if ((ifa->ifa_flags & IFF_LOOPBACK) != 0)
849 			continue;
850 		if ((ifa->ifa_flags & IFF_MULTICAST) == 0)
851 			continue;
852 
853 		if (ifa->ifa_addr->sa_family != AF_INET6)
854 			continue;
855 
856 		found = 0;
857 		for (i = 0; i < n; i++) {
858 			if (strcmp(argv[i], ifa->ifa_name) == 0) {
859 				found++;
860 				break;
861 			}
862 		}
863 		if (found)
864 			continue;
865 
866 		/*
867 		 * Skip the interfaces which IPv6 and/or accepting RA
868 		 * is disabled.
869 		 */
870 		if (!Fflag) {
871 			memset(&nd, 0, sizeof(nd));
872 			strlcpy(nd.ifname, ifa->ifa_name, sizeof(nd.ifname));
873 			if (ioctl(s, SIOCGIFINFO_IN6, (caddr_t)&nd) < 0) {
874 				warnmsg(LOG_ERR, __func__,
875 					"ioctl(SIOCGIFINFO_IN6)");
876 				exit(1);
877 			}
878 			if ((nd.ndi.flags & ND6_IFF_IFDISABLED))
879 				continue;
880 			if (!(nd.ndi.flags & ND6_IFF_ACCEPT_RTADV))
881 				continue;
882 		}
883 
884 		/* if we find multiple candidates, just warn. */
885 		if (n != 0 && dflag > 1)
886 			warnmsg(LOG_WARNING, __func__,
887 				"multiple interfaces found");
888 
889 		a = realloc(argv, (n + 1) * sizeof(char *));
890 		if (a == NULL) {
891 			warnmsg(LOG_ERR, __func__, "realloc");
892 			exit(1);
893 		}
894 		argv = a;
895 		argv[n] = strdup(ifa->ifa_name);
896 		if (!argv[n]) {
897 			warnmsg(LOG_ERR, __func__, "malloc");
898 			exit(1);
899 		}
900 		n++;
901 	}
902 
903 	if (n) {
904 		a = realloc(argv, (n + 1) * sizeof(char *));
905 		if (a == NULL) {
906 			warnmsg(LOG_ERR, __func__, "realloc");
907 			exit(1);
908 		}
909 		argv = a;
910 		argv[n] = NULL;
911 
912 		if (dflag > 0) {
913 			for (i = 0; i < n; i++)
914 				warnmsg(LOG_WARNING, __func__, "probing %s",
915 					argv[i]);
916 		}
917 	}
918 	if (!Fflag)
919 		close(s);
920 	freeifaddrs(ifap);
921 	return (argv);
922 }
923