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