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