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