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