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