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