xref: /freebsd/usr.bin/netstat/route.c (revision 1f03c62e43a02ec705b9998f37edde0258c442e9)
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
routepr(int fibnum,int af)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
pr_family(int af1)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
pr_rthdr(int af1 __unused)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} {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.metric,	wid.metric,	"Metric",
216 			wid.expire,			"Expire");
217 	} else {
218 		xo_emit("{T:/%-*.*s} {T:/%-*.*s} {T:/%-*.*s} {T:/%*.*s} "
219 		    "{T:/%*s}\n",
220 			wid.dst,	wid.dst,	"Destination",
221 			wid.gw,		wid.gw,		"Gateway",
222 			wid.flags,	wid.flags,	"Flags",
223 			wid.iface,	wid.iface,	"Netif",
224 			wid.expire,			"Expire");
225 	}
226 }
227 
228 void
set_wid(int fam)229 set_wid(int fam)
230 {
231 	wid.dst = WID_DST_DEFAULT(fam);
232 	wid.gw = WID_GW_DEFAULT(fam);
233 	wid.flags = 6;
234 	wid.pksent = 8;
235 	wid.mtu = 6;
236 	wid.iface = WID_IF_DEFAULT;
237 	wid.metric = 8;
238 	wid.expire = 6;
239 }
240 
241 #ifdef WITHOUT_NETLINK
242 static void
p_rtable_sysctl(int fibnum,int af)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 		xo_err(EX_OSERR, "sysctl: net.route.0.%d.dump.%d estimate", af,
264 		    fibnum);
265 	if ((buf = malloc(needed)) == NULL)
266 		xo_errx(EX_OSERR, "malloc(%lu)", (unsigned long)needed);
267 	if (sysctl(mib, nitems(mib), buf, &needed, NULL, 0) < 0)
268 		xo_err(EX_OSERR, "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
p_rtentry_sysctl(const char * name,struct rt_msghdr * rtm)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 and metric as non-visual property */
332 	xo_emit("{e:weight/%u}", rtm->rtm_rmx.rmx_weight);
333 	xo_emit("{e:metric/%lu}", rtm->rtm_rmx.rmx_metric);
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 		xo_emit("{t:metric/%*lu} ", wid.metric, rtm->rtm_rmx.rmx_metric);
355 	} else
356 		xo_emit("{t:interface-name/%*.*s}", wid.iface, wid.iface,
357 		    prettyname);
358 	if (rtm->rtm_rmx.rmx_expire) {
359 		time_t expire_time;
360 
361 		if ((expire_time = rtm->rtm_rmx.rmx_expire - uptime.tv_sec) > 0)
362 			xo_emit(" {:expire-time/%*d}", wid.expire,
363 			    (int)expire_time);
364 	}
365 
366 	xo_emit("\n");
367 	xo_close_instance(name);
368 }
369 #endif
370 
371 int
p_sockaddr(const char * name,struct sockaddr * sa,struct sockaddr * mask,int flags,int width)372 p_sockaddr(const char *name, struct sockaddr *sa, struct sockaddr *mask,
373     int flags, int width)
374 {
375 	const char *cp;
376 	char buf[128];
377 	int protrusion;
378 
379 	cp = fmt_sockaddr(sa, mask, flags);
380 
381 	if (width < 0) {
382 		snprintf(buf, sizeof(buf), "{:%s/%%s} ", name);
383 		xo_emit(buf, cp);
384 		protrusion = 0;
385 	} else {
386 		if (Wflag != 0 || numeric_addr) {
387 			snprintf(buf, sizeof(buf), "{[:%d}{:%s/%%s}{]:} ",
388 			    -width, name);
389 			xo_emit(buf, cp);
390 			protrusion = strlen(cp) - width;
391 			if (protrusion < 0)
392 				protrusion = 0;
393 		} else {
394 			snprintf(buf, sizeof(buf), "{[:%d}{:%s/%%-.*s}{]:} ",
395 			    -width, name);
396 			xo_emit(buf, width, cp);
397 			protrusion = 0;
398 		}
399 	}
400 	return (protrusion);
401 }
402 
403 const char *
fmt_sockaddr(struct sockaddr * sa,struct sockaddr * mask,int flags)404 fmt_sockaddr(struct sockaddr *sa, struct sockaddr *mask, int flags)
405 {
406 	static char buf[128];
407 	const char *cp;
408 
409 	if (sa == NULL)
410 		return ("null");
411 
412 	switch(sa->sa_family) {
413 #ifdef INET6
414 	case AF_INET6:
415 		/*
416 		 * The sa6->sin6_scope_id must be filled here because
417 		 * this sockaddr is extracted from kmem(4) directly
418 		 * and has KAME-specific embedded scope id in
419 		 * sa6->sin6_addr.s6_addr[2].
420 		 */
421 		in6_fillscopeid(satosin6(sa));
422 		/* FALLTHROUGH */
423 #endif /*INET6*/
424 	case AF_INET:
425 		if (flags & RTF_HOST)
426 			cp = routename(sa, numeric_addr);
427 		else if (mask)
428 			cp = netname(sa, mask);
429 		else
430 			cp = netname(sa, NULL);
431 		break;
432 	case AF_NETGRAPH:
433 	    {
434 		strlcpy(buf, ((struct sockaddr_ng *)sa)->sg_data,
435 		    sizeof(buf));
436 		cp = buf;
437 		break;
438 	    }
439 	case AF_LINK:
440 	    {
441 #if 0
442 		struct sockaddr_dl *sdl = (struct sockaddr_dl *)sa;
443 
444 		/* Interface route. */
445 		if (sdl->sdl_nlen)
446 			cp = sdl->sdl_data;
447 		else
448 #endif
449 			cp = routename(sa, 1);
450 		break;
451 	    }
452 	default:
453 	    {
454 		u_char *s = (u_char *)sa->sa_data, *slim;
455 		char *cq, *cqlim;
456 
457 		cq = buf;
458 		slim =  sa->sa_len + (u_char *) sa;
459 		cqlim = cq + sizeof(buf) - sizeof(" ffff");
460 		snprintf(cq, sizeof(buf), "(%d)", sa->sa_family);
461 		cq += strlen(cq);
462 		while (s < slim && cq < cqlim) {
463 			snprintf(cq, sizeof(" ff"), " %02x", *s++);
464 			cq += strlen(cq);
465 			if (s < slim) {
466 			    snprintf(cq, sizeof("ff"), "%02x", *s++);
467 			    cq += strlen(cq);
468 			}
469 		}
470 		cp = buf;
471 	    }
472 	}
473 
474 	return (cp);
475 }
476 
477 void
p_flags(int f,const char * format)478 p_flags(int f, const char *format)
479 {
480 
481 	print_flags_generic(f, rt_bits, format, "flags_pretty");
482 }
483 
484 
485 char *
routename(struct sockaddr * sa,int flags)486 routename(struct sockaddr *sa, int flags)
487 {
488 	static char line[NI_MAXHOST];
489 	int error, f;
490 
491 	f = (flags) ? NI_NUMERICHOST : 0;
492 	error = getnameinfo(sa, sa->sa_len, line, sizeof(line),
493 	    NULL, 0, f);
494 	if (error) {
495 		const void *src;
496 		switch (sa->sa_family) {
497 #ifdef INET
498 		case AF_INET:
499 			src = &satosin(sa)->sin_addr;
500 			break;
501 #endif /* INET */
502 #ifdef INET6
503 		case AF_INET6:
504 			src = &satosin6(sa)->sin6_addr;
505 			break;
506 #endif /* INET6 */
507 		default:
508 			return(line);
509 		}
510 		inet_ntop(sa->sa_family, src, line, sizeof(line) - 1);
511 		return (line);
512 	}
513 	trimdomain(line, strlen(line));
514 
515 	return (line);
516 }
517 
518 #define	NSHIFT(m) (							\
519 	(m) == IN_CLASSA_NET ? IN_CLASSA_NSHIFT :			\
520 	(m) == IN_CLASSB_NET ? IN_CLASSB_NSHIFT :			\
521 	(m) == IN_CLASSC_NET ? IN_CLASSC_NSHIFT :			\
522 	0)
523 
524 static void
domask(char * dst,size_t buflen,u_long mask)525 domask(char *dst, size_t buflen, u_long mask)
526 {
527 	int b, i;
528 
529 	if (mask == 0) {
530 		*dst = '\0';
531 		return;
532 	}
533 	i = 0;
534 	for (b = 0; b < 32; b++)
535 		if (mask & (1 << b)) {
536 			int bb;
537 
538 			i = b;
539 			for (bb = b+1; bb < 32; bb++)
540 				if (!(mask & (1 << bb))) {
541 					i = -1;	/* noncontig */
542 					break;
543 				}
544 			break;
545 		}
546 	if (i == -1)
547 		snprintf(dst, buflen, "&0x%lx", mask);
548 	else
549 		snprintf(dst, buflen, "/%d", 32-i);
550 }
551 
552 /*
553  * Return the name of the network whose address is given.
554  */
555 const char *
netname(struct sockaddr * sa,struct sockaddr * mask)556 netname(struct sockaddr *sa, struct sockaddr *mask)
557 {
558 	switch (sa->sa_family) {
559 	case AF_INET:
560 		if (mask != NULL)
561 			return (netname4(satosin(sa)->sin_addr.s_addr,
562 			    satosin(mask)->sin_addr.s_addr));
563 		else
564 			return (netname4(satosin(sa)->sin_addr.s_addr,
565 			    INADDR_ANY));
566 		break;
567 #ifdef INET6
568 	case AF_INET6:
569 		return (netname6(satosin6(sa), satosin6(mask)));
570 #endif /* INET6 */
571 	default:
572 		return (NULL);
573 	}
574 }
575 
576 static const char *
netname4(in_addr_t in,in_addr_t mask)577 netname4(in_addr_t in, in_addr_t mask)
578 {
579 	char *cp = 0;
580 	static char line[MAXHOSTNAMELEN + sizeof("&0xffffffff")];
581 	char nline[INET_ADDRSTRLEN];
582 	struct netent *np = 0;
583 	in_addr_t i;
584 
585 	if (numeric_addr < 2 && in == INADDR_ANY && mask == 0) {
586 		strlcpy(line, "default", sizeof(line));
587 		return (line);
588 	}
589 
590 	/* It is ok to supply host address. */
591 	in &= mask;
592 
593 	i = ntohl(in);
594 	if (!numeric_addr && i) {
595 		np = getnetbyaddr(i >> NSHIFT(ntohl(mask)), AF_INET);
596 		if (np != NULL) {
597 			cp = np->n_name;
598 			trimdomain(cp, strlen(cp));
599 		}
600 	}
601 	if (cp != NULL)
602 		strlcpy(line, cp, sizeof(line));
603 	else {
604 		inet_ntop(AF_INET, &in, nline, sizeof(nline));
605 		strlcpy(line, nline, sizeof(line));
606 		domask(line + strlen(line), sizeof(line) - strlen(line), ntohl(mask));
607 	}
608 
609 	return (line);
610 }
611 
612 #undef NSHIFT
613 
614 #ifdef INET6
615 void
in6_fillscopeid(struct sockaddr_in6 * sa6)616 in6_fillscopeid(struct sockaddr_in6 *sa6)
617 {
618 #if defined(__KAME__)
619 	/*
620 	 * XXX: This is a special workaround for KAME kernels.
621 	 * sin6_scope_id field of SA should be set in the future.
622 	 */
623 	if (IN6_IS_ADDR_LINKLOCAL(&sa6->sin6_addr) ||
624 	    IN6_IS_ADDR_MC_NODELOCAL(&sa6->sin6_addr) ||
625 	    IN6_IS_ADDR_MC_LINKLOCAL(&sa6->sin6_addr)) {
626 		if (sa6->sin6_scope_id == 0)
627 			sa6->sin6_scope_id =
628 			    ntohs(*(u_int16_t *)&sa6->sin6_addr.s6_addr[2]);
629 		sa6->sin6_addr.s6_addr[2] = sa6->sin6_addr.s6_addr[3] = 0;
630 	}
631 #endif
632 }
633 
634 /* Mask to length table.  To check an invalid value, (length + 1) is used. */
635 static const u_char masktolen[256] = {
636 	[0xff] = 8 + 1,
637 	[0xfe] = 7 + 1,
638 	[0xfc] = 6 + 1,
639 	[0xf8] = 5 + 1,
640 	[0xf0] = 4 + 1,
641 	[0xe0] = 3 + 1,
642 	[0xc0] = 2 + 1,
643 	[0x80] = 1 + 1,
644 	[0x00] = 0 + 1,
645 };
646 
647 static const char *
netname6(struct sockaddr_in6 * sa6,struct sockaddr_in6 * mask)648 netname6(struct sockaddr_in6 *sa6, struct sockaddr_in6 *mask)
649 {
650 	static char line[NI_MAXHOST + sizeof("/xxx") - 1];
651 	struct sockaddr_in6 addr;
652 	char nline[NI_MAXHOST];
653 	char maskbuf[sizeof("/xxx")];
654 	u_char *p, *lim;
655 	u_char masklen;
656 	int i;
657 	bool illegal = false;
658 
659 	if (mask) {
660 		p = (u_char *)&mask->sin6_addr;
661 		for (masklen = 0, lim = p + 16; p < lim; p++) {
662 			if (masktolen[*p] > 0) {
663 				/* -1 is required. */
664 				masklen += (masktolen[*p] - 1);
665 			} else
666 				illegal = true;
667 		}
668 		if (illegal)
669 			xo_error("illegal prefixlen\n");
670 
671 		memcpy(&addr, sa6, sizeof(addr));
672 		for (i = 0; i < 16; ++i)
673 			addr.sin6_addr.s6_addr[i] &=
674 			    mask->sin6_addr.s6_addr[i];
675 		sa6 = &addr;
676 	}
677 	else
678 		masklen = 128;
679 
680 	if (numeric_addr < 2 && masklen == 0 &&
681 	    IN6_IS_ADDR_UNSPECIFIED(&sa6->sin6_addr))
682 		return("default");
683 
684 	getnameinfo((struct sockaddr *)sa6, sa6->sin6_len, nline, sizeof(nline),
685 	    NULL, 0, NI_NUMERICHOST);
686 	if (numeric_addr)
687 		strlcpy(line, nline, sizeof(line));
688 	else
689 		getnameinfo((struct sockaddr *)sa6, sa6->sin6_len, line,
690 		    sizeof(line), NULL, 0, 0);
691 	if (numeric_addr || strcmp(line, nline) == 0) {
692 		snprintf(maskbuf, sizeof(maskbuf), "/%d", masklen);
693 		strlcat(line, maskbuf, sizeof(line));
694 	}
695 
696 	return (line);
697 }
698 #endif /*INET6*/
699 
700 /*
701  * Print routing statistics
702  */
703 void
rt_stats(void)704 rt_stats(void)
705 {
706 	struct rtstat rtstat;
707 
708 	if (fetch_stats("net.route.stats", nl[N_RTSTAT].n_value, &rtstat,
709 	    sizeof(rtstat), kread_counters) != 0)
710 		return;
711 
712 	xo_emit("{T:routing}:\n");
713 
714 #define	p(f, m) if (rtstat.f || sflag <= 1) \
715 	xo_emit(m, rtstat.f, plural(rtstat.f))
716 
717 	p(rts_badredirect, "\t{:bad-redirects/%ju} "
718 	    "{N:/bad routing redirect%s}\n");
719 	p(rts_dynamic, "\t{:dynamically-created/%ju} "
720 	    "{N:/dynamically created route%s}\n");
721 	p(rts_newgateway, "\t{:new-gateways/%ju} "
722 	    "{N:/new gateway%s due to redirects}\n");
723 	p(rts_unreach, "\t{:unreachable-destination/%ju} "
724 	    "{N:/destination%s found unreachable}\n");
725 	p(rts_wildcard, "\t{:wildcard-uses/%ju} "
726 	    "{N:/use%s of a wildcard route}\n");
727 #undef p
728 }
729