xref: /freebsd/usr.bin/netstat/route.c (revision 68636dcb6fded1058318052454eabe35d1f65cb2)
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 
112 /*
113  * Print routing tables.
114  */
115 void
116 routepr(int fibnum, int af)
117 {
118 	size_t intsize;
119 	int numfibs;
120 
121 	if (live == 0)
122 		return;
123 
124 	intsize = sizeof(int);
125 	if (fibnum == -1 &&
126 	    sysctlbyname("net.my_fibnum", &fibnum, &intsize, NULL, 0) == -1)
127 		fibnum = 0;
128 	if (sysctlbyname("net.fibs", &numfibs, &intsize, NULL, 0) == -1)
129 		numfibs = 1;
130 	if (fibnum < 0 || fibnum > numfibs - 1)
131 		errx(EX_USAGE, "%d: invalid fib", fibnum);
132 	/*
133 	 * Since kernel & userland use different timebase
134 	 * (time_uptime vs time_second) and we are reading kernel memory
135 	 * directly we should do rt_expire --> expire_time conversion.
136 	 */
137 	if (clock_gettime(CLOCK_UPTIME, &uptime) < 0)
138 		err(EX_OSERR, "clock_gettime() failed");
139 
140 	xo_open_container("route-information");
141 	xo_emit("{T:Routing tables}");
142 	if (fibnum)
143 		xo_emit(" ({L:fib}: {:fib/%d})", fibnum);
144 	xo_emit("\n");
145 	if (!p_rtable_netlink(fibnum, af))
146 		p_rtable_sysctl(fibnum, af);
147 	xo_close_container("route-information");
148 }
149 
150 
151 /*
152  * Print address family header before a section of the routing table.
153  */
154 void
155 pr_family(int af1)
156 {
157 	const char *afname;
158 
159 	switch (af1) {
160 	case AF_INET:
161 		afname = "Internet";
162 		break;
163 #ifdef INET6
164 	case AF_INET6:
165 		afname = "Internet6";
166 		break;
167 #endif /*INET6*/
168 	case AF_ISO:
169 		afname = "ISO";
170 		break;
171 	case AF_CCITT:
172 		afname = "X.25";
173 		break;
174 	case AF_NETGRAPH:
175 		afname = "Netgraph";
176 		break;
177 	default:
178 		afname = NULL;
179 		break;
180 	}
181 	if (afname)
182 		xo_emit("\n{k:address-family/%s}:\n", afname);
183 	else
184 		xo_emit("\n{L:Protocol Family} {k:address-family/%d}:\n", af1);
185 }
186 
187 /* column widths; each followed by one space */
188 #ifndef INET6
189 #define	WID_DST_DEFAULT(af) 	18	/* width of destination column */
190 #define	WID_GW_DEFAULT(af)	18	/* width of gateway column */
191 #define	WID_IF_DEFAULT(af)	(Wflag ? 10 : 8) /* width of netif column */
192 #else
193 #define	WID_DST_DEFAULT(af) \
194 	((af) == AF_INET6 ? (numeric_addr ? 33: 18) : 18)
195 #define	WID_GW_DEFAULT(af) \
196 	((af) == AF_INET6 ? (numeric_addr ? 29 : 18) : 18)
197 #define	WID_IF_DEFAULT(af)	((af) == AF_INET6 ? 8 : (Wflag ? 10 : 8))
198 #endif /*INET6*/
199 
200 struct _wid wid;
201 
202 /*
203  * Print header for routing table columns.
204  */
205 void
206 pr_rthdr(int af1 __unused)
207 {
208 
209 	if (Wflag) {
210 		xo_emit("{T:/%-*.*s} {T:/%-*.*s} {T:/%-*.*s} {T:/%*.*s} "
211 		    "{T:/%*.*s} {T:/%*.*s} {T:/%*s}\n",
212 			wid.dst,	wid.dst,	"Destination",
213 			wid.gw,		wid.gw,		"Gateway",
214 			wid.flags,	wid.flags,	"Flags",
215 			wid.mtu,	wid.mtu,	"Nhop#",
216 			wid.mtu,	wid.mtu,	"Mtu",
217 			wid.iface,	wid.iface,	"Netif",
218 			wid.expire,			"Expire");
219 	} else {
220 		xo_emit("{T:/%-*.*s} {T:/%-*.*s} {T:/%-*.*s} {T:/%*.*s} "
221 		    "{T:/%*s}\n",
222 			wid.dst,	wid.dst,	"Destination",
223 			wid.gw,		wid.gw,		"Gateway",
224 			wid.flags,	wid.flags,	"Flags",
225 			wid.iface,	wid.iface,	"Netif",
226 			wid.expire,			"Expire");
227 	}
228 }
229 
230 void
231 set_wid(int fam)
232 {
233 	wid.dst = WID_DST_DEFAULT(fam);
234 	wid.gw = WID_GW_DEFAULT(fam);
235 	wid.flags = 6;
236 	wid.pksent = 8;
237 	wid.mtu = 6;
238 	wid.iface = WID_IF_DEFAULT(fam);
239 	wid.expire = 6;
240 }
241 
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 
368 int
369 p_sockaddr(const char *name, struct sockaddr *sa, struct sockaddr *mask,
370     int flags, int width)
371 {
372 	const char *cp;
373 	char buf[128];
374 	int protrusion;
375 
376 	cp = fmt_sockaddr(sa, mask, flags);
377 
378 	if (width < 0) {
379 		snprintf(buf, sizeof(buf), "{:%s/%%s} ", name);
380 		xo_emit(buf, cp);
381 		protrusion = 0;
382 	} else {
383 		if (Wflag != 0 || numeric_addr) {
384 			snprintf(buf, sizeof(buf), "{[:%d}{:%s/%%s}{]:} ",
385 			    -width, name);
386 			xo_emit(buf, cp);
387 			protrusion = strlen(cp) - width;
388 			if (protrusion < 0)
389 				protrusion = 0;
390 		} else {
391 			snprintf(buf, sizeof(buf), "{[:%d}{:%s/%%-.*s}{]:} ",
392 			    -width, name);
393 			xo_emit(buf, width, cp);
394 			protrusion = 0;
395 		}
396 	}
397 	return (protrusion);
398 }
399 
400 const char *
401 fmt_sockaddr(struct sockaddr *sa, struct sockaddr *mask, int flags)
402 {
403 	static char buf[128];
404 	const char *cp;
405 
406 	if (sa == NULL)
407 		return ("null");
408 
409 	switch(sa->sa_family) {
410 #ifdef INET6
411 	case AF_INET6:
412 		/*
413 		 * The sa6->sin6_scope_id must be filled here because
414 		 * this sockaddr is extracted from kmem(4) directly
415 		 * and has KAME-specific embedded scope id in
416 		 * sa6->sin6_addr.s6_addr[2].
417 		 */
418 		in6_fillscopeid(satosin6(sa));
419 		/* FALLTHROUGH */
420 #endif /*INET6*/
421 	case AF_INET:
422 		if (flags & RTF_HOST)
423 			cp = routename(sa, numeric_addr);
424 		else if (mask)
425 			cp = netname(sa, mask);
426 		else
427 			cp = netname(sa, NULL);
428 		break;
429 	case AF_NETGRAPH:
430 	    {
431 		strlcpy(buf, ((struct sockaddr_ng *)sa)->sg_data,
432 		    sizeof(buf));
433 		cp = buf;
434 		break;
435 	    }
436 	case AF_LINK:
437 	    {
438 #if 0
439 		struct sockaddr_dl *sdl = (struct sockaddr_dl *)sa;
440 
441 		/* Interface route. */
442 		if (sdl->sdl_nlen)
443 			cp = sdl->sdl_data;
444 		else
445 #endif
446 			cp = routename(sa, 1);
447 		break;
448 	    }
449 	default:
450 	    {
451 		u_char *s = (u_char *)sa->sa_data, *slim;
452 		char *cq, *cqlim;
453 
454 		cq = buf;
455 		slim =  sa->sa_len + (u_char *) sa;
456 		cqlim = cq + sizeof(buf) - sizeof(" ffff");
457 		snprintf(cq, sizeof(buf), "(%d)", sa->sa_family);
458 		cq += strlen(cq);
459 		while (s < slim && cq < cqlim) {
460 			snprintf(cq, sizeof(" ff"), " %02x", *s++);
461 			cq += strlen(cq);
462 			if (s < slim) {
463 			    snprintf(cq, sizeof("ff"), "%02x", *s++);
464 			    cq += strlen(cq);
465 			}
466 		}
467 		cp = buf;
468 	    }
469 	}
470 
471 	return (cp);
472 }
473 
474 void
475 p_flags(int f, const char *format)
476 {
477 
478 	print_flags_generic(f, rt_bits, format, "flags_pretty");
479 }
480 
481 
482 char *
483 routename(struct sockaddr *sa, int flags)
484 {
485 	static char line[NI_MAXHOST];
486 	int error, f;
487 
488 	f = (flags) ? NI_NUMERICHOST : 0;
489 	error = getnameinfo(sa, sa->sa_len, line, sizeof(line),
490 	    NULL, 0, f);
491 	if (error) {
492 		const void *src;
493 		switch (sa->sa_family) {
494 #ifdef INET
495 		case AF_INET:
496 			src = &satosin(sa)->sin_addr;
497 			break;
498 #endif /* INET */
499 #ifdef INET6
500 		case AF_INET6:
501 			src = &satosin6(sa)->sin6_addr;
502 			break;
503 #endif /* INET6 */
504 		default:
505 			return(line);
506 		}
507 		inet_ntop(sa->sa_family, src, line, sizeof(line) - 1);
508 		return (line);
509 	}
510 	trimdomain(line, strlen(line));
511 
512 	return (line);
513 }
514 
515 #define	NSHIFT(m) (							\
516 	(m) == IN_CLASSA_NET ? IN_CLASSA_NSHIFT :			\
517 	(m) == IN_CLASSB_NET ? IN_CLASSB_NSHIFT :			\
518 	(m) == IN_CLASSC_NET ? IN_CLASSC_NSHIFT :			\
519 	0)
520 
521 static void
522 domask(char *dst, size_t buflen, u_long mask)
523 {
524 	int b, i;
525 
526 	if (mask == 0) {
527 		*dst = '\0';
528 		return;
529 	}
530 	i = 0;
531 	for (b = 0; b < 32; b++)
532 		if (mask & (1 << b)) {
533 			int bb;
534 
535 			i = b;
536 			for (bb = b+1; bb < 32; bb++)
537 				if (!(mask & (1 << bb))) {
538 					i = -1;	/* noncontig */
539 					break;
540 				}
541 			break;
542 		}
543 	if (i == -1)
544 		snprintf(dst, buflen, "&0x%lx", mask);
545 	else
546 		snprintf(dst, buflen, "/%d", 32-i);
547 }
548 
549 /*
550  * Return the name of the network whose address is given.
551  */
552 const char *
553 netname(struct sockaddr *sa, struct sockaddr *mask)
554 {
555 	switch (sa->sa_family) {
556 	case AF_INET:
557 		if (mask != NULL)
558 			return (netname4(satosin(sa)->sin_addr.s_addr,
559 			    satosin(mask)->sin_addr.s_addr));
560 		else
561 			return (netname4(satosin(sa)->sin_addr.s_addr,
562 			    INADDR_ANY));
563 		break;
564 #ifdef INET6
565 	case AF_INET6:
566 		return (netname6(satosin6(sa), satosin6(mask)));
567 #endif /* INET6 */
568 	default:
569 		return (NULL);
570 	}
571 }
572 
573 static const char *
574 netname4(in_addr_t in, in_addr_t mask)
575 {
576 	char *cp = 0;
577 	static char line[MAXHOSTNAMELEN + sizeof("&0xffffffff")];
578 	char nline[INET_ADDRSTRLEN];
579 	struct netent *np = 0;
580 	in_addr_t i;
581 
582 	if (in == INADDR_ANY && mask == 0) {
583 		strlcpy(line, "default", sizeof(line));
584 		return (line);
585 	}
586 
587 	/* It is ok to supply host address. */
588 	in &= mask;
589 
590 	i = ntohl(in);
591 	if (!numeric_addr && i) {
592 		np = getnetbyaddr(i >> NSHIFT(ntohl(mask)), AF_INET);
593 		if (np != NULL) {
594 			cp = np->n_name;
595 			trimdomain(cp, strlen(cp));
596 		}
597 	}
598 	if (cp != NULL)
599 		strlcpy(line, cp, sizeof(line));
600 	else {
601 		inet_ntop(AF_INET, &in, nline, sizeof(nline));
602 		strlcpy(line, nline, sizeof(line));
603 		domask(line + strlen(line), sizeof(line) - strlen(line), ntohl(mask));
604 	}
605 
606 	return (line);
607 }
608 
609 #undef NSHIFT
610 
611 #ifdef INET6
612 void
613 in6_fillscopeid(struct sockaddr_in6 *sa6)
614 {
615 #if defined(__KAME__)
616 	/*
617 	 * XXX: This is a special workaround for KAME kernels.
618 	 * sin6_scope_id field of SA should be set in the future.
619 	 */
620 	if (IN6_IS_ADDR_LINKLOCAL(&sa6->sin6_addr) ||
621 	    IN6_IS_ADDR_MC_NODELOCAL(&sa6->sin6_addr) ||
622 	    IN6_IS_ADDR_MC_LINKLOCAL(&sa6->sin6_addr)) {
623 		if (sa6->sin6_scope_id == 0)
624 			sa6->sin6_scope_id =
625 			    ntohs(*(u_int16_t *)&sa6->sin6_addr.s6_addr[2]);
626 		sa6->sin6_addr.s6_addr[2] = sa6->sin6_addr.s6_addr[3] = 0;
627 	}
628 #endif
629 }
630 
631 /* Mask to length table.  To check an invalid value, (length + 1) is used. */
632 static const u_char masktolen[256] = {
633 	[0xff] = 8 + 1,
634 	[0xfe] = 7 + 1,
635 	[0xfc] = 6 + 1,
636 	[0xf8] = 5 + 1,
637 	[0xf0] = 4 + 1,
638 	[0xe0] = 3 + 1,
639 	[0xc0] = 2 + 1,
640 	[0x80] = 1 + 1,
641 	[0x00] = 0 + 1,
642 };
643 
644 static const char *
645 netname6(struct sockaddr_in6 *sa6, struct sockaddr_in6 *mask)
646 {
647 	static char line[NI_MAXHOST + sizeof("/xxx") - 1];
648 	struct sockaddr_in6 addr;
649 	char nline[NI_MAXHOST];
650 	char maskbuf[sizeof("/xxx")];
651 	u_char *p, *lim;
652 	u_char masklen;
653 	int i;
654 	bool illegal = false;
655 
656 	if (mask) {
657 		p = (u_char *)&mask->sin6_addr;
658 		for (masklen = 0, lim = p + 16; p < lim; p++) {
659 			if (masktolen[*p] > 0) {
660 				/* -1 is required. */
661 				masklen += (masktolen[*p] - 1);
662 			} else
663 				illegal = true;
664 		}
665 		if (illegal)
666 			xo_error("illegal prefixlen\n");
667 
668 		memcpy(&addr, sa6, sizeof(addr));
669 		for (i = 0; i < 16; ++i)
670 			addr.sin6_addr.s6_addr[i] &=
671 			    mask->sin6_addr.s6_addr[i];
672 		sa6 = &addr;
673 	}
674 	else
675 		masklen = 128;
676 
677 	if (masklen == 0 && 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 	u_long rtsaddr;
704 
705 	if ((rtsaddr = nl[N_RTSTAT].n_value) == 0) {
706 		xo_emit("{W:rtstat: symbol not in namelist}\n");
707 		return;
708 	}
709 	kread_counters(rtsaddr, (char *)&rtstat, sizeof (rtstat));
710 	xo_emit("{T:routing}:\n");
711 
712 #define	p(f, m) if (rtstat.f || sflag <= 1) \
713 	xo_emit(m, rtstat.f, plural(rtstat.f))
714 
715 	p(rts_badredirect, "\t{:bad-redirects/%ju} "
716 	    "{N:/bad routing redirect%s}\n");
717 	p(rts_dynamic, "\t{:dynamically-created/%ju} "
718 	    "{N:/dynamically created route%s}\n");
719 	p(rts_newgateway, "\t{:new-gateways/%ju} "
720 	    "{N:/new gateway%s due to redirects}\n");
721 	p(rts_unreach, "\t{:unreachable-destination/%ju} "
722 	    "{N:/destination%s found unreachable}\n");
723 	p(rts_wildcard, "\t{:wildcard-uses/%ju} "
724 	    "{N:/use%s of a wildcard route}\n");
725 #undef p
726 }
727