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