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