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