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