xref: /netbsd-src/usr.sbin/rtadvd/rtadvd.c (revision e6c7e151de239c49d2e38720a061ed9d1fa99309)
1 /*	$NetBSD: rtadvd.c,v 1.71 2019/11/11 13:42:49 roy Exp $	*/
2 /*	$KAME: rtadvd.c,v 1.92 2005/10/17 14:40:02 suz Exp $	*/
3 
4 /*
5  * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
6  * All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. Neither the name of the project nor the names of its contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  */
32 
33 #include <sys/param.h>
34 #include <sys/socket.h>
35 #include <sys/uio.h>
36 #include <sys/time.h>
37 #include <sys/queue.h>
38 
39 #include <net/if.h>
40 #include <net/route.h>
41 #include <net/if_dl.h>
42 #include <netinet/in.h>
43 #include <netinet/ip6.h>
44 #include <netinet6/ip6_var.h>
45 #include <netinet/icmp6.h>
46 
47 #include <arpa/inet.h>
48 
49 #include <time.h>
50 #include <unistd.h>
51 #include <stdio.h>
52 #include <err.h>
53 #include <errno.h>
54 #include <string.h>
55 #include <stdlib.h>
56 #include <syslog.h>
57 #include <stdarg.h>
58 #ifdef __NetBSD__
59 #include <util.h>
60 #endif
61 #include <poll.h>
62 #include <pwd.h>
63 
64 #include "rtadvd.h"
65 #include "rrenum.h"
66 #include "advcap.h"
67 #include "timer.h"
68 #include "if.h"
69 #include "config.h"
70 #include "dump.h"
71 #include "logit.h"
72 #include "prog_ops.h"
73 #include "expandm.h"
74 
75 struct msghdr rcvmhdr;
76 static unsigned char *rcvcmsgbuf;
77 static size_t rcvcmsgbuflen;
78 static unsigned char *sndcmsgbuf;
79 static size_t sndcmsgbuflen;
80 volatile sig_atomic_t do_dump;
81 volatile sig_atomic_t do_reconf;
82 volatile sig_atomic_t do_die;
83 struct msghdr sndmhdr;
84 struct iovec rcviov[2];
85 struct iovec sndiov[2];
86 struct sockaddr_in6 rcvfrom;
87 static const char *dumpfilename = "/var/run/rtadvd.dump"; /* XXX configurable */
88 static char *mcastif;
89 int sock;
90 int rtsock = -1;
91 int accept_rr = 0;
92 int Cflag = 0, dflag = 0, sflag = 0, Dflag;
93 
94 static char **if_argv;
95 static int if_argc;
96 
97 char *conffile = NULL;
98 
99 struct ralist_head_t ralist = TAILQ_HEAD_INITIALIZER(ralist);
100 
101 struct nd_optlist {
102 	TAILQ_ENTRY(nd_optlist) next;
103 	struct nd_opt_hdr *opt;
104 };
105 union nd_opts {
106 	struct nd_opt_hdr *nd_opt_array[9];
107 	struct {
108 		struct nd_opt_hdr *zero;
109 		struct nd_opt_hdr *src_lladdr;
110 		struct nd_opt_hdr *tgt_lladdr;
111 		struct nd_opt_prefix_info *pi;
112 		struct nd_opt_rd_hdr *rh;
113 		struct nd_opt_mtu *mtu;
114 		TAILQ_HEAD(, nd_optlist) list;
115 	} nd_opt_each;
116 };
117 #define nd_opts_src_lladdr	nd_opt_each.src_lladdr
118 #define nd_opts_tgt_lladdr	nd_opt_each.tgt_lladdr
119 #define nd_opts_pi		nd_opt_each.pi
120 #define nd_opts_rh		nd_opt_each.rh
121 #define nd_opts_mtu		nd_opt_each.mtu
122 #define nd_opts_list		nd_opt_each.list
123 
124 #define NDOPT_FLAG_SRCLINKADDR	(1 << 0)
125 #define NDOPT_FLAG_TGTLINKADDR	(1 << 1)
126 #define NDOPT_FLAG_PREFIXINFO	(1 << 2)
127 #define NDOPT_FLAG_RDHDR	(1 << 3)
128 #define NDOPT_FLAG_MTU		(1 << 4)
129 #define NDOPT_FLAG_RDNSS	(1 << 5)
130 #define NDOPT_FLAG_DNSSL	(1 << 6)
131 
132 uint32_t ndopt_flags[] = {
133 	[ND_OPT_SOURCE_LINKADDR] =	NDOPT_FLAG_SRCLINKADDR,
134 	[ND_OPT_TARGET_LINKADDR] =	NDOPT_FLAG_TGTLINKADDR,
135 	[ND_OPT_PREFIX_INFORMATION] =	NDOPT_FLAG_PREFIXINFO,
136 	[ND_OPT_REDIRECTED_HEADER] =	NDOPT_FLAG_RDHDR,
137 	[ND_OPT_MTU] =			NDOPT_FLAG_MTU,
138 	[ND_OPT_RDNSS] =		NDOPT_FLAG_RDNSS,
139 	[ND_OPT_DNSSL] =		NDOPT_FLAG_DNSSL,
140 };
141 
142 struct sockaddr_in6 sin6_linklocal_allnodes = {
143 	.sin6_len =	sizeof(sin6_linklocal_allnodes),
144 	.sin6_family =	AF_INET6,
145 	.sin6_addr =	IN6ADDR_LINKLOCAL_ALLNODES_INIT,
146 };
147 #ifdef notdef
148 struct sockaddr_in6 sin6_linklocal_allrouters = {
149 	.sin6_len =	sizeof(sin6_linklocal_allrouters),
150 	.sin6_family =	AF_INET6,
151 	.sin6_addr =	IN6ADDR_LINKLOCAL_ALLROUTERS_INIT,
152 };
153 #endif
154 struct sockaddr_in6 sin6_sitelocal_allrouters = {
155 	.sin6_len =	sizeof(sin6_sitelocal_allrouters),
156 	.sin6_family =	AF_INET6,
157 	.sin6_addr =	IN6ADDR_SITELOCAL_ALLROUTERS_INIT,
158 };
159 
160 static void set_die(int);
161 static void die(void);
162 static void set_reconf(int);
163 static void sock_open(void);
164 static void rtsock_open(void);
165 static void rtadvd_input(void);
166 static void rs_input(int, struct nd_router_solicit *,
167     struct in6_pktinfo *, struct sockaddr_in6 *);
168 static void ra_input(int, struct nd_router_advert *,
169     struct in6_pktinfo *, struct sockaddr_in6 *);
170 static struct rainfo *ra_output(struct rainfo *, bool);
171 static int prefix_check(struct nd_opt_prefix_info *, struct rainfo *,
172     struct sockaddr_in6 *);
173 static int nd6_options(struct nd_opt_hdr *, int, union nd_opts *, uint32_t);
174 static void free_ndopts(union nd_opts *);
175 static void rtmsg_input(void);
176 static void rtadvd_set_dump_file(int);
177 
178 int
179 main(int argc, char *argv[])
180 {
181 	struct pollfd set[2];
182 	struct timespec *timeout;
183 	int i, ch;
184 	int fflag = 0, logopt;
185 	struct passwd *pw;
186 	const char *pidfilepath = NULL;
187 	pid_t pid;
188 
189 	/* get command line options and arguments */
190 #define OPTIONS "c:dDfM:p:Rs"
191 	while ((ch = getopt(argc, argv, OPTIONS)) != -1) {
192 #undef OPTIONS
193 		switch (ch) {
194 		case 'c':
195 			conffile = optarg;
196 			break;
197 		case 'C':
198 			Cflag++;
199 			break;
200 		case 'd':
201 			dflag++;
202 			break;
203 		case 'D':
204 			Dflag++;
205 			break;
206 		case 'f':
207 			fflag = 1;
208 			break;
209 		case 'M':
210 			mcastif = optarg;
211 			break;
212 		case 'p':
213 			pidfilepath = optarg;
214 			break;
215 		case 'R':
216 			fprintf(stderr, "rtadvd: "
217 				"the -R option is currently ignored.\n");
218 			/* accept_rr = 1; */
219 			/* run anyway... */
220 			break;
221 		case 's':
222 			sflag = 1;
223 			break;
224 		}
225 	}
226 	argc -= optind;
227 	argv += optind;
228 	if (argc == 0) {
229 		fprintf(stderr, "Ysage: %s [-DdfRs] [-c conffile]"
230 		    " [-M ifname] [-p pidfile] interface ...\n", getprogname());
231 		return EXIT_FAILURE;
232 	}
233 
234 	if ((pid = pidfile_lock(pidfilepath)) != 0) {
235 		if (pid == -1)
236 			logit(LOG_ERR, "pidfile_lock: %m");
237 			/* Continue */
238 		else {
239 			logit(LOG_ERR, "Another instance of `%s' is running "
240 			    "(pid %d); exiting.", getprogname(), pid);
241 			return EXIT_FAILURE;
242 		}
243 	}
244 
245 	if (prog_init && prog_init() == -1)
246 		err(EXIT_FAILURE, "init failed");
247 
248 	logopt = LOG_NDELAY | LOG_PID;
249 	if (fflag)
250 		logopt |= LOG_PERROR;
251 	openlog("rtadvd", logopt, LOG_DAEMON);
252 
253 	/* set log level */
254 	if (dflag == 0)
255 		(void)setlogmask(LOG_UPTO(LOG_ERR));
256 	if (dflag == 1)
257 		(void)setlogmask(LOG_UPTO(LOG_INFO));
258 
259 	errno = 0; /* Ensure errno is 0 so we know if getpwnam errors or not */
260 	if ((pw = getpwnam(RTADVD_USER)) == NULL) {
261 		if (errno == 0)
262 			logit(LOG_ERR,
263 			    "user %s does not exist, aborting",
264 			    RTADVD_USER);
265 		else
266 			logit(LOG_ERR, "getpwnam: %s: %m", RTADVD_USER);
267 		return EXIT_FAILURE;
268 	}
269 
270 	/* timer initialization */
271 	rtadvd_timer_init();
272 
273 	if_argc = argc;
274 	if_argv = argv;
275 	while (argc--)
276 		getconfig(*argv++, 1);
277 
278 	if (!fflag) {
279 		prog_daemon(1, 0);
280 		if (pidfile_lock(pidfilepath) != 0)
281 			logit(LOG_ERR, " pidfile_lock: %m");
282 	}
283 
284 	sock_open();
285 
286 	set[0].fd = sock;
287 	set[0].events = POLLIN;
288 	if (sflag == 0) {
289 		rtsock_open();
290 		set[1].fd = rtsock;
291 		set[1].events = POLLIN;
292 	} else
293 		set[1].fd = -1;
294 
295 	logit(LOG_INFO, "dropping privileges to %s", RTADVD_USER);
296 	if (prog_chroot(pw->pw_dir) == -1) {
297 		logit(LOG_ERR, "chroot: %s: %m", pw->pw_dir);
298 		return EXIT_FAILURE;
299 	}
300 	if (prog_chdir("/") == -1) {
301 		logit(LOG_ERR, "chdir: /: %m");
302 		return EXIT_FAILURE;
303 	}
304 	if (prog_setgroups(1, &pw->pw_gid) == -1 ||
305 	    prog_setgid(pw->pw_gid) == -1 ||
306 	    prog_setuid(pw->pw_uid) == -1)
307 	{
308 		logit(LOG_ERR, "failed to drop privileges: %m");
309 		return EXIT_FAILURE;
310 	}
311 
312 	signal(SIGINT, set_die);
313 	signal(SIGTERM, set_die);
314 	signal(SIGHUP, set_reconf);
315 	signal(SIGUSR1, rtadvd_set_dump_file);
316 
317 	for (;;) {
318 		if (do_dump) {	/* SIGUSR1 */
319 			do_dump = 0;
320 			rtadvd_dump_file(dumpfilename);
321 		}
322 
323 		if (do_reconf) { /* SIGHUP */
324 			do_reconf = 0;
325 			logit(LOG_INFO, "%s: reloading config on SIGHUP",
326 			       __func__);
327 			argc = if_argc;
328 			argv = if_argv;
329 			while (argc--)
330 				getconfig(*argv++, 0);
331 		}
332 
333 		/* timer expiration check and reset the timer */
334 		timeout = rtadvd_check_timer();
335 
336 		if (do_die) {
337 			die();
338 			/*NOTREACHED*/
339 		}
340 
341 		if (timeout != NULL) {
342 			logit(LOG_DEBUG,
343 			    "%s: set timer to %jd:%jd. waiting for "
344 			    "inputs or timeout", __func__,
345 			    (intmax_t)timeout->tv_sec,
346 			    (intmax_t)timeout->tv_nsec);
347 		} else {
348 			logit(LOG_DEBUG,
349 			    "%s: there's no timer. waiting for inputs",
350 			    __func__);
351 		}
352 
353 		if ((i = prog_poll(set, 2, timeout ? (timeout->tv_sec * 1000 +
354 		    (timeout->tv_nsec + 999999) / 1000000) : INFTIM)) == -1)
355 		{
356 			/* EINTR would occur upon SIGUSR1 for status dump */
357 			if (errno == EINTR) {
358 				if (do_die)
359 					die();
360 				continue;
361 			}
362 
363 			logit(LOG_ERR, "%s: poll: %m", __func__);
364 			if (Dflag)
365 				exit(1);
366 		}
367 		if (i == 0)	/* timeout */
368 			continue;
369 		if (rtsock != -1 && set[1].revents & POLLIN)
370 			rtmsg_input();
371 		if (set[0].revents & POLLIN)
372 			rtadvd_input();
373 	}
374 	return EXIT_SUCCESS;	/* NOTREACHED */
375 }
376 
377 static void
378 rtadvd_set_dump_file(__unused int sig)
379 {
380 
381 	do_dump = 1;
382 }
383 
384 static void
385 set_reconf(__unused int sig)
386 {
387 
388 	do_reconf = 1;
389 }
390 
391 static void
392 set_die(__unused int sig)
393 {
394 
395 	do_die = 1;
396 }
397 
398 static void
399 die(void)
400 {
401 	static int waiting;
402 	struct rainfo *rai, *ran;
403 	struct rdnss *rdnss;
404 	struct dnssl *dnssl;
405 
406 	if (waiting) {
407 		if (TAILQ_FIRST(&ralist)) {
408 			logit(LOG_INFO,
409 			       "%s: waiting for expiration of all RA timers",
410 			       __func__);
411 			return;
412 		}
413 		logit(LOG_NOTICE, "%s: gracefully terminated", __func__);
414 		free(rcvcmsgbuf);
415 		free(sndcmsgbuf);
416 		exit(EXIT_SUCCESS);
417 		/* NOT REACHED */
418 	}
419 
420 	if (TAILQ_FIRST(&ralist) == NULL) {
421 		logit(LOG_NOTICE, "%s: gracefully terminated", __func__);
422 		exit(EXIT_SUCCESS);
423 		/* NOT REACHED */
424 	}
425 
426 	waiting = 1;
427 	logit(LOG_NOTICE, "%s: final RA transmission started", __func__);
428 
429 	TAILQ_FOREACH_SAFE(rai, &ralist, next, ran) {
430 		if (rai->leaving) {
431 			TAILQ_REMOVE(&ralist, rai, next);
432 			TAILQ_INSERT_HEAD(&ralist, rai->leaving, next);
433 			rai->leaving->leaving = rai->leaving;
434 			rai->leaving->leaving_for = rai->leaving;
435 			free_rainfo(rai);
436 			continue;
437 		}
438 		rai->lifetime = 0;
439 		TAILQ_FOREACH(rdnss, &rai->rdnss, next)
440 			rdnss->lifetime = 0;
441 		TAILQ_FOREACH(dnssl, &rai->dnssl, next)
442 			dnssl->lifetime = 0;
443 		make_packet(rai);
444 		rai->leaving = rai;
445 		rai->leaving_for = rai;
446 		rai->initcounter = MAX_INITIAL_RTR_ADVERTISEMENTS;
447 		rai->mininterval = MIN_DELAY_BETWEEN_RAS;
448 		rai->maxinterval = MIN_DELAY_BETWEEN_RAS;
449 		rai->leaving_adv = MAX_FINAL_RTR_ADVERTISEMENTS;
450 		ra_output(rai, false);
451 		ra_timer_update(rai, &rai->timer->tm);
452 		rtadvd_set_timer(&rai->timer->tm, rai->timer);
453 	}
454 	exit(EXIT_SUCCESS);
455 }
456 
457 static void
458 ra_timer_reset(struct rainfo *rai)
459 {
460 
461 	rtadvd_remove_timer(&rai->timer);
462 	rai->timer = rtadvd_add_timer(ra_timeout, ra_timer_update, rai, rai);
463 	ra_timer_update(rai, &rai->timer->tm);
464 	rtadvd_set_timer(&rai->timer->tm, rai->timer);
465 	rtadvd_remove_timer(&rai->timer_sol);
466 	rai->timer_sol = rtadvd_add_timer(ra_timeout_sol, NULL, rai, NULL);
467 }
468 
469 static void
470 rtmsg_input(void)
471 {
472 	int n, type, ifindex = 0, plen;
473 	size_t len;
474 	union rt_msghdr_buf {
475 		struct rt_msghdr	rt_msghdr;
476 		char			data[2048];
477 	} buffer;
478 	char *msg, *next, *lim, **argv;
479 	char ifname[IF_NAMESIZE];
480 	struct prefix *prefix;
481 	struct rainfo *rai;
482 	struct in6_addr *addr;
483 	char addrbuf[INET6_ADDRSTRLEN];
484 	int prefixchange = 0, argc;
485 
486 	memset(&buffer, 0, sizeof(buffer));
487 	n = prog_read(rtsock, &buffer, sizeof(buffer));
488 
489 	/* We read the buffer first to clear the FD */
490 	if (do_die)
491 		return;
492 
493 	msg = buffer.data;
494 	if (dflag > 1) {
495 		logit(LOG_DEBUG, "%s: received a routing message "
496 		    "(type = %d, len = %d)", __func__, rtmsg_type(msg),
497 		    rtmsg_len(msg));
498 	}
499 	if (n > rtmsg_len(msg)) {
500 		/*
501 		 * This usually won't happen for messages received on
502 		 * a routing socket.
503 		 */
504 		if (dflag > 1)
505 			logit(LOG_DEBUG,
506 			    "%s: received data length is larger than "
507 			    "1st routing message len. multiple messages? "
508 			    "read %d bytes, but 1st msg len = %d",
509 			    __func__, n, rtmsg_len(msg));
510 #if 0
511 		/* adjust length */
512 		n = rtmsg_len(msg);
513 #endif
514 	}
515 
516 	lim = msg + n;
517 	for (next = msg; next < lim; next += len) {
518 		int oldifflags;
519 
520 		next = get_next_msg(next, lim, 0, &len,
521 				    RTADV_TYPE2BITMASK(RTM_ADD) |
522 				    RTADV_TYPE2BITMASK(RTM_DELETE) |
523 				    RTADV_TYPE2BITMASK(RTM_NEWADDR) |
524 				    RTADV_TYPE2BITMASK(RTM_DELADDR) |
525 #ifdef RTM_IFANNOUNCE
526 				    RTADV_TYPE2BITMASK(RTM_IFANNOUNCE) |
527 #endif
528 				    RTADV_TYPE2BITMASK(RTM_IFINFO));
529 		if (len == 0)
530 			break;
531 		type = rtmsg_type(next);
532 		switch (type) {
533 		case RTM_ADD:
534 		case RTM_DELETE:
535 			ifindex = get_rtm_ifindex(next);
536 			break;
537 		case RTM_NEWADDR:
538 		case RTM_DELADDR:
539 			ifindex = get_ifam_ifindex(next);
540 			break;
541 #ifdef RTM_IFANNOUNCE
542 		case RTM_IFANNOUNCE:
543 			ifindex = get_ifan_ifindex(next);
544 			if (get_ifan_what(next) == IFAN_ARRIVAL) {
545 				logit(LOG_DEBUG,
546 				       "%s: interface %s arrived",
547 				       __func__,
548 				       if_indextoname(ifindex, ifname));
549 				if (if_argc == 0) {
550 					getconfig(ifname, 0);
551 					continue;
552 				}
553 				argc = if_argc;
554 				argv = if_argv;
555 				while (argc--) {
556 					if (strcmp(ifname, *argv++) == 0) {
557 						getconfig(ifname, 0);
558 						break;
559 					}
560 				}
561 				continue;
562 			}
563 			break;
564 #endif
565 		case RTM_IFINFO:
566 			ifindex = get_ifm_ifindex(next);
567 			break;
568 		default:
569 			/* should not reach here */
570 			if (dflag > 1) {
571 				logit(LOG_DEBUG, "%s: unknown rtmsg %d on %s",
572 				       __func__, type,
573 				       if_indextoname(ifindex, ifname));
574 			}
575 			continue;
576 		}
577 
578 		if ((rai = if_indextorainfo(ifindex)) == NULL) {
579 			if (dflag > 1) {
580 				logit(LOG_DEBUG,
581 				       "%s: route changed on "
582 				       "non advertising interface %s (%d)",
583 				       __func__,
584 				       if_indextoname(ifindex, ifname),
585 				       ifindex);
586 			}
587 			continue;
588 		}
589 		oldifflags = rai->ifflags;
590 
591 		switch (type) {
592 		case RTM_ADD:
593 			/* init ifflags because it may have changed */
594 			rai->ifflags = if_getflags(ifindex, rai->ifflags);
595 
596 			if (sflag)
597 				break;	/* we aren't interested in prefixes  */
598 
599 			addr = get_addr(msg);
600 			plen = get_prefixlen(msg);
601 			/* sanity check for plen */
602 			/* as RFC2373, prefixlen is at least 4 */
603 			if (plen < 4 || plen > 127) {
604 				logit(LOG_INFO, "%s: new interface route's"
605 				    "plen %d is invalid for a prefix",
606 				    __func__, plen);
607 				break;
608 			}
609 			prefix = find_prefix(rai, addr, plen);
610 			if (prefix) {
611 				if (prefix->timer) {
612 					/*
613 					 * If the prefix has been invalidated,
614 					 * make it available again.
615 					 */
616 					update_prefix(prefix);
617 					prefixchange = 1;
618 				} else if (dflag > 1) {
619 					logit(LOG_DEBUG,
620 					    "%s: new prefix(%s/%d) "
621 					    "added on %s, "
622 					    "but it was already in list",
623 					    __func__,
624 					    inet_ntop(AF_INET6, addr,
625 					    (char *)addrbuf, INET6_ADDRSTRLEN),
626 					    plen, rai->ifname);
627 				}
628 				break;
629 			}
630 			make_prefix(rai, ifindex, addr, plen);
631 			prefixchange = 1;
632 			break;
633 		case RTM_DELETE:
634 			/* init ifflags because it may have changed */
635 			rai->ifflags = if_getflags(ifindex, rai->ifflags);
636 
637 			if (sflag)
638 				break;
639 
640 			addr = get_addr(msg);
641 			plen = get_prefixlen(msg);
642 			/* sanity check for plen */
643 			/* as RFC2373, prefixlen is at least 4 */
644 			if (plen < 4 || plen > 127) {
645 				logit(LOG_INFO,
646 				    "%s: deleted interface route's "
647 				    "plen %d is invalid for a prefix",
648 				    __func__, plen);
649 				break;
650 			}
651 			prefix = find_prefix(rai, addr, plen);
652 			if (prefix == NULL) {
653 				if (dflag > 1) {
654 					logit(LOG_DEBUG,
655 					    "%s: prefix(%s/%d) was "
656 					    "deleted on %s, "
657 					    "but it was not in list",
658 					    __func__,
659 					    inet_ntop(AF_INET6, addr,
660 					    (char *)addrbuf, INET6_ADDRSTRLEN),
661 					    plen, rai->ifname);
662 				}
663 				break;
664 			}
665 			invalidate_prefix(prefix);
666 			prefixchange = 1;
667 			break;
668 		case RTM_NEWADDR:
669 		case RTM_DELADDR:
670 			/* init ifflags because it may have changed */
671 			rai->ifflags = if_getflags(ifindex, rai->ifflags);
672 			break;
673 		case RTM_IFINFO:
674 			rai->ifflags = get_ifm_flags(next);
675 			break;
676 #ifdef RTM_IFANNOUNCE
677 		case RTM_IFANNOUNCE:
678 			if (get_ifan_what(next) == IFAN_DEPARTURE) {
679 				logit(LOG_DEBUG,
680 				       "%s: interface %s departed",
681 				       __func__, rai->ifname);
682 				TAILQ_REMOVE(&ralist, rai, next);
683 				if (rai->leaving)
684 					free_rainfo(rai->leaving);
685 				free_rainfo(rai);
686 				continue;
687 			}
688 			break;
689 #endif
690 		default:
691 			/* should not reach here */
692 			if (dflag > 1) {
693 				logit(LOG_DEBUG,
694 				    "%s: unknown rtmsg %d on %s",
695 				    __func__, type,
696 				    if_indextoname(ifindex, ifname));
697 			}
698 			return;
699 		}
700 
701 		/* check if an interface flag is changed */
702 		if ((oldifflags & IFF_UP) != 0 &&	/* UP to DOWN */
703 		    (rai->ifflags & IFF_UP) == 0) {
704 			logit(LOG_INFO,
705 			    "%s: interface %s becomes down. stop timer.",
706 			    __func__, rai->ifname);
707 			rtadvd_remove_timer(&rai->timer);
708 		} else if ((oldifflags & IFF_UP) == 0 && /* DOWN to UP */
709 			 (rai->ifflags & IFF_UP) != 0) {
710 			logit(LOG_INFO,
711 			    "%s: interface %s becomes up. restart timer.",
712 			    __func__, rai->ifname);
713 
714 			rai->initcounter = 0; /* reset the counter */
715 			rai->waiting = 0; /* XXX */
716 			ra_timer_reset(rai);
717 		} else if (prefixchange && rai->ifflags & IFF_UP) {
718 			/*
719 			 * An advertised prefix has been added or invalidated.
720 			 * Will notice the change in a short delay.
721 			 */
722 			rai->initcounter = 0;
723 			ra_timer_set_short_delay(rai, rai->timer);
724 		}
725 	}
726 
727 	return;
728 }
729 
730 void
731 rtadvd_input(void)
732 {
733 	ssize_t i;
734 	int *hlimp = NULL;
735 	struct icmp6_hdr *icp;
736 	int ifindex = 0;
737 	struct cmsghdr *cm;
738 	struct in6_pktinfo *pi = NULL;
739 	char ntopbuf[INET6_ADDRSTRLEN], ifnamebuf[IFNAMSIZ];
740 	struct in6_addr dst = in6addr_any;
741 	struct rainfo *rai;
742 
743 	/*
744 	 * Get message. We reset msg_controllen since the field could
745 	 * be modified if we had received a message before setting
746 	 * receive options.
747 	 */
748 	rcvmhdr.msg_controllen = rcvcmsgbuflen;
749 	if ((i = prog_recvmsg(sock, &rcvmhdr, 0)) == -1)
750 		return;
751 
752 	/* We read the buffer first to clear the FD */
753 	if (do_die)
754 		return;
755 
756 	/* extract optional information via Advanced API */
757 	for (cm = (struct cmsghdr *)CMSG_FIRSTHDR(&rcvmhdr);
758 	     cm;
759 	     cm = (struct cmsghdr *)CMSG_NXTHDR(&rcvmhdr, cm)) {
760 		if (cm->cmsg_level == IPPROTO_IPV6 &&
761 		    cm->cmsg_type == IPV6_PKTINFO &&
762 		    cm->cmsg_len == CMSG_LEN(sizeof(struct in6_pktinfo))) {
763 			pi = (struct in6_pktinfo *)(CMSG_DATA(cm));
764 			ifindex = pi->ipi6_ifindex;
765 			dst = pi->ipi6_addr;
766 		}
767 		if (cm->cmsg_level == IPPROTO_IPV6 &&
768 		    cm->cmsg_type == IPV6_HOPLIMIT &&
769 		    cm->cmsg_len == CMSG_LEN(sizeof(int)))
770 			hlimp = (int *)CMSG_DATA(cm);
771 	}
772 	if (ifindex == 0) {
773 		logit(LOG_ERR,
774 		       "%s: failed to get receiving interface",
775 		       __func__);
776 		return;
777 	}
778 	if (hlimp == NULL) {
779 		logit(LOG_ERR,
780 		       "%s: failed to get receiving hop limit",
781 		       __func__);
782 		return;
783 	}
784 
785 	if ((rai = if_indextorainfo(pi->ipi6_ifindex)) == NULL) {
786 		if (dflag > 1) {
787 			logit(LOG_DEBUG,
788 			       "%s: received data for non advertising "
789 			       "interface (%s)",
790 			       __func__,
791 			       if_indextoname(pi->ipi6_ifindex, ifnamebuf));
792 		}
793 		return;
794 	}
795 	/*
796 	 * If we happen to receive data on an interface which is now down,
797 	 * just discard the data.
798 	 */
799 	if ((rai->ifflags & IFF_UP) == 0) {
800 		logit(LOG_INFO,
801 		       "%s: received data on a disabled interface (%s)",
802 		       __func__,
803 		       if_indextoname(pi->ipi6_ifindex, ifnamebuf));
804 		return;
805 	}
806 
807 	if ((size_t)i < sizeof(struct icmp6_hdr)) {
808 		logit(LOG_ERR,
809 		       "%s: packet size(%zd) is too short",
810 		       __func__, i);
811 		return;
812 	}
813 
814 	icp = (struct icmp6_hdr *)rcvmhdr.msg_iov[0].iov_base;
815 
816 	switch (icp->icmp6_type) {
817 	case ND_ROUTER_SOLICIT:
818 		/*
819 		 * Message verification - RFC-2461 6.1.1
820 		 * XXX: these checks must be done in the kernel as well,
821 		 *      but we can't completely rely on them.
822 		 */
823 		if (*hlimp != 255) {
824 			logit(LOG_NOTICE,
825 			    "%s: RS with invalid hop limit(%d) "
826 			    "received from %s on %s",
827 			    __func__, *hlimp,
828 			    inet_ntop(AF_INET6, &rcvfrom.sin6_addr, ntopbuf,
829 			    INET6_ADDRSTRLEN),
830 			    if_indextoname(pi->ipi6_ifindex, ifnamebuf));
831 			return;
832 		}
833 		if (icp->icmp6_code) {
834 			logit(LOG_NOTICE,
835 			    "%s: RS with invalid ICMP6 code(%d) "
836 			    "received from %s on %s",
837 			    __func__, icp->icmp6_code,
838 			    inet_ntop(AF_INET6, &rcvfrom.sin6_addr, ntopbuf,
839 			    INET6_ADDRSTRLEN),
840 			    if_indextoname(pi->ipi6_ifindex, ifnamebuf));
841 			return;
842 		}
843 		if ((size_t)i < sizeof(struct nd_router_solicit)) {
844 			logit(LOG_NOTICE,
845 			    "%s: RS from %s on %s does not have enough "
846 			    "length (len = %zd)",
847 			    __func__,
848 			    inet_ntop(AF_INET6, &rcvfrom.sin6_addr, ntopbuf,
849 			    INET6_ADDRSTRLEN),
850 			    if_indextoname(pi->ipi6_ifindex, ifnamebuf), i);
851 			return;
852 		}
853 		rs_input(i, (struct nd_router_solicit *)icp, pi, &rcvfrom);
854 		break;
855 	case ND_ROUTER_ADVERT:
856 		/*
857 		 * Message verification - RFC-2461 6.1.2
858 		 * XXX: there's a same dilemma as above...
859 		 */
860 		if (*hlimp != 255) {
861 			logit(LOG_NOTICE,
862 			    "%s: RA with invalid hop limit(%d) "
863 			    "received from %s on %s",
864 			    __func__, *hlimp,
865 			    inet_ntop(AF_INET6, &rcvfrom.sin6_addr, ntopbuf,
866 			    INET6_ADDRSTRLEN),
867 			    if_indextoname(pi->ipi6_ifindex, ifnamebuf));
868 			return;
869 		}
870 		if (icp->icmp6_code) {
871 			logit(LOG_NOTICE,
872 			    "%s: RA with invalid ICMP6 code(%d) "
873 			    "received from %s on %s",
874 			    __func__, icp->icmp6_code,
875 			    inet_ntop(AF_INET6, &rcvfrom.sin6_addr, ntopbuf,
876 			    INET6_ADDRSTRLEN),
877 			    if_indextoname(pi->ipi6_ifindex, ifnamebuf));
878 			return;
879 		}
880 		if ((size_t)i < sizeof(struct nd_router_advert)) {
881 			logit(LOG_NOTICE,
882 			    "%s: RA from %s on %s does not have enough "
883 			    "length (len = %zd)",
884 			    __func__,
885 			    inet_ntop(AF_INET6, &rcvfrom.sin6_addr, ntopbuf,
886 			    INET6_ADDRSTRLEN),
887 			    if_indextoname(pi->ipi6_ifindex, ifnamebuf), i);
888 			return;
889 		}
890 		ra_input(i, (struct nd_router_advert *)icp, pi, &rcvfrom);
891 		break;
892 	case ICMP6_ROUTER_RENUMBERING:
893 		if (accept_rr == 0) {
894 			logit(LOG_ERR, "%s: received a router renumbering "
895 			    "message, but not allowed to be accepted",
896 			    __func__);
897 			break;
898 		}
899 		rr_input(i, (struct icmp6_router_renum *)icp, pi, &rcvfrom,
900 			 &dst);
901 		break;
902 	default:
903 		/*
904 		 * Note that this case is POSSIBLE, especially just
905 		 * after invocation of the daemon. This is because we
906 		 * could receive message after opening the socket and
907 		 * before setting ICMP6 type filter(see sock_open()).
908 		 */
909 		logit(LOG_ERR, "%s: invalid icmp type(%d)",
910 		    __func__, icp->icmp6_type);
911 		return;
912 	}
913 }
914 
915 static void
916 rs_input(int len, struct nd_router_solicit *rs,
917 	 struct in6_pktinfo *pi, struct sockaddr_in6 *from)
918 {
919 	char ntopbuf[INET6_ADDRSTRLEN], ifnamebuf[IFNAMSIZ];
920 	union nd_opts ndopts;
921 	struct rainfo *rai;
922 	struct soliciter *sol;
923 
924 	logit(LOG_DEBUG,
925 	       "%s: RS received from %s on %s",
926 	       __func__,
927 	       inet_ntop(AF_INET6, &from->sin6_addr,
928 			 ntopbuf, INET6_ADDRSTRLEN),
929 	       if_indextoname(pi->ipi6_ifindex, ifnamebuf));
930 
931 	/* ND option check */
932 	memset(&ndopts, 0, sizeof(ndopts));
933 	TAILQ_INIT(&ndopts.nd_opts_list);
934 	if (nd6_options((struct nd_opt_hdr *)(rs + 1),
935 			len - sizeof(struct nd_router_solicit),
936 			&ndopts, NDOPT_FLAG_SRCLINKADDR)) {
937 		logit(LOG_INFO,
938 		       "%s: ND option check failed for an RS from %s on %s",
939 		       __func__,
940 		       inet_ntop(AF_INET6, &from->sin6_addr,
941 				 ntopbuf, INET6_ADDRSTRLEN),
942 		       if_indextoname(pi->ipi6_ifindex, ifnamebuf));
943 		return;
944 	}
945 
946 	/*
947 	 * If the IP source address is the unspecified address, there
948 	 * must be no source link-layer address option in the message.
949 	 * (RFC-2461 6.1.1)
950 	 */
951 	if (IN6_IS_ADDR_UNSPECIFIED(&from->sin6_addr) &&
952 	    ndopts.nd_opts_src_lladdr) {
953 		logit(LOG_INFO,
954 		       "%s: RS from unspecified src on %s has a link-layer"
955 		       " address option",
956 		       __func__,
957 		       if_indextoname(pi->ipi6_ifindex, ifnamebuf));
958 		goto done;
959 	}
960 
961 	if ((rai = if_indextorainfo(pi->ipi6_ifindex)) == NULL) {
962 		logit(LOG_INFO,
963 		       "%s: RS received on non advertising interface(%s)",
964 		       __func__,
965 		       if_indextoname(pi->ipi6_ifindex, ifnamebuf));
966 		goto done;
967 	}
968 
969 	if (rai->leaving) {
970 		logit(LOG_INFO,
971 		       "%s: RS received on reconfiguring advertising interface(%s)",
972 		       __func__, rai->ifname);
973 		goto done;
974 	}
975 
976 	rai->rsinput++;		/* increment statistics */
977 
978 	/*
979 	 * Decide whether to send RA according to the rate-limit
980 	 * consideration.
981 	 */
982 
983 	/* record sockaddr waiting for RA, if possible */
984 	TAILQ_FOREACH(sol, &rai->soliciter, next) {
985 		if (IN6_ARE_ADDR_EQUAL(&sol->addr.sin6_addr, &from->sin6_addr))
986 			break;
987 	}
988 	if (sol == NULL) {
989 		sol = malloc(sizeof(*sol));
990 		if (sol == NULL) {
991 			logit(LOG_ERR, "%s: malloc: %m", __func__);
992 		} else {
993 			sol->addr = *from;
994 			/* XXX RFC2553 need clarification on flowinfo */
995 			sol->addr.sin6_flowinfo = 0;
996 			TAILQ_INSERT_TAIL(&rai->soliciter, sol, next);
997 		}
998 	}
999 
1000 	/*
1001 	 * If there is already a waiting RS packet, don't
1002 	 * update the timer.
1003 	 */
1004 	if (rai->waiting++)
1005 		goto done;
1006 
1007 	ra_timer_set_short_delay(rai, rai->timer_sol);
1008 
1009 done:
1010 	free_ndopts(&ndopts);
1011 }
1012 
1013 void
1014 ra_timer_set_short_delay(struct rainfo *rai, struct rtadvd_timer *timer)
1015 {
1016 	long delay;	/* must not be greater than 1000000 */
1017 	struct timespec interval, now, min_delay, tm_tmp, *rest;
1018 
1019 	/*
1020 	 * Compute a random delay. If the computed value
1021 	 * corresponds to a time later than the time the next
1022 	 * multicast RA is scheduled to be sent, ignore the random
1023 	 * delay and send the advertisement at the
1024 	 * already-scheduled time. RFC2461 6.2.6
1025 	 */
1026 	delay = arc4random() % MAX_RA_DELAY_TIME;
1027 	interval.tv_sec = 0;
1028 	interval.tv_nsec = delay;
1029 	rest = rtadvd_timer_rest(rai->timer);
1030 	if (timespeccmp(rest, &interval, <)) {
1031 		logit(LOG_DEBUG, "%s: random delay is larger than "
1032 		    "the rest of current timer", __func__);
1033 		interval = *rest;
1034 	}
1035 
1036 	/*
1037 	 * If we sent a multicast Router Advertisement within
1038 	 * the last MIN_DELAY_BETWEEN_RAS seconds, schedule
1039 	 * the advertisement to be sent at a time corresponding to
1040 	 * MIN_DELAY_BETWEEN_RAS plus the random value after the
1041 	 * previous advertisement was sent.
1042 	 */
1043 	prog_clock_gettime(CLOCK_MONOTONIC, &now);
1044 	timespecsub(&now, &rai->lastsent, &tm_tmp);
1045 	min_delay.tv_sec = MIN_DELAY_BETWEEN_RAS;
1046 	min_delay.tv_nsec = 0;
1047 	if (timespeccmp(&tm_tmp, &min_delay, <)) {
1048 		timespecsub(&min_delay, &tm_tmp, &min_delay);
1049 		timespecadd(&min_delay, &interval, &interval);
1050 	}
1051 	rtadvd_set_timer(&interval, timer);
1052 }
1053 
1054 static void
1055 ra_input(int len, struct nd_router_advert *ra,
1056 	 struct in6_pktinfo *pi, struct sockaddr_in6 *from)
1057 {
1058 	struct rainfo *rai;
1059 	char ntopbuf[INET6_ADDRSTRLEN], ifnamebuf[IFNAMSIZ];
1060 	union nd_opts ndopts;
1061 	const char *on_off[] = {"OFF", "ON"};
1062 	uint32_t reachabletime, retranstimer, mtu;
1063 	struct nd_optlist *optp;
1064 	int inconsistent = 0;
1065 
1066 	logit(LOG_DEBUG,
1067 	       "%s: RA received from %s on %s",
1068 	       __func__,
1069 	       inet_ntop(AF_INET6, &from->sin6_addr,
1070 			 ntopbuf, INET6_ADDRSTRLEN),
1071 	       if_indextoname(pi->ipi6_ifindex, ifnamebuf));
1072 
1073 	/* ND option check */
1074 	memset(&ndopts, 0, sizeof(ndopts));
1075 	TAILQ_INIT(&ndopts.nd_opts_list);
1076 	if (nd6_options((struct nd_opt_hdr *)(ra + 1),
1077 	    len - sizeof(struct nd_router_advert),
1078 	    &ndopts, NDOPT_FLAG_SRCLINKADDR |
1079 	    NDOPT_FLAG_PREFIXINFO | NDOPT_FLAG_MTU |
1080 	    NDOPT_FLAG_RDNSS | NDOPT_FLAG_DNSSL))
1081 	{
1082 		logit(LOG_INFO,
1083 		    "%s: ND option check failed for an RA from %s on %s",
1084 		    __func__,
1085 		    inet_ntop(AF_INET6, &from->sin6_addr,
1086 		        ntopbuf, INET6_ADDRSTRLEN),
1087 		        if_indextoname(pi->ipi6_ifindex, ifnamebuf));
1088 		return;
1089 	}
1090 
1091 	/*
1092 	 * RA consistency check according to RFC-2461 6.2.7
1093 	 */
1094 	if ((rai = if_indextorainfo(pi->ipi6_ifindex)) == 0) {
1095 		logit(LOG_INFO,
1096 		       "%s: received RA from %s on non-advertising"
1097 		       " interface(%s)",
1098 		       __func__,
1099 		       inet_ntop(AF_INET6, &from->sin6_addr,
1100 				 ntopbuf, INET6_ADDRSTRLEN),
1101 		       if_indextoname(pi->ipi6_ifindex, ifnamebuf));
1102 		goto done;
1103 	}
1104 	if (rai->leaving) {
1105 		logit(LOG_DEBUG,
1106 		       "%s: received RA on re-configuring interface (%s)",
1107 			__func__, rai->ifname);
1108 		goto done;
1109 	}
1110 	rai->rainput++;		/* increment statistics */
1111 
1112 	/* Cur Hop Limit value */
1113 	if (ra->nd_ra_curhoplimit && rai->hoplimit &&
1114 	    ra->nd_ra_curhoplimit != rai->hoplimit) {
1115 		logit(LOG_INFO,
1116 		       "%s: CurHopLimit inconsistent on %s:"
1117 		       " %d from %s, %d from us",
1118 		       __func__,
1119 		       rai->ifname,
1120 		       ra->nd_ra_curhoplimit,
1121 		       inet_ntop(AF_INET6, &from->sin6_addr,
1122 				 ntopbuf, INET6_ADDRSTRLEN),
1123 		       rai->hoplimit);
1124 		inconsistent++;
1125 	}
1126 	/* M flag */
1127 	if ((ra->nd_ra_flags_reserved & ND_RA_FLAG_MANAGED) !=
1128 	    rai->managedflg) {
1129 		logit(LOG_INFO,
1130 		       "%s: M flag inconsistent on %s:"
1131 		       " %s from %s, %s from us",
1132 		       __func__,
1133 		       rai->ifname,
1134 		       on_off[!rai->managedflg],
1135 		       inet_ntop(AF_INET6, &from->sin6_addr,
1136 				 ntopbuf, INET6_ADDRSTRLEN),
1137 		       on_off[rai->managedflg]);
1138 		inconsistent++;
1139 	}
1140 	/* O flag */
1141 	if ((ra->nd_ra_flags_reserved & ND_RA_FLAG_OTHER) !=
1142 	    rai->otherflg) {
1143 		logit(LOG_INFO,
1144 		       "%s: O flag inconsistent on %s:"
1145 		       " %s from %s, %s from us",
1146 		       __func__,
1147 		       rai->ifname,
1148 		       on_off[!rai->otherflg],
1149 		       inet_ntop(AF_INET6, &from->sin6_addr,
1150 				 ntopbuf, INET6_ADDRSTRLEN),
1151 		       on_off[rai->otherflg]);
1152 		inconsistent++;
1153 	}
1154 	/* Reachable Time */
1155 	reachabletime = ntohl(ra->nd_ra_reachable);
1156 	if (reachabletime && rai->reachabletime &&
1157 	    reachabletime != rai->reachabletime) {
1158 		logit(LOG_INFO,
1159 		       "%s: ReachableTime inconsistent on %s:"
1160 		       " %d from %s, %d from us",
1161 		       __func__,
1162 		       rai->ifname,
1163 		       reachabletime,
1164 		       inet_ntop(AF_INET6, &from->sin6_addr,
1165 				 ntopbuf, INET6_ADDRSTRLEN),
1166 		       rai->reachabletime);
1167 		inconsistent++;
1168 	}
1169 	/* Retrans Timer */
1170 	retranstimer = ntohl(ra->nd_ra_retransmit);
1171 	if (retranstimer && rai->retranstimer &&
1172 	    retranstimer != rai->retranstimer) {
1173 		logit(LOG_INFO,
1174 		       "%s: RetranceTimer inconsistent on %s:"
1175 		       " %d from %s, %d from us",
1176 		       __func__,
1177 		       rai->ifname,
1178 		       retranstimer,
1179 		       inet_ntop(AF_INET6, &from->sin6_addr,
1180 				 ntopbuf, INET6_ADDRSTRLEN),
1181 		       rai->retranstimer);
1182 		inconsistent++;
1183 	}
1184 	/* Values in the MTU options */
1185 	if (ndopts.nd_opts_mtu) {
1186 		mtu = ntohl(ndopts.nd_opts_mtu->nd_opt_mtu_mtu);
1187 		if (mtu && rai->linkmtu && mtu != rai->linkmtu) {
1188 			logit(LOG_INFO,
1189 			       "%s: MTU option value inconsistent on %s:"
1190 			       " %d from %s, %d from us",
1191 			       __func__,
1192 			       rai->ifname, mtu,
1193 			       inet_ntop(AF_INET6, &from->sin6_addr,
1194 					 ntopbuf, INET6_ADDRSTRLEN),
1195 			       rai->linkmtu);
1196 			inconsistent++;
1197 		}
1198 	}
1199 	/* Preferred and Valid Lifetimes for prefixes */
1200 	if (ndopts.nd_opts_pi)
1201 		if (prefix_check(ndopts.nd_opts_pi, rai, from))
1202 			inconsistent++;
1203 	TAILQ_FOREACH(optp, &ndopts.nd_opts_list, next)
1204 		if (prefix_check((struct nd_opt_prefix_info *)optp->opt,
1205 		    rai, from))
1206 			inconsistent++;
1207 
1208 	if (inconsistent)
1209 		rai->rainconsistent++;
1210 
1211 done:
1212 	free_ndopts(&ndopts);
1213 }
1214 
1215 /* return a non-zero value if the received prefix is inconsitent with ours */
1216 static int
1217 prefix_check(struct nd_opt_prefix_info *pinfo,
1218 	     struct rainfo *rai, struct sockaddr_in6 *from)
1219 {
1220 	uint32_t preferred_time, valid_time;
1221 	struct prefix *pp;
1222 	int inconsistent = 0;
1223 	char ntopbuf[INET6_ADDRSTRLEN], prefixbuf[INET6_ADDRSTRLEN];
1224 	struct timespec now;
1225 	struct in6_addr prefix;
1226 
1227 #if 0				/* impossible */
1228 	if (pinfo->nd_opt_pi_type != ND_OPT_PREFIX_INFORMATION)
1229 		return 0;
1230 #endif
1231 
1232 	memcpy(&prefix, &pinfo->nd_opt_pi_prefix, sizeof(prefix));
1233 
1234 	/*
1235 	 * log if the adveritsed prefix has link-local scope(sanity check?)
1236 	 */
1237 	if (IN6_IS_ADDR_LINKLOCAL(&prefix)) {
1238 		logit(LOG_INFO,
1239 		       "%s: link-local prefix %s/%d is advertised "
1240 		       "from %s on %s",
1241 		       __func__,
1242 		       inet_ntop(AF_INET6, &prefix,
1243 				 prefixbuf, INET6_ADDRSTRLEN),
1244 		       pinfo->nd_opt_pi_prefix_len,
1245 		       inet_ntop(AF_INET6, &from->sin6_addr,
1246 				 ntopbuf, INET6_ADDRSTRLEN),
1247 		       rai->ifname);
1248 	}
1249 
1250 	if ((pp = find_prefix(rai, &prefix,
1251 			      pinfo->nd_opt_pi_prefix_len)) == NULL) {
1252 		logit(LOG_INFO,
1253 		       "%s: prefix %s/%d from %s on %s is not in our list",
1254 		       __func__,
1255 		       inet_ntop(AF_INET6, &prefix,
1256 				 prefixbuf, INET6_ADDRSTRLEN),
1257 		       pinfo->nd_opt_pi_prefix_len,
1258 		       inet_ntop(AF_INET6, &from->sin6_addr,
1259 				 ntopbuf, INET6_ADDRSTRLEN),
1260 		       rai->ifname);
1261 		return 0;
1262 	}
1263 
1264 	preferred_time = ntohl(pinfo->nd_opt_pi_preferred_time);
1265 	if (pp->pltimeexpire) {
1266 		/*
1267 		 * The lifetime is decremented in real time, so we should
1268 		 * compare the expiration time.
1269 		 * (RFC 2461 Section 6.2.7.)
1270 		 * XXX: can we really expect that all routers on the link
1271 		 * have synchronized clocks?
1272 		 */
1273 		prog_clock_gettime(CLOCK_MONOTONIC, &now);
1274 		preferred_time += now.tv_sec;
1275 
1276 		if (!pp->timer && rai->clockskew &&
1277 		    llabs((long long)preferred_time - pp->pltimeexpire) > rai->clockskew) {
1278 			logit(LOG_INFO,
1279 			       "%s: preferred lifetime for %s/%d"
1280 			       " (decr. in real time) inconsistent on %s:"
1281 			       " %d from %s, %ld from us",
1282 			       __func__,
1283 			       inet_ntop(AF_INET6, &prefix,
1284 					 prefixbuf, INET6_ADDRSTRLEN),
1285 			       pinfo->nd_opt_pi_prefix_len,
1286 			       rai->ifname, preferred_time,
1287 			       inet_ntop(AF_INET6, &from->sin6_addr,
1288 					 ntopbuf, INET6_ADDRSTRLEN),
1289 			       pp->pltimeexpire);
1290 			inconsistent++;
1291 		}
1292 	} else if (!pp->timer && preferred_time != pp->preflifetime) {
1293 		logit(LOG_INFO,
1294 		       "%s: preferred lifetime for %s/%d"
1295 		       " inconsistent on %s:"
1296 		       " %d from %s, %d from us",
1297 		       __func__,
1298 		       inet_ntop(AF_INET6, &prefix,
1299 				 prefixbuf, INET6_ADDRSTRLEN),
1300 		       pinfo->nd_opt_pi_prefix_len,
1301 		       rai->ifname, preferred_time,
1302 		       inet_ntop(AF_INET6, &from->sin6_addr,
1303 				 ntopbuf, INET6_ADDRSTRLEN),
1304 		       pp->preflifetime);
1305 	}
1306 
1307 	valid_time = ntohl(pinfo->nd_opt_pi_valid_time);
1308 	if (pp->vltimeexpire) {
1309 		prog_clock_gettime(CLOCK_MONOTONIC, &now);
1310 		valid_time += now.tv_sec;
1311 
1312 		if (!pp->timer && rai->clockskew &&
1313 		    llabs((long long)valid_time - pp->vltimeexpire) > rai->clockskew) {
1314 			logit(LOG_INFO,
1315 			       "%s: valid lifetime for %s/%d"
1316 			       " (decr. in real time) inconsistent on %s:"
1317 			       " %d from %s, %ld from us",
1318 			       __func__,
1319 			       inet_ntop(AF_INET6, &prefix,
1320 					 prefixbuf, INET6_ADDRSTRLEN),
1321 			       pinfo->nd_opt_pi_prefix_len,
1322 			       rai->ifname, preferred_time,
1323 			       inet_ntop(AF_INET6, &from->sin6_addr,
1324 					 ntopbuf, INET6_ADDRSTRLEN),
1325 			       pp->vltimeexpire);
1326 			inconsistent++;
1327 		}
1328 	} else if (!pp->timer && valid_time != pp->validlifetime) {
1329 		logit(LOG_INFO,
1330 		       "%s: valid lifetime for %s/%d"
1331 		       " inconsistent on %s:"
1332 		       " %d from %s, %d from us",
1333 		       __func__,
1334 		       inet_ntop(AF_INET6, &prefix,
1335 				 prefixbuf, INET6_ADDRSTRLEN),
1336 		       pinfo->nd_opt_pi_prefix_len,
1337 		       rai->ifname, valid_time,
1338 		       inet_ntop(AF_INET6, &from->sin6_addr,
1339 				 ntopbuf, INET6_ADDRSTRLEN),
1340 		       pp->validlifetime);
1341 		inconsistent++;
1342 	}
1343 
1344 	return inconsistent;
1345 }
1346 
1347 struct prefix *
1348 find_prefix(struct rainfo *rai, struct in6_addr *prefix, int plen)
1349 {
1350 	struct prefix *pp;
1351 	int bytelen, bitlen;
1352 	unsigned char bitmask;
1353 
1354 	TAILQ_FOREACH(pp, &rai->prefix, next) {
1355 		if (plen != pp->prefixlen)
1356 			continue;
1357 		bytelen = plen / 8;
1358 		bitlen = plen % 8;
1359 		bitmask = 0xff << (8 - bitlen);
1360 		if (memcmp(prefix, &pp->prefix, bytelen))
1361 			continue;
1362 		if (bitlen == 0 ||
1363 		    ((prefix->s6_addr[bytelen] & bitmask) ==
1364 		     (pp->prefix.s6_addr[bytelen] & bitmask))) {
1365 			return pp;
1366 		}
1367 	}
1368 
1369 	return NULL;
1370 }
1371 
1372 /* check if p0/plen0 matches p1/plen1; return 1 if matches, otherwise 0. */
1373 int
1374 prefix_match(struct in6_addr *p0, int plen0,
1375 	     struct in6_addr *p1, int plen1)
1376 {
1377 	int bytelen, bitlen;
1378 	unsigned char bitmask;
1379 
1380 	if (plen0 < plen1)
1381 		return 0;
1382 	bytelen = plen1 / 8;
1383 	bitlen = plen1 % 8;
1384 	bitmask = 0xff << (8 - bitlen);
1385 	if (memcmp(p0, p1, bytelen))
1386 		return 0;
1387 	if (bitlen == 0 ||
1388 	    ((p0->s6_addr[bytelen] & bitmask) ==
1389 	     (p1->s6_addr[bytelen] & bitmask))) {
1390 		return 1;
1391 	}
1392 
1393 	return 0;
1394 }
1395 
1396 static int
1397 nd6_options(struct nd_opt_hdr *hdr, int limit,
1398 	    union nd_opts *ndopts, uint32_t optflags)
1399 {
1400 	int optlen = 0;
1401 
1402 	for (; limit > 0; limit -= optlen) {
1403 		if ((size_t)limit < sizeof(struct nd_opt_hdr)) {
1404 			logit(LOG_INFO, "%s: short option header", __func__);
1405 			goto bad;
1406 		}
1407 
1408 		hdr = (struct nd_opt_hdr *)((char *)hdr + optlen);
1409 		if (hdr->nd_opt_len == 0) {
1410 			logit(LOG_INFO,
1411 			    "%s: bad ND option length(0) (type = %d)",
1412 			    __func__, hdr->nd_opt_type);
1413 			goto bad;
1414 		}
1415 		optlen = hdr->nd_opt_len << 3;
1416 		if (optlen > limit) {
1417 			logit(LOG_INFO, "%s: short option", __func__);
1418 			goto bad;
1419 		}
1420 
1421 		if (hdr->nd_opt_type > ND_OPT_MTU &&
1422 		    hdr->nd_opt_type != ND_OPT_RDNSS &&
1423 		    hdr->nd_opt_type != ND_OPT_DNSSL)
1424 		{
1425 			logit(LOG_INFO, "%s: unknown ND option(type %d)",
1426 			    __func__, hdr->nd_opt_type);
1427 			continue;
1428 		}
1429 
1430 		if ((ndopt_flags[hdr->nd_opt_type] & optflags) == 0) {
1431 			logit(LOG_INFO, "%s: unexpected ND option(type %d)",
1432 			    __func__, hdr->nd_opt_type);
1433 			continue;
1434 		}
1435 
1436 		/*
1437 		 * Option length check.  Do it here for all fixed-length
1438 		 * options.
1439 		 */
1440 		if ((hdr->nd_opt_type == ND_OPT_MTU &&
1441 		    (optlen != sizeof(struct nd_opt_mtu))) ||
1442 		    ((hdr->nd_opt_type == ND_OPT_PREFIX_INFORMATION &&
1443 		    optlen != sizeof(struct nd_opt_prefix_info))) ||
1444 		    (hdr->nd_opt_type == ND_OPT_RDNSS &&
1445 		    ((optlen < (int)sizeof(struct nd_opt_rdnss) ||
1446 		    (optlen - sizeof(struct nd_opt_rdnss)) % 16 != 0))) ||
1447 		    (hdr->nd_opt_type == ND_OPT_DNSSL &&
1448 		    optlen < (int)sizeof(struct nd_opt_dnssl)))
1449 		{
1450 			logit(LOG_INFO, "%s: invalid option length",
1451 			    __func__);
1452 			continue;
1453 		}
1454 
1455 		switch (hdr->nd_opt_type) {
1456 		case ND_OPT_TARGET_LINKADDR:
1457 		case ND_OPT_REDIRECTED_HEADER:
1458 		case ND_OPT_RDNSS:
1459 		case ND_OPT_DNSSL:
1460 			break;	/* we don't care about these options */
1461 		case ND_OPT_SOURCE_LINKADDR:
1462 		case ND_OPT_MTU:
1463 			if (ndopts->nd_opt_array[hdr->nd_opt_type]) {
1464 				logit(LOG_INFO,
1465 				    "%s: duplicated ND option (type = %d)",
1466 				    __func__, hdr->nd_opt_type);
1467 			}
1468 			ndopts->nd_opt_array[hdr->nd_opt_type] = hdr;
1469 			break;
1470 		case ND_OPT_PREFIX_INFORMATION:
1471 		{
1472 			struct nd_optlist *pfxlist;
1473 
1474 			if (ndopts->nd_opts_pi == 0) {
1475 				ndopts->nd_opts_pi =
1476 				    (struct nd_opt_prefix_info *)hdr;
1477 				continue;
1478 			}
1479 			if ((pfxlist = malloc(sizeof(*pfxlist))) == NULL) {
1480 				logit(LOG_ERR, "%s: can't allocate memory",
1481 				    __func__);
1482 				goto bad;
1483 			}
1484 			pfxlist->opt = hdr;
1485 			TAILQ_INSERT_TAIL(&ndopts->nd_opts_list, pfxlist, next);
1486 
1487 			break;
1488 		}
1489 		default:	/* impossible */
1490 			break;
1491 		}
1492 	}
1493 
1494 	return 0;
1495 
1496   bad:
1497 	free_ndopts(ndopts);
1498 	return -1;
1499 }
1500 
1501 static void
1502 free_ndopts(union nd_opts *ndopts)
1503 {
1504 	struct nd_optlist *opt;
1505 
1506 	while ((opt = TAILQ_FIRST(&ndopts->nd_opts_list)) != NULL) {
1507 		TAILQ_REMOVE(&ndopts->nd_opts_list, opt, next);
1508 		free(opt);
1509 	}
1510 }
1511 
1512 void
1513 sock_open(void)
1514 {
1515 	struct icmp6_filter filt;
1516 	struct ipv6_mreq mreq;
1517 	struct rainfo *ra;
1518 	int on;
1519 	/* XXX: should be max MTU attached to the node */
1520 	static unsigned char answer[1500];
1521 
1522 	rcvcmsgbuflen = CMSG_SPACE(sizeof(struct in6_pktinfo)) +
1523 				CMSG_SPACE(sizeof(int));
1524 	rcvcmsgbuf = malloc(rcvcmsgbuflen);
1525 	if (rcvcmsgbuf == NULL) {
1526 		logit(LOG_ERR, "%s: malloc: %m", __func__);
1527 		exit(EXIT_FAILURE);
1528 	}
1529 
1530 	sndcmsgbuflen = CMSG_SPACE(sizeof(struct in6_pktinfo));
1531 	sndcmsgbuf = malloc(sndcmsgbuflen);
1532 	if (sndcmsgbuf == NULL) {
1533 		logit(LOG_ERR, "%s: malloc: %m", __func__);
1534 		exit(EXIT_FAILURE);
1535 	}
1536 
1537 	if ((sock = prog_socket(AF_INET6, SOCK_RAW, IPPROTO_ICMPV6)) == -1) {
1538 		logit(LOG_ERR, "%s: socket: %m", __func__);
1539 		exit(EXIT_FAILURE);
1540 	}
1541 
1542 	/* RFC 4861 Section 4.2 */
1543 	on = 255;
1544 	if (prog_setsockopt(sock, IPPROTO_IPV6, IPV6_MULTICAST_HOPS, &on,
1545 		       sizeof(on)) == -1) {
1546 		logit(LOG_ERR, "%s: IPV6_MULTICAST_HOPS: %m", __func__);
1547 		exit(EXIT_FAILURE);
1548 	}
1549 	on = 255;
1550 	if (prog_setsockopt(sock, IPPROTO_IPV6, IPV6_UNICAST_HOPS, &on,
1551 		       sizeof(on)) == -1) {
1552 		logit(LOG_ERR, "%s: IPV6_UNICAST_HOPS: %m", __func__);
1553 		exit(EXIT_FAILURE);
1554 	}
1555 
1556 	/* specify to tell receiving interface */
1557 	on = 1;
1558 	if (prog_setsockopt(sock, IPPROTO_IPV6, IPV6_RECVPKTINFO, &on,
1559 		       sizeof(on)) == -1) {
1560 		logit(LOG_ERR, "%s: IPV6_RECVPKTINFO: %m", __func__);
1561 		exit(EXIT_FAILURE);
1562 	}
1563 
1564 	on = 1;
1565 	/* specify to tell value of hoplimit field of received IP6 hdr */
1566 	if (prog_setsockopt(sock, IPPROTO_IPV6, IPV6_RECVHOPLIMIT, &on,
1567 		       sizeof(on)) == -1) {
1568 		logit(LOG_ERR, "%s: IPV6_RECVHOPLIMIT: %m", __func__);
1569 		exit(EXIT_FAILURE);
1570 	}
1571 
1572 	ICMP6_FILTER_SETBLOCKALL(&filt);
1573 	ICMP6_FILTER_SETPASS(ND_ROUTER_SOLICIT, &filt);
1574 	ICMP6_FILTER_SETPASS(ND_ROUTER_ADVERT, &filt);
1575 	if (accept_rr)
1576 		ICMP6_FILTER_SETPASS(ICMP6_ROUTER_RENUMBERING, &filt);
1577 	if (prog_setsockopt(sock, IPPROTO_ICMPV6, ICMP6_FILTER, &filt,
1578 		       sizeof(filt)) == -1) {
1579 		logit(LOG_ERR, "%s: IICMP6_FILTER: %m", __func__);
1580 		exit(EXIT_FAILURE);
1581 	}
1582 
1583 	/*
1584 	 * join all routers multicast address on each advertising interface.
1585 	 */
1586 	if (inet_pton(AF_INET6, ALLROUTERS_LINK,
1587 	    mreq.ipv6mr_multiaddr.s6_addr) != 1)
1588 	{
1589 		logit(LOG_ERR, "%s: inet_pton failed(library bug?)",
1590 		    __func__);
1591 		exit(EXIT_FAILURE);
1592 	}
1593 	TAILQ_FOREACH(ra, &ralist, next) {
1594 		mreq.ipv6mr_interface = ra->ifindex;
1595 		if (prog_setsockopt(sock, IPPROTO_IPV6, IPV6_JOIN_GROUP, &mreq,
1596 			       sizeof(mreq)) == -1) {
1597 			logit(LOG_ERR, "%s: IPV6_JOIN_GROUP(link) on %s: %m",
1598 			       __func__, ra->ifname);
1599 			continue;
1600 		}
1601 	}
1602 
1603 	/*
1604 	 * When attending router renumbering, join all-routers site-local
1605 	 * multicast group.
1606 	 */
1607 	if (accept_rr) {
1608 		if (inet_pton(AF_INET6, ALLROUTERS_SITE,
1609 		     mreq.ipv6mr_multiaddr.s6_addr) != 1)
1610 		{
1611 			logit(LOG_ERR, "%s: inet_pton failed(library bug?)",
1612 			    __func__);
1613 			exit(EXIT_FAILURE);
1614 		}
1615 		ra = TAILQ_FIRST(&ralist);
1616 		if (mcastif) {
1617 			if ((mreq.ipv6mr_interface = if_nametoindex(mcastif))
1618 			    == 0) {
1619 				logit(LOG_ERR,
1620 				       "%s: invalid interface: %s",
1621 				       __func__, mcastif);
1622 				exit(EXIT_FAILURE);
1623 			}
1624 		} else
1625 			mreq.ipv6mr_interface = ra->ifindex;
1626 		if (prog_setsockopt(sock, IPPROTO_IPV6, IPV6_JOIN_GROUP,
1627 			       &mreq, sizeof(mreq)) == -1) {
1628 			logit(LOG_ERR,
1629 			       "%s: IPV6_JOIN_GROUP(site) on %s: %m",
1630 			       __func__,
1631 			       mcastif ? mcastif : ra->ifname);
1632 			exit(EXIT_FAILURE);
1633 		}
1634 	}
1635 
1636 	/* initialize msghdr for receiving packets */
1637 	rcviov[0].iov_base = answer;
1638 	rcviov[0].iov_len = sizeof(answer);
1639 	rcvmhdr.msg_name = &rcvfrom;
1640 	rcvmhdr.msg_namelen = sizeof(rcvfrom);
1641 	rcvmhdr.msg_iov = rcviov;
1642 	rcvmhdr.msg_iovlen = 1;
1643 	rcvmhdr.msg_control = rcvcmsgbuf;
1644 	rcvmhdr.msg_controllen = rcvcmsgbuflen;
1645 
1646 	/* initialize msghdr for sending packets */
1647 	sndmhdr.msg_namelen = sizeof(struct sockaddr_in6);
1648 	sndmhdr.msg_iov = sndiov;
1649 	sndmhdr.msg_iovlen = 1;
1650 	sndmhdr.msg_control = sndcmsgbuf;
1651 	sndmhdr.msg_controllen = sndcmsgbuflen;
1652 }
1653 
1654 /* open a routing socket to watch the routing table */
1655 static void
1656 rtsock_open(void)
1657 {
1658 #ifdef RO_MSGFILTER
1659 	unsigned char msgfilter[] = {
1660 		RTM_ADD, RTM_DELETE,
1661 		RTM_NEWADDR, RTM_DELADDR,
1662 #ifdef RTM_IFANNOUNCE
1663 		RTM_IFANNOUNCE,
1664 #endif
1665 		RTM_IFINFO,
1666 	};
1667 #endif
1668 
1669 	if ((rtsock = prog_socket(PF_ROUTE, SOCK_RAW, 0)) == -1) {
1670 		logit(LOG_ERR, "%s: socket: %m", __func__);
1671 		exit(EXIT_FAILURE);
1672 	}
1673 #ifdef RO_MSGFILTER
1674 	if (setsockopt(rtsock, PF_ROUTE, RO_MSGFILTER,
1675 	    &msgfilter, sizeof(msgfilter) == -1))
1676 		logit(LOG_ERR, "%s: RO_MSGFILTER: %m", __func__);
1677 #endif
1678 }
1679 
1680 struct rainfo *
1681 if_indextorainfo(unsigned int idx)
1682 {
1683 	struct rainfo *rai;
1684 
1685 	TAILQ_FOREACH(rai, &ralist, next) {
1686 		if (rai->ifindex == idx)
1687 			return rai;
1688 	}
1689 
1690 	return NULL;		/* search failed */
1691 }
1692 
1693 struct rainfo *
1694 ra_output(struct rainfo *rai, bool solicited)
1695 {
1696 	int i;
1697 	struct cmsghdr *cm;
1698 	struct in6_pktinfo *pi;
1699 	struct soliciter *sol;
1700 
1701 	if ((rai->ifflags & IFF_UP) == 0) {
1702 		logit(LOG_DEBUG, "%s: %s is not up, skip sending RA",
1703 		       __func__, rai->ifname);
1704 		return NULL;
1705 	}
1706 
1707 	make_packet(rai);	/* XXX: inefficient */
1708 
1709 	sndmhdr.msg_name = (void *)&sin6_linklocal_allnodes;
1710 	sndmhdr.msg_iov[0].iov_base = (void *)rai->ra_data;
1711 	sndmhdr.msg_iov[0].iov_len = rai->ra_datalen;
1712 
1713 	/* specify the outgoing interface */
1714 	cm = CMSG_FIRSTHDR(&sndmhdr);
1715 	cm->cmsg_level = IPPROTO_IPV6;
1716 	cm->cmsg_type = IPV6_PKTINFO;
1717 	cm->cmsg_len = CMSG_LEN(sizeof(struct in6_pktinfo));
1718 	pi = (struct in6_pktinfo *)CMSG_DATA(cm);
1719 	memset(&pi->ipi6_addr, 0, sizeof(pi->ipi6_addr));	/*XXX*/
1720 	pi->ipi6_ifindex = rai->ifindex;
1721 
1722 	logit(LOG_DEBUG,
1723 	       "%s: send RA on %s, # of waitings = %d",
1724 	       __func__, rai->ifname, rai->waiting);
1725 
1726 	if (solicited) {
1727 		/* unicast solicited RA's as per RFC 7772 */
1728 		while ((sol = TAILQ_FIRST(&rai->soliciter)) != NULL) {
1729 			sndmhdr.msg_name = (void *)&sol->addr;
1730 			i = prog_sendmsg(sock, &sndmhdr, 0);
1731 			if (i < 0 || (size_t)i != rai->ra_datalen)  {
1732 				if (i < 0) {
1733 					logit(LOG_ERR,
1734 					    "%s: unicast sendmsg on %s: %m",
1735 					    __func__, rai->ifname);
1736 				}
1737 			}
1738 			TAILQ_REMOVE(&rai->soliciter, sol, next);
1739 			free(sol);
1740 		}
1741 
1742 		/* reset waiting conter */
1743 		rai->waiting = 0;
1744 
1745 		/* disable timer */
1746 		rai->timer_sol->enabled = false;
1747 
1748 		return rai;
1749 	}
1750 
1751 	i = prog_sendmsg(sock, &sndmhdr, 0);
1752 	if (i < 0 || (size_t)i != rai->ra_datalen)  {
1753 		if (i < 0) {
1754 			logit(LOG_ERR, "%s: sendmsg on %s: %m",
1755 			       __func__, rai->ifname);
1756 		}
1757 	}
1758 
1759 	if (rai->leaving_adv > 0) {
1760 		if (--(rai->leaving_adv) == 0) {
1761 			/* leaving for ourself means we're shutting down */
1762 			if (rai->leaving_for == rai) {
1763 				TAILQ_REMOVE(&ralist, rai, next);
1764 				free_rainfo(rai);
1765 				return NULL;
1766 			}
1767 			logit(LOG_DEBUG,
1768 			       "%s: expired RA,"
1769 			       " new config active for interface (%s)",
1770 			       __func__, rai->ifname);
1771 			ra_timer_reset(rai->leaving_for);
1772 			rai->leaving_for->leaving = NULL;
1773 			free_rainfo(rai);
1774 			return NULL;
1775 		}
1776 	}
1777 
1778 	/* update counter */
1779 	if (rai->initcounter < MAX_INITIAL_RTR_ADVERTISEMENTS)
1780 		rai->initcounter++;
1781 	rai->raoutput++;
1782 
1783 	/* update timestamp */
1784 	prog_clock_gettime(CLOCK_MONOTONIC, &rai->lastsent);
1785 	return rai;
1786 }
1787 
1788 /* process unsolicited RA timer */
1789 struct rtadvd_timer *
1790 ra_timeout(void *data)
1791 {
1792 	struct rainfo *rai = (struct rainfo *)data;
1793 
1794 	logit(LOG_DEBUG,
1795 	       "%s: unsolicited RA timer on %s is expired",
1796 	       __func__, rai->ifname);
1797 
1798 	if (ra_output(rai, false))
1799 		return rai->timer;
1800 	return NULL;
1801 }
1802 
1803 /* process solicited RA timer */
1804 struct rtadvd_timer *
1805 ra_timeout_sol(void *data)
1806 {
1807 	struct rainfo *rai = (struct rainfo *)data;
1808 
1809 	logit(LOG_DEBUG,
1810 	       "%s: solicited RA timer on %s is expired",
1811 	       __func__, rai->ifname);
1812 
1813 	if (ra_output(rai, true))
1814 		return rai->timer_sol;
1815 	return NULL;
1816 }
1817 
1818 /* update RA timer */
1819 void
1820 ra_timer_update(void *data, struct timespec *tm)
1821 {
1822 	struct rainfo *rai = (struct rainfo *)data;
1823 	long interval;
1824 
1825 	/*
1826 	 * Whenever a multicast advertisement is sent from an interface,
1827 	 * the timer is reset to a uniformly-distributed random value
1828 	 * between the interface's configured MinRtrAdvInterval and
1829 	 * MaxRtrAdvInterval (RFC2461 6.2.4).
1830 	 */
1831 	interval = rai->mininterval;
1832 	if (rai->mininterval != rai->maxinterval)
1833 		interval += arc4random() % (rai->maxinterval-rai->mininterval);
1834 
1835 	/*
1836 	 * For the first few advertisements (up to
1837 	 * MAX_INITIAL_RTR_ADVERTISEMENTS), if the randomly chosen interval
1838 	 * is greater than MAX_INITIAL_RTR_ADVERT_INTERVAL, the timer
1839 	 * SHOULD be set to MAX_INITIAL_RTR_ADVERT_INTERVAL instead.
1840 	 * (RFC-2461 6.2.4)
1841 	 */
1842 	if (rai->initcounter < MAX_INITIAL_RTR_ADVERTISEMENTS &&
1843 	    interval > MAX_INITIAL_RTR_ADVERT_INTERVAL)
1844 		interval = MAX_INITIAL_RTR_ADVERT_INTERVAL;
1845 
1846 	tm->tv_sec = interval;
1847 	tm->tv_nsec = 0;
1848 
1849 	logit(LOG_DEBUG,
1850 	       "%s: RA timer on %s is set to %jd:%jd",
1851 	       __func__, rai->ifname,
1852 	       (intmax_t)tm->tv_sec, (intmax_t)tm->tv_nsec);
1853 }
1854 
1855 void
1856 logit(int level, const char *fmt, ...)
1857 {
1858 	va_list ap;
1859 	char *buf;
1860 
1861 	va_start(ap, fmt);
1862 	if (!Dflag) {
1863 		vsyslog(level, fmt, ap);
1864 		va_end(ap);
1865 		return;
1866 	}
1867 
1868 	vfprintf(stderr, expandm(fmt, "\n", &buf), ap);
1869 	free(buf);
1870 	va_end(ap);
1871 }
1872