xref: /freebsd/usr.bin/netstat/route.c (revision 8c784bb8cf36911b828652f0bf7e88f443abec50)
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 static struct ifmap_entry *ifmap;
100 static size_t ifmap_size;
101 static struct timespec uptime;
102 
103 static const char *netname4(in_addr_t, in_addr_t);
104 #ifdef INET6
105 static const char *netname6(struct sockaddr_in6 *, struct sockaddr_in6 *);
106 #endif
107 static void p_rtable_sysctl(int, int);
108 static void p_rtentry_sysctl(const char *name, struct rt_msghdr *);
109 static void domask(char *, size_t, u_long);
110 
111 const uint32_t rt_default_weight = RT_DEFAULT_WEIGHT;
112 
113 /*
114  * Print routing tables.
115  */
116 void
117 routepr(int fibnum, int af)
118 {
119 	size_t intsize;
120 	int numfibs;
121 
122 	if (live == 0)
123 		return;
124 
125 	intsize = sizeof(int);
126 	if (fibnum == -1 &&
127 	    sysctlbyname("net.my_fibnum", &fibnum, &intsize, NULL, 0) == -1)
128 		fibnum = 0;
129 	if (sysctlbyname("net.fibs", &numfibs, &intsize, NULL, 0) == -1)
130 		numfibs = 1;
131 	if (fibnum < 0 || fibnum > numfibs - 1)
132 		errx(EX_USAGE, "%d: invalid fib", fibnum);
133 	/*
134 	 * Since kernel & userland use different timebase
135 	 * (time_uptime vs time_second) and we are reading kernel memory
136 	 * directly we should do rt_expire --> expire_time conversion.
137 	 */
138 	if (clock_gettime(CLOCK_UPTIME, &uptime) < 0)
139 		err(EX_OSERR, "clock_gettime() failed");
140 
141 	xo_open_container("route-information");
142 	xo_emit("{T:Routing tables}");
143 	if (fibnum)
144 		xo_emit(" ({L:fib}: {:fib/%d})", fibnum);
145 	xo_emit("\n");
146 	if (!p_rtable_netlink(fibnum, af))
147 		p_rtable_sysctl(fibnum, af);
148 	xo_close_container("route-information");
149 }
150 
151 
152 /*
153  * Print address family header before a section of the routing table.
154  */
155 void
156 pr_family(int af1)
157 {
158 	const char *afname;
159 
160 	switch (af1) {
161 	case AF_INET:
162 		afname = "Internet";
163 		break;
164 #ifdef INET6
165 	case AF_INET6:
166 		afname = "Internet6";
167 		break;
168 #endif /*INET6*/
169 	case AF_ISO:
170 		afname = "ISO";
171 		break;
172 	case AF_CCITT:
173 		afname = "X.25";
174 		break;
175 	case AF_NETGRAPH:
176 		afname = "Netgraph";
177 		break;
178 	default:
179 		afname = NULL;
180 		break;
181 	}
182 	if (afname)
183 		xo_emit("\n{k:address-family/%s}:\n", afname);
184 	else
185 		xo_emit("\n{L:Protocol Family} {k:address-family/%d}:\n", af1);
186 }
187 
188 /* column widths; each followed by one space */
189 #ifndef INET6
190 #define	WID_DST_DEFAULT(af) 	18	/* width of destination column */
191 #define	WID_GW_DEFAULT(af)	18	/* width of gateway column */
192 #define	WID_IF_DEFAULT(af)	(Wflag ? 10 : 8) /* width of netif column */
193 #else
194 #define	WID_DST_DEFAULT(af) \
195 	((af) == AF_INET6 ? (numeric_addr ? 33: 18) : 18)
196 #define	WID_GW_DEFAULT(af) \
197 	((af) == AF_INET6 ? (numeric_addr ? 29 : 18) : 18)
198 #define	WID_IF_DEFAULT(af)	((af) == AF_INET6 ? 8 : (Wflag ? 10 : 8))
199 #endif /*INET6*/
200 
201 struct _wid wid;
202 
203 /*
204  * Print header for routing table columns.
205  */
206 void
207 pr_rthdr(int af1 __unused)
208 {
209 
210 	if (Wflag) {
211 		xo_emit("{T:/%-*.*s} {T:/%-*.*s} {T:/%-*.*s} {T:/%*.*s} "
212 		    "{T:/%*.*s} {T:/%*.*s} {T:/%*s}\n",
213 			wid.dst,	wid.dst,	"Destination",
214 			wid.gw,		wid.gw,		"Gateway",
215 			wid.flags,	wid.flags,	"Flags",
216 			wid.mtu,	wid.mtu,	"Nhop#",
217 			wid.mtu,	wid.mtu,	"Mtu",
218 			wid.iface,	wid.iface,	"Netif",
219 			wid.expire,			"Expire");
220 	} else {
221 		xo_emit("{T:/%-*.*s} {T:/%-*.*s} {T:/%-*.*s} {T:/%*.*s} "
222 		    "{T:/%*s}\n",
223 			wid.dst,	wid.dst,	"Destination",
224 			wid.gw,		wid.gw,		"Gateway",
225 			wid.flags,	wid.flags,	"Flags",
226 			wid.iface,	wid.iface,	"Netif",
227 			wid.expire,			"Expire");
228 	}
229 }
230 
231 void
232 set_wid(int fam)
233 {
234 	wid.dst = WID_DST_DEFAULT(fam);
235 	wid.gw = WID_GW_DEFAULT(fam);
236 	wid.flags = 6;
237 	wid.pksent = 8;
238 	wid.mtu = 6;
239 	wid.iface = WID_IF_DEFAULT(fam);
240 	wid.expire = 6;
241 }
242 
243 static void
244 p_rtable_sysctl(int fibnum, int af)
245 {
246 	size_t needed;
247 	int mib[7];
248 	char *buf, *next, *lim;
249 	struct rt_msghdr *rtm;
250 	struct sockaddr *sa;
251 	int fam = AF_UNSPEC;
252 	int need_table_close = false;
253 
254 	ifmap = prepare_ifmap(&ifmap_size);
255 
256 	mib[0] = CTL_NET;
257 	mib[1] = PF_ROUTE;
258 	mib[2] = 0;
259 	mib[3] = af;
260 	mib[4] = NET_RT_DUMP;
261 	mib[5] = 0;
262 	mib[6] = fibnum;
263 	if (sysctl(mib, nitems(mib), NULL, &needed, NULL, 0) < 0)
264 		err(EX_OSERR, "sysctl: net.route.0.%d.dump.%d estimate", af,
265 		    fibnum);
266 	if ((buf = malloc(needed)) == NULL)
267 		errx(2, "malloc(%lu)", (unsigned long)needed);
268 	if (sysctl(mib, nitems(mib), buf, &needed, NULL, 0) < 0)
269 		err(1, "sysctl: net.route.0.%d.dump.%d", af, fibnum);
270 	lim  = buf + needed;
271 	xo_open_container("route-table");
272 	xo_open_list("rt-family");
273 	for (next = buf; next < lim; next += rtm->rtm_msglen) {
274 		rtm = (struct rt_msghdr *)next;
275 		if (rtm->rtm_version != RTM_VERSION)
276 			continue;
277 		/*
278 		 * Peek inside header to determine AF
279 		 */
280 		sa = (struct sockaddr *)(rtm + 1);
281 		/* Only print family first time. */
282 		if (fam != sa->sa_family) {
283 			if (need_table_close) {
284 				xo_close_list("rt-entry");
285 				xo_close_instance("rt-family");
286 			}
287 			need_table_close = true;
288 			fam = sa->sa_family;
289 			set_wid(fam);
290 			xo_open_instance("rt-family");
291 			pr_family(fam);
292 			xo_open_list("rt-entry");
293 
294 			pr_rthdr(fam);
295 		}
296 		p_rtentry_sysctl("rt-entry", rtm);
297 	}
298 	if (need_table_close) {
299 		xo_close_list("rt-entry");
300 		xo_close_instance("rt-family");
301 	}
302 	xo_close_list("rt-family");
303 	xo_close_container("route-table");
304 	free(buf);
305 }
306 
307 static void
308 p_rtentry_sysctl(const char *name, struct rt_msghdr *rtm)
309 {
310 	struct sockaddr *sa, *addr[RTAX_MAX];
311 	char buffer[128];
312 	char prettyname[128];
313 	int i, protrusion;
314 
315 	xo_open_instance(name);
316 	sa = (struct sockaddr *)(rtm + 1);
317 	for (i = 0; i < RTAX_MAX; i++) {
318 		if (rtm->rtm_addrs & (1 << i)) {
319 			addr[i] = sa;
320 			sa = (struct sockaddr *)((char *)sa + SA_SIZE(sa));
321 		}
322 	}
323 
324 	protrusion = p_sockaddr("destination", addr[RTAX_DST],
325 	    addr[RTAX_NETMASK],
326 	    rtm->rtm_flags, wid.dst);
327 	protrusion = p_sockaddr("gateway", addr[RTAX_GATEWAY], NULL, RTF_HOST,
328 	    wid.gw - protrusion);
329 	snprintf(buffer, sizeof(buffer), "{[:-%d}{:flags/%%s}{]:} ",
330 	    wid.flags - protrusion);
331 	p_flags(rtm->rtm_flags, buffer);
332 	/* Output path weight as non-visual property */
333 	xo_emit("{e:weight/%u}", rtm->rtm_rmx.rmx_weight);
334 	if (Wflag) {
335 		/* XXX: use=0? */
336 		xo_emit("{t:nhop/%*lu} ", wid.mtu, rtm->rtm_rmx.rmx_nhidx);
337 
338 		if (rtm->rtm_rmx.rmx_mtu != 0)
339 			xo_emit("{t:mtu/%*lu} ", wid.mtu, rtm->rtm_rmx.rmx_mtu);
340 		else
341 			xo_emit("{P:/%*s} ", wid.mtu, "");
342 	}
343 
344 	memset(prettyname, 0, sizeof(prettyname));
345 	if (rtm->rtm_index < ifmap_size) {
346 		strlcpy(prettyname, ifmap[rtm->rtm_index].ifname,
347 		    sizeof(prettyname));
348 		if (*prettyname == '\0')
349 			strlcpy(prettyname, "---", sizeof(prettyname));
350 	}
351 
352 	if (Wflag)
353 		xo_emit("{t:interface-name/%*s}", wid.iface, prettyname);
354 	else
355 		xo_emit("{t:interface-name/%*.*s}", wid.iface, wid.iface,
356 		    prettyname);
357 	if (rtm->rtm_rmx.rmx_expire) {
358 		time_t expire_time;
359 
360 		if ((expire_time = rtm->rtm_rmx.rmx_expire - uptime.tv_sec) > 0)
361 			xo_emit(" {:expire-time/%*d}", wid.expire,
362 			    (int)expire_time);
363 	}
364 
365 	xo_emit("\n");
366 	xo_close_instance(name);
367 }
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