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