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