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