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