xref: /freebsd/usr.bin/netstat/route.c (revision 2f513db7)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 1983, 1988, 1993
5  *	The Regents of the University of California.  All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. Neither the name of the University nor the names of its contributors
16  *    may be used to endorse or promote products derived from this software
17  *    without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  */
31 
32 #if 0
33 #ifndef lint
34 static char sccsid[] = "From: @(#)route.c	8.6 (Berkeley) 4/28/95";
35 #endif /* not lint */
36 #endif
37 
38 #include <sys/cdefs.h>
39 __FBSDID("$FreeBSD$");
40 
41 #include <sys/param.h>
42 #include <sys/protosw.h>
43 #include <sys/socket.h>
44 #include <sys/socketvar.h>
45 #include <sys/sysctl.h>
46 #include <sys/time.h>
47 
48 #include <net/ethernet.h>
49 #include <net/if.h>
50 #include <net/if_dl.h>
51 #include <net/if_types.h>
52 #include <net/route.h>
53 
54 #include <netinet/in.h>
55 #include <netgraph/ng_socket.h>
56 
57 #include <arpa/inet.h>
58 #include <ifaddrs.h>
59 #include <libutil.h>
60 #include <netdb.h>
61 #include <stdbool.h>
62 #include <stdint.h>
63 #include <stdio.h>
64 #include <stdlib.h>
65 #include <stdbool.h>
66 #include <string.h>
67 #include <sysexits.h>
68 #include <unistd.h>
69 #include <err.h>
70 #include <libxo/xo.h>
71 #include "netstat.h"
72 #include "nl_defs.h"
73 
74 /*
75  * Definitions for showing gateway flags.
76  */
77 static struct bits {
78 	u_long	b_mask;
79 	char	b_val;
80 	const char *b_name;
81 } bits[] = {
82 	{ RTF_UP,	'U', "up" },
83 	{ RTF_GATEWAY,	'G', "gateway" },
84 	{ RTF_HOST,	'H', "host" },
85 	{ RTF_REJECT,	'R', "reject" },
86 	{ RTF_DYNAMIC,	'D', "dynamic" },
87 	{ RTF_MODIFIED,	'M', "modified" },
88 	{ RTF_DONE,	'd', "done" }, /* Completed -- for routing msgs only */
89 	{ RTF_XRESOLVE,	'X', "xresolve" },
90 	{ RTF_STATIC,	'S', "static" },
91 	{ RTF_PROTO1,	'1', "proto1" },
92 	{ RTF_PROTO2,	'2', "proto2" },
93 	{ RTF_PROTO3,	'3', "proto3" },
94 	{ RTF_BLACKHOLE,'B', "blackhole" },
95 	{ RTF_BROADCAST,'b', "broadcast" },
96 #ifdef RTF_LLINFO
97 	{ RTF_LLINFO,	'L', "llinfo" },
98 #endif
99 	{ 0 , 0, NULL }
100 };
101 
102 struct ifmap_entry {
103 	char ifname[IFNAMSIZ];
104 };
105 static struct ifmap_entry *ifmap;
106 static int ifmap_size;
107 static struct timespec uptime;
108 
109 static const char *netname4(in_addr_t, in_addr_t);
110 #ifdef INET6
111 static const char *netname6(struct sockaddr_in6 *, struct sockaddr_in6 *);
112 #endif
113 static void p_rtable_sysctl(int, int);
114 static void p_rtentry_sysctl(const char *name, struct rt_msghdr *);
115 static int p_sockaddr(const char *name, struct sockaddr *, struct sockaddr *,
116     int, int);
117 static const char *fmt_sockaddr(struct sockaddr *sa, struct sockaddr *mask,
118     int flags);
119 static void p_flags(int, const char *);
120 static const char *fmt_flags(int f);
121 static void domask(char *, size_t, u_long);
122 
123 
124 /*
125  * Print routing tables.
126  */
127 void
128 routepr(int fibnum, int af)
129 {
130 	size_t intsize;
131 	int numfibs;
132 
133 	if (live == 0)
134 		return;
135 
136 	intsize = sizeof(int);
137 	if (fibnum == -1 &&
138 	    sysctlbyname("net.my_fibnum", &fibnum, &intsize, NULL, 0) == -1)
139 		fibnum = 0;
140 	if (sysctlbyname("net.fibs", &numfibs, &intsize, NULL, 0) == -1)
141 		numfibs = 1;
142 	if (fibnum < 0 || fibnum > numfibs - 1)
143 		errx(EX_USAGE, "%d: invalid fib", fibnum);
144 	/*
145 	 * Since kernel & userland use different timebase
146 	 * (time_uptime vs time_second) and we are reading kernel memory
147 	 * directly we should do rt_expire --> expire_time conversion.
148 	 */
149 	if (clock_gettime(CLOCK_UPTIME, &uptime) < 0)
150 		err(EX_OSERR, "clock_gettime() failed");
151 
152 	xo_open_container("route-information");
153 	xo_emit("{T:Routing tables}");
154 	if (fibnum)
155 		xo_emit(" ({L:fib}: {:fib/%d})", fibnum);
156 	xo_emit("\n");
157 	p_rtable_sysctl(fibnum, af);
158 	xo_close_container("route-information");
159 }
160 
161 
162 /*
163  * Print address family header before a section of the routing table.
164  */
165 void
166 pr_family(int af1)
167 {
168 	const char *afname;
169 
170 	switch (af1) {
171 	case AF_INET:
172 		afname = "Internet";
173 		break;
174 #ifdef INET6
175 	case AF_INET6:
176 		afname = "Internet6";
177 		break;
178 #endif /*INET6*/
179 	case AF_ISO:
180 		afname = "ISO";
181 		break;
182 	case AF_CCITT:
183 		afname = "X.25";
184 		break;
185 	case AF_NETGRAPH:
186 		afname = "Netgraph";
187 		break;
188 	default:
189 		afname = NULL;
190 		break;
191 	}
192 	if (afname)
193 		xo_emit("\n{k:address-family/%s}:\n", afname);
194 	else
195 		xo_emit("\n{L:Protocol Family} {k:address-family/%d}:\n", af1);
196 }
197 
198 /* column widths; each followed by one space */
199 #ifndef INET6
200 #define	WID_DST_DEFAULT(af) 	18	/* width of destination column */
201 #define	WID_GW_DEFAULT(af)	18	/* width of gateway column */
202 #define	WID_IF_DEFAULT(af)	(Wflag ? 10 : 8) /* width of netif column */
203 #else
204 #define	WID_DST_DEFAULT(af) \
205 	((af) == AF_INET6 ? (numeric_addr ? 33: 18) : 18)
206 #define	WID_GW_DEFAULT(af) \
207 	((af) == AF_INET6 ? (numeric_addr ? 29 : 18) : 18)
208 #define	WID_IF_DEFAULT(af)	((af) == AF_INET6 ? 8 : (Wflag ? 10 : 8))
209 #endif /*INET6*/
210 
211 static int wid_dst;
212 static int wid_gw;
213 static int wid_flags;
214 static int wid_pksent;
215 static int wid_mtu;
216 static int wid_if;
217 static int wid_expire;
218 
219 /*
220  * Print header for routing table columns.
221  */
222 static void
223 pr_rthdr(int af1 __unused)
224 {
225 
226 	if (Wflag) {
227 		xo_emit("{T:/%-*.*s} {T:/%-*.*s} {T:/%-*.*s} {T:/%*.*s} "
228 		    "{T:/%*.*s} {T:/%*.*s} {T:/%*s}\n",
229 			wid_dst,	wid_dst,	"Destination",
230 			wid_gw,		wid_gw,		"Gateway",
231 			wid_flags,	wid_flags,	"Flags",
232 			wid_pksent,	wid_pksent,	"Use",
233 			wid_mtu,	wid_mtu,	"Mtu",
234 			wid_if,		wid_if,		"Netif",
235 			wid_expire,			"Expire");
236 	} else {
237 		xo_emit("{T:/%-*.*s} {T:/%-*.*s} {T:/%-*.*s} {T:/%*.*s} "
238 		    "{T:/%*s}\n",
239 			wid_dst,	wid_dst,	"Destination",
240 			wid_gw,		wid_gw,		"Gateway",
241 			wid_flags,	wid_flags,	"Flags",
242 			wid_if,		wid_if,		"Netif",
243 			wid_expire,			"Expire");
244 	}
245 }
246 
247 static void
248 p_rtable_sysctl(int fibnum, int af)
249 {
250 	size_t needed;
251 	int mib[7];
252 	char *buf, *next, *lim;
253 	struct rt_msghdr *rtm;
254 	struct sockaddr *sa;
255 	int fam = AF_UNSPEC, ifindex = 0, size;
256 	int need_table_close = false;
257 
258 	struct ifaddrs *ifap, *ifa;
259 	struct sockaddr_dl *sdl;
260 
261 	/*
262 	 * Retrieve interface list at first
263 	 * since we need #ifindex -> if_xname match
264 	 */
265 	if (getifaddrs(&ifap) != 0)
266 		err(EX_OSERR, "getifaddrs");
267 
268 	for (ifa = ifap; ifa; ifa = ifa->ifa_next) {
269 
270 		if (ifa->ifa_addr->sa_family != AF_LINK)
271 			continue;
272 
273 		sdl = (struct sockaddr_dl *)ifa->ifa_addr;
274 		ifindex = sdl->sdl_index;
275 
276 		if (ifindex >= ifmap_size) {
277 			size = roundup(ifindex + 1, 32) *
278 			    sizeof(struct ifmap_entry);
279 			if ((ifmap = realloc(ifmap, size)) == NULL)
280 				errx(2, "realloc(%d) failed", size);
281 			memset(&ifmap[ifmap_size], 0,
282 			    size - ifmap_size *
283 			    sizeof(struct ifmap_entry));
284 
285 			ifmap_size = roundup(ifindex + 1, 32);
286 		}
287 
288 		if (*ifmap[ifindex].ifname != '\0')
289 			continue;
290 
291 		strlcpy(ifmap[ifindex].ifname, ifa->ifa_name, IFNAMSIZ);
292 	}
293 
294 	freeifaddrs(ifap);
295 
296 	mib[0] = CTL_NET;
297 	mib[1] = PF_ROUTE;
298 	mib[2] = 0;
299 	mib[3] = af;
300 	mib[4] = NET_RT_DUMP;
301 	mib[5] = 0;
302 	mib[6] = fibnum;
303 	if (sysctl(mib, nitems(mib), NULL, &needed, NULL, 0) < 0)
304 		err(EX_OSERR, "sysctl: net.route.0.%d.dump.%d estimate", af,
305 		    fibnum);
306 	if ((buf = malloc(needed)) == NULL)
307 		errx(2, "malloc(%lu)", (unsigned long)needed);
308 	if (sysctl(mib, nitems(mib), buf, &needed, NULL, 0) < 0)
309 		err(1, "sysctl: net.route.0.%d.dump.%d", af, fibnum);
310 	lim  = buf + needed;
311 	xo_open_container("route-table");
312 	xo_open_list("rt-family");
313 	for (next = buf; next < lim; next += rtm->rtm_msglen) {
314 		rtm = (struct rt_msghdr *)next;
315 		if (rtm->rtm_version != RTM_VERSION)
316 			continue;
317 		/*
318 		 * Peek inside header to determine AF
319 		 */
320 		sa = (struct sockaddr *)(rtm + 1);
321 		/* Only print family first time. */
322 		if (fam != sa->sa_family) {
323 			if (need_table_close) {
324 				xo_close_list("rt-entry");
325 				xo_close_instance("rt-family");
326 			}
327 			need_table_close = true;
328 
329 			fam = sa->sa_family;
330 			wid_dst = WID_DST_DEFAULT(fam);
331 			wid_gw = WID_GW_DEFAULT(fam);
332 			wid_flags = 6;
333 			wid_pksent = 8;
334 			wid_mtu = 6;
335 			wid_if = WID_IF_DEFAULT(fam);
336 			wid_expire = 6;
337 			xo_open_instance("rt-family");
338 			pr_family(fam);
339 			xo_open_list("rt-entry");
340 
341 			pr_rthdr(fam);
342 		}
343 		p_rtentry_sysctl("rt-entry", rtm);
344 	}
345 	if (need_table_close) {
346 		xo_close_list("rt-entry");
347 		xo_close_instance("rt-family");
348 	}
349 	xo_close_list("rt-family");
350 	xo_close_container("route-table");
351 	free(buf);
352 }
353 
354 static void
355 p_rtentry_sysctl(const char *name, struct rt_msghdr *rtm)
356 {
357 	struct sockaddr *sa, *addr[RTAX_MAX];
358 	char buffer[128];
359 	char prettyname[128];
360 	int i, protrusion;
361 
362 	xo_open_instance(name);
363 	sa = (struct sockaddr *)(rtm + 1);
364 	for (i = 0; i < RTAX_MAX; i++) {
365 		if (rtm->rtm_addrs & (1 << i)) {
366 			addr[i] = sa;
367 			sa = (struct sockaddr *)((char *)sa + SA_SIZE(sa));
368 		}
369 	}
370 
371 	protrusion = p_sockaddr("destination", addr[RTAX_DST],
372 	    addr[RTAX_NETMASK],
373 	    rtm->rtm_flags, wid_dst);
374 	protrusion = p_sockaddr("gateway", addr[RTAX_GATEWAY], NULL, RTF_HOST,
375 	    wid_gw - protrusion);
376 	snprintf(buffer, sizeof(buffer), "{[:-%d}{:flags/%%s}{]:} ",
377 	    wid_flags - protrusion);
378 	p_flags(rtm->rtm_flags, buffer);
379 	if (Wflag) {
380 		xo_emit("{t:use/%*lu} ", wid_pksent, rtm->rtm_rmx.rmx_pksent);
381 
382 		if (rtm->rtm_rmx.rmx_mtu != 0)
383 			xo_emit("{t:mtu/%*lu} ", wid_mtu, rtm->rtm_rmx.rmx_mtu);
384 		else
385 			xo_emit("{P:/%*s} ", wid_mtu, "");
386 	}
387 
388 	memset(prettyname, 0, sizeof(prettyname));
389 	if (rtm->rtm_index < ifmap_size) {
390 		strlcpy(prettyname, ifmap[rtm->rtm_index].ifname,
391 		    sizeof(prettyname));
392 		if (*prettyname == '\0')
393 			strlcpy(prettyname, "---", sizeof(prettyname));
394 	}
395 
396 	if (Wflag)
397 		xo_emit("{t:interface-name/%*s}", wid_if, prettyname);
398 	else
399 		xo_emit("{t:interface-name/%*.*s}", wid_if, wid_if,
400 		    prettyname);
401 	if (rtm->rtm_rmx.rmx_expire) {
402 		time_t expire_time;
403 
404 		if ((expire_time = rtm->rtm_rmx.rmx_expire - uptime.tv_sec) > 0)
405 			xo_emit(" {:expire-time/%*d}", wid_expire,
406 			    (int)expire_time);
407 	}
408 
409 	xo_emit("\n");
410 	xo_close_instance(name);
411 }
412 
413 static int
414 p_sockaddr(const char *name, struct sockaddr *sa, struct sockaddr *mask,
415     int flags, int width)
416 {
417 	const char *cp;
418 	char buf[128];
419 	int protrusion;
420 
421 	cp = fmt_sockaddr(sa, mask, flags);
422 
423 	if (width < 0) {
424 		snprintf(buf, sizeof(buf), "{:%s/%%s} ", name);
425 		xo_emit(buf, cp);
426 		protrusion = 0;
427 	} else {
428 		if (Wflag != 0 || numeric_addr) {
429 			snprintf(buf, sizeof(buf), "{[:%d}{:%s/%%s}{]:} ",
430 			    -width, name);
431 			xo_emit(buf, cp);
432 			protrusion = strlen(cp) - width;
433 			if (protrusion < 0)
434 				protrusion = 0;
435 		} else {
436 			snprintf(buf, sizeof(buf), "{[:%d}{:%s/%%-.*s}{]:} ",
437 			    -width, name);
438 			xo_emit(buf, width, cp);
439 			protrusion = 0;
440 		}
441 	}
442 	return (protrusion);
443 }
444 
445 static const char *
446 fmt_sockaddr(struct sockaddr *sa, struct sockaddr *mask, int flags)
447 {
448 	static char buf[128];
449 	const char *cp;
450 
451 	if (sa == NULL)
452 		return ("null");
453 
454 	switch(sa->sa_family) {
455 #ifdef INET6
456 	case AF_INET6:
457 		/*
458 		 * The sa6->sin6_scope_id must be filled here because
459 		 * this sockaddr is extracted from kmem(4) directly
460 		 * and has KAME-specific embedded scope id in
461 		 * sa6->sin6_addr.s6_addr[2].
462 		 */
463 		in6_fillscopeid(satosin6(sa));
464 		/* FALLTHROUGH */
465 #endif /*INET6*/
466 	case AF_INET:
467 		if (flags & RTF_HOST)
468 			cp = routename(sa, numeric_addr);
469 		else if (mask)
470 			cp = netname(sa, mask);
471 		else
472 			cp = netname(sa, NULL);
473 		break;
474 	case AF_NETGRAPH:
475 	    {
476 		strlcpy(buf, ((struct sockaddr_ng *)sa)->sg_data,
477 		    sizeof(buf));
478 		cp = buf;
479 		break;
480 	    }
481 	case AF_LINK:
482 	    {
483 #if 0
484 		struct sockaddr_dl *sdl = (struct sockaddr_dl *)sa;
485 
486 		/* Interface route. */
487 		if (sdl->sdl_nlen)
488 			cp = sdl->sdl_data;
489 		else
490 #endif
491 			cp = routename(sa, 1);
492 		break;
493 	    }
494 	default:
495 	    {
496 		u_char *s = (u_char *)sa->sa_data, *slim;
497 		char *cq, *cqlim;
498 
499 		cq = buf;
500 		slim =  sa->sa_len + (u_char *) sa;
501 		cqlim = cq + sizeof(buf) - sizeof(" ffff");
502 		snprintf(cq, sizeof(buf), "(%d)", sa->sa_family);
503 		cq += strlen(cq);
504 		while (s < slim && cq < cqlim) {
505 			snprintf(cq, sizeof(" ff"), " %02x", *s++);
506 			cq += strlen(cq);
507 			if (s < slim) {
508 			    snprintf(cq, sizeof("ff"), "%02x", *s++);
509 			    cq += strlen(cq);
510 			}
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, size_t buflen, 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 		snprintf(dst, buflen, "&0x%lx", mask);
610 	else
611 		snprintf(dst, buflen, "/%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("&0xffffffff")];
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), sizeof(line) - strlen(line), 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 const u_char 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 	char maskbuf[sizeof("/xxx")];
716 	u_char *p, *lim;
717 	u_char masklen;
718 	int i;
719 	bool illegal = false;
720 
721 	if (mask) {
722 		p = (u_char *)&mask->sin6_addr;
723 		for (masklen = 0, lim = p + 16; p < lim; p++) {
724 			if (masktolen[*p] > 0) {
725 				/* -1 is required. */
726 				masklen += (masktolen[*p] - 1);
727 			} else
728 				illegal = true;
729 		}
730 		if (illegal)
731 			xo_error("illegal prefixlen\n");
732 
733 		memcpy(&addr, sa6, sizeof(addr));
734 		for (i = 0; i < 16; ++i)
735 			addr.sin6_addr.s6_addr[i] &=
736 			    mask->sin6_addr.s6_addr[i];
737 		sa6 = &addr;
738 	}
739 	else
740 		masklen = 128;
741 
742 	if (masklen == 0 && IN6_IS_ADDR_UNSPECIFIED(&sa6->sin6_addr))
743 		return("default");
744 
745 	getnameinfo((struct sockaddr *)sa6, sa6->sin6_len, nline, sizeof(nline),
746 	    NULL, 0, NI_NUMERICHOST);
747 	if (numeric_addr)
748 		strlcpy(line, nline, sizeof(line));
749 	else
750 		getnameinfo((struct sockaddr *)sa6, sa6->sin6_len, line,
751 		    sizeof(line), NULL, 0, 0);
752 	if (numeric_addr || strcmp(line, nline) == 0) {
753 		snprintf(maskbuf, sizeof(maskbuf), "/%d", masklen);
754 		strlcat(line, maskbuf, sizeof(line));
755 	}
756 
757 	return (line);
758 }
759 #endif /*INET6*/
760 
761 /*
762  * Print routing statistics
763  */
764 void
765 rt_stats(void)
766 {
767 	struct rtstat rtstat;
768 	u_long rtsaddr, rttaddr;
769 	int rttrash;
770 
771 	if ((rtsaddr = nl[N_RTSTAT].n_value) == 0) {
772 		xo_emit("{W:rtstat: symbol not in namelist}\n");
773 		return;
774 	}
775 	if ((rttaddr = nl[N_RTTRASH].n_value) == 0) {
776 		xo_emit("{W:rttrash: symbol not in namelist}\n");
777 		return;
778 	}
779 	kread_counters(rtsaddr, (char *)&rtstat, sizeof (rtstat));
780 	kread(rttaddr, (char *)&rttrash, sizeof (rttrash));
781 	xo_emit("{T:routing}:\n");
782 
783 #define	p(f, m) if (rtstat.f || sflag <= 1) \
784 	xo_emit(m, rtstat.f, plural(rtstat.f))
785 
786 	p(rts_badredirect, "\t{:bad-redirects/%ju} "
787 	    "{N:/bad routing redirect%s}\n");
788 	p(rts_dynamic, "\t{:dynamically-created/%ju} "
789 	    "{N:/dynamically created route%s}\n");
790 	p(rts_newgateway, "\t{:new-gateways/%ju} "
791 	    "{N:/new gateway%s due to redirects}\n");
792 	p(rts_unreach, "\t{:unreachable-destination/%ju} "
793 	    "{N:/destination%s found unreachable}\n");
794 	p(rts_wildcard, "\t{:wildcard-uses/%ju} "
795 	    "{N:/use%s of a wildcard route}\n");
796 #undef p
797 
798 	if (rttrash || sflag <= 1)
799 		xo_emit("\t{:unused-but-not-freed/%u} "
800 		    "{N:/route%s not in table but not freed}\n",
801 		    rttrash, plural(rttrash));
802 }
803