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