Home | History | Annotate | Line # | Download | only in route6d
route6d.c revision 1.71
      1 /*	$NetBSD: route6d.c,v 1.71 2018/05/09 07:30:21 maxv Exp $	*/
      2 /*	$KAME: route6d.c,v 1.94 2002/10/26 20:08:55 itojun Exp $	*/
      3 
      4 /*
      5  * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
      6  * All rights reserved.
      7  *
      8  * Redistribution and use in source and binary forms, with or without
      9  * modification, are permitted provided that the following conditions
     10  * are met:
     11  * 1. Redistributions of source code must retain the above copyright
     12  *    notice, this list of conditions and the following disclaimer.
     13  * 2. Redistributions in binary form must reproduce the above copyright
     14  *    notice, this list of conditions and the following disclaimer in the
     15  *    documentation and/or other materials provided with the distribution.
     16  * 3. Neither the name of the project nor the names of its contributors
     17  *    may be used to endorse or promote products derived from this software
     18  *    without specific prior written permission.
     19  *
     20  * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
     21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
     24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     30  * SUCH DAMAGE.
     31  */
     32 
     33 #include <sys/cdefs.h>
     34 #ifndef	lint
     35 __RCSID("$NetBSD: route6d.c,v 1.71 2018/05/09 07:30:21 maxv Exp $");
     36 #endif
     37 
     38 #include <stdbool.h>
     39 #include <stdio.h>
     40 
     41 #include <time.h>
     42 #include <unistd.h>
     43 #include <stdlib.h>
     44 #include <string.h>
     45 #include <signal.h>
     46 #include <stdarg.h>
     47 #include <syslog.h>
     48 #include <stddef.h>
     49 #include <errno.h>
     50 #include <err.h>
     51 #include <util.h>
     52 #include <poll.h>
     53 
     54 #include <sys/types.h>
     55 #include <sys/param.h>
     56 #include <sys/file.h>
     57 #include <sys/socket.h>
     58 #include <sys/ioctl.h>
     59 #include <sys/sysctl.h>
     60 #include <sys/uio.h>
     61 #include <net/if.h>
     62 #include <net/route.h>
     63 #include <netinet/in.h>
     64 #include <netinet/in_var.h>
     65 #include <netinet/ip6.h>
     66 #include <netinet/udp.h>
     67 #include <netdb.h>
     68 #include <ifaddrs.h>
     69 
     70 #include <arpa/inet.h>
     71 
     72 #include "route6d.h"
     73 
     74 #define MAXFILTER	40
     75 
     76 #ifdef DEBUG
     77 #define INIT_INTERVAL6	6
     78 #else
     79 #define INIT_INTERVAL6	10	/* Wait to submit a initial riprequest */
     80 #endif
     81 
     82 /* alignment constraint for routing socket */
     83 #if defined(RT_ROUNDUP)
     84 #define ROUNDUP(a) RT_ROUNDUP(a)
     85 #else
     86 #define ROUNDUP(a) \
     87 	((a) > 0 ? (1 + (((a) - 1) | (sizeof(long) - 1))) : sizeof(long))
     88 #endif
     89 
     90 /*
     91  * Following two macros are highly depending on KAME Release
     92  */
     93 #define	IN6_LINKLOCAL_IFINDEX(addr) \
     94 	((addr).s6_addr[2] << 8 | (addr).s6_addr[3])
     95 
     96 #define	SET_IN6_LINKLOCAL_IFINDEX(addr, index) \
     97 	do { \
     98 		(addr).s6_addr[2] = ((index) >> 8) & 0xff; \
     99 		(addr).s6_addr[3] = (index) & 0xff; \
    100 	} while (0)
    101 
    102 struct	ifc {			/* Configuration of an interface */
    103 	char	*ifc_name;			/* if name */
    104 	struct	ifc *ifc_next;
    105 	int	ifc_index;			/* if index */
    106 	int	ifc_mtu;			/* if mtu */
    107 	int	ifc_metric;			/* if metric */
    108 	u_int	ifc_flags;			/* flags */
    109 	short	ifc_cflags;			/* IFC_XXX */
    110 	struct	in6_addr ifc_mylladdr;		/* my link-local address */
    111 	struct	sockaddr_in6 ifc_ripsin;	/* rip multicast address */
    112 	struct	iff *ifc_filter;		/* filter structure */
    113 	struct	ifac *ifc_addr;			/* list of AF_INET6 addresses */
    114 	int	ifc_joined;			/* joined to ff02::9 */
    115 };
    116 
    117 struct ifac {			/* Address associated to an interface */
    118 	struct	ifc *ifa_conf;		/* back pointer */
    119 	struct	ifac *ifa_next;
    120 	struct	in6_addr ifa_addr;	/* address */
    121 	struct	in6_addr ifa_raddr;	/* remote address, valid in p2p */
    122 	int	ifa_plen;		/* prefix length */
    123 };
    124 
    125 struct	iff {
    126 	int	iff_type;
    127 	struct	in6_addr iff_addr;
    128 	int	iff_plen;
    129 	struct	iff *iff_next;
    130 };
    131 
    132 static struct	ifc *ifc;
    133 static int	nifc;		/* number of valid ifc's */
    134 static struct	ifc **index2ifc;
    135 static int	nindex2ifc;
    136 static struct	ifc *loopifcp = NULL;	/* pointing to loopback */
    137 static struct	pollfd set[2];
    138 static int	rtsock;		/* the routing socket */
    139 static int	ripsock;	/* socket to send/receive RIP datagram */
    140 
    141 static struct	rip6 *ripbuf;	/* packet buffer for sending */
    142 
    143 /*
    144  * Maintain the routes in a linked list.  When the number of the routes
    145  * grows, somebody would like to introduce a hash based or a radix tree
    146  * based structure.  I believe the number of routes handled by RIP is
    147  * limited and I don't have to manage a complex data structure, however.
    148  *
    149  * One of the major drawbacks of the linear linked list is the difficulty
    150  * of representing the relationship between a couple of routes.  This may
    151  * be a significant problem when we have to support route aggregation with
    152  * supressing the specifices covered by the aggregate.
    153  */
    154 
    155 struct	riprt {
    156 	struct	riprt *rrt_next;	/* next destination */
    157 	struct	riprt *rrt_same;	/* same destination - future use */
    158 	struct	netinfo6 rrt_info;	/* network info */
    159 	struct	in6_addr rrt_gw;	/* gateway */
    160 	u_long	rrt_flags;		/* kernel routing table flags */
    161 	u_long	rrt_rflags;		/* route6d routing table flags */
    162 	time_t	rrt_t;			/* when the route validated */
    163 	int	rrt_index;		/* ifindex from which this route got */
    164 };
    165 
    166 static struct	riprt *riprt = 0;
    167 
    168 static int	dflag = 0;	/* debug flag */
    169 static int	qflag = 0;	/* quiet flag */
    170 static int	nflag = 0;	/* don't update kernel routing table */
    171 static int	aflag = 0;	/* age out even the statically defined routes */
    172 static int	hflag = 0;	/* don't split horizon */
    173 static int	lflag = 0;	/* exchange site local routes */
    174 static int	sflag = 0;	/* announce static routes w/ split horizon */
    175 static int	Sflag = 0;	/* announce static routes to every interface */
    176 static unsigned long routetag = 0;	/* route tag attached on originating case */
    177 
    178 static char	*filter[MAXFILTER];
    179 static int	filtertype[MAXFILTER];
    180 static int	nfilter = 0;
    181 
    182 static pid_t	pid;
    183 
    184 static struct	sockaddr_storage ripsin;
    185 
    186 static int	interval = 1;
    187 static time_t	nextalarm = 0;
    188 
    189 static FILE	*rtlog = NULL;
    190 
    191 static int logopened = 0;
    192 
    193 static int	seq = 0;
    194 
    195 static volatile sig_atomic_t seenalrm;
    196 static volatile sig_atomic_t seenquit;
    197 static volatile sig_atomic_t seenusr1;
    198 
    199 #define RRTF_AGGREGATE		0x08000000
    200 #define RRTF_NOADVERTISE	0x10000000
    201 #define RRTF_NH_NOT_LLADDR	0x20000000
    202 #define RRTF_SENDANYWAY		0x40000000
    203 #define RRTF_CHANGED		0x80000000
    204 
    205 static void	sighandler(int);
    206 static void	ripalarm(void);
    207 static void	riprecv(void);
    208 static void	ripsend(struct ifc *, struct sockaddr_in6 *, int);
    209 static int	out_filter(struct riprt *, struct ifc *);
    210 static void	init(void);
    211 static void	ifconfig(void);
    212 static void	ifconfig1(const char *, const struct sockaddr *, struct ifc *, int);
    213 static void	rtrecv(void);
    214 static int	rt_del(const struct sockaddr_in6 *, const struct sockaddr_in6 *,
    215 	    const struct sockaddr_in6 *);
    216 static int	rt_deladdr(struct ifc *, const struct sockaddr_in6 *,
    217 	    const struct sockaddr_in6 *);
    218 static void	filterconfig(void);
    219 static int	getifmtu(int);
    220 static const char *
    221 	rttypes(struct rt_msghdr *);
    222 static const char *
    223 	rtflags(struct rt_msghdr *);
    224 static const char *
    225 	ifflags(int);
    226 static int	ifrt(struct ifc *, int);
    227 static void	ifrt_p2p(struct ifc *, int);
    228 static void	applyplen(struct in6_addr *, int);
    229 static void	ifrtdump(int);
    230 static void	ifdump(int);
    231 static void	ifdump0(FILE *, const struct ifc *);
    232 static void	rtdump(int);
    233 static void	rt_entry(struct rt_msghdr *, int);
    234 static void	rtdexit(void) __dead;
    235 static void	riprequest(struct ifc *, struct netinfo6 *, int,
    236 	    struct sockaddr_in6 *);
    237 static void	ripflush(struct ifc *, struct sockaddr_in6 *);
    238 static void	sendrequest(struct ifc *);
    239 static int	sin6mask2len(const struct sockaddr_in6 *);
    240 static int	mask2len(const struct in6_addr *, int);
    241 static int	sendpacket(struct sockaddr_in6 *, int);
    242 static int	addroute(struct riprt *, const struct in6_addr *, struct ifc *);
    243 static int	delroute(struct netinfo6 *, struct in6_addr *);
    244 static void	krtread(int);
    245 static int	tobeadv(struct riprt *, struct ifc *);
    246 static char *	xstrdup(char *);
    247 static char *	hms(void);
    248 static const char *
    249 	inet6_n2p(const struct in6_addr *);
    250 static struct ifac *
    251 	ifa_match(const struct ifc *, const struct in6_addr *, int);
    252 static struct in6_addr *
    253 	plen2mask(int);
    254 static struct riprt *
    255 	rtsearch(struct netinfo6 *, struct riprt **);
    256 static int	ripinterval(int);
    257 static void	fatal(const char *, ...) __printflike(1, 2) __dead;
    258 static void	trace(int, const char *, ...) __printflike(2, 3);
    259 static void	tracet(int, const char *, ...) __printflike(2, 3);
    260 static struct ifc *
    261 	ifc_find(char *);
    262 static struct iff *
    263 	iff_find(struct ifc *, int);
    264 static void	setindex2ifc(int, struct ifc *);
    265 
    266 #define	MALLOC(type)	(malloc(sizeof(type)))
    267 
    268 int
    269 main(int argc, char **argv)
    270 {
    271 	int ch;
    272 	int error = 0;
    273 	struct ifc *ifcp;
    274 	sigset_t mask, omask;
    275 	char *progname;
    276 	char *ep;
    277 
    278 	progname = strrchr(*argv, '/');
    279 	if (progname)
    280 		progname++;
    281 	else
    282 		progname = *argv;
    283 
    284 	pid = getpid();
    285 	while ((ch = getopt(argc, argv, "A:N:O:R:T:L:t:adDhlnqsS")) != -1) {
    286 		switch (ch) {
    287 		case 'A':
    288 		case 'N':
    289 		case 'O':
    290 		case 'T':
    291 		case 'L':
    292 			if (nfilter >= MAXFILTER) {
    293 				fatal("Exceeds MAXFILTER");
    294 			}
    295 			filtertype[nfilter] = ch;
    296 			filter[nfilter++] = xstrdup(optarg);
    297 			break;
    298 		case 't':
    299 			ep = NULL;
    300 			routetag = strtoul(optarg, &ep, 0);
    301 			if (!ep || *ep != '\0' || (routetag & ~0xffff) != 0) {
    302 				fatal("invalid route tag");
    303 			}
    304 			break;
    305 		case 'R':
    306 			if ((rtlog = fopen(optarg, "w")) == NULL) {
    307 				fatal("Can not write to routelog");
    308 			}
    309 			break;
    310 #define	FLAG(c, flag, n)	case c: do { flag = n; break; } while(0)
    311 		FLAG('a', aflag, 1); break;
    312 		FLAG('d', dflag, 1); break;
    313 		FLAG('D', dflag, 2); break;
    314 		FLAG('h', hflag, 1); break;
    315 		FLAG('l', lflag, 1); break;
    316 		FLAG('n', nflag, 1); break;
    317 		FLAG('q', qflag, 1); break;
    318 		FLAG('s', sflag, 1); break;
    319 		FLAG('S', Sflag, 1); break;
    320 #undef	FLAG
    321 		default:
    322 			fatal("Invalid option specified, terminating");
    323 		}
    324 	}
    325 	argc -= optind;
    326 	argv += optind;
    327 	if (argc > 0) {
    328 		fatal("bogus extra arguments");
    329 	}
    330 
    331 	if (geteuid()) {
    332 		nflag = 1;
    333 		fprintf(stderr, "No kernel update is allowed\n");
    334 	}
    335 
    336 	if (dflag == 0) {
    337 		if (daemon(0, 0) < 0) {
    338 			fatal("daemon");
    339 		}
    340 	}
    341 
    342 	openlog(progname, LOG_NDELAY|LOG_PID, LOG_DAEMON);
    343 	logopened++;
    344 
    345 	if ((ripbuf = malloc(RIP6_MAXMTU)) == NULL)
    346 		fatal("malloc");
    347 	memset(ripbuf, 0, RIP6_MAXMTU);
    348 	ripbuf->rip6_cmd = RIP6_RESPONSE;
    349 	ripbuf->rip6_vers = RIP6_VERSION;
    350 	ripbuf->rip6_res1[0] = 0;
    351 	ripbuf->rip6_res1[1] = 0;
    352 
    353 	init();
    354 	ifconfig();
    355 	for (ifcp = ifc; ifcp; ifcp = ifcp->ifc_next) {
    356 		if (ifcp->ifc_index < 0) {
    357 			fprintf(stderr,
    358 "No ifindex found at %s (no link-local address?)\n",
    359 				ifcp->ifc_name);
    360 			error++;
    361 		}
    362 	}
    363 	if (error)
    364 		exit(1);
    365 	if (loopifcp == NULL) {
    366 		fatal("No loopback found");
    367 	}
    368 	for (ifcp = ifc; ifcp; ifcp = ifcp->ifc_next)
    369 		ifrt(ifcp, 0);
    370 	filterconfig();
    371 	krtread(0);
    372 	if (dflag)
    373 		ifrtdump(0);
    374 
    375 	pidfile(NULL);
    376 
    377 	if ((ripbuf = malloc(RIP6_MAXMTU)) == NULL) {
    378 		fatal("malloc");
    379 	}
    380 	memset(ripbuf, 0, RIP6_MAXMTU);
    381 	ripbuf->rip6_cmd = RIP6_RESPONSE;
    382 	ripbuf->rip6_vers = RIP6_VERSION;
    383 	ripbuf->rip6_res1[0] = 0;
    384 	ripbuf->rip6_res1[1] = 0;
    385 
    386 	if (signal(SIGALRM, sighandler) == SIG_ERR ||
    387 	    signal(SIGQUIT, sighandler) == SIG_ERR ||
    388 	    signal(SIGTERM, sighandler) == SIG_ERR ||
    389 	    signal(SIGUSR1, sighandler) == SIG_ERR ||
    390 	    signal(SIGHUP, sighandler) == SIG_ERR ||
    391 	    signal(SIGINT, sighandler) == SIG_ERR) {
    392 		fatal("signal");
    393 	}
    394 	/*
    395 	 * To avoid rip packet congestion (not on a cable but in this
    396 	 * process), wait for a moment to send the first RIP6_RESPONSE
    397 	 * packets.
    398 	 */
    399 	alarm(ripinterval(INIT_INTERVAL6));
    400 
    401 	for (ifcp = ifc; ifcp; ifcp = ifcp->ifc_next) {
    402 		if (iff_find(ifcp, 'N'))
    403 			continue;
    404 		if (ifcp->ifc_index > 0 && (ifcp->ifc_flags & IFF_UP))
    405 			sendrequest(ifcp);
    406 	}
    407 
    408 	syslog(LOG_INFO, "**** Started ****");
    409 	sigemptyset(&mask);
    410 	sigaddset(&mask, SIGALRM);
    411 	while (1) {
    412 		if (seenalrm) {
    413 			ripalarm();
    414 			seenalrm = 0;
    415 			continue;
    416 		}
    417 		if (seenquit) {
    418 			rtdexit();
    419 			seenquit = 0;
    420 			continue;
    421 		}
    422 		if (seenusr1) {
    423 			ifrtdump(SIGUSR1);
    424 			seenusr1 = 0;
    425 			continue;
    426 		}
    427 
    428 		switch (poll(set, 2, INFTIM))
    429 		{
    430 		case -1:
    431 			if (errno != EINTR) {
    432 				fatal("poll");
    433 			}
    434 			continue;
    435 		case 0:
    436 			continue;
    437 		default:
    438 			if (set[0].revents & POLLIN)
    439 			{
    440 				sigprocmask(SIG_BLOCK, &mask, &omask);
    441 				riprecv();
    442 				sigprocmask(SIG_SETMASK, &omask, NULL);
    443 			}
    444 			if (set[1].revents & POLLIN)
    445 			{
    446 				sigprocmask(SIG_BLOCK, &mask, &omask);
    447 				rtrecv();
    448 				sigprocmask(SIG_SETMASK, &omask, NULL);
    449 			}
    450 		}
    451 	}
    452 }
    453 
    454 static void
    455 sighandler(int signo)
    456 {
    457 
    458 	switch (signo) {
    459 	case SIGALRM:
    460 		seenalrm++;
    461 		break;
    462 	case SIGQUIT:
    463 	case SIGTERM:
    464 		seenquit++;
    465 		break;
    466 	case SIGUSR1:
    467 	case SIGHUP:
    468 	case SIGINT:
    469 		seenusr1++;
    470 		break;
    471 	}
    472 }
    473 
    474 /*
    475  * gracefully exits after resetting sockopts.
    476  */
    477 /* ARGSUSED */
    478 static void
    479 rtdexit(void)
    480 {
    481 	struct riprt *rrt;
    482 
    483 	alarm(0);
    484 	for (rrt = riprt; rrt; rrt = rrt->rrt_next) {
    485 		if (rrt->rrt_rflags & RRTF_AGGREGATE) {
    486 			delroute(&rrt->rrt_info, &rrt->rrt_gw);
    487 		}
    488 	}
    489 	close(ripsock);
    490 	close(rtsock);
    491 	syslog(LOG_INFO, "**** Terminated ****");
    492 	closelog();
    493 	exit(1);
    494 }
    495 
    496 /*
    497  * Called periodically:
    498  *	1. age out the learned route. remove it if necessary.
    499  *	2. submit RIP6_RESPONSE packets.
    500  * Invoked in every SUPPLY_INTERVAL6 (30) seconds.  I believe we don't have
    501  * to invoke this function in every 1 or 5 or 10 seconds only to age the
    502  * routes more precisely.
    503  */
    504 /* ARGSUSED */
    505 static void
    506 ripalarm(void)
    507 {
    508 	struct ifc *ifcp;
    509 	struct riprt *rrt, *rrt_prev, *rrt_next;
    510 	time_t t_lifetime, t_holddown;
    511 
    512 	/* age the RIP routes */
    513 	rrt_prev = 0;
    514 	t_lifetime = time(NULL) - RIP_LIFETIME;
    515 	t_holddown = t_lifetime - RIP_HOLDDOWN;
    516 	for (rrt = riprt; rrt; rrt = rrt_next) {
    517 		rrt_next = rrt->rrt_next;
    518 
    519 		if (rrt->rrt_t == 0) {
    520 			rrt_prev = rrt;
    521 			continue;
    522 		}
    523 		if (rrt->rrt_t < t_holddown) {
    524 			if (rrt_prev) {
    525 				rrt_prev->rrt_next = rrt->rrt_next;
    526 			} else {
    527 				riprt = rrt->rrt_next;
    528 			}
    529 			delroute(&rrt->rrt_info, &rrt->rrt_gw);
    530 			free(rrt);
    531 			continue;
    532 		}
    533 		if (rrt->rrt_t < t_lifetime)
    534 			rrt->rrt_info.rip6_metric = HOPCNT_INFINITY6;
    535 		rrt_prev = rrt;
    536 	}
    537 	/* Supply updates */
    538 	for (ifcp = ifc; ifcp; ifcp = ifcp->ifc_next) {
    539 		if (ifcp->ifc_index > 0 && (ifcp->ifc_flags & IFF_UP))
    540 			ripsend(ifcp, &ifcp->ifc_ripsin, 0);
    541 	}
    542 	alarm(ripinterval(SUPPLY_INTERVAL6));
    543 }
    544 
    545 static void
    546 init(void)
    547 {
    548 	int i, error;
    549 	const int int0 = 0, int1 = 1, int255 = 255;
    550 	struct addrinfo hints, *res;
    551 	char port[NI_MAXSERV];
    552 
    553 	ifc = NULL;
    554 	nifc = 0;
    555 	nindex2ifc = 0;	/*initial guess*/
    556 	index2ifc = NULL;
    557 	snprintf(port, sizeof(port), "%u", RIP6_PORT);
    558 
    559 	memset(&hints, 0, sizeof(hints));
    560 	hints.ai_family = PF_INET6;
    561 	hints.ai_socktype = SOCK_DGRAM;
    562 	hints.ai_flags = AI_PASSIVE;
    563 	error = getaddrinfo(NULL, port, &hints, &res);
    564 	if (error) {
    565 		fatal("%s", gai_strerror(error));
    566 	}
    567 	if (res->ai_next) {
    568 		fatal(":: resolved to multiple address");
    569 	}
    570 
    571 	ripsock = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
    572 	if (ripsock < 0) {
    573 		fatal("rip socket");
    574 	}
    575 	if (setsockopt(ripsock, IPPROTO_IPV6, IPV6_V6ONLY,
    576 	    &int1, sizeof(int1)) < 0) {
    577 		fatal("rip IPV6_V6ONLY");
    578 	}
    579 	if (bind(ripsock, res->ai_addr, res->ai_addrlen) < 0) {
    580 		fatal("rip bind");
    581 	}
    582 	if (setsockopt(ripsock, IPPROTO_IPV6, IPV6_MULTICAST_HOPS,
    583 	    &int255, sizeof(int255)) < 0) {
    584 		fatal("rip IPV6_MULTICAST_HOPS");
    585 	}
    586 	if (setsockopt(ripsock, IPPROTO_IPV6, IPV6_MULTICAST_LOOP,
    587 	    &int0, sizeof(int0)) < 0) {
    588 		fatal("rip IPV6_MULTICAST_LOOP");
    589 	}
    590 
    591 	i = 1;
    592 	if (setsockopt(ripsock, IPPROTO_IPV6, IPV6_RECVPKTINFO, &i,
    593 	    sizeof(i)) < 0) {
    594 		fatal("rip IPV6_RECVPKTINFO");
    595 	}
    596 
    597 	memset(&hints, 0, sizeof(hints));
    598 	hints.ai_family = PF_INET6;
    599 	hints.ai_socktype = SOCK_DGRAM;
    600 	error = getaddrinfo(RIP6_DEST, port, &hints, &res);
    601 	if (error) {
    602 		fatal("%s", gai_strerror(error));
    603 	}
    604 	if (res->ai_next) {
    605 		fatal("%s resolved to multiple address", RIP6_DEST);
    606 	}
    607 	memcpy(&ripsin, res->ai_addr, res->ai_addrlen);
    608 
    609 	set[0].fd = ripsock;
    610 	set[0].events = POLLIN;
    611 
    612 	if (nflag == 0) {
    613 		if ((rtsock = socket(PF_ROUTE, SOCK_RAW, 0)) < 0) {
    614 			fatal("route socket");
    615 		}
    616 		set[1].fd = rtsock;
    617 		set[1].events = POLLIN;
    618 	} else {
    619 		set[1].fd = -1;
    620 	}
    621 }
    622 
    623 #define	RIPSIZE(n) \
    624 	(sizeof(struct rip6) + ((n)-1) * sizeof(struct netinfo6))
    625 
    626 /*
    627  * ripflush flushes the rip datagram stored in the rip buffer
    628  */
    629 static int nrt;
    630 static struct netinfo6 *nip;
    631 
    632 static void
    633 ripflush(struct ifc *ifcp, struct sockaddr_in6 *sin6)
    634 {
    635 	int i;
    636 	int error;
    637 
    638 	if (ifcp)
    639 		tracet(1, "Send(%s): info(%d) to %s.%d\n",
    640 			ifcp->ifc_name, nrt,
    641 			inet6_n2p(&sin6->sin6_addr), ntohs(sin6->sin6_port));
    642 	else
    643 		tracet(1, "Send: info(%d) to %s.%d\n",
    644 			nrt, inet6_n2p(&sin6->sin6_addr), ntohs(sin6->sin6_port));
    645 	if (dflag >= 2) {
    646 		nip = ripbuf->rip6_nets;
    647 		for (i = 0; i < nrt; i++, nip++) {
    648 			if (nip->rip6_metric == NEXTHOP_METRIC) {
    649 				if (IN6_IS_ADDR_UNSPECIFIED(&nip->rip6_dest))
    650 					trace(2, "    NextHop reset");
    651 				else {
    652 					trace(2, "    NextHop %s",
    653 						inet6_n2p(&nip->rip6_dest));
    654 				}
    655 			} else {
    656 				trace(2, "    %s/%d[%d]",
    657 					inet6_n2p(&nip->rip6_dest),
    658 					nip->rip6_plen, nip->rip6_metric);
    659 			}
    660 			if (nip->rip6_tag) {
    661 				trace(2, "  tag=0x%04x",
    662 					ntohs(nip->rip6_tag) & 0xffff);
    663 			}
    664 			trace(2, "\n");
    665 		}
    666 	}
    667 	error = sendpacket(sin6, RIPSIZE(nrt));
    668 	if (error == EAFNOSUPPORT && ifcp) {
    669 		/* Protocol not supported */
    670 		tracet(1, "Could not send info to %s (%s): "
    671 			"set IFF_UP to 0\n",
    672 			ifcp->ifc_name, inet6_n2p(&ifcp->ifc_ripsin.sin6_addr));
    673 		ifcp->ifc_flags &= ~IFF_UP;	/* As if down for AF_INET6 */
    674 	}
    675 	nrt = 0; nip = ripbuf->rip6_nets;
    676 }
    677 
    678 /*
    679  * Generate RIP6_RESPONSE packets and send them.
    680  */
    681 static void
    682 ripsend(struct ifc *ifcp, struct sockaddr_in6 *sin6, int flag)
    683 {
    684 	struct riprt *rrt;
    685 	struct in6_addr *nh;	/* next hop */
    686 	int maxrte;
    687 
    688 	if (qflag)
    689 		return;
    690 
    691 	if (ifcp == NULL) {
    692 		/*
    693 		 * Request from non-link local address is not
    694 		 * a regular route6d update.
    695 		 */
    696 		maxrte = (IFMINMTU - sizeof(struct ip6_hdr) -
    697 				sizeof(struct udphdr) -
    698 				sizeof(struct rip6) + sizeof(struct netinfo6)) /
    699 				sizeof(struct netinfo6);
    700 		nrt = 0; nip = ripbuf->rip6_nets; nh = NULL;
    701 		for (rrt = riprt; rrt; rrt = rrt->rrt_next) {
    702 			if (rrt->rrt_rflags & RRTF_NOADVERTISE)
    703 				continue;
    704 			/* Put the route to the buffer */
    705 			*nip = rrt->rrt_info;
    706 			nip++; nrt++;
    707 			if (nrt == maxrte) {
    708 				ripflush(NULL, sin6);
    709 				nh = NULL;
    710 			}
    711 		}
    712 		if (nrt)	/* Send last packet */
    713 			ripflush(NULL, sin6);
    714 		return;
    715 	}
    716 
    717 	if ((flag & RRTF_SENDANYWAY) == 0 &&
    718 	    (qflag || (ifcp->ifc_flags & IFF_LOOPBACK)))
    719 		return;
    720 
    721 	/* -N: no use */
    722 	if (iff_find(ifcp, 'N') != NULL)
    723 		return;
    724 
    725 	/* -T: generate default route only */
    726 	if (iff_find(ifcp, 'T') != NULL) {
    727 		struct netinfo6 rrt_info;
    728 		memset(&rrt_info, 0, sizeof(struct netinfo6));
    729 		rrt_info.rip6_dest = in6addr_any;
    730 		rrt_info.rip6_plen = 0;
    731 		rrt_info.rip6_metric = 1;
    732 		rrt_info.rip6_metric += ifcp->ifc_metric;
    733 		rrt_info.rip6_tag = htons(routetag & 0xffff);
    734 		nip = ripbuf->rip6_nets;
    735 		*nip = rrt_info;
    736 		nrt = 1;
    737 		ripflush(ifcp, sin6);
    738 		return;
    739 	}
    740 
    741 	maxrte = (ifcp->ifc_mtu - sizeof(struct ip6_hdr) -
    742 			sizeof(struct udphdr) -
    743 			sizeof(struct rip6) + sizeof(struct netinfo6)) /
    744 			sizeof(struct netinfo6);
    745 
    746 	nrt = 0; nip = ripbuf->rip6_nets; nh = NULL;
    747 	for (rrt = riprt; rrt; rrt = rrt->rrt_next) {
    748 		if (rrt->rrt_rflags & RRTF_NOADVERTISE)
    749 			continue;
    750 
    751 		/* Need to check filter here */
    752 		if (out_filter(rrt, ifcp) == 0)
    753 			continue;
    754 
    755 		/* Check split horizon and other conditions */
    756 		if (tobeadv(rrt, ifcp) == 0)
    757 			continue;
    758 
    759 		/* Only considers the routes with flag if specified */
    760 		if ((flag & RRTF_CHANGED) &&
    761 		    (rrt->rrt_rflags & RRTF_CHANGED) == 0)
    762 			continue;
    763 
    764 		/* Check nexthop */
    765 		if (rrt->rrt_index == ifcp->ifc_index &&
    766 		    !IN6_IS_ADDR_UNSPECIFIED(&rrt->rrt_gw) &&
    767 		    (rrt->rrt_rflags & RRTF_NH_NOT_LLADDR) == 0) {
    768 			if (nh == NULL || !IN6_ARE_ADDR_EQUAL(nh, &rrt->rrt_gw)) {
    769 				if (nrt == maxrte - 2)
    770 					ripflush(ifcp, sin6);
    771 				nip->rip6_dest = rrt->rrt_gw;
    772 				if (IN6_IS_ADDR_LINKLOCAL(&nip->rip6_dest))
    773 					SET_IN6_LINKLOCAL_IFINDEX(nip->rip6_dest, 0);
    774 				nip->rip6_plen = 0;
    775 				nip->rip6_tag = 0;
    776 				nip->rip6_metric = NEXTHOP_METRIC;
    777 				nh = &rrt->rrt_gw;
    778 				nip++; nrt++;
    779 			}
    780 		} else if (nh && (rrt->rrt_index != ifcp->ifc_index ||
    781 			          !IN6_ARE_ADDR_EQUAL(nh, &rrt->rrt_gw) ||
    782 				  rrt->rrt_rflags & RRTF_NH_NOT_LLADDR)) {
    783 			/* Reset nexthop */
    784 			if (nrt == maxrte - 2)
    785 				ripflush(ifcp, sin6);
    786 			memset(nip, 0, sizeof(struct netinfo6));
    787 			nip->rip6_metric = NEXTHOP_METRIC;
    788 			nh = NULL;
    789 			nip++; nrt++;
    790 		}
    791 
    792 		/* Put the route to the buffer */
    793 		*nip = rrt->rrt_info;
    794 		nip++; nrt++;
    795 		if (nrt == maxrte) {
    796 			ripflush(ifcp, sin6);
    797 			nh = NULL;
    798 		}
    799 	}
    800 	if (nrt)	/* Send last packet */
    801 		ripflush(ifcp, sin6);
    802 }
    803 
    804 /*
    805  * outbound filter logic, per-route/interface.
    806  */
    807 static int
    808 out_filter(struct riprt *rrt, struct ifc *ifcp)
    809 {
    810 	struct iff *iffp;
    811 	struct in6_addr ia;
    812 	int ok;
    813 
    814 	/*
    815 	 * -A: filter out less specific routes, if we have aggregated
    816 	 * route configured.
    817 	 */
    818 	for (iffp = ifcp->ifc_filter; iffp; iffp = iffp->iff_next) {
    819 		if (iffp->iff_type != 'A')
    820 			continue;
    821 		if (rrt->rrt_info.rip6_plen <= iffp->iff_plen)
    822 			continue;
    823 		ia = rrt->rrt_info.rip6_dest;
    824 		applyplen(&ia, iffp->iff_plen);
    825 		if (IN6_ARE_ADDR_EQUAL(&ia, &iffp->iff_addr))
    826 			return 0;
    827 	}
    828 
    829 	/*
    830 	 * if it is an aggregated route, advertise it only to the
    831 	 * interfaces specified on -A.
    832 	 */
    833 	if ((rrt->rrt_rflags & RRTF_AGGREGATE) != 0) {
    834 		ok = 0;
    835 		for (iffp = ifcp->ifc_filter; iffp; iffp = iffp->iff_next) {
    836 			if (iffp->iff_type != 'A')
    837 				continue;
    838 			if (rrt->rrt_info.rip6_plen == iffp->iff_plen &&
    839 			    IN6_ARE_ADDR_EQUAL(&rrt->rrt_info.rip6_dest,
    840 			    &iffp->iff_addr)) {
    841 				ok = 1;
    842 				break;
    843 			}
    844 		}
    845 		if (!ok)
    846 			return 0;
    847 	}
    848 
    849 	/*
    850 	 * -O: advertise only if prefix matches the configured prefix.
    851 	 */
    852 	if (iff_find(ifcp, 'O')) {
    853 		ok = 0;
    854 		for (iffp = ifcp->ifc_filter; iffp; iffp = iffp->iff_next) {
    855 			if (iffp->iff_type != 'O')
    856 				continue;
    857 			if (rrt->rrt_info.rip6_plen < iffp->iff_plen)
    858 				continue;
    859 			ia = rrt->rrt_info.rip6_dest;
    860 			applyplen(&ia, iffp->iff_plen);
    861 			if (IN6_ARE_ADDR_EQUAL(&ia, &iffp->iff_addr)) {
    862 				ok = 1;
    863 				break;
    864 			}
    865 		}
    866 		if (!ok)
    867 			return 0;
    868 	}
    869 
    870 	/* the prefix should be advertised */
    871 	return 1;
    872 }
    873 
    874 /*
    875  * Determine if the route is to be advertised on the specified interface.
    876  * It checks options specified in the arguments and the split horizon rule.
    877  */
    878 static int
    879 tobeadv(struct riprt *rrt, struct ifc *ifcp)
    880 {
    881 
    882 	/* Special care for static routes */
    883 	if (rrt->rrt_flags & RTF_STATIC) {
    884 		/* XXX don't advertise reject/blackhole routes */
    885 		if (rrt->rrt_flags & (RTF_REJECT | RTF_BLACKHOLE))
    886 			return 0;
    887 
    888 		if (Sflag)	/* Yes, advertise it anyway */
    889 			return 1;
    890 		if (sflag && rrt->rrt_index != ifcp->ifc_index)
    891 			return 1;
    892 		return 0;
    893 	}
    894 	/* Regular split horizon */
    895 	if (hflag == 0 && rrt->rrt_index == ifcp->ifc_index)
    896 		return 0;
    897 	return 1;
    898 }
    899 
    900 /*
    901  * Send a rip packet actually.
    902  */
    903 static int
    904 sendpacket(struct sockaddr_in6 *sin6, int len)
    905 {
    906 	struct msghdr m;
    907 	struct cmsghdr *cm;
    908 	struct iovec iov[2];
    909 	u_char cmsgbuf[256];
    910 	struct in6_pktinfo *pi;
    911 	int idx;
    912 	struct sockaddr_in6 sincopy;
    913 
    914 	/* do not overwrite the given sin */
    915 	sincopy = *sin6;
    916 	sin6 = &sincopy;
    917 
    918 	if (IN6_IS_ADDR_LINKLOCAL(&sin6->sin6_addr) ||
    919 	    IN6_IS_ADDR_MULTICAST(&sin6->sin6_addr)) {
    920 		/* XXX: do not mix the interface index and link index */
    921 		idx = IN6_LINKLOCAL_IFINDEX(sin6->sin6_addr);
    922 		SET_IN6_LINKLOCAL_IFINDEX(sin6->sin6_addr, 0);
    923 		sin6->sin6_scope_id = idx;
    924 	} else
    925 		idx = 0;
    926 
    927 	m.msg_name = (caddr_t)sin6;
    928 	m.msg_namelen = sizeof(*sin6);
    929 	iov[0].iov_base = (caddr_t)ripbuf;
    930 	iov[0].iov_len = len;
    931 	m.msg_iov = iov;
    932 	m.msg_iovlen = 1;
    933 	if (!idx) {
    934 		m.msg_control = NULL;
    935 		m.msg_controllen = 0;
    936 	} else {
    937 		memset(cmsgbuf, 0, sizeof(cmsgbuf));
    938 		cm = (struct cmsghdr *)cmsgbuf;
    939 		m.msg_control = (caddr_t)cm;
    940 		m.msg_controllen = CMSG_SPACE(sizeof(struct in6_pktinfo));
    941 
    942 		cm->cmsg_len = CMSG_LEN(sizeof(struct in6_pktinfo));
    943 		cm->cmsg_level = IPPROTO_IPV6;
    944 		cm->cmsg_type = IPV6_PKTINFO;
    945 		pi = (struct in6_pktinfo *)CMSG_DATA(cm);
    946 		memset(&pi->ipi6_addr, 0, sizeof(pi->ipi6_addr)); /*::*/
    947 		pi->ipi6_ifindex = idx;
    948 	}
    949 
    950 	if (sendmsg(ripsock, &m, 0 /*MSG_DONTROUTE*/) < 0) {
    951 		trace(1, "sendmsg: %s\n", strerror(errno));
    952 		return errno;
    953 	}
    954 
    955 	return 0;
    956 }
    957 
    958 /*
    959  * Receive and process RIP packets.  Update the routes/kernel forwarding
    960  * table if necessary.
    961  */
    962 static void
    963 riprecv(void)
    964 {
    965 	struct ifc *ifcp, *ic;
    966 	struct sockaddr_in6 fsock;
    967 	struct in6_addr nh;	/* next hop */
    968 	struct rip6 *rp;
    969 	struct netinfo6 *np, *nq;
    970 	struct riprt *rrt;
    971 	ssize_t len, nn;
    972 	unsigned int need_trigger, idx;
    973 	char buf[4 * RIP6_MAXMTU];
    974 	time_t t;
    975 	struct msghdr m;
    976 	struct cmsghdr *cm;
    977 	struct iovec iov[2];
    978 	u_char cmsgbuf[256];
    979 	struct in6_pktinfo *pi;
    980 	struct iff *iffp;
    981 	struct in6_addr ia;
    982 	int ok;
    983 	time_t t_half_lifetime;
    984 
    985 	need_trigger = 0;
    986 
    987 	m.msg_name = (caddr_t)&fsock;
    988 	m.msg_namelen = sizeof(fsock);
    989 	iov[0].iov_base = (caddr_t)buf;
    990 	iov[0].iov_len = sizeof(buf);
    991 	m.msg_iov = iov;
    992 	m.msg_iovlen = 1;
    993 	cm = (struct cmsghdr *)cmsgbuf;
    994 	m.msg_control = (caddr_t)cm;
    995 	m.msg_controllen = sizeof(cmsgbuf);
    996 	if ((len = recvmsg(ripsock, &m, 0)) < 0) {
    997 		fatal("recvmsg");
    998 	}
    999 	idx = 0;
   1000 	for (cm = (struct cmsghdr *)CMSG_FIRSTHDR(&m);
   1001 	     cm;
   1002 	     cm = (struct cmsghdr *)CMSG_NXTHDR(&m, cm)) {
   1003 		if (cm->cmsg_level == IPPROTO_IPV6 &&
   1004 		    cm->cmsg_type == IPV6_PKTINFO) {
   1005 			pi = (struct in6_pktinfo *)(CMSG_DATA(cm));
   1006 			idx = pi->ipi6_ifindex;
   1007 			break;
   1008 		}
   1009 	}
   1010 	if (idx && IN6_IS_ADDR_LINKLOCAL(&fsock.sin6_addr))
   1011 		SET_IN6_LINKLOCAL_IFINDEX(fsock.sin6_addr, idx);
   1012 
   1013 	if (len < (int)sizeof(struct rip6)) {
   1014 		trace(1, "Packet too short\n");
   1015 		return;
   1016 	}
   1017 
   1018 	nh = fsock.sin6_addr;
   1019 	nn = (len - sizeof(struct rip6) + sizeof(struct netinfo6)) /
   1020 		sizeof(struct netinfo6);
   1021 	rp = (struct rip6 *)buf;
   1022 	np = rp->rip6_nets;
   1023 
   1024 	if (rp->rip6_vers != RIP6_VERSION) {
   1025 		trace(1, "Incorrect RIP version %d\n", rp->rip6_vers);
   1026 		return;
   1027 	}
   1028 	if (rp->rip6_cmd == RIP6_REQUEST) {
   1029 		if (idx && idx < (unsigned)nindex2ifc) {
   1030 			ifcp = index2ifc[idx];
   1031 			riprequest(ifcp, np, nn, &fsock);
   1032 		} else {
   1033 			riprequest(NULL, np, nn, &fsock);
   1034 		}
   1035 		return;
   1036 	}
   1037 
   1038 	if (!IN6_IS_ADDR_LINKLOCAL(&fsock.sin6_addr)) {
   1039 		trace(1, "Packets from non-ll addr: %s\n",
   1040 		    inet6_n2p(&fsock.sin6_addr));
   1041 		return;		/* Ignore packets from non-link-local addr */
   1042 	}
   1043 	idx = IN6_LINKLOCAL_IFINDEX(fsock.sin6_addr);
   1044 	ifcp = (idx < (unsigned)nindex2ifc) ? index2ifc[idx] : NULL;
   1045 	if (!ifcp) {
   1046 		trace(1, "Packets to unknown interface index %d\n", idx);
   1047 		return;		/* Ignore it */
   1048 	}
   1049 	if (IN6_ARE_ADDR_EQUAL(&ifcp->ifc_mylladdr, &fsock.sin6_addr))
   1050 		return;		/* The packet is from me; ignore */
   1051 	if (rp->rip6_cmd != RIP6_RESPONSE) {
   1052 		trace(1, "Invalid command %d\n", rp->rip6_cmd);
   1053 		return;
   1054 	}
   1055 
   1056 	/* -N: no use */
   1057 	if (iff_find(ifcp, 'N') != NULL)
   1058 		return;
   1059 
   1060 	tracet(1, "Recv(%s): from %s.%d info(%d)\n",
   1061 	    ifcp->ifc_name, inet6_n2p(&nh), ntohs(fsock.sin6_port), (int)nn);
   1062 
   1063 	t = time(NULL);
   1064 	t_half_lifetime = t - (RIP_LIFETIME/2);
   1065 	for (; nn; nn--, np++) {
   1066 		if (np->rip6_metric == NEXTHOP_METRIC) {
   1067 			/* modify neighbor address */
   1068 			if (IN6_IS_ADDR_LINKLOCAL(&np->rip6_dest)) {
   1069 				nh = np->rip6_dest;
   1070 				SET_IN6_LINKLOCAL_IFINDEX(nh, idx);
   1071 				trace(1, "\tNexthop: %s\n", inet6_n2p(&nh));
   1072 			} else if (IN6_IS_ADDR_UNSPECIFIED(&np->rip6_dest)) {
   1073 				nh = fsock.sin6_addr;
   1074 				trace(1, "\tNexthop: %s\n", inet6_n2p(&nh));
   1075 			} else {
   1076 				nh = fsock.sin6_addr;
   1077 				trace(1, "\tInvalid Nexthop: %s\n",
   1078 				    inet6_n2p(&np->rip6_dest));
   1079 			}
   1080 			continue;
   1081 		}
   1082 		if (IN6_IS_ADDR_MULTICAST(&np->rip6_dest)) {
   1083 			trace(1, "\tMulticast netinfo6: %s/%d [%d]\n",
   1084 				inet6_n2p(&np->rip6_dest),
   1085 				np->rip6_plen, np->rip6_metric);
   1086 			continue;
   1087 		}
   1088 		if (IN6_IS_ADDR_LOOPBACK(&np->rip6_dest)) {
   1089 			trace(1, "\tLoopback netinfo6: %s/%d [%d]\n",
   1090 				inet6_n2p(&np->rip6_dest),
   1091 				np->rip6_plen, np->rip6_metric);
   1092 			continue;
   1093 		}
   1094 		if (IN6_IS_ADDR_LINKLOCAL(&np->rip6_dest)) {
   1095 			trace(1, "\tLink Local netinfo6: %s/%d [%d]\n",
   1096 				inet6_n2p(&np->rip6_dest),
   1097 				np->rip6_plen, np->rip6_metric);
   1098 			continue;
   1099 		}
   1100 		/* may need to pass sitelocal prefix in some case, however*/
   1101 		if (IN6_IS_ADDR_SITELOCAL(&np->rip6_dest) && !lflag) {
   1102 			trace(1, "\tSite Local netinfo6: %s/%d [%d]\n",
   1103 				inet6_n2p(&np->rip6_dest),
   1104 				np->rip6_plen, np->rip6_metric);
   1105 			continue;
   1106 		}
   1107 		trace(2, "\tnetinfo6: %s/%d [%d]",
   1108 			inet6_n2p(&np->rip6_dest),
   1109 			np->rip6_plen, np->rip6_metric);
   1110 		if (np->rip6_tag)
   1111 			trace(2, "  tag=0x%04x", ntohs(np->rip6_tag) & 0xffff);
   1112 		if (dflag >= 2) {
   1113 			ia = np->rip6_dest;
   1114 			applyplen(&ia, np->rip6_plen);
   1115 			if (!IN6_ARE_ADDR_EQUAL(&ia, &np->rip6_dest))
   1116 				trace(2, " [junk outside prefix]");
   1117 		}
   1118 
   1119 		/*
   1120 		 * -L: listen only if the prefix matches the configuration
   1121 		 */
   1122 		ok = 1;		/* if there's no L filter, it is ok */
   1123 		for (iffp = ifcp->ifc_filter; iffp; iffp = iffp->iff_next) {
   1124 			if (iffp->iff_type != 'L')
   1125 				continue;
   1126 			ok = 0;
   1127 			if (np->rip6_plen < iffp->iff_plen)
   1128 				continue;
   1129 			/* special rule: ::/0 means default, not "in /0" */
   1130 			if (iffp->iff_plen == 0 && np->rip6_plen > 0)
   1131 				continue;
   1132 			ia = np->rip6_dest;
   1133 			applyplen(&ia, iffp->iff_plen);
   1134 			if (IN6_ARE_ADDR_EQUAL(&ia, &iffp->iff_addr)) {
   1135 				ok = 1;
   1136 				break;
   1137 			}
   1138 		}
   1139 		if (!ok) {
   1140 			trace(2, "  (filtered)\n");
   1141 			continue;
   1142 		}
   1143 
   1144 		trace(2, "\n");
   1145 		np->rip6_metric++;
   1146 		np->rip6_metric += ifcp->ifc_metric;
   1147 		if (np->rip6_metric > HOPCNT_INFINITY6)
   1148 			np->rip6_metric = HOPCNT_INFINITY6;
   1149 
   1150 		applyplen(&np->rip6_dest, np->rip6_plen);
   1151 		if ((rrt = rtsearch(np, NULL)) != NULL) {
   1152 			if (rrt->rrt_t == 0)
   1153 				continue;	/* Intf route has priority */
   1154 			nq = &rrt->rrt_info;
   1155 			if (nq->rip6_metric > np->rip6_metric) {
   1156 				if (rrt->rrt_index == ifcp->ifc_index &&
   1157 				    IN6_ARE_ADDR_EQUAL(&nh, &rrt->rrt_gw)) {
   1158 					/* Small metric from the same gateway */
   1159 					nq->rip6_metric = np->rip6_metric;
   1160 				} else {
   1161 					/* Better route found */
   1162 					rrt->rrt_index = ifcp->ifc_index;
   1163 					/* Update routing table */
   1164 					delroute(nq, &rrt->rrt_gw);
   1165 					rrt->rrt_gw = nh;
   1166 					*nq = *np;
   1167 					addroute(rrt, &nh, ifcp);
   1168 				}
   1169 				rrt->rrt_rflags |= RRTF_CHANGED;
   1170 				rrt->rrt_t = t;
   1171 				need_trigger = 1;
   1172 			} else if (nq->rip6_metric < np->rip6_metric &&
   1173 				   rrt->rrt_index == ifcp->ifc_index &&
   1174 				   IN6_ARE_ADDR_EQUAL(&nh, &rrt->rrt_gw)) {
   1175 				/* Got worse route from same gw */
   1176 				nq->rip6_metric = np->rip6_metric;
   1177 				rrt->rrt_t = t;
   1178 				rrt->rrt_rflags |= RRTF_CHANGED;
   1179 				need_trigger = 1;
   1180 			} else if (nq->rip6_metric == np->rip6_metric &&
   1181 				   np->rip6_metric < HOPCNT_INFINITY6) {
   1182 				if (rrt->rrt_index == ifcp->ifc_index &&
   1183 				   IN6_ARE_ADDR_EQUAL(&nh, &rrt->rrt_gw)) {
   1184 					/* same metric, same route from same gw */
   1185 					rrt->rrt_t = t;
   1186 				} else if (rrt->rrt_t < t_half_lifetime) {
   1187 					/* Better route found */
   1188 					rrt->rrt_index = ifcp->ifc_index;
   1189 					/* Update routing table */
   1190 					delroute(nq, &rrt->rrt_gw);
   1191 					rrt->rrt_gw = nh;
   1192 					*nq = *np;
   1193 					addroute(rrt, &nh, ifcp);
   1194 					rrt->rrt_rflags |= RRTF_CHANGED;
   1195 					rrt->rrt_t = t;
   1196 				}
   1197 			}
   1198 			/*
   1199 			 * if nq->rip6_metric == HOPCNT_INFINITY6 then
   1200 			 * do not update age value.  Do nothing.
   1201 			 */
   1202 		} else if (np->rip6_metric < HOPCNT_INFINITY6) {
   1203 			/* Got a new valid route */
   1204 			if ((rrt = MALLOC(struct riprt)) == NULL) {
   1205 				fatal("malloc: struct riprt");
   1206 			}
   1207 			memset(rrt, 0, sizeof(*rrt));
   1208 			nq = &rrt->rrt_info;
   1209 
   1210 			rrt->rrt_same = NULL;
   1211 			rrt->rrt_index = ifcp->ifc_index;
   1212 			rrt->rrt_flags = RTF_UP|RTF_GATEWAY;
   1213 			rrt->rrt_gw = nh;
   1214 			*nq = *np;
   1215 			applyplen(&nq->rip6_dest, nq->rip6_plen);
   1216 			if (nq->rip6_plen == sizeof(struct in6_addr) * 8)
   1217 				rrt->rrt_flags |= RTF_HOST;
   1218 
   1219 			/* Put the route to the list */
   1220 			rrt->rrt_next = riprt;
   1221 			riprt = rrt;
   1222 			/* Update routing table */
   1223 			addroute(rrt, &nh, ifcp);
   1224 			rrt->rrt_rflags |= RRTF_CHANGED;
   1225 			need_trigger = 1;
   1226 			rrt->rrt_t = t;
   1227 		}
   1228 	}
   1229 	/* XXX need to care the interval between triggered updates */
   1230 	if (need_trigger) {
   1231 		if (nextalarm > time(NULL) + RIP_TRIG_INT6_MAX) {
   1232 			for (ic = ifc; ic; ic = ic->ifc_next) {
   1233 				if (ifcp->ifc_index == ic->ifc_index)
   1234 					continue;
   1235 				if (ic->ifc_flags & IFF_UP)
   1236 					ripsend(ic, &ic->ifc_ripsin,
   1237 						RRTF_CHANGED);
   1238 			}
   1239 		}
   1240 		/* Reset the flag */
   1241 		for (rrt = riprt; rrt; rrt = rrt->rrt_next)
   1242 			rrt->rrt_rflags &= ~RRTF_CHANGED;
   1243 	}
   1244 }
   1245 
   1246 /*
   1247  * Send all routes request packet to the specified interface.
   1248  */
   1249 static void
   1250 sendrequest(struct ifc *ifcp)
   1251 {
   1252 	struct netinfo6 *np;
   1253 	int error;
   1254 
   1255 	if (ifcp->ifc_flags & IFF_LOOPBACK)
   1256 		return;
   1257 	ripbuf->rip6_cmd = RIP6_REQUEST;
   1258 	np = ripbuf->rip6_nets;
   1259 	memset(np, 0, sizeof(struct netinfo6));
   1260 	np->rip6_metric = HOPCNT_INFINITY6;
   1261 	tracet(1, "Send rtdump Request to %s (%s)\n",
   1262 		ifcp->ifc_name, inet6_n2p(&ifcp->ifc_ripsin.sin6_addr));
   1263 	error = sendpacket(&ifcp->ifc_ripsin, RIPSIZE(1));
   1264 	if (error == EAFNOSUPPORT) {
   1265 		/* Protocol not supported */
   1266 		tracet(1, "Could not send rtdump Request to %s (%s): "
   1267 			"set IFF_UP to 0\n",
   1268 			ifcp->ifc_name, inet6_n2p(&ifcp->ifc_ripsin.sin6_addr));
   1269 		ifcp->ifc_flags &= ~IFF_UP;	/* As if down for AF_INET6 */
   1270 	}
   1271 	ripbuf->rip6_cmd = RIP6_RESPONSE;
   1272 }
   1273 
   1274 /*
   1275  * Process a RIP6_REQUEST packet.
   1276  */
   1277 static void
   1278 riprequest(struct ifc *ifcp, struct netinfo6 *np, int nn,
   1279 	   struct sockaddr_in6 *sin6)
   1280 {
   1281 	int i;
   1282 	struct riprt *rrt;
   1283 
   1284 	if (!(nn == 1 && IN6_IS_ADDR_UNSPECIFIED(&np->rip6_dest) &&
   1285 	      np->rip6_plen == 0 && np->rip6_metric == HOPCNT_INFINITY6)) {
   1286 		/* Specific response, don't split-horizon */
   1287 		trace(1, "\tRIP Request\n");
   1288 		for (i = 0; i < nn; i++, np++) {
   1289 			rrt = rtsearch(np, NULL);
   1290 			if (rrt)
   1291 				np->rip6_metric = rrt->rrt_info.rip6_metric;
   1292 			else
   1293 				np->rip6_metric = HOPCNT_INFINITY6;
   1294 		}
   1295 		(void)sendpacket(sin6, RIPSIZE(nn));
   1296 		return;
   1297 	}
   1298 	/* Whole routing table dump */
   1299 	trace(1, "\tRIP Request -- whole routing table\n");
   1300 	ripsend(ifcp, sin6, RRTF_SENDANYWAY);
   1301 }
   1302 
   1303 /*
   1304  * Get information of each interface.
   1305  */
   1306 static void
   1307 ifconfig(void)
   1308 {
   1309 	struct ifaddrs *ifap, *ifa;
   1310 	struct ifc *ifcp;
   1311 	struct ipv6_mreq mreq;
   1312 	int s;
   1313 
   1314 	if ((s = socket(AF_INET6, SOCK_DGRAM, 0)) < 0) {
   1315 		fatal("socket");
   1316 	}
   1317 
   1318 	if (getifaddrs(&ifap) != 0) {
   1319 		fatal("getifaddrs");
   1320 	}
   1321 
   1322 	for (ifa = ifap; ifa; ifa = ifa->ifa_next) {
   1323 		if (ifa->ifa_addr->sa_family != AF_INET6)
   1324 			continue;
   1325 		ifcp = ifc_find(ifa->ifa_name);
   1326 		/* we are interested in multicast-capable interfaces */
   1327 		if ((ifa->ifa_flags & IFF_MULTICAST) == 0)
   1328 			continue;
   1329 		if (!ifcp) {
   1330 			/* new interface */
   1331 			if ((ifcp = MALLOC(struct ifc)) == NULL) {
   1332 				fatal("malloc: struct ifc");
   1333 			}
   1334 			memset(ifcp, 0, sizeof(*ifcp));
   1335 			ifcp->ifc_index = -1;
   1336 			ifcp->ifc_next = ifc;
   1337 			ifc = ifcp;
   1338 			nifc++;
   1339 			ifcp->ifc_name = xstrdup(ifa->ifa_name);
   1340 			ifcp->ifc_addr = 0;
   1341 			ifcp->ifc_filter = 0;
   1342 			ifcp->ifc_flags = ifa->ifa_flags;
   1343 			trace(1, "newif %s <%s>\n", ifcp->ifc_name,
   1344 				ifflags(ifcp->ifc_flags));
   1345 			if (!strcmp(ifcp->ifc_name, LOOPBACK_IF))
   1346 				loopifcp = ifcp;
   1347 		} else {
   1348 			/* update flag, this may be up again */
   1349 			if (ifcp->ifc_flags != ifa->ifa_flags) {
   1350 				trace(1, "%s: <%s> -> ", ifcp->ifc_name,
   1351 					ifflags(ifcp->ifc_flags));
   1352 				trace(1, "<%s>\n", ifflags(ifa->ifa_flags));
   1353 				ifcp->ifc_cflags |= IFC_CHANGED;
   1354 			}
   1355 			ifcp->ifc_flags = ifa->ifa_flags;
   1356 		}
   1357 		ifconfig1(ifa->ifa_name, ifa->ifa_addr, ifcp, s);
   1358 		if ((ifcp->ifc_flags & (IFF_LOOPBACK | IFF_UP)) == IFF_UP
   1359 		 && 0 < ifcp->ifc_index && !ifcp->ifc_joined) {
   1360 			mreq.ipv6mr_multiaddr = ifcp->ifc_ripsin.sin6_addr;
   1361 			mreq.ipv6mr_interface = ifcp->ifc_index;
   1362 			if (setsockopt(ripsock, IPPROTO_IPV6, IPV6_JOIN_GROUP,
   1363 			    &mreq, sizeof(mreq)) < 0) {
   1364 				fatal("IPV6_JOIN_GROUP");
   1365 			}
   1366 			trace(1, "join %s %s\n", ifcp->ifc_name, RIP6_DEST);
   1367 			ifcp->ifc_joined++;
   1368 		}
   1369 	}
   1370 	close(s);
   1371 	freeifaddrs(ifap);
   1372 }
   1373 
   1374 static void
   1375 ifconfig1(const char *name, const struct sockaddr *sa, struct ifc *ifcp, int s)
   1376 {
   1377 	struct in6_ifreq ifr;
   1378 	const struct sockaddr_in6 *sin6;
   1379 	struct ifac *ifa;
   1380 	int plen;
   1381 	char buf[BUFSIZ];
   1382 
   1383 	sin6 = (const struct sockaddr_in6 *)sa;
   1384 	if (IN6_IS_ADDR_SITELOCAL(&sin6->sin6_addr) && !lflag)
   1385 		return;
   1386 	ifr.ifr_addr = *sin6;
   1387 	strncpy(ifr.ifr_name, name, sizeof(ifr.ifr_name));
   1388 	if (ioctl(s, SIOCGIFNETMASK_IN6, (char *)&ifr) < 0) {
   1389 		fatal("ioctl: SIOCGIFNETMASK_IN6");
   1390 	}
   1391 	plen = sin6mask2len(&ifr.ifr_addr);
   1392 	if ((ifa = ifa_match(ifcp, &sin6->sin6_addr, plen)) != NULL) {
   1393 		/* same interface found */
   1394 		/* need check if something changed */
   1395 		/* XXX not yet implemented */
   1396 		return;
   1397 	}
   1398 	/*
   1399 	 * New address is found
   1400 	 */
   1401 	if ((ifa = MALLOC(struct ifac)) == NULL) {
   1402 		fatal("malloc: struct ifac");
   1403 	}
   1404 	memset(ifa, 0, sizeof(*ifa));
   1405 	ifa->ifa_conf = ifcp;
   1406 	ifa->ifa_next = ifcp->ifc_addr;
   1407 	ifcp->ifc_addr = ifa;
   1408 	ifa->ifa_addr = sin6->sin6_addr;
   1409 	ifa->ifa_plen = plen;
   1410 	if (ifcp->ifc_flags & IFF_POINTOPOINT) {
   1411 		ifr.ifr_addr = *sin6;
   1412 		if (ioctl(s, SIOCGIFDSTADDR_IN6, (char *)&ifr) < 0) {
   1413 			fatal("ioctl: SIOCGIFDSTADDR_IN6");
   1414 		}
   1415 		ifa->ifa_raddr = ifr.ifr_dstaddr.sin6_addr;
   1416 		inet_ntop(AF_INET6, (void *)&ifa->ifa_raddr, buf, sizeof(buf));
   1417 		trace(1, "found address %s/%d -- %s\n",
   1418 			inet6_n2p(&ifa->ifa_addr), ifa->ifa_plen, buf);
   1419 	} else {
   1420 		trace(1, "found address %s/%d\n",
   1421 			inet6_n2p(&ifa->ifa_addr), ifa->ifa_plen);
   1422 	}
   1423 	if (ifcp->ifc_index < 0 && IN6_IS_ADDR_LINKLOCAL(&ifa->ifa_addr)) {
   1424 		ifcp->ifc_mylladdr = ifa->ifa_addr;
   1425 		ifcp->ifc_index = IN6_LINKLOCAL_IFINDEX(ifa->ifa_addr);
   1426 		memcpy(&ifcp->ifc_ripsin, &ripsin, ripsin.ss_len);
   1427 		SET_IN6_LINKLOCAL_IFINDEX(ifcp->ifc_ripsin.sin6_addr,
   1428 			ifcp->ifc_index);
   1429 		setindex2ifc(ifcp->ifc_index, ifcp);
   1430 		ifcp->ifc_mtu = getifmtu(ifcp->ifc_index);
   1431 		if (ifcp->ifc_mtu > RIP6_MAXMTU)
   1432 			ifcp->ifc_mtu = RIP6_MAXMTU;
   1433 		if (ioctl(s, SIOCGIFMETRIC, (char *)&ifr) < 0) {
   1434 			fatal("ioctl: SIOCGIFMETRIC");
   1435 		}
   1436 		ifcp->ifc_metric = ifr.ifr_metric;
   1437 		trace(1, "\tindex: %d, mtu: %d, metric: %d\n",
   1438 			ifcp->ifc_index, ifcp->ifc_mtu, ifcp->ifc_metric);
   1439 	} else
   1440 		ifcp->ifc_cflags |= IFC_CHANGED;
   1441 }
   1442 
   1443 /*
   1444  * Receive and process routing messages.
   1445  * Update interface information as necessary.
   1446  */
   1447 static void
   1448 rtrecv(void)
   1449 {
   1450 	char buf[BUFSIZ];
   1451 	char *p, *q;
   1452 	struct rt_msghdr *rtm;
   1453 	struct ifa_msghdr *ifam;
   1454 	struct if_msghdr *ifm;
   1455 	int len;
   1456 	struct ifc *ifcp, *ic;
   1457 	int iface = 0, rtable = 0;
   1458 	struct sockaddr_in6 *rta[RTAX_MAX];
   1459 	struct sockaddr_in6 mask;
   1460 	int i, addrs;
   1461 	struct riprt *rrt;
   1462 
   1463 	if ((len = read(rtsock, buf, sizeof(buf))) < 0) {
   1464 		perror("read from rtsock");
   1465 		exit(1);
   1466 	}
   1467 	if (len < (int)sizeof(*rtm)) {
   1468 		trace(1, "short read from rtsock: %d (should be > %lu)\n",
   1469 			len, (u_long)sizeof(*rtm));
   1470 		return;
   1471 	}
   1472 	if (dflag >= 2) {
   1473 		fprintf(stderr, "rtmsg:\n");
   1474 		for (i = 0; i < len; i++) {
   1475 			fprintf(stderr, "%02x ", buf[i] & 0xff);
   1476 			if (i % 16 == 15) fprintf(stderr, "\n");
   1477 		}
   1478 		fprintf(stderr, "\n");
   1479 	}
   1480 
   1481 	for (p = buf; p - buf < len; p += ((struct rt_msghdr *)p)->rtm_msglen) {
   1482 		/* safety against bogus message */
   1483 		if (((struct rt_msghdr *)p)->rtm_msglen <= 0) {
   1484 			trace(1, "bogus rtmsg: length=%d\n",
   1485 				((struct rt_msghdr *)p)->rtm_msglen);
   1486 			break;
   1487 		}
   1488 		rtm = NULL;
   1489 		ifam = NULL;
   1490 		ifm = NULL;
   1491 		switch (((struct rt_msghdr *)p)->rtm_type) {
   1492 		case RTM_NEWADDR:
   1493 		case RTM_DELADDR:
   1494 			ifam = (struct ifa_msghdr *)p;
   1495 			addrs = ifam->ifam_addrs;
   1496 			q = (char *)(ifam + 1);
   1497 			break;
   1498 		case RTM_IFINFO:
   1499 			ifm = (struct if_msghdr *)p;
   1500 			addrs = ifm->ifm_addrs;
   1501 			q = (char *)(ifm + 1);
   1502 			break;
   1503 		default:
   1504 			rtm = (struct rt_msghdr *)p;
   1505 			addrs = rtm->rtm_addrs;
   1506 			q = (char *)(rtm + 1);
   1507 			if (rtm->rtm_version != RTM_VERSION) {
   1508 				trace(1, "unexpected rtmsg version %d "
   1509 					"(should be %d)\n",
   1510 					rtm->rtm_version, RTM_VERSION);
   1511 				continue;
   1512 			}
   1513 			if (rtm->rtm_pid == pid) {
   1514 #if 0
   1515 				trace(1, "rtmsg looped back to me, ignored\n");
   1516 #endif
   1517 				continue;
   1518 			}
   1519 			break;
   1520 		}
   1521 		memset(&rta, 0, sizeof(rta));
   1522 		for (i = 0; i < RTAX_MAX; i++) {
   1523 			if (addrs & (1 << i)) {
   1524 				rta[i] = (struct sockaddr_in6 *)q;
   1525 				q += ROUNDUP(rta[i]->sin6_len);
   1526 			}
   1527 		}
   1528 
   1529 		trace(1, "rtsock: %s (addrs=%x)\n",
   1530 			rttypes((struct rt_msghdr *)p), addrs);
   1531 		if (dflag >= 2) {
   1532 			for (i = 0;
   1533 			     i < ((struct rt_msghdr *)p)->rtm_msglen;
   1534 			     i++) {
   1535 				fprintf(stderr, "%02x ", p[i] & 0xff);
   1536 				if (i % 16 == 15) fprintf(stderr, "\n");
   1537 			}
   1538 			fprintf(stderr, "\n");
   1539 		}
   1540 
   1541 		/*
   1542 		 * Easy ones first.
   1543 		 *
   1544 		 * We may be able to optimize by using ifm->ifm_index or
   1545 		 * ifam->ifam_index.  For simplicity we don't do that here.
   1546 		 */
   1547 		switch (((struct rt_msghdr *)p)->rtm_type) {
   1548 		case RTM_NEWADDR:
   1549 		case RTM_IFINFO:
   1550 			iface++;
   1551 			continue;
   1552 		case RTM_ADD:
   1553 			rtable++;
   1554 			continue;
   1555 		case RTM_LOSING:
   1556 		case RTM_MISS:
   1557 		case RTM_GET:
   1558 		case RTM_LOCK:
   1559 			/* nothing to be done here */
   1560 			trace(1, "\tnothing to be done, ignored\n");
   1561 			continue;
   1562 		}
   1563 
   1564 #if 0
   1565 		if (rta[RTAX_DST] == NULL) {
   1566 			trace(1, "\tno destination, ignored\n");
   1567 			continue;
   1568 		}
   1569 		if (rta[RTAX_DST]->sin6_family != AF_INET6) {
   1570 			trace(1, "\taf mismatch, ignored\n");
   1571 			continue;
   1572 		}
   1573 		if (IN6_IS_ADDR_LINKLOCAL(&rta[RTAX_DST]->sin6_addr)) {
   1574 			trace(1, "\tlinklocal destination, ignored\n");
   1575 			continue;
   1576 		}
   1577 		if (IN6_ARE_ADDR_EQUAL(&rta[RTAX_DST]->sin6_addr, &in6addr_loopback)) {
   1578 			trace(1, "\tloopback destination, ignored\n");
   1579 			continue;		/* Loopback */
   1580 		}
   1581 		if (IN6_IS_ADDR_MULTICAST(&rta[RTAX_DST]->sin6_addr)) {
   1582 			trace(1, "\tmulticast destination, ignored\n");
   1583 			continue;
   1584 		}
   1585 #endif
   1586 
   1587 		/* hard ones */
   1588 		switch (((struct rt_msghdr *)p)->rtm_type) {
   1589 		case RTM_NEWADDR:
   1590 		case RTM_IFINFO:
   1591 		case RTM_ADD:
   1592 		case RTM_LOSING:
   1593 		case RTM_MISS:
   1594 		case RTM_GET:
   1595 		case RTM_LOCK:
   1596 			/* should already be handled */
   1597 			fatal("rtrecv: never reach here");
   1598 			/* NOTREACHED */
   1599 		case RTM_DELETE:
   1600 			if (!rta[RTAX_DST] || !rta[RTAX_GATEWAY]) {
   1601 				trace(1, "\tsome of dst/gw/netamsk are "
   1602 				    "unavailable, ignored\n");
   1603 				break;
   1604 			}
   1605 			if ((rtm->rtm_flags & RTF_HOST) != 0) {
   1606 				mask.sin6_len = sizeof(mask);
   1607 				memset(&mask.sin6_addr, 0xff,
   1608 				    sizeof(mask.sin6_addr));
   1609 				rta[RTAX_NETMASK] = &mask;
   1610 			} else if (!rta[RTAX_NETMASK]) {
   1611 				trace(1, "\tsome of dst/gw/netamsk are "
   1612 				    "unavailable, ignored\n");
   1613 				break;
   1614 			}
   1615 			if (rt_del(rta[RTAX_DST], rta[RTAX_GATEWAY],
   1616 			    rta[RTAX_NETMASK]) == 0) {
   1617 				rtable++;	/*just to be sure*/
   1618 			}
   1619 			break;
   1620 		case RTM_CHANGE:
   1621 		case RTM_REDIRECT:
   1622 			trace(1, "\tnot supported yet, ignored\n");
   1623 			break;
   1624 		case RTM_DELADDR:
   1625 			if (!rta[RTAX_NETMASK] || !rta[RTAX_IFA]) {
   1626 				trace(1, "\tno netmask or ifa given, ignored\n");
   1627 				break;
   1628 			}
   1629 			if (ifam->ifam_index < nindex2ifc)
   1630 				ifcp = index2ifc[ifam->ifam_index];
   1631 			else
   1632 				ifcp = NULL;
   1633 			if (!ifcp) {
   1634 				trace(1, "\tinvalid ifam_index %d, ignored\n",
   1635 					ifam->ifam_index);
   1636 				break;
   1637 			}
   1638 			if (!rt_deladdr(ifcp, rta[RTAX_IFA], rta[RTAX_NETMASK]))
   1639 				iface++;
   1640 			break;
   1641 		case RTM_OLDADD:
   1642 		case RTM_OLDDEL:
   1643 			trace(1, "\tnot supported yet, ignored\n");
   1644 			break;
   1645 		}
   1646 
   1647 	}
   1648 
   1649 	if (iface) {
   1650 		trace(1, "rtsock: reconfigure interfaces, refresh interface routes\n");
   1651 		ifconfig();
   1652 		for (ifcp = ifc; ifcp; ifcp = ifcp->ifc_next)
   1653 			if (ifcp->ifc_cflags & IFC_CHANGED) {
   1654 				if (ifrt(ifcp, 1)) {
   1655 					for (ic = ifc; ic; ic = ic->ifc_next) {
   1656 						if (ifcp->ifc_index == ic->ifc_index)
   1657 							continue;
   1658 						if (ic->ifc_flags & IFF_UP)
   1659 							ripsend(ic, &ic->ifc_ripsin,
   1660 							RRTF_CHANGED);
   1661 					}
   1662 					/* Reset the flag */
   1663 					for (rrt = riprt; rrt; rrt = rrt->rrt_next)
   1664 						rrt->rrt_rflags &= ~RRTF_CHANGED;
   1665 				}
   1666 				ifcp->ifc_cflags &= ~IFC_CHANGED;
   1667 			}
   1668 	}
   1669 	if (rtable) {
   1670 		trace(1, "rtsock: read routing table again\n");
   1671 		krtread(1);
   1672 	}
   1673 }
   1674 
   1675 /*
   1676  * remove specified route from the internal routing table.
   1677  */
   1678 static int
   1679 rt_del(const struct sockaddr_in6 *sdst, const struct sockaddr_in6 *sgw,
   1680        const struct sockaddr_in6 *smask)
   1681 {
   1682 	const struct in6_addr *dst = NULL;
   1683 	const struct in6_addr *gw = NULL;
   1684 	int prefix;
   1685 	struct netinfo6 ni6;
   1686 	struct riprt *rrt = NULL;
   1687 	time_t t_lifetime;
   1688 
   1689 	if (sdst->sin6_family != AF_INET6) {
   1690 		trace(1, "\tother AF, ignored\n");
   1691 		return -1;
   1692 	}
   1693 	if (IN6_IS_ADDR_LINKLOCAL(&sdst->sin6_addr)
   1694 	 || IN6_ARE_ADDR_EQUAL(&sdst->sin6_addr, &in6addr_loopback)
   1695 	 || IN6_IS_ADDR_MULTICAST(&sdst->sin6_addr)) {
   1696 		trace(1, "\taddress %s not interesting, ignored\n",
   1697 			inet6_n2p(&sdst->sin6_addr));
   1698 		return -1;
   1699 	}
   1700 	dst = &sdst->sin6_addr;
   1701 	if (sgw->sin6_family == AF_INET6) {
   1702 		/* easy case */
   1703 		gw = &sgw->sin6_addr;
   1704 		prefix = sin6mask2len(smask);
   1705 	} else if (sgw->sin6_family == AF_LINK) {
   1706 		/*
   1707 		 * Interface route... a hard case.  We need to get the prefix
   1708 		 * length from the kernel, but we now are parsing rtmsg.
   1709 		 * We'll purge matching routes from my list, then get the
   1710 		 * fresh list.
   1711 		 */
   1712 		struct riprt *longest;
   1713 		trace(1, "\t%s is an interface route, guessing prefixlen\n",
   1714 			inet6_n2p(dst));
   1715 		longest = NULL;
   1716 		for (rrt = riprt; rrt; rrt = rrt->rrt_next) {
   1717 			if (IN6_ARE_ADDR_EQUAL(&rrt->rrt_info.rip6_dest,
   1718 					&sdst->sin6_addr)
   1719 			 && IN6_IS_ADDR_LOOPBACK(&rrt->rrt_gw)) {
   1720 				if (!longest
   1721 				 || longest->rrt_info.rip6_plen <
   1722 						 rrt->rrt_info.rip6_plen) {
   1723 					longest = rrt;
   1724 				}
   1725 			}
   1726 		}
   1727 		rrt = longest;
   1728 		if (!rrt) {
   1729 			trace(1, "\tno matching interface route found\n");
   1730 			return -1;
   1731 		}
   1732 		gw = &in6addr_loopback;
   1733 		prefix = rrt->rrt_info.rip6_plen;
   1734 	} else {
   1735 		trace(1, "\tunsupported af: (gw=%d)\n", sgw->sin6_family);
   1736 		return -1;
   1737 	}
   1738 
   1739 	trace(1, "\tdeleting %s/%d ", inet6_n2p(dst), prefix);
   1740 	trace(1, "gw %s\n", inet6_n2p(gw));
   1741 	t_lifetime = time(NULL) - RIP_LIFETIME;
   1742 	/* age route for interface address */
   1743 	memset(&ni6, 0, sizeof(ni6));
   1744 	ni6.rip6_dest = *dst;
   1745 	ni6.rip6_plen = prefix;
   1746 	applyplen(&ni6.rip6_dest, ni6.rip6_plen);	/*to be sure*/
   1747 	trace(1, "\tfind route %s/%d\n", inet6_n2p(&ni6.rip6_dest),
   1748 		ni6.rip6_plen);
   1749 	if (!rrt && (rrt = rtsearch(&ni6, NULL)) == NULL) {
   1750 		trace(1, "\tno route found\n");
   1751 		return -1;
   1752 	}
   1753 #if 0
   1754 	if ((rrt->rrt_flags & RTF_STATIC) == 0) {
   1755 		trace(1, "\tyou can delete static routes only\n");
   1756 	} else
   1757 #endif
   1758 	if (!IN6_ARE_ADDR_EQUAL(&rrt->rrt_gw, gw)) {
   1759 		trace(1, "\tgw mismatch: %s <-> ",
   1760 			inet6_n2p(&rrt->rrt_gw));
   1761 		trace(1, "%s\n", inet6_n2p(gw));
   1762 	} else {
   1763 		trace(1, "\troute found, age it\n");
   1764 		if (rrt->rrt_t == 0 || rrt->rrt_t > t_lifetime) {
   1765 			rrt->rrt_t = t_lifetime;
   1766 			rrt->rrt_info.rip6_metric = HOPCNT_INFINITY6;
   1767 		}
   1768 	}
   1769 	return 0;
   1770 }
   1771 
   1772 /*
   1773  * remove specified address from internal interface/routing table.
   1774  */
   1775 static int
   1776 rt_deladdr(struct ifc *ifcp, const struct sockaddr_in6 *sifa,
   1777 	   const struct sockaddr_in6 *smask)
   1778 {
   1779 	const struct in6_addr *addr = NULL;
   1780 	int prefix;
   1781 	struct ifac *ifa = NULL;
   1782 	struct netinfo6 ni6;
   1783 	struct riprt *rrt = NULL;
   1784 	time_t t_lifetime;
   1785 	int updated = 0;
   1786 
   1787 	if (sifa->sin6_family != AF_INET6) {
   1788 		trace(1, "\tother AF, ignored\n");
   1789 		return -1;
   1790 	}
   1791 	addr = &sifa->sin6_addr;
   1792 	prefix = sin6mask2len(smask);
   1793 
   1794 	trace(1, "\tdeleting %s/%d from %s\n",
   1795 		inet6_n2p(addr), prefix, ifcp->ifc_name);
   1796 	ifa = ifa_match(ifcp, addr, prefix);
   1797 	if (!ifa) {
   1798 		trace(1, "\tno matching ifa found for %s/%d on %s\n",
   1799 			inet6_n2p(addr), prefix, ifcp->ifc_name);
   1800 		return -1;
   1801 	}
   1802 	if (ifa->ifa_conf != ifcp) {
   1803 		trace(1, "\taddress table corrupt: back pointer does not match "
   1804 			"(%s != %s)\n",
   1805 			ifcp->ifc_name, ifa->ifa_conf->ifc_name);
   1806 		return -1;
   1807 	}
   1808 	/* remove ifa from interface */
   1809 	if (ifcp->ifc_addr == ifa)
   1810 		ifcp->ifc_addr = ifa->ifa_next;
   1811 	else {
   1812 		struct ifac *p;
   1813 		for (p = ifcp->ifc_addr; p; p = p->ifa_next) {
   1814 			if (p->ifa_next == ifa) {
   1815 				p->ifa_next = ifa->ifa_next;
   1816 				break;
   1817 			}
   1818 		}
   1819 	}
   1820 	ifa->ifa_next = NULL;
   1821 	ifa->ifa_conf = NULL;
   1822 	t_lifetime = time(NULL) - RIP_LIFETIME;
   1823 	/* age route for interface address */
   1824 	memset(&ni6, 0, sizeof(ni6));
   1825 	ni6.rip6_dest = ifa->ifa_addr;
   1826 	ni6.rip6_plen = ifa->ifa_plen;
   1827 	applyplen(&ni6.rip6_dest, ni6.rip6_plen);
   1828 	trace(1, "\tfind interface route %s/%d on %d\n",
   1829 		inet6_n2p(&ni6.rip6_dest), ni6.rip6_plen, ifcp->ifc_index);
   1830 	if ((rrt = rtsearch(&ni6, NULL)) != NULL) {
   1831 		struct in6_addr none;
   1832 		memset(&none, 0, sizeof(none));
   1833 		if (rrt->rrt_index == ifcp->ifc_index &&
   1834 		    (IN6_ARE_ADDR_EQUAL(&rrt->rrt_gw, &none) ||
   1835 		     IN6_IS_ADDR_LOOPBACK(&rrt->rrt_gw))) {
   1836 			trace(1, "\troute found, age it\n");
   1837 			if (rrt->rrt_t == 0 || rrt->rrt_t > t_lifetime) {
   1838 				rrt->rrt_t = t_lifetime;
   1839 				rrt->rrt_info.rip6_metric = HOPCNT_INFINITY6;
   1840 			}
   1841 			updated++;
   1842 		} else {
   1843 			trace(1, "\tnon-interface route found: %s/%d on %d\n",
   1844 				inet6_n2p(&rrt->rrt_info.rip6_dest),
   1845 				rrt->rrt_info.rip6_plen,
   1846 				rrt->rrt_index);
   1847 		}
   1848 	} else
   1849 		trace(1, "\tno interface route found\n");
   1850 	/* age route for p2p destination */
   1851 	if (ifcp->ifc_flags & IFF_POINTOPOINT) {
   1852 		memset(&ni6, 0, sizeof(ni6));
   1853 		ni6.rip6_dest = ifa->ifa_raddr;
   1854 		ni6.rip6_plen = 128;
   1855 		applyplen(&ni6.rip6_dest, ni6.rip6_plen);	/*to be sure*/
   1856 		trace(1, "\tfind p2p route %s/%d on %d\n",
   1857 			inet6_n2p(&ni6.rip6_dest), ni6.rip6_plen,
   1858 			ifcp->ifc_index);
   1859 		if ((rrt = rtsearch(&ni6, NULL)) != NULL) {
   1860 			if (rrt->rrt_index == ifcp->ifc_index &&
   1861 			    IN6_ARE_ADDR_EQUAL(&rrt->rrt_gw, &ifa->ifa_addr)) {
   1862 				trace(1, "\troute found, age it\n");
   1863 				if (rrt->rrt_t == 0 || rrt->rrt_t > t_lifetime) {
   1864 					rrt->rrt_t = t_lifetime;
   1865 					rrt->rrt_info.rip6_metric =
   1866 					    HOPCNT_INFINITY6;
   1867 					updated++;
   1868 				}
   1869 			} else {
   1870 				trace(1, "\tnon-p2p route found: %s/%d on %d\n",
   1871 					inet6_n2p(&rrt->rrt_info.rip6_dest),
   1872 					rrt->rrt_info.rip6_plen,
   1873 					rrt->rrt_index);
   1874 			}
   1875 		} else
   1876 			trace(1, "\tno p2p route found\n");
   1877 	}
   1878 	return updated ? 0 : -1;
   1879 }
   1880 
   1881 /*
   1882  * Get each interface address and put those interface routes to the route
   1883  * list.
   1884  */
   1885 static int
   1886 ifrt(struct ifc *ifcp, int again)
   1887 {
   1888 	struct ifac *ifa;
   1889 	struct riprt *rrt = NULL, *search_rrt, *prev_rrt, *loop_rrt;
   1890 	struct netinfo6 *np;
   1891 	time_t t_lifetime;
   1892 	int need_trigger = 0;
   1893 
   1894 #if 0
   1895 	if (ifcp->ifc_flags & IFF_LOOPBACK)
   1896 		return 0;			/* ignore loopback */
   1897 #endif
   1898 
   1899 	if (ifcp->ifc_flags & IFF_POINTOPOINT) {
   1900 		ifrt_p2p(ifcp, again);
   1901 		return 0;
   1902 	}
   1903 
   1904 	for (ifa = ifcp->ifc_addr; ifa; ifa = ifa->ifa_next) {
   1905 		if (IN6_IS_ADDR_LINKLOCAL(&ifa->ifa_addr)) {
   1906 #if 0
   1907 			trace(1, "route: %s on %s: "
   1908 			    "skip linklocal interface address\n",
   1909 			    inet6_n2p(&ifa->ifa_addr), ifcp->ifc_name);
   1910 #endif
   1911 			continue;
   1912 		}
   1913 		if (IN6_IS_ADDR_UNSPECIFIED(&ifa->ifa_addr)) {
   1914 #if 0
   1915 			trace(1, "route: %s: skip unspec interface address\n",
   1916 			    ifcp->ifc_name);
   1917 #endif
   1918 			continue;
   1919 		}
   1920 		if (IN6_IS_ADDR_LOOPBACK(&ifa->ifa_addr)) {
   1921 #if 0
   1922 			trace(1, "route: %s: skip loopback address\n",
   1923 			    ifcp->ifc_name);
   1924 #endif
   1925 			continue;
   1926 		}
   1927 		if (ifcp->ifc_flags & IFF_UP) {
   1928 			if ((rrt = MALLOC(struct riprt)) == NULL)
   1929 				fatal("malloc: struct riprt");
   1930 			memset(rrt, 0, sizeof(*rrt));
   1931 			rrt->rrt_same = NULL;
   1932 			rrt->rrt_index = ifcp->ifc_index;
   1933 			rrt->rrt_t = 0;	/* don't age */
   1934 			rrt->rrt_info.rip6_dest = ifa->ifa_addr;
   1935 			rrt->rrt_info.rip6_tag = htons(routetag & 0xffff);
   1936 			rrt->rrt_info.rip6_metric = 1 + ifcp->ifc_metric;
   1937 			rrt->rrt_info.rip6_plen = ifa->ifa_plen;
   1938 			if (ifa->ifa_plen == 128)
   1939 				rrt->rrt_flags = RTF_HOST;
   1940 			else
   1941 				rrt->rrt_flags = RTF_CONNECTED;
   1942 			rrt->rrt_rflags |= RRTF_CHANGED;
   1943 			applyplen(&rrt->rrt_info.rip6_dest, ifa->ifa_plen);
   1944 			memset(&rrt->rrt_gw, 0, sizeof(struct in6_addr));
   1945 			rrt->rrt_gw = ifa->ifa_addr;
   1946 			np = &rrt->rrt_info;
   1947 			search_rrt = rtsearch(np, &prev_rrt);
   1948 			if (search_rrt != NULL) {
   1949 				if (search_rrt->rrt_info.rip6_metric <=
   1950 				    rrt->rrt_info.rip6_metric) {
   1951 					/* Already have better route */
   1952 					if (!again) {
   1953 						trace(1, "route: %s/%d: "
   1954 						    "already registered (%s)\n",
   1955 						    inet6_n2p(&np->rip6_dest), np->rip6_plen,
   1956 						    ifcp->ifc_name);
   1957 					}
   1958 					goto next;
   1959 				}
   1960 
   1961 				if (prev_rrt)
   1962 					prev_rrt->rrt_next = rrt->rrt_next;
   1963 				else
   1964 					riprt = rrt->rrt_next;
   1965 				delroute(&rrt->rrt_info, &rrt->rrt_gw);
   1966 			}
   1967 			/* Attach the route to the list */
   1968 			trace(1, "route: %s/%d: register route (%s)\n",
   1969 			    inet6_n2p(&np->rip6_dest), np->rip6_plen,
   1970 			    ifcp->ifc_name);
   1971 			rrt->rrt_next = riprt;
   1972 			riprt = rrt;
   1973 			addroute(rrt, &rrt->rrt_gw, ifcp);
   1974 			rrt = NULL;
   1975 			sendrequest(ifcp);
   1976 			ripsend(ifcp, &ifcp->ifc_ripsin, 0);
   1977 			need_trigger = 1;
   1978 		} else {
   1979 			for (loop_rrt = riprt; loop_rrt; loop_rrt = loop_rrt->rrt_next) {
   1980 				if (loop_rrt->rrt_index == ifcp->ifc_index) {
   1981 					t_lifetime = time(NULL) - RIP_LIFETIME;
   1982 					if (loop_rrt->rrt_t == 0 || loop_rrt->rrt_t > t_lifetime) {
   1983 						loop_rrt->rrt_t = t_lifetime;
   1984 						loop_rrt->rrt_info.rip6_metric = HOPCNT_INFINITY6;
   1985 						loop_rrt->rrt_rflags |= RRTF_CHANGED;
   1986 						need_trigger = 1;
   1987 					}
   1988 				}
   1989 			}
   1990 		}
   1991 	next:
   1992 		if (rrt)
   1993 			free(rrt);
   1994 	}
   1995 	return need_trigger;
   1996 }
   1997 
   1998 /*
   1999  * there are couple of p2p interface routing models.  "behavior" lets
   2000  * you pick one.  it looks that gated behavior fits best with BSDs,
   2001  * since BSD kernels do not look at prefix length on p2p interfaces.
   2002  */
   2003 static void
   2004 ifrt_p2p(struct ifc *ifcp, int again)
   2005 {
   2006 	struct ifac *ifa;
   2007 	struct riprt *rrt, *orrt, *prevrrt;
   2008 	struct netinfo6 *np;
   2009 	struct in6_addr addr, dest;
   2010 	int advert, ignore, i;
   2011 #define P2PADVERT_NETWORK	1
   2012 #define P2PADVERT_ADDR		2
   2013 #define P2PADVERT_DEST		4
   2014 #define P2PADVERT_MAX		4
   2015 #define	CISCO	0
   2016 #define	GATED	1
   2017 #define ROUTE6D	2
   2018 #define BEHAVIOR GATED
   2019 	const char *category = "";
   2020 	const char *noadv;
   2021 
   2022 	for (ifa = ifcp->ifc_addr; ifa; ifa = ifa->ifa_next) {
   2023 		addr = ifa->ifa_addr;
   2024 		dest = ifa->ifa_raddr;
   2025 		applyplen(&addr, ifa->ifa_plen);
   2026 		applyplen(&dest, ifa->ifa_plen);
   2027 		advert = ignore = 0;
   2028 #if BEHAVIOR == CISCO
   2029 		/*
   2030 		 * honor addr/plen, just like normal shared medium
   2031 		 * interface.  this may cause trouble if you reuse
   2032 		 * addr/plen on other interfaces.
   2033 		 *
   2034 		 * advertise addr/plen.
   2035 		 */
   2036 		advert |= P2PADVERT_NETWORK;
   2037 #endif
   2038 #if BEHAVIOR == GATED
   2039 		/*
   2040 		 * prefixlen on p2p interface is meaningless.
   2041 		 * advertise addr/128 and dest/128.
   2042 		 *
   2043 		 * do not install network route to route6d routing
   2044 		 * table (if we do, it would prevent route installation
   2045 		 * for other p2p interface that shares addr/plen).
   2046 		 *
   2047 		 * XXX what should we do if dest is ::?  it will not
   2048 		 * get announced anyways (see following filter),
   2049 		 * but we need to think.
   2050 		 */
   2051 		advert |= P2PADVERT_ADDR;
   2052 		advert |= P2PADVERT_DEST;
   2053 		ignore |= P2PADVERT_NETWORK;
   2054 #endif
   2055 #if BEHAVIOR == ROUTE6D
   2056 		/*
   2057 		 * just for testing.  actually the code is redundant
   2058 		 * given the current p2p interface address assignment
   2059 		 * rule for kame kernel.
   2060 		 *
   2061 		 * intent:
   2062 		 *	A/n -> announce A/n
   2063 		 *	A B/n, A and B share prefix -> A/n (= B/n)
   2064 		 *	A B/n, do not share prefix -> A/128 and B/128
   2065 		 * actually, A/64 and A B/128 are the only cases
   2066 		 * permitted by the kernel:
   2067 		 *	A/64 -> A/64
   2068 		 *	A B/128 -> A/128 and B/128
   2069 		 */
   2070 		if (!IN6_IS_ADDR_UNSPECIFIED(&ifa->ifa_raddr)) {
   2071 			if (IN6_ARE_ADDR_EQUAL(&addr, &dest))
   2072 				advert |= P2PADVERT_NETWORK;
   2073 			else {
   2074 				advert |= P2PADVERT_ADDR;
   2075 				advert |= P2PADVERT_DEST;
   2076 				ignore |= P2PADVERT_NETWORK;
   2077 			}
   2078 		} else
   2079 			advert |= P2PADVERT_NETWORK;
   2080 #endif
   2081 
   2082 		for (i = 1; i <= P2PADVERT_MAX; i *= 2) {
   2083 			if ((ignore & i) != 0)
   2084 				continue;
   2085 			if ((rrt = MALLOC(struct riprt)) == NULL) {
   2086 				fatal("malloc: struct riprt");
   2087 			}
   2088 			memset(rrt, 0, sizeof(*rrt));
   2089 			rrt->rrt_same = NULL;
   2090 			rrt->rrt_index = ifcp->ifc_index;
   2091 			rrt->rrt_t = 0;	/* don't age */
   2092 			switch (i) {
   2093 			case P2PADVERT_NETWORK:
   2094 				rrt->rrt_info.rip6_dest = ifa->ifa_addr;
   2095 				rrt->rrt_info.rip6_plen = ifa->ifa_plen;
   2096 				applyplen(&rrt->rrt_info.rip6_dest,
   2097 				    ifa->ifa_plen);
   2098 				category = "network";
   2099 				break;
   2100 			case P2PADVERT_ADDR:
   2101 				rrt->rrt_info.rip6_dest = ifa->ifa_addr;
   2102 				rrt->rrt_info.rip6_plen = 128;
   2103 				rrt->rrt_gw = in6addr_loopback;
   2104 				category = "addr";
   2105 				break;
   2106 			case P2PADVERT_DEST:
   2107 				rrt->rrt_info.rip6_dest = ifa->ifa_raddr;
   2108 				rrt->rrt_info.rip6_plen = 128;
   2109 				rrt->rrt_gw = ifa->ifa_addr;
   2110 				category = "dest";
   2111 				break;
   2112 			}
   2113 			if (IN6_IS_ADDR_UNSPECIFIED(&rrt->rrt_info.rip6_dest) ||
   2114 			    IN6_IS_ADDR_LINKLOCAL(&rrt->rrt_info.rip6_dest)) {
   2115 #if 0
   2116 				trace(1, "route: %s: skip unspec/linklocal "
   2117 				    "(%s on %s)\n", category, ifcp->ifc_name);
   2118 #endif
   2119 				free(rrt);
   2120 				continue;
   2121 			}
   2122 			if ((advert & i) == 0) {
   2123 				rrt->rrt_rflags |= RRTF_NOADVERTISE;
   2124 				noadv = ", NO-ADV";
   2125 			} else
   2126 				noadv = "";
   2127 			rrt->rrt_info.rip6_tag = htons(routetag & 0xffff);
   2128 			rrt->rrt_info.rip6_metric = 1 + ifcp->ifc_metric;
   2129 			np = &rrt->rrt_info;
   2130 			orrt = rtsearch(np, &prevrrt);
   2131 			if (!orrt) {
   2132 				/* Attach the route to the list */
   2133 				trace(1, "route: %s/%d: register route "
   2134 				    "(%s on %s%s)\n",
   2135 				    inet6_n2p(&np->rip6_dest), np->rip6_plen,
   2136 				    category, ifcp->ifc_name, noadv);
   2137 				rrt->rrt_next = riprt;
   2138 				riprt = rrt;
   2139 			} else if (rrt->rrt_index != orrt->rrt_index ||
   2140 			    rrt->rrt_info.rip6_metric != orrt->rrt_info.rip6_metric) {
   2141 				/* swap route */
   2142 				rrt->rrt_next = orrt->rrt_next;
   2143 				if (prevrrt)
   2144 					prevrrt->rrt_next = rrt;
   2145 				else
   2146 					riprt = rrt;
   2147 				free(orrt);
   2148 
   2149 				trace(1, "route: %s/%d: update (%s on %s%s)\n",
   2150 				    inet6_n2p(&np->rip6_dest), np->rip6_plen,
   2151 				    category, ifcp->ifc_name, noadv);
   2152 			} else {
   2153 				/* Already found */
   2154 				if (!again) {
   2155 					trace(1, "route: %s/%d: "
   2156 					    "already registered (%s on %s%s)\n",
   2157 					    inet6_n2p(&np->rip6_dest),
   2158 					    np->rip6_plen, category,
   2159 					    ifcp->ifc_name, noadv);
   2160 				}
   2161 				free(rrt);
   2162 			}
   2163 		}
   2164 	}
   2165 #undef P2PADVERT_NETWORK
   2166 #undef P2PADVERT_ADDR
   2167 #undef P2PADVERT_DEST
   2168 #undef P2PADVERT_MAX
   2169 }
   2170 
   2171 static int
   2172 getifmtu(int ifindex)
   2173 {
   2174 	int mib[6];
   2175 	char *buf;
   2176 	size_t msize;
   2177 	struct if_msghdr *ifm;
   2178 	int mtu;
   2179 
   2180 	mib[0] = CTL_NET;
   2181 	mib[1] = PF_ROUTE;
   2182 	mib[2] = 0;
   2183 	mib[3] = AF_INET6;
   2184 	mib[4] = NET_RT_IFLIST;
   2185 	mib[5] = ifindex;
   2186 	if (sysctl(mib, 6, NULL, &msize, NULL, 0) < 0) {
   2187 		fatal("sysctl estimate NET_RT_IFLIST");
   2188 	}
   2189 	if ((buf = malloc(msize)) == NULL) {
   2190 		fatal("malloc");
   2191 	}
   2192 	if (sysctl(mib, 6, buf, &msize, NULL, 0) < 0) {
   2193 		fatal("sysctl NET_RT_IFLIST");
   2194 	}
   2195 	ifm = (struct if_msghdr *)buf;
   2196 	mtu = ifm->ifm_data.ifi_mtu;
   2197 
   2198 	free(buf);
   2199 	return mtu;
   2200 }
   2201 
   2202 static const char *
   2203 rttypes(struct rt_msghdr *rtm)
   2204 {
   2205 #define	RTTYPE(s, f) \
   2206 do { \
   2207 	if (rtm->rtm_type == (f)) \
   2208 		return (s); \
   2209 } while (0)
   2210 	RTTYPE("ADD", RTM_ADD);
   2211 	RTTYPE("DELETE", RTM_DELETE);
   2212 	RTTYPE("CHANGE", RTM_CHANGE);
   2213 	RTTYPE("GET", RTM_GET);
   2214 	RTTYPE("LOSING", RTM_LOSING);
   2215 	RTTYPE("REDIRECT", RTM_REDIRECT);
   2216 	RTTYPE("MISS", RTM_MISS);
   2217 	RTTYPE("LOCK", RTM_LOCK);
   2218 	RTTYPE("OLDADD", RTM_OLDADD);
   2219 	RTTYPE("OLDDEL", RTM_OLDDEL);
   2220 	RTTYPE("NEWADDR", RTM_NEWADDR);
   2221 	RTTYPE("DELADDR", RTM_DELADDR);
   2222 	RTTYPE("IFINFO", RTM_IFINFO);
   2223 #ifdef RTM_OLDADD
   2224 	RTTYPE("OLDADD", RTM_OLDADD);
   2225 #endif
   2226 #ifdef RTM_OLDDEL
   2227 	RTTYPE("OLDDEL", RTM_OLDDEL);
   2228 #endif
   2229 #ifdef RTM_OIFINFO
   2230 	RTTYPE("OIFINFO", RTM_OIFINFO);
   2231 #endif
   2232 #ifdef RTM_IFANNOUNCE
   2233 	RTTYPE("IFANNOUNCE", RTM_IFANNOUNCE);
   2234 #endif
   2235 #ifdef RTM_NEWMADDR
   2236 	RTTYPE("NEWMADDR", RTM_NEWMADDR);
   2237 #endif
   2238 #ifdef RTM_DELMADDR
   2239 	RTTYPE("DELMADDR", RTM_DELMADDR);
   2240 #endif
   2241 #undef RTTYPE
   2242 	return NULL;
   2243 }
   2244 
   2245 static const char *
   2246 rtflags(struct rt_msghdr *rtm)
   2247 {
   2248 	static char buf[BUFSIZ];
   2249 
   2250 	/*
   2251 	 * letter conflict should be okay.  painful when *BSD diverges...
   2252 	 */
   2253 	strlcpy(buf, "", sizeof(buf));
   2254 #define	RTFLAG(s, f) \
   2255 do { \
   2256 	if (rtm->rtm_flags & (f)) \
   2257 		strlcat(buf, (s), sizeof(buf)); \
   2258 } while (0)
   2259 	RTFLAG("U", RTF_UP);
   2260 	RTFLAG("G", RTF_GATEWAY);
   2261 	RTFLAG("H", RTF_HOST);
   2262 	RTFLAG("R", RTF_REJECT);
   2263 	RTFLAG("D", RTF_DYNAMIC);
   2264 	RTFLAG("M", RTF_MODIFIED);
   2265 	RTFLAG("d", RTF_DONE);
   2266 #ifdef	RTF_MASK
   2267 	RTFLAG("m", RTF_MASK);
   2268 #endif
   2269 	RTFLAG("C", RTF_CONNECTED);
   2270 #ifdef RTF_CLONED
   2271 	RTFLAG("c", RTF_CLONED);
   2272 #endif
   2273 #ifdef RTF_PRCLONING
   2274 	RTFLAG("c", RTF_PRCLONING);
   2275 #endif
   2276 #ifdef RTF_WASCLONED
   2277 	RTFLAG("W", RTF_WASCLONED);
   2278 #endif
   2279 	RTFLAG("S", RTF_STATIC);
   2280 	RTFLAG("B", RTF_BLACKHOLE);
   2281 #ifdef RTF_PROTO3
   2282 	RTFLAG("3", RTF_PROTO3);
   2283 #endif
   2284 	RTFLAG("2", RTF_PROTO2);
   2285 	RTFLAG("1", RTF_PROTO1);
   2286 #ifdef RTF_BROADCAST
   2287 	RTFLAG("b", RTF_BROADCAST);
   2288 #endif
   2289 #ifdef RTF_DEFAULT
   2290 	RTFLAG("d", RTF_DEFAULT);
   2291 #endif
   2292 #ifdef RTF_ISAROUTER
   2293 	RTFLAG("r", RTF_ISAROUTER);
   2294 #endif
   2295 #ifdef RTF_TUNNEL
   2296 	RTFLAG("T", RTF_TUNNEL);
   2297 #endif
   2298 #ifdef RTF_AUTH
   2299 	RTFLAG("A", RTF_AUTH);
   2300 #endif
   2301 #ifdef RTF_CRYPT
   2302 	RTFLAG("E", RTF_CRYPT);
   2303 #endif
   2304 #undef RTFLAG
   2305 	return buf;
   2306 }
   2307 
   2308 static const char *
   2309 ifflags(int flags)
   2310 {
   2311 	static char buf[BUFSIZ];
   2312 
   2313 	strlcpy(buf, "", sizeof(buf));
   2314 #define	IFFLAG(s, f) \
   2315 do { \
   2316 	if (flags & (f)) { \
   2317 		if (buf[0]) \
   2318 			strlcat(buf, ",", sizeof(buf)); \
   2319 		strlcat(buf, (s), sizeof(buf)); \
   2320 	} \
   2321 } while (0)
   2322 	IFFLAG("UP", IFF_UP);
   2323 	IFFLAG("BROADCAST", IFF_BROADCAST);
   2324 	IFFLAG("DEBUG", IFF_DEBUG);
   2325 	IFFLAG("LOOPBACK", IFF_LOOPBACK);
   2326 	IFFLAG("POINTOPOINT", IFF_POINTOPOINT);
   2327 #ifdef IFF_NOTRAILERS
   2328 	IFFLAG("NOTRAILERS", IFF_NOTRAILERS);
   2329 #endif
   2330 #ifdef IFF_SMART
   2331 	IFFLAG("SMART", IFF_SMART);
   2332 #endif
   2333 	IFFLAG("RUNNING", IFF_RUNNING);
   2334 	IFFLAG("NOARP", IFF_NOARP);
   2335 	IFFLAG("PROMISC", IFF_PROMISC);
   2336 	IFFLAG("ALLMULTI", IFF_ALLMULTI);
   2337 	IFFLAG("OACTIVE", IFF_OACTIVE);
   2338 	IFFLAG("SIMPLEX", IFF_SIMPLEX);
   2339 	IFFLAG("LINK0", IFF_LINK0);
   2340 	IFFLAG("LINK1", IFF_LINK1);
   2341 	IFFLAG("LINK2", IFF_LINK2);
   2342 	IFFLAG("MULTICAST", IFF_MULTICAST);
   2343 #undef IFFLAG
   2344 	return buf;
   2345 }
   2346 
   2347 static void
   2348 krtread(int again)
   2349 {
   2350 	int mib[6];
   2351 	size_t msize;
   2352 	char *buf = NULL, *p, *lim;
   2353 	struct rt_msghdr *rtm;
   2354 	int retry;
   2355 	const char *errmsg;
   2356 
   2357 	retry = 0;
   2358 	buf = NULL;
   2359 	mib[0] = CTL_NET;
   2360 	mib[1] = PF_ROUTE;
   2361 	mib[2] = 0;
   2362 	mib[3] = AF_INET6;	/* Address family */
   2363 	mib[4] = NET_RT_DUMP;	/* Dump the kernel routing table */
   2364 	mib[5] = 0;		/* No flags */
   2365 	do {
   2366 		retry++;
   2367 		errmsg = NULL;
   2368 		if (buf) {
   2369 			free(buf);
   2370 			buf = NULL;
   2371 		}
   2372 		if (sysctl(mib, 6, NULL, &msize, NULL, 0) < 0) {
   2373 			errmsg = "sysctl estimate";
   2374 			continue;
   2375 		}
   2376 		if ((buf = malloc(msize)) == NULL) {
   2377 			errmsg = "malloc";
   2378 			continue;
   2379 		}
   2380 		if (sysctl(mib, 6, buf, &msize, NULL, 0) < 0) {
   2381 			errmsg = "sysctl NET_RT_DUMP";
   2382 			continue;
   2383 		}
   2384 	} while (retry < 5 && errmsg != NULL);
   2385 	if (errmsg) {
   2386 		fatal("%s (with %d retries, msize=%lu)", errmsg, retry,
   2387 		    (u_long)msize);
   2388 	} else if (1 < retry)
   2389 		syslog(LOG_INFO, "NET_RT_DUMP %d retries", retry);
   2390 
   2391 	lim = buf + msize;
   2392 	for (p = buf; p < lim; p += rtm->rtm_msglen) {
   2393 		rtm = (struct rt_msghdr *)p;
   2394 		rt_entry(rtm, again);
   2395 	}
   2396 	free(buf);
   2397 }
   2398 
   2399 static void
   2400 rt_entry(struct rt_msghdr *rtm, int again)
   2401 {
   2402 	struct sockaddr_in6 *sin6_dst, *sin6_gw, *sin6_mask;
   2403 	struct sockaddr_in6 *sin6_genmask, *sin6_ifp;
   2404 	char *rtmp, *ifname = NULL;
   2405 	struct riprt *rrt, *orrt;
   2406 	struct netinfo6 *np;
   2407 	int s;
   2408 
   2409 	sin6_dst = sin6_gw = sin6_mask = sin6_genmask = sin6_ifp = 0;
   2410 	if ((rtm->rtm_flags & RTF_UP) == 0 || rtm->rtm_flags &
   2411 	    (RTF_CONNECTED|RTF_BLACKHOLE)) {
   2412 		return;		/* not interested in the link route */
   2413 	}
   2414 	/* do not look at cloned routes */
   2415 #ifdef RTF_WASCLONED
   2416 	if (rtm->rtm_flags & RTF_WASCLONED)
   2417 		return;
   2418 #endif
   2419 #ifdef RTF_CLONED
   2420 	if (rtm->rtm_flags & RTF_CLONED)
   2421 		return;
   2422 #endif
   2423 	/*
   2424 	 * do not look at dynamic routes.
   2425 	 * netbsd/openbsd cloned routes have UGHD.
   2426 	 */
   2427 	if (rtm->rtm_flags & RTF_DYNAMIC)
   2428 		return;
   2429 	rtmp = (char *)(rtm + 1);
   2430 	/* Destination */
   2431 	if ((rtm->rtm_addrs & RTA_DST) == 0)
   2432 		return;		/* ignore routes without destination address */
   2433 	sin6_dst = (struct sockaddr_in6 *)rtmp;
   2434 	rtmp += ROUNDUP(sin6_dst->sin6_len);
   2435 	if (rtm->rtm_addrs & RTA_GATEWAY) {
   2436 		sin6_gw = (struct sockaddr_in6 *)rtmp;
   2437 		rtmp += ROUNDUP(sin6_gw->sin6_len);
   2438 	}
   2439 	if (rtm->rtm_addrs & RTA_NETMASK) {
   2440 		sin6_mask = (struct sockaddr_in6 *)rtmp;
   2441 		rtmp += ROUNDUP(sin6_mask->sin6_len);
   2442 	}
   2443 	if (rtm->rtm_addrs & RTA_GENMASK) {
   2444 		sin6_genmask = (struct sockaddr_in6 *)rtmp;
   2445 		rtmp += ROUNDUP(sin6_genmask->sin6_len);
   2446 	}
   2447 	if (rtm->rtm_addrs & RTA_IFP) {
   2448 		sin6_ifp = (struct sockaddr_in6 *)rtmp;
   2449 		rtmp += ROUNDUP(sin6_ifp->sin6_len);
   2450 	}
   2451 
   2452 	/* Destination */
   2453 	if (sin6_dst->sin6_family != AF_INET6)
   2454 		return;
   2455 	if (IN6_IS_ADDR_LINKLOCAL(&sin6_dst->sin6_addr))
   2456 		return;		/* Link-local */
   2457 	if (IN6_ARE_ADDR_EQUAL(&sin6_dst->sin6_addr, &in6addr_loopback))
   2458 		return;		/* Loopback */
   2459 	if (IN6_IS_ADDR_MULTICAST(&sin6_dst->sin6_addr))
   2460 		return;
   2461 
   2462 	if ((rrt = MALLOC(struct riprt)) == NULL) {
   2463 		fatal("malloc: struct riprt");
   2464 	}
   2465 	memset(rrt, 0, sizeof(*rrt));
   2466 	np = &rrt->rrt_info;
   2467 	rrt->rrt_same = NULL;
   2468 	rrt->rrt_t = time(NULL);
   2469 	if (aflag == 0 && (rtm->rtm_flags & RTF_STATIC))
   2470 		rrt->rrt_t = 0;	/* Don't age static routes */
   2471 	if ((rtm->rtm_flags & (RTF_HOST|RTF_GATEWAY)) == RTF_HOST)
   2472 		rrt->rrt_t = 0;	/* Don't age non-gateway host routes */
   2473 	np->rip6_tag = 0;
   2474 	np->rip6_metric = rtm->rtm_rmx.rmx_hopcount;
   2475 	if (np->rip6_metric < 1)
   2476 		np->rip6_metric = 1;
   2477 	rrt->rrt_flags = rtm->rtm_flags;
   2478 	np->rip6_dest = sin6_dst->sin6_addr;
   2479 
   2480 	/* Mask or plen */
   2481 	if (rtm->rtm_flags & RTF_HOST)
   2482 		np->rip6_plen = 128;	/* Host route */
   2483 	else if (sin6_mask)
   2484 		np->rip6_plen = sin6mask2len(sin6_mask);
   2485 	else
   2486 		np->rip6_plen = 0;
   2487 
   2488 	orrt = rtsearch(np, NULL);
   2489 	if (orrt && orrt->rrt_info.rip6_metric != HOPCNT_INFINITY6) {
   2490 		/* Already found */
   2491 		if (!again) {
   2492 			trace(1, "route: %s/%d flags %s: already registered\n",
   2493 				inet6_n2p(&np->rip6_dest), np->rip6_plen,
   2494 				rtflags(rtm));
   2495 		}
   2496 		free(rrt);
   2497 		return;
   2498 	}
   2499 	/* Gateway */
   2500 	if (!sin6_gw)
   2501 		memset(&rrt->rrt_gw, 0, sizeof(struct in6_addr));
   2502 	else {
   2503 		if (sin6_gw->sin6_family == AF_INET6)
   2504 			rrt->rrt_gw = sin6_gw->sin6_addr;
   2505 		else if (sin6_gw->sin6_family == AF_LINK) {
   2506 			/* XXX in case ppp link? */
   2507 			rrt->rrt_gw = in6addr_loopback;
   2508 		} else
   2509 			memset(&rrt->rrt_gw, 0, sizeof(struct in6_addr));
   2510 	}
   2511 	trace(1, "route: %s/%d flags %s",
   2512 		inet6_n2p(&np->rip6_dest), np->rip6_plen, rtflags(rtm));
   2513 	trace(1, " gw %s", inet6_n2p(&rrt->rrt_gw));
   2514 
   2515 	/* Interface */
   2516 	s = rtm->rtm_index;
   2517 	if (s < nindex2ifc && index2ifc[s])
   2518 		ifname = index2ifc[s]->ifc_name;
   2519 	else {
   2520 		trace(1, " not configured\n");
   2521 		free(rrt);
   2522 		return;
   2523 	}
   2524 	trace(1, " if %s sock %d", ifname, s);
   2525 	rrt->rrt_index = s;
   2526 
   2527 	trace(1, "\n");
   2528 
   2529 	/* Check gateway */
   2530 	if (!IN6_IS_ADDR_LINKLOCAL(&rrt->rrt_gw) &&
   2531 	    !IN6_IS_ADDR_LOOPBACK(&rrt->rrt_gw)) {
   2532 		trace(0, "***** Gateway %s is not a link-local address.\n",
   2533 			inet6_n2p(&rrt->rrt_gw));
   2534 		trace(0, "*****     dest(%s) if(%s) -- Not optimized.\n",
   2535 			inet6_n2p(&rrt->rrt_info.rip6_dest), ifname);
   2536 		rrt->rrt_rflags |= RRTF_NH_NOT_LLADDR;
   2537 	}
   2538 
   2539 	/* Put it to the route list */
   2540 	if (orrt && orrt->rrt_info.rip6_metric == HOPCNT_INFINITY6) {
   2541 		/* replace route list */
   2542 		rrt->rrt_next = orrt->rrt_next;
   2543 		*orrt = *rrt;
   2544 		trace(1, "route: %s/%d flags %s: replace new route\n",
   2545 		    inet6_n2p(&np->rip6_dest), np->rip6_plen,
   2546 		    rtflags(rtm));
   2547 		free(rrt);
   2548 	} else {
   2549 		rrt->rrt_next = riprt;
   2550 		riprt = rrt;
   2551 	}
   2552 }
   2553 
   2554 static int
   2555 addroute(struct riprt *rrt, const struct in6_addr *gw, struct ifc *ifcp)
   2556 {
   2557 	struct netinfo6 *np;
   2558 	u_char buf[BUFSIZ], buf1[BUFSIZ], buf2[BUFSIZ];
   2559 	struct rt_msghdr *rtm;
   2560 	struct sockaddr_in6 *sin6;
   2561 	int len;
   2562 
   2563 	np = &rrt->rrt_info;
   2564 	inet_ntop(AF_INET6, (const void *)gw, (char *)buf1, sizeof(buf1));
   2565 	inet_ntop(AF_INET6, (void *)&ifcp->ifc_mylladdr, (char *)buf2, sizeof(buf2));
   2566 	tracet(1, "ADD: %s/%d gw %s [%d] ifa %s\n",
   2567 		inet6_n2p(&np->rip6_dest), np->rip6_plen, buf1,
   2568 		np->rip6_metric - 1, buf2);
   2569 	if (rtlog)
   2570 		fprintf(rtlog, "%s: ADD: %s/%d gw %s [%d] ifa %s\n", hms(),
   2571 			inet6_n2p(&np->rip6_dest), np->rip6_plen, buf1,
   2572 			np->rip6_metric - 1, buf2);
   2573 	if (nflag)
   2574 		return 0;
   2575 
   2576 	memset(buf, 0, sizeof(buf));
   2577 	rtm = (struct rt_msghdr *)buf;
   2578 	rtm->rtm_type = RTM_ADD;
   2579 	rtm->rtm_version = RTM_VERSION;
   2580 	rtm->rtm_seq = ++seq;
   2581 	rtm->rtm_pid = pid;
   2582 	rtm->rtm_flags = rrt->rrt_flags;
   2583 	rtm->rtm_addrs = RTA_DST | RTA_GATEWAY | RTA_NETMASK;
   2584 	rtm->rtm_rmx.rmx_hopcount = np->rip6_metric - 1;
   2585 	rtm->rtm_inits = RTV_HOPCOUNT;
   2586 	sin6 = (struct sockaddr_in6 *)&buf[sizeof(struct rt_msghdr)];
   2587 	/* Destination */
   2588 	sin6->sin6_len = sizeof(struct sockaddr_in6);
   2589 	sin6->sin6_family = AF_INET6;
   2590 	sin6->sin6_addr = np->rip6_dest;
   2591 	sin6 = (struct sockaddr_in6 *)((char *)sin6 + ROUNDUP(sin6->sin6_len));
   2592 	/* Gateway */
   2593 	sin6->sin6_len = sizeof(struct sockaddr_in6);
   2594 	sin6->sin6_family = AF_INET6;
   2595 	sin6->sin6_addr = *gw;
   2596 	sin6 = (struct sockaddr_in6 *)((char *)sin6 + ROUNDUP(sin6->sin6_len));
   2597 	/* Netmask */
   2598 	sin6->sin6_len = sizeof(struct sockaddr_in6);
   2599 	sin6->sin6_family = AF_INET6;
   2600 	sin6->sin6_addr = *(plen2mask(np->rip6_plen));
   2601 	sin6 = (struct sockaddr_in6 *)((char *)sin6 + ROUNDUP(sin6->sin6_len));
   2602 
   2603 	len = (char *)sin6 - (char *)buf;
   2604 	rtm->rtm_msglen = len;
   2605 	if (write(rtsock, buf, len) > 0)
   2606 		return 0;
   2607 
   2608 	if (errno == EEXIST) {
   2609 		trace(0, "ADD: Route already exists %s/%d gw %s\n",
   2610 		    inet6_n2p(&np->rip6_dest), np->rip6_plen, buf1);
   2611 		if (rtlog)
   2612 			fprintf(rtlog, "ADD: Route already exists %s/%d gw %s\n",
   2613 			    inet6_n2p(&np->rip6_dest), np->rip6_plen, buf1);
   2614 	} else {
   2615 		trace(0, "Can not write to rtsock (addroute): %s\n",
   2616 		    strerror(errno));
   2617 		if (rtlog)
   2618 			fprintf(rtlog, "\tCan not write to rtsock: %s\n",
   2619 			    strerror(errno));
   2620 	}
   2621 	return -1;
   2622 }
   2623 
   2624 static int
   2625 delroute(struct netinfo6 *np, struct in6_addr *gw)
   2626 {
   2627 	u_char buf[BUFSIZ], buf2[BUFSIZ];
   2628 	struct rt_msghdr *rtm;
   2629 	struct sockaddr_in6 *sin6;
   2630 	int len;
   2631 
   2632 	inet_ntop(AF_INET6, (void *)gw, (char *)buf2, sizeof(buf2));
   2633 	tracet(1, "DEL: %s/%d gw %s\n", inet6_n2p(&np->rip6_dest),
   2634 		np->rip6_plen, buf2);
   2635 	if (rtlog)
   2636 		fprintf(rtlog, "%s: DEL: %s/%d gw %s\n",
   2637 			hms(), inet6_n2p(&np->rip6_dest), np->rip6_plen, buf2);
   2638 	if (nflag)
   2639 		return 0;
   2640 
   2641 	memset(buf, 0, sizeof(buf));
   2642 	rtm = (struct rt_msghdr *)buf;
   2643 	rtm->rtm_type = RTM_DELETE;
   2644 	rtm->rtm_version = RTM_VERSION;
   2645 	rtm->rtm_seq = ++seq;
   2646 	rtm->rtm_pid = pid;
   2647 	rtm->rtm_flags = RTF_UP | RTF_GATEWAY;
   2648 	if (np->rip6_plen == sizeof(struct in6_addr) * 8)
   2649 		rtm->rtm_flags |= RTF_HOST;
   2650 	rtm->rtm_addrs = RTA_DST | RTA_GATEWAY | RTA_NETMASK;
   2651 	sin6 = (struct sockaddr_in6 *)&buf[sizeof(struct rt_msghdr)];
   2652 	/* Destination */
   2653 	sin6->sin6_len = sizeof(struct sockaddr_in6);
   2654 	sin6->sin6_family = AF_INET6;
   2655 	sin6->sin6_addr = np->rip6_dest;
   2656 	sin6 = (struct sockaddr_in6 *)((char *)sin6 + ROUNDUP(sin6->sin6_len));
   2657 	/* Gateway */
   2658 	sin6->sin6_len = sizeof(struct sockaddr_in6);
   2659 	sin6->sin6_family = AF_INET6;
   2660 	sin6->sin6_addr = *gw;
   2661 	sin6 = (struct sockaddr_in6 *)((char *)sin6 + ROUNDUP(sin6->sin6_len));
   2662 	/* Netmask */
   2663 	sin6->sin6_len = sizeof(struct sockaddr_in6);
   2664 	sin6->sin6_family = AF_INET6;
   2665 	sin6->sin6_addr = *(plen2mask(np->rip6_plen));
   2666 	sin6 = (struct sockaddr_in6 *)((char *)sin6 + ROUNDUP(sin6->sin6_len));
   2667 
   2668 	len = (char *)sin6 - (char *)buf;
   2669 	rtm->rtm_msglen = len;
   2670 	if (write(rtsock, buf, len) >= 0)
   2671 		return 0;
   2672 
   2673 	if (errno == ESRCH) {
   2674 		trace(0, "RTDEL: Route does not exist: %s/%d gw %s\n",
   2675 		    inet6_n2p(&np->rip6_dest), np->rip6_plen, buf2);
   2676 		if (rtlog)
   2677 			fprintf(rtlog, "RTDEL: Route does not exist: %s/%d gw %s\n",
   2678 			    inet6_n2p(&np->rip6_dest), np->rip6_plen, buf2);
   2679 	} else {
   2680 		trace(0, "Can not write to rtsock (delroute): %s\n",
   2681 		    strerror(errno));
   2682 		if (rtlog)
   2683 			fprintf(rtlog, "\tCan not write to rtsock: %s\n",
   2684 			    strerror(errno));
   2685 	}
   2686 	return -1;
   2687 }
   2688 
   2689 static const char *
   2690 inet6_n2p(const struct in6_addr *p)
   2691 {
   2692 	static char buf[BUFSIZ];
   2693 
   2694 	return inet_ntop(AF_INET6, (const void *)p, buf, sizeof(buf));
   2695 }
   2696 
   2697 static void
   2698 ifrtdump(int sig)
   2699 {
   2700 
   2701 	ifdump(sig);
   2702 	rtdump(sig);
   2703 }
   2704 
   2705 static void
   2706 ifdump(int sig)
   2707 {
   2708 	struct ifc *ifcp;
   2709 	FILE *dump;
   2710 	int i;
   2711 
   2712 	if (sig == 0)
   2713 		dump = stderr;
   2714 	else
   2715 		if ((dump = fopen(ROUTE6D_DUMP, "a")) == NULL)
   2716 			dump = stderr;
   2717 
   2718 	fprintf(dump, "%s: Interface Table Dump\n", hms());
   2719 	fprintf(dump, "  Number of interfaces: %d\n", nifc);
   2720 	for (i = 0; i < 2; i++) {
   2721 		fprintf(dump, "  %sadvertising interfaces:\n", i ? "non-" : "");
   2722 		for (ifcp = ifc; ifcp; ifcp = ifcp->ifc_next) {
   2723 			if (i == 0) {
   2724 				if ((ifcp->ifc_flags & IFF_UP) == 0)
   2725 					continue;
   2726 				if (iff_find(ifcp, 'N') != NULL)
   2727 					continue;
   2728 			} else {
   2729 				if (ifcp->ifc_flags & IFF_UP)
   2730 					continue;
   2731 			}
   2732 			ifdump0(dump, ifcp);
   2733 		}
   2734 	}
   2735 	fprintf(dump, "\n");
   2736 	if (dump != stderr)
   2737 		fclose(dump);
   2738 }
   2739 
   2740 static void
   2741 ifdump0(FILE *dump, const struct ifc *ifcp)
   2742 {
   2743 	struct ifac *ifa;
   2744 	struct iff *iffp;
   2745 	char buf[BUFSIZ];
   2746 	const char *ft;
   2747 	int addr;
   2748 
   2749 	fprintf(dump, "    %s: index(%d) flags(%s) addr(%s) mtu(%d) metric(%d)\n",
   2750 		ifcp->ifc_name, ifcp->ifc_index, ifflags(ifcp->ifc_flags),
   2751 		inet6_n2p(&ifcp->ifc_mylladdr),
   2752 		ifcp->ifc_mtu, ifcp->ifc_metric);
   2753 	for (ifa = ifcp->ifc_addr; ifa; ifa = ifa->ifa_next) {
   2754 		if (ifcp->ifc_flags & IFF_POINTOPOINT) {
   2755 			inet_ntop(AF_INET6, (void *)&ifa->ifa_raddr,
   2756 				buf, sizeof(buf));
   2757 			fprintf(dump, "\t%s/%d -- %s\n",
   2758 				inet6_n2p(&ifa->ifa_addr),
   2759 				ifa->ifa_plen, buf);
   2760 		} else {
   2761 			fprintf(dump, "\t%s/%d\n",
   2762 				inet6_n2p(&ifa->ifa_addr),
   2763 				ifa->ifa_plen);
   2764 		}
   2765 	}
   2766 	if (ifcp->ifc_filter) {
   2767 		fprintf(dump, "\tFilter:");
   2768 		for (iffp = ifcp->ifc_filter; iffp; iffp = iffp->iff_next) {
   2769 			addr = 0;
   2770 			switch (iffp->iff_type) {
   2771 			case 'A':
   2772 				ft = "Aggregate"; addr++; break;
   2773 			case 'N':
   2774 				ft = "No-use"; break;
   2775 			case 'O':
   2776 				ft = "Advertise-only"; addr++; break;
   2777 			case 'T':
   2778 				ft = "Default-only"; break;
   2779 			case 'L':
   2780 				ft = "Listen-only"; addr++; break;
   2781 			default:
   2782 				snprintf(buf, sizeof(buf), "Unknown-%c", iffp->iff_type);
   2783 				ft = buf;
   2784 				addr++;
   2785 				break;
   2786 			}
   2787 			fprintf(dump, " %s", ft);
   2788 			if (addr) {
   2789 				fprintf(dump, "(%s/%d)", inet6_n2p(&iffp->iff_addr),
   2790 					iffp->iff_plen);
   2791 			}
   2792 		}
   2793 		fprintf(dump, "\n");
   2794 	}
   2795 }
   2796 
   2797 static void
   2798 rtdump(int sig)
   2799 {
   2800 	struct riprt *rrt;
   2801 	char buf[BUFSIZ];
   2802 	FILE *dump;
   2803 	time_t t, age;
   2804 
   2805 	if (sig == 0)
   2806 		dump = stderr;
   2807 	else
   2808 		if ((dump = fopen(ROUTE6D_DUMP, "a")) == NULL)
   2809 			dump = stderr;
   2810 
   2811 	t = time(NULL);
   2812 	fprintf(dump, "\n%s: Routing Table Dump\n", hms());
   2813 	for (rrt = riprt; rrt; rrt = rrt->rrt_next) {
   2814 		if (rrt->rrt_t == 0)
   2815 			age = 0;
   2816 		else
   2817 			age = t - rrt->rrt_t;
   2818 		inet_ntop(AF_INET6, (void *)&rrt->rrt_info.rip6_dest,
   2819 			buf, sizeof(buf));
   2820 		fprintf(dump, "    %s/%d if(%d:%s) gw(%s) [%d] age(%ld)",
   2821 			buf, rrt->rrt_info.rip6_plen, rrt->rrt_index,
   2822 			index2ifc[rrt->rrt_index]->ifc_name,
   2823 			inet6_n2p(&rrt->rrt_gw),
   2824 			rrt->rrt_info.rip6_metric, (long)age);
   2825 		if (rrt->rrt_info.rip6_tag) {
   2826 			fprintf(dump, " tag(0x%04x)",
   2827 				ntohs(rrt->rrt_info.rip6_tag) & 0xffff);
   2828 		}
   2829 		if (rrt->rrt_rflags & RRTF_NH_NOT_LLADDR)
   2830 			fprintf(dump, " NOT-LL");
   2831 		if (rrt->rrt_rflags & RRTF_NOADVERTISE)
   2832 			fprintf(dump, " NO-ADV");
   2833 		fprintf(dump, "\n");
   2834 	}
   2835 	fprintf(dump, "\n");
   2836 	if (dump != stderr)
   2837 		fclose(dump);
   2838 }
   2839 
   2840 /*
   2841  * Parse the -A (and -O) options and put corresponding filter object to the
   2842  * specified interface structures.  Each of the -A/O option has the following
   2843  * syntax:	-A 5f09:c400::/32,ef0,ef1  (aggregate)
   2844  * 		-O 5f09:c400::/32,ef0,ef1  (only when match)
   2845  */
   2846 static void
   2847 filterconfig(void)
   2848 {
   2849 	int i;
   2850 	char *p, *ap, *iflp, *ifname, *ep;
   2851 	struct iff ftmp, *iff_obj;
   2852 	struct ifc *ifcp;
   2853 	struct riprt *rrt;
   2854 #if 0
   2855 	struct in6_addr gw;
   2856 #endif
   2857 	u_long plen;
   2858 
   2859 	for (i = 0; i < nfilter; i++) {
   2860 		ap = filter[i];
   2861 		iflp = NULL;
   2862 		ifcp = NULL;
   2863 		if (filtertype[i] == 'N' || filtertype[i] == 'T') {
   2864 			iflp = ap;
   2865 			goto ifonly;
   2866 		}
   2867 		if ((p = strchr(ap, ',')) != NULL) {
   2868 			*p++ = '\0';
   2869 			iflp = p;
   2870 		}
   2871 		if ((p = strchr(ap, '/')) == NULL) {
   2872 			fatal("no prefixlen specified for '%s'", ap);
   2873 		}
   2874 		*p++ = '\0';
   2875 		if (inet_pton(AF_INET6, ap, &ftmp.iff_addr) != 1) {
   2876 			fatal("invalid prefix specified for '%s'", ap);
   2877 		}
   2878 		errno = 0;
   2879 		ep = NULL;
   2880 		plen = strtoul(p, &ep, 10);
   2881 		if (errno || !*p || *ep || plen > sizeof(ftmp.iff_addr) * 8) {
   2882 			fatal("invalid prefix length specified for '%s'", ap);
   2883 		}
   2884 		ftmp.iff_plen = plen;
   2885 		ftmp.iff_next = NULL;
   2886 		applyplen(&ftmp.iff_addr, ftmp.iff_plen);
   2887 ifonly:
   2888 		ftmp.iff_type = filtertype[i];
   2889 		if (iflp == NULL || *iflp == '\0') {
   2890 			fatal("no interface specified for '%s'", ap);
   2891 		}
   2892 		/* parse the interface listing portion */
   2893 		while (iflp) {
   2894 			ifname = iflp;
   2895 			if ((iflp = strchr(iflp, ',')) != NULL)
   2896 				*iflp++ = '\0';
   2897 			ifcp = ifc_find(ifname);
   2898 			if (ifcp == NULL) {
   2899 				fatal("no interface %s exists", ifname);
   2900 			}
   2901 			iff_obj = malloc(sizeof(struct iff));
   2902 			if (iff_obj == NULL) {
   2903 				fatal("malloc of iff_obj");
   2904 			}
   2905 			memcpy((void *)iff_obj, (void *)&ftmp,
   2906 			    sizeof(struct iff));
   2907 			/* link it to the interface filter */
   2908 			iff_obj->iff_next = ifcp->ifc_filter;
   2909 			ifcp->ifc_filter = iff_obj;
   2910 		}
   2911 
   2912 		/*
   2913 		 * -A: aggregate configuration.
   2914 		 */
   2915 		if (filtertype[i] != 'A')
   2916 			continue;
   2917 		/* put the aggregate to the kernel routing table */
   2918 		rrt = malloc(sizeof(struct riprt));
   2919 		if (rrt == NULL) {
   2920 			fatal("malloc: rrt");
   2921 		}
   2922 		memset(rrt, 0, sizeof(struct riprt));
   2923 		rrt->rrt_info.rip6_dest = ftmp.iff_addr;
   2924 		rrt->rrt_info.rip6_plen = ftmp.iff_plen;
   2925 		rrt->rrt_info.rip6_metric = 1;
   2926 		rrt->rrt_info.rip6_tag = htons(routetag & 0xffff);
   2927 		rrt->rrt_gw = in6addr_loopback;
   2928 		rrt->rrt_flags = RTF_UP | RTF_REJECT;
   2929 		rrt->rrt_rflags = RRTF_AGGREGATE;
   2930 		rrt->rrt_t = 0;
   2931 		rrt->rrt_index = loopifcp->ifc_index;
   2932 #if 0
   2933 		if (getroute(&rrt->rrt_info, &gw)) {
   2934 #if 0
   2935 			/*
   2936 			 * When the address has already been registered in the
   2937 			 * kernel routing table, it should be removed
   2938 			 */
   2939 			delroute(&rrt->rrt_info, &gw);
   2940 #else
   2941 			/* it is safer behavior */
   2942 			errno = EINVAL;
   2943 			fatal("%s/%u already in routing table, "
   2944 			    "cannot aggregate",
   2945 			    inet6_n2p(&rrt->rrt_info.rip6_dest),
   2946 			    rrt->rrt_info.rip6_plen);
   2947 #endif
   2948 		}
   2949 #endif
   2950 		/* Put the route to the list */
   2951 		rrt->rrt_next = riprt;
   2952 		riprt = rrt;
   2953 		trace(1, "Aggregate: %s/%d for %s\n",
   2954 			inet6_n2p(&ftmp.iff_addr), ftmp.iff_plen,
   2955 			ifcp->ifc_name);
   2956 		/* Add this route to the kernel */
   2957 		if (nflag) 	/* do not modify kernel routing table */
   2958 			continue;
   2959 		addroute(rrt, &in6addr_loopback, loopifcp);
   2960 	}
   2961 }
   2962 
   2963 /***************** utility functions *****************/
   2964 
   2965 /*
   2966  * Returns a pointer to ifac whose address and prefix length matches
   2967  * with the address and prefix length specified in the arguments.
   2968  */
   2969 static struct ifac *
   2970 ifa_match(const struct ifc *ifcp, const struct in6_addr *ia, int plen)
   2971 {
   2972 	struct ifac *ifa;
   2973 
   2974 	for (ifa = ifcp->ifc_addr; ifa; ifa = ifa->ifa_next) {
   2975 		if (IN6_ARE_ADDR_EQUAL(&ifa->ifa_addr, ia) &&
   2976 		    ifa->ifa_plen == plen)
   2977 			break;
   2978 	}
   2979 	return ifa;
   2980 }
   2981 
   2982 /*
   2983  * Return a pointer to riprt structure whose address and prefix length
   2984  * matches with the address and prefix length found in the argument.
   2985  * Note: This is not a rtalloc().  Therefore exact match is necessary.
   2986  */
   2987 static struct riprt *
   2988 rtsearch(struct netinfo6 *np, struct riprt **prev_rrt)
   2989 {
   2990 	struct riprt *rrt;
   2991 
   2992 	if (prev_rrt)
   2993 		*prev_rrt = NULL;
   2994 	for (rrt = riprt; rrt; rrt = rrt->rrt_next) {
   2995 		if (rrt->rrt_info.rip6_plen == np->rip6_plen &&
   2996 		    IN6_ARE_ADDR_EQUAL(&rrt->rrt_info.rip6_dest,
   2997 				       &np->rip6_dest))
   2998 			return rrt;
   2999 		if (prev_rrt)
   3000 			*prev_rrt = rrt;
   3001 	}
   3002 	if (prev_rrt)
   3003 		*prev_rrt = NULL;
   3004 	return 0;
   3005 }
   3006 
   3007 static int
   3008 sin6mask2len(const struct sockaddr_in6 *sin6)
   3009 {
   3010 
   3011 	return mask2len(&sin6->sin6_addr,
   3012 	    sin6->sin6_len - offsetof(struct sockaddr_in6, sin6_addr));
   3013 }
   3014 
   3015 static int
   3016 mask2len(const struct in6_addr *addr, int lenlim)
   3017 {
   3018 	int i = 0, j;
   3019 	const u_char *p = (const u_char *)addr;
   3020 
   3021 	for (j = 0; j < lenlim; j++, p++) {
   3022 		if (*p != 0xff)
   3023 			break;
   3024 		i += 8;
   3025 	}
   3026 	if (j < lenlim) {
   3027 		switch (*p) {
   3028 #define	MASKLEN(m, l)	case m: do { i += l; break; } while (0)
   3029 		MASKLEN(0xfe, 7); break;
   3030 		MASKLEN(0xfc, 6); break;
   3031 		MASKLEN(0xf8, 5); break;
   3032 		MASKLEN(0xf0, 4); break;
   3033 		MASKLEN(0xe0, 3); break;
   3034 		MASKLEN(0xc0, 2); break;
   3035 		MASKLEN(0x80, 1); break;
   3036 #undef	MASKLEN
   3037 		}
   3038 	}
   3039 	return i;
   3040 }
   3041 
   3042 static const u_char plent[8] = {
   3043 	0x00, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe
   3044 };
   3045 
   3046 static void
   3047 applyplen(struct in6_addr *ia, int plen)
   3048 {
   3049 	u_char *p;
   3050 	int i;
   3051 
   3052 	p = ia->s6_addr;
   3053 	for (i = 0; i < 16; i++) {
   3054 		if (plen <= 0)
   3055 			*p = 0;
   3056 		else if (plen < 8)
   3057 			*p &= plent[plen];
   3058 		p++, plen -= 8;
   3059 	}
   3060 }
   3061 
   3062 static const int pl2m[9] = {
   3063 	0x00, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe, 0xff
   3064 };
   3065 
   3066 static struct in6_addr *
   3067 plen2mask(int n)
   3068 {
   3069 	static struct in6_addr ia;
   3070 	u_char *p;
   3071 	int i;
   3072 
   3073 	memset(&ia, 0, sizeof(struct in6_addr));
   3074 	p = (u_char *)&ia;
   3075 	for (i = 0; i < 16; i++, p++, n -= 8) {
   3076 		if (n >= 8) {
   3077 			*p = 0xff;
   3078 			continue;
   3079 		}
   3080 		*p = pl2m[n];
   3081 		break;
   3082 	}
   3083 	return &ia;
   3084 }
   3085 
   3086 static char *
   3087 xstrdup(char *p)
   3088 {
   3089 	char *buf = strdup(p);
   3090 	if (buf == NULL) {
   3091 		fatal("strdup");
   3092 	}
   3093 	return buf;
   3094 }
   3095 
   3096 static char *
   3097 hms(void)
   3098 {
   3099 	static char buf[BUFSIZ];
   3100 	time_t t;
   3101 	struct	tm *tm;
   3102 
   3103 	t = time(NULL);
   3104 	if ((tm = localtime(&t)) == 0) {
   3105 		fatal("localtime");
   3106 	}
   3107 	snprintf(buf, sizeof(buf), "%02d:%02d:%02d", tm->tm_hour, tm->tm_min,
   3108 	    tm->tm_sec);
   3109 	return buf;
   3110 }
   3111 
   3112 #define	RIPRANDDEV	1.0	/* 30 +- 15, max - min = 30 */
   3113 
   3114 static int
   3115 ripinterval(int timer)
   3116 {
   3117 	double r = rand();
   3118 
   3119 	interval = (int)(timer + timer * RIPRANDDEV * (r / RAND_MAX - 0.5));
   3120 	nextalarm = time(NULL) + interval;
   3121 	return interval;
   3122 }
   3123 
   3124 static void
   3125 fatal(const char *fmt, ...)
   3126 {
   3127 	va_list ap;
   3128 	char buf[1024];
   3129 
   3130 	va_start(ap, fmt);
   3131 	vsnprintf(buf, sizeof(buf), fmt, ap);
   3132 	va_end(ap);
   3133 	perror(buf);
   3134 	if (errno)
   3135 		syslog(LOG_ERR, "%s: %s", buf, strerror(errno));
   3136 	else
   3137 		syslog(LOG_ERR, "%s", buf);
   3138 	rtdexit();
   3139 }
   3140 
   3141 static void
   3142 tracet(int level, const char *fmt, ...)
   3143 {
   3144 	va_list ap;
   3145 
   3146 	if (level <= dflag) {
   3147 		va_start(ap, fmt);
   3148 		fprintf(stderr, "%s: ", hms());
   3149 		vfprintf(stderr, fmt, ap);
   3150 		va_end(ap);
   3151 	}
   3152 	if (dflag) {
   3153 		va_start(ap, fmt);
   3154 		if (level > 0)
   3155 			vsyslog(LOG_DEBUG, fmt, ap);
   3156 		else
   3157 			vsyslog(LOG_WARNING, fmt, ap);
   3158 		va_end(ap);
   3159 	}
   3160 }
   3161 
   3162 static void
   3163 trace(int level, const char *fmt, ...)
   3164 {
   3165 	va_list ap;
   3166 
   3167 	if (level <= dflag) {
   3168 		va_start(ap, fmt);
   3169 		vfprintf(stderr, fmt, ap);
   3170 		va_end(ap);
   3171 	}
   3172 	if (dflag) {
   3173 		va_start(ap, fmt);
   3174 		if (level > 0)
   3175 			vsyslog(LOG_DEBUG, fmt, ap);
   3176 		else
   3177 			vsyslog(LOG_WARNING, fmt, ap);
   3178 		va_end(ap);
   3179 	}
   3180 }
   3181 
   3182 static struct ifc *
   3183 ifc_find(char *name)
   3184 {
   3185 	struct ifc *ifcp;
   3186 
   3187 	for (ifcp = ifc; ifcp; ifcp = ifcp->ifc_next) {
   3188 		if (strcmp(name, ifcp->ifc_name) == 0)
   3189 			return ifcp;
   3190 	}
   3191 	return NULL;
   3192 }
   3193 
   3194 static struct iff *
   3195 iff_find(struct ifc *ifcp, int type)
   3196 {
   3197 	struct iff *iffp;
   3198 
   3199 	for (iffp = ifcp->ifc_filter; iffp; iffp = iffp->iff_next) {
   3200 		if (iffp->iff_type == type)
   3201 			return iffp;
   3202 	}
   3203 	return NULL;
   3204 }
   3205 
   3206 static void
   3207 setindex2ifc(int idx, struct ifc *ifcp)
   3208 {
   3209 	int n, nsize;
   3210 	struct ifc **p;
   3211 
   3212 	if (!index2ifc) {
   3213 		nindex2ifc = 5;	/*initial guess*/
   3214 		index2ifc = malloc(sizeof(*index2ifc) * nindex2ifc);
   3215 		if (index2ifc == NULL) {
   3216 			fatal("malloc");
   3217 		}
   3218 		memset(index2ifc, 0, sizeof(*index2ifc) * nindex2ifc);
   3219 	}
   3220 	n = nindex2ifc;
   3221 	for (nsize = nindex2ifc; nsize <= idx; nsize *= 2)
   3222 		;
   3223 	if (n != nsize) {
   3224 		p = (struct ifc **)realloc(index2ifc,
   3225 		    sizeof(*index2ifc) * nsize);
   3226 		if (p == NULL) {
   3227 			fatal("realloc");
   3228 		}
   3229 		memset(p + n, 0, sizeof(*index2ifc) * (nindex2ifc - n));
   3230 		index2ifc = p;
   3231 		nindex2ifc = nsize;
   3232 	}
   3233 	index2ifc[idx] = ifcp;
   3234 }
   3235