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