xref: /freebsd-src/usr.bin/netstat/route.c (revision 3cc31a047e6f1e974cbcc7a83a4ab9689f72765b)
1 /*-
2  * Copyright (c) 1983, 1988, 1993
3  *	The Regents of the University of California.  All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 4. Neither the name of the University nor the names of its contributors
14  *    may be used to endorse or promote products derived from this software
15  *    without specific prior written permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  */
29 
30 #if 0
31 #ifndef lint
32 static char sccsid[] = "From: @(#)route.c	8.6 (Berkeley) 4/28/95";
33 #endif /* not lint */
34 #endif
35 
36 #include <sys/cdefs.h>
37 __FBSDID("$FreeBSD$");
38 
39 #include <sys/param.h>
40 #include <sys/protosw.h>
41 #include <sys/socket.h>
42 #include <sys/socketvar.h>
43 #include <sys/sysctl.h>
44 #include <sys/time.h>
45 
46 #include <net/ethernet.h>
47 #include <net/if.h>
48 #include <net/if_dl.h>
49 #include <net/if_types.h>
50 #include <net/route.h>
51 
52 #include <netinet/in.h>
53 #include <netgraph/ng_socket.h>
54 
55 #include <arpa/inet.h>
56 #include <ifaddrs.h>
57 #include <libutil.h>
58 #include <netdb.h>
59 #include <nlist.h>
60 #include <stdint.h>
61 #include <stdio.h>
62 #include <stdlib.h>
63 #include <stdbool.h>
64 #include <string.h>
65 #include <sysexits.h>
66 #include <unistd.h>
67 #include <err.h>
68 #include <libxo/xo.h>
69 #include "netstat.h"
70 
71 /*
72  * Definitions for showing gateway flags.
73  */
74 static struct bits {
75 	u_long	b_mask;
76 	char	b_val;
77 	const char *b_name;
78 } bits[] = {
79 	{ RTF_UP,	'U', "up" },
80 	{ RTF_GATEWAY,	'G', "gateway" },
81 	{ RTF_HOST,	'H', "host" },
82 	{ RTF_REJECT,	'R', "reject" },
83 	{ RTF_DYNAMIC,	'D', "dynamic" },
84 	{ RTF_MODIFIED,	'M', "modified" },
85 	{ RTF_DONE,	'd', "done" }, /* Completed -- for routing msgs only */
86 	{ RTF_XRESOLVE,	'X', "xresolve" },
87 	{ RTF_STATIC,	'S', "static" },
88 	{ RTF_PROTO1,	'1', "proto1" },
89 	{ RTF_PROTO2,	'2', "proto2" },
90 	{ RTF_PROTO3,	'3', "proto3" },
91 	{ RTF_BLACKHOLE,'B', "blackhole" },
92 	{ RTF_BROADCAST,'b', "broadcast" },
93 #ifdef RTF_LLINFO
94 	{ RTF_LLINFO,	'L', "llinfo" },
95 #endif
96 	{ 0 , 0, NULL }
97 };
98 
99 /*
100  * kvm(3) bindings for every needed symbol
101  */
102 static struct nlist rl[] = {
103 #define	N_RTSTAT	0
104 	{ .n_name = "_rtstat" },
105 #define	N_RTTRASH	1
106 	{ .n_name = "_rttrash" },
107 	{ .n_name = NULL },
108 };
109 
110 struct ifmap_entry {
111 	char ifname[IFNAMSIZ];
112 };
113 static struct ifmap_entry *ifmap;
114 static int ifmap_size;
115 static struct timespec uptime;
116 
117 static const char *netname4(in_addr_t, in_addr_t);
118 static const char *netname6(struct sockaddr_in6 *, struct sockaddr_in6 *);
119 static void p_rtable_sysctl(int, int);
120 static void p_rtentry_sysctl(const char *name, struct rt_msghdr *);
121 static void p_sockaddr(const char *name, struct sockaddr *, struct sockaddr *,
122     int, int);
123 static const char *fmt_sockaddr(struct sockaddr *sa, struct sockaddr *mask,
124     int flags);
125 static void p_flags(int, const char *);
126 static const char *fmt_flags(int f);
127 static void domask(char *, in_addr_t, u_long);
128 
129 
130 /*
131  * Print routing tables.
132  */
133 void
134 routepr(int fibnum, int af)
135 {
136 	size_t intsize;
137 	int numfibs;
138 
139 	if (live == 0)
140 		return;
141 
142 	intsize = sizeof(int);
143 	if (fibnum == -1 &&
144 	    sysctlbyname("net.my_fibnum", &fibnum, &intsize, NULL, 0) == -1)
145 		fibnum = 0;
146 	if (sysctlbyname("net.fibs", &numfibs, &intsize, NULL, 0) == -1)
147 		numfibs = 1;
148 	if (fibnum < 0 || fibnum > numfibs - 1)
149 		errx(EX_USAGE, "%d: invalid fib", fibnum);
150 	/*
151 	 * Since kernel & userland use different timebase
152 	 * (time_uptime vs time_second) and we are reading kernel memory
153 	 * directly we should do rt_expire --> expire_time conversion.
154 	 */
155 	if (clock_gettime(CLOCK_UPTIME, &uptime) < 0)
156 		err(EX_OSERR, "clock_gettime() failed");
157 
158 	xo_open_container("route-information");
159 	xo_emit("{T:Routing tables}");
160 	if (fibnum)
161 		xo_emit(" ({L:fib}: {:fib/%d})", fibnum);
162 	xo_emit("\n");
163 	p_rtable_sysctl(fibnum, af);
164 	xo_close_container("route-information");
165 }
166 
167 
168 /*
169  * Print address family header before a section of the routing table.
170  */
171 void
172 pr_family(int af1)
173 {
174 	const char *afname;
175 
176 	switch (af1) {
177 	case AF_INET:
178 		afname = "Internet";
179 		break;
180 #ifdef INET6
181 	case AF_INET6:
182 		afname = "Internet6";
183 		break;
184 #endif /*INET6*/
185 	case AF_ISO:
186 		afname = "ISO";
187 		break;
188 	case AF_CCITT:
189 		afname = "X.25";
190 		break;
191 	case AF_NETGRAPH:
192 		afname = "Netgraph";
193 		break;
194 	default:
195 		afname = NULL;
196 		break;
197 	}
198 	if (afname)
199 		xo_emit("\n{k:address-family/%s}:\n", afname);
200 	else
201 		xo_emit("\n{L:Protocol Family} {k:address-family/%d}:\n", af1);
202 }
203 
204 /* column widths; each followed by one space */
205 #ifndef INET6
206 #define	WID_DST_DEFAULT(af) 	18	/* width of destination column */
207 #define	WID_GW_DEFAULT(af)	18	/* width of gateway column */
208 #define	WID_IF_DEFAULT(af)	(Wflag ? 10 : 8) /* width of netif column */
209 #else
210 #define	WID_DST_DEFAULT(af) \
211 	((af) == AF_INET6 ? (numeric_addr ? 33: 18) : 18)
212 #define	WID_GW_DEFAULT(af) \
213 	((af) == AF_INET6 ? (numeric_addr ? 29 : 18) : 18)
214 #define	WID_IF_DEFAULT(af)	((af) == AF_INET6 ? 8 : (Wflag ? 10 : 8))
215 #endif /*INET6*/
216 
217 static int wid_dst;
218 static int wid_gw;
219 static int wid_flags;
220 static int wid_pksent;
221 static int wid_mtu;
222 static int wid_if;
223 static int wid_expire;
224 
225 /*
226  * Print header for routing table columns.
227  */
228 static void
229 pr_rthdr(int af1 __unused)
230 {
231 
232 	if (Wflag) {
233 		xo_emit("{T:/%-*.*s} {T:/%-*.*s} {T:/%-*.*s} {T:/%*.*s} "
234 		    "{T:/%*.*s} {T:/%*.*s} {T:/%*s}\n",
235 			wid_dst,	wid_dst,	"Destination",
236 			wid_gw,		wid_gw,		"Gateway",
237 			wid_flags,	wid_flags,	"Flags",
238 			wid_pksent,	wid_pksent,	"Use",
239 			wid_mtu,	wid_mtu,	"Mtu",
240 			wid_if,		wid_if,		"Netif",
241 			wid_expire,			"Expire");
242 	} else {
243 		xo_emit("{T:/%-*.*s} {T:/%-*.*s} {T:/%-*.*s} {T:/%*.*s} "
244 		    "{T:/%*s}\n",
245 			wid_dst,	wid_dst,	"Destination",
246 			wid_gw,		wid_gw,		"Gateway",
247 			wid_flags,	wid_flags,	"Flags",
248 			wid_if,		wid_if,		"Netif",
249 			wid_expire,			"Expire");
250 	}
251 }
252 
253 static void
254 p_rtable_sysctl(int fibnum, int af)
255 {
256 	size_t needed;
257 	int mib[7];
258 	char *buf, *next, *lim;
259 	struct rt_msghdr *rtm;
260 	struct sockaddr *sa;
261 	int fam = AF_UNSPEC, ifindex = 0, size;
262 	int need_table_close = false;
263 
264 	struct ifaddrs *ifap, *ifa;
265 	struct sockaddr_dl *sdl;
266 
267 	/*
268 	 * Retrieve interface list at first
269 	 * since we need #ifindex -> if_xname match
270 	 */
271 	if (getifaddrs(&ifap) != 0)
272 		err(EX_OSERR, "getifaddrs");
273 
274 	for (ifa = ifap; ifa; ifa = ifa->ifa_next) {
275 
276 		if (ifa->ifa_addr->sa_family != AF_LINK)
277 			continue;
278 
279 		sdl = (struct sockaddr_dl *)ifa->ifa_addr;
280 		ifindex = sdl->sdl_index;
281 
282 		if (ifindex >= ifmap_size) {
283 			size = roundup(ifindex + 1, 32) *
284 			    sizeof(struct ifmap_entry);
285 			if ((ifmap = realloc(ifmap, size)) == NULL)
286 				errx(2, "realloc(%d) failed", size);
287 			memset(&ifmap[ifmap_size], 0,
288 			    size - ifmap_size *
289 			    sizeof(struct ifmap_entry));
290 
291 			ifmap_size = roundup(ifindex + 1, 32);
292 		}
293 
294 		if (*ifmap[ifindex].ifname != '\0')
295 			continue;
296 
297 		strlcpy(ifmap[ifindex].ifname, ifa->ifa_name, IFNAMSIZ);
298 	}
299 
300 	freeifaddrs(ifap);
301 
302 	mib[0] = CTL_NET;
303 	mib[1] = PF_ROUTE;
304 	mib[2] = 0;
305 	mib[3] = af;
306 	mib[4] = NET_RT_DUMP;
307 	mib[5] = 0;
308 	mib[6] = fibnum;
309 	if (sysctl(mib, nitems(mib), NULL, &needed, NULL, 0) < 0)
310 		err(EX_OSERR, "sysctl: net.route.0.%d.dump.%d estimate", af,
311 		    fibnum);
312 	if ((buf = malloc(needed)) == NULL)
313 		errx(2, "malloc(%lu)", (unsigned long)needed);
314 	if (sysctl(mib, nitems(mib), buf, &needed, NULL, 0) < 0)
315 		err(1, "sysctl: net.route.0.%d.dump.%d", af, fibnum);
316 	lim  = buf + needed;
317 	xo_open_container("route-table");
318 	xo_open_list("rt-family");
319 	for (next = buf; next < lim; next += rtm->rtm_msglen) {
320 		rtm = (struct rt_msghdr *)next;
321 		if (rtm->rtm_version != RTM_VERSION)
322 			continue;
323 		/*
324 		 * Peek inside header to determine AF
325 		 */
326 		sa = (struct sockaddr *)(rtm + 1);
327 		/* Only print family first time. */
328 		if (fam != sa->sa_family) {
329 			if (need_table_close) {
330 				xo_close_list("rt-entry");
331 				xo_close_instance("rt-family");
332 			}
333 			need_table_close = true;
334 
335 			fam = sa->sa_family;
336 			wid_dst = WID_DST_DEFAULT(fam);
337 			wid_gw = WID_GW_DEFAULT(fam);
338 			wid_flags = 6;
339 			wid_pksent = 8;
340 			wid_mtu = 6;
341 			wid_if = WID_IF_DEFAULT(fam);
342 			wid_expire = 6;
343 			xo_open_instance("rt-family");
344 			pr_family(fam);
345 			xo_open_list("rt-entry");
346 
347 			pr_rthdr(fam);
348 		}
349 		p_rtentry_sysctl("rt-entry", rtm);
350 	}
351 	if (need_table_close) {
352 		xo_close_list("rt-entry");
353 		xo_close_instance("rt-family");
354 	}
355 	xo_close_list("rt-family");
356 	xo_close_container("route-table");
357 	free(buf);
358 }
359 
360 static void
361 p_rtentry_sysctl(const char *name, struct rt_msghdr *rtm)
362 {
363 	struct sockaddr *sa, *addr[RTAX_MAX];
364 	char buffer[128];
365 	char prettyname[128];
366 	int i;
367 
368 	xo_open_instance(name);
369 	sa = (struct sockaddr *)(rtm + 1);
370 	for (i = 0; i < RTAX_MAX; i++) {
371 		if (rtm->rtm_addrs & (1 << i))
372 			addr[i] = sa;
373 		sa = (struct sockaddr *)((char *)sa + SA_SIZE(sa));
374 	}
375 
376 	p_sockaddr("destination", addr[RTAX_DST], addr[RTAX_NETMASK],
377 	    rtm->rtm_flags, wid_dst);
378 	p_sockaddr("gateway", addr[RTAX_GATEWAY], NULL, RTF_HOST, wid_gw);
379 	snprintf(buffer, sizeof(buffer), "{[:-%d}{:flags/%%s}{]:} ",
380 	    wid_flags);
381 	p_flags(rtm->rtm_flags, buffer);
382 	if (Wflag) {
383 		xo_emit("{t:use/%*lu} ", wid_pksent, rtm->rtm_rmx.rmx_pksent);
384 
385 		if (rtm->rtm_rmx.rmx_mtu != 0)
386 			xo_emit("{t:mtu/%*lu} ", wid_mtu, rtm->rtm_rmx.rmx_mtu);
387 		else
388 			xo_emit("{P:/%*s} ", wid_mtu, "");
389 	}
390 
391 	memset(prettyname, 0, sizeof(prettyname));
392 	if (rtm->rtm_index < ifmap_size) {
393 		strlcpy(prettyname, ifmap[rtm->rtm_index].ifname,
394 		    sizeof(prettyname));
395 		if (*prettyname == '\0')
396 			strlcpy(prettyname, "---", sizeof(prettyname));
397 	}
398 
399 	xo_emit("{t:interface-name/%*.*s}", wid_if, wid_if, prettyname);
400 	if (rtm->rtm_rmx.rmx_expire) {
401 		time_t expire_time;
402 
403 		if ((expire_time = rtm->rtm_rmx.rmx_expire - uptime.tv_sec) > 0)
404 			xo_emit(" {:expire-time/%*d}", wid_expire,
405 			    (int)expire_time);
406 	}
407 
408 	xo_emit("\n");
409 	xo_close_instance(name);
410 }
411 
412 static void
413 p_sockaddr(const char *name, struct sockaddr *sa, struct sockaddr *mask,
414     int flags, int width)
415 {
416 	const char *cp;
417 	char buf[128];
418 
419 	cp = fmt_sockaddr(sa, mask, flags);
420 
421 	if (width < 0) {
422 		snprintf(buf, sizeof(buf), "{:%s/%%s} ", name);
423 		xo_emit(buf, cp);
424 	} else {
425 		if (Wflag != 0 || numeric_addr) {
426 			snprintf(buf, sizeof(buf), "{[:%d}{:%s/%%s}{]:} ",
427 			    -width, name);
428 			xo_emit(buf, cp);
429 		} else {
430 			snprintf(buf, sizeof(buf), "{[:%d}{:%s/%%-.*s}{]:} ",
431 			    -width, name);
432 			xo_emit(buf, width, cp);
433 		}
434 	}
435 }
436 
437 static const char *
438 fmt_sockaddr(struct sockaddr *sa, struct sockaddr *mask, int flags)
439 {
440 	static char buf[128];
441 	const char *cp;
442 
443 	if (sa == NULL)
444 		return ("null");
445 
446 	switch(sa->sa_family) {
447 #ifdef INET6
448 	case AF_INET6:
449 		/*
450 		 * The sa6->sin6_scope_id must be filled here because
451 		 * this sockaddr is extracted from kmem(4) directly
452 		 * and has KAME-specific embedded scope id in
453 		 * sa6->sin6_addr.s6_addr[2].
454 		 */
455 		in6_fillscopeid(satosin6(sa));
456 		/* FALLTHROUGH */
457 #endif /*INET6*/
458 	case AF_INET:
459 		if (flags & RTF_HOST)
460 			cp = routename(sa, numeric_addr);
461 		else if (mask)
462 			cp = netname(sa, mask);
463 		else
464 			cp = netname(sa, NULL);
465 		break;
466 	case AF_NETGRAPH:
467 	    {
468 		strlcpy(buf, ((struct sockaddr_ng *)sa)->sg_data,
469 		    sizeof(buf));
470 		cp = buf;
471 		break;
472 	    }
473 	case AF_LINK:
474 	    {
475 #if 0
476 		struct sockaddr_dl *sdl = (struct sockaddr_dl *)sa;
477 
478 		/* Interface route. */
479 		if (sdl->sdl_nlen)
480 			cp = sdl->sdl_data;
481 		else
482 #endif
483 			cp = routename(sa, 1);
484 		break;
485 	    }
486 	default:
487 	    {
488 		u_char *s = (u_char *)sa->sa_data, *slim;
489 		char *cq, *cqlim;
490 
491 		cq = buf;
492 		slim =  sa->sa_len + (u_char *) sa;
493 		cqlim = cq + sizeof(buf) - 6;
494 		cq += sprintf(cq, "(%d)", sa->sa_family);
495 		while (s < slim && cq < cqlim) {
496 			cq += sprintf(cq, " %02x", *s++);
497 			if (s < slim)
498 			    cq += sprintf(cq, "%02x", *s++);
499 		}
500 		cp = buf;
501 	    }
502 	}
503 
504 	return (cp);
505 }
506 
507 static void
508 p_flags(int f, const char *format)
509 {
510 	struct bits *p;
511 
512 	xo_emit(format, fmt_flags(f));
513 
514 	xo_open_list("flags_pretty");
515 	for (p = bits; p->b_mask; p++)
516 		if (p->b_mask & f)
517 			xo_emit("{le:flags_pretty/%s}", p->b_name);
518 	xo_close_list("flags_pretty");
519 }
520 
521 static const char *
522 fmt_flags(int f)
523 {
524 	static char name[33];
525 	char *flags;
526 	struct bits *p = bits;
527 
528 	for (flags = name; p->b_mask; p++)
529 		if (p->b_mask & f)
530 			*flags++ = p->b_val;
531 	*flags = '\0';
532 	return (name);
533 }
534 
535 char *
536 routename(struct sockaddr *sa, int flags)
537 {
538 	static char line[NI_MAXHOST];
539 	int error, f;
540 
541 	f = (flags) ? NI_NUMERICHOST : 0;
542 	error = getnameinfo(sa, sa->sa_len, line, sizeof(line),
543 	    NULL, 0, f);
544 	if (error) {
545 		const void *src;
546 		switch (sa->sa_family) {
547 #ifdef INET
548 		case AF_INET:
549 			src = &satosin(sa)->sin_addr;
550 			break;
551 #endif /* INET */
552 #ifdef INET6
553 		case AF_INET6:
554 			src = &satosin6(sa)->sin6_addr;
555 			break;
556 #endif /* INET6 */
557 		default:
558 			return(line);
559 		}
560 		inet_ntop(sa->sa_family, src, line, sizeof(line) - 1);
561 		return (line);
562 	}
563 	trimdomain(line, strlen(line));
564 
565 	return (line);
566 }
567 
568 #define	NSHIFT(m) (							\
569 	(m) == IN_CLASSA_NET ? IN_CLASSA_NSHIFT :			\
570 	(m) == IN_CLASSB_NET ? IN_CLASSB_NSHIFT :			\
571 	(m) == IN_CLASSC_NET ? IN_CLASSC_NSHIFT :			\
572 	0)
573 
574 static void
575 domask(char *dst, in_addr_t addr __unused, u_long mask)
576 {
577 	int b, i;
578 
579 	if (mask == 0) {
580 		*dst = '\0';
581 		return;
582 	}
583 	i = 0;
584 	for (b = 0; b < 32; b++)
585 		if (mask & (1 << b)) {
586 			int bb;
587 
588 			i = b;
589 			for (bb = b+1; bb < 32; bb++)
590 				if (!(mask & (1 << bb))) {
591 					i = -1;	/* noncontig */
592 					break;
593 				}
594 			break;
595 		}
596 	if (i == -1)
597 		sprintf(dst, "&0x%lx", mask);
598 	else
599 		sprintf(dst, "/%d", 32-i);
600 }
601 
602 /*
603  * Return the name of the network whose address is given.
604  */
605 const char *
606 netname(struct sockaddr *sa, struct sockaddr *mask)
607 {
608 	switch (sa->sa_family) {
609 	case AF_INET:
610 		if (mask != NULL)
611 			return (netname4(satosin(sa)->sin_addr.s_addr,
612 			    satosin(mask)->sin_addr.s_addr));
613 		else
614 			return (netname4(satosin(sa)->sin_addr.s_addr,
615 			    INADDR_ANY));
616 		break;
617 #ifdef INET6
618 	case AF_INET6:
619 		return (netname6(satosin6(sa), satosin6(mask)));
620 #endif /* INET6 */
621 	default:
622 		return (NULL);
623 	}
624 }
625 
626 static const char *
627 netname4(in_addr_t in, in_addr_t mask)
628 {
629 	char *cp = 0;
630 	static char line[MAXHOSTNAMELEN + sizeof("/xx")];
631 	char nline[INET_ADDRSTRLEN];
632 	struct netent *np = 0;
633 	in_addr_t i;
634 
635 	if (in == INADDR_ANY && mask == 0) {
636 		strlcpy(line, "default", sizeof(line));
637 		return (line);
638 	}
639 
640 	/* It is ok to supply host address. */
641 	in &= mask;
642 
643 	i = ntohl(in);
644 	if (!numeric_addr && i) {
645 		np = getnetbyaddr(i >> NSHIFT(ntohl(mask)), AF_INET);
646 		if (np != NULL) {
647 			cp = np->n_name;
648 			trimdomain(cp, strlen(cp));
649 		}
650 	}
651 	inet_ntop(AF_INET, &in, nline, sizeof(line));
652 	if (cp != NULL) {
653 		if (strcpy(cp, nline) != 0)
654 			return (line);
655 		strlcpy(line, cp, sizeof(line));
656 	} else
657 		strlcpy(line, nline, sizeof(line));
658 	domask(line + strlen(line), i, ntohl(mask));
659 
660 	return (line);
661 }
662 
663 #undef NSHIFT
664 
665 #ifdef INET6
666 void
667 in6_fillscopeid(struct sockaddr_in6 *sa6)
668 {
669 #if defined(__KAME__)
670 	/*
671 	 * XXX: This is a special workaround for KAME kernels.
672 	 * sin6_scope_id field of SA should be set in the future.
673 	 */
674 	if (IN6_IS_ADDR_LINKLOCAL(&sa6->sin6_addr) ||
675 	    IN6_IS_ADDR_MC_NODELOCAL(&sa6->sin6_addr) ||
676 	    IN6_IS_ADDR_MC_LINKLOCAL(&sa6->sin6_addr)) {
677 		if (sa6->sin6_scope_id == 0)
678 			sa6->sin6_scope_id =
679 			    ntohs(*(u_int16_t *)&sa6->sin6_addr.s6_addr[2]);
680 		sa6->sin6_addr.s6_addr[2] = sa6->sin6_addr.s6_addr[3] = 0;
681 	}
682 #endif
683 }
684 
685 /* Mask to length table.  To check an invalid value, (length + 1) is used. */
686 static int masktolen[256] = {
687 	[0xff] = 8 + 1,
688 	[0xfe] = 7 + 1,
689 	[0xfc] = 6 + 1,
690 	[0xf8] = 5 + 1,
691 	[0xf0] = 4 + 1,
692 	[0xe0] = 3 + 1,
693 	[0xc0] = 2 + 1,
694 	[0x80] = 1 + 1,
695 	[0x00] = 0 + 1,
696 };
697 
698 static const char *
699 netname6(struct sockaddr_in6 *sa6, struct sockaddr_in6 *mask)
700 {
701 	static char line[NI_MAXHOST + sizeof("/xxx") - 1];
702 	char nline[NI_MAXHOST];
703 	u_char *p, *lim;
704 	int masklen, illegal = 0;
705 
706 	if (mask) {
707 		p = (u_char *)&mask->sin6_addr;
708 		for (masklen = 0, lim = p + 16; p < lim; p++) {
709 			if (masktolen[*p] > 0)
710 				/* -1 is required. */
711 				masklen += masktolen[*p] - 1;
712 			else
713 				illegal++;
714 		}
715 		if (illegal)
716 			xo_error("illegal prefixlen\n");
717 	}
718 	else
719 		masklen = 128;
720 
721 	if (masklen == 0 && IN6_IS_ADDR_UNSPECIFIED(&sa6->sin6_addr))
722 		return("default");
723 
724 	getnameinfo((struct sockaddr *)sa6, sa6->sin6_len, nline, sizeof(nline),
725 	    NULL, 0, NI_NUMERICHOST);
726 	if (numeric_addr)
727 		strlcpy(line, nline, sizeof(line));
728 	else
729 		getnameinfo((struct sockaddr *)sa6, sa6->sin6_len, line,
730 		    sizeof(line), NULL, 0, 0);
731 	if (numeric_addr || strcmp(line, nline) == 0)
732 		sprintf(&line[strlen(line)], "/%d", masklen);
733 
734 	return (line);
735 }
736 #endif /*INET6*/
737 
738 /*
739  * Print routing statistics
740  */
741 void
742 rt_stats(void)
743 {
744 	struct rtstat rtstat;
745 	u_long rtsaddr, rttaddr;
746 	int rttrash;
747 
748 	kresolve_list(rl);
749 
750 	if ((rtsaddr = rl[N_RTSTAT].n_value) == 0) {
751 		xo_emit("{W:rtstat: symbol not in namelist}\n");
752 		return;
753 	}
754 	if ((rttaddr = rl[N_RTTRASH].n_value) == 0) {
755 		xo_emit("{W:rttrash: symbol not in namelist}\n");
756 		return;
757 	}
758 	kread(rtsaddr, (char *)&rtstat, sizeof (rtstat));
759 	kread(rttaddr, (char *)&rttrash, sizeof (rttrash));
760 	xo_emit("{T:routing}:\n");
761 
762 #define	p(f, m) if (rtstat.f || sflag <= 1) \
763 	xo_emit(m, rtstat.f, plural(rtstat.f))
764 
765 	p(rts_badredirect, "\t{:bad-redirects/%hu} "
766 	    "{N:/bad routing redirect%s}\n");
767 	p(rts_dynamic, "\t{:dynamically-created/%hu} "
768 	    "{N:/dynamically created route%s}\n");
769 	p(rts_newgateway, "\t{:new-gateways/%hu} "
770 	    "{N:/new gateway%s due to redirects}\n");
771 	p(rts_unreach, "\t{:unreachable-destination/%hu} "
772 	    "{N:/destination%s found unreachable}\n");
773 	p(rts_wildcard, "\t{:wildcard-uses/%hu} "
774 	    "{N:/use%s of a wildcard route}\n");
775 #undef p
776 
777 	if (rttrash || sflag <= 1)
778 		xo_emit("\t{:unused-but-not-freed/%u} "
779 		    "{N:/route%s not in table but not freed}\n",
780 		    rttrash, plural(rttrash));
781 }
782