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