xref: /freebsd/usr.bin/netstat/route.c (revision dda5b39711dab90ae1c5624bdd6ff7453177df31)
1 /*-
2  * Copyright (c) 1983, 1988, 1993
3  *	The Regents of the University of California.  All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 4. Neither the name of the University nor the names of its contributors
14  *    may be used to endorse or promote products derived from this software
15  *    without specific prior written permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  */
29 
30 #if 0
31 #ifndef lint
32 static char sccsid[] = "From: @(#)route.c	8.6 (Berkeley) 4/28/95";
33 #endif /* not lint */
34 #endif
35 
36 #include <sys/cdefs.h>
37 __FBSDID("$FreeBSD$");
38 
39 #include <sys/param.h>
40 #include <sys/protosw.h>
41 #include <sys/socket.h>
42 #include <sys/socketvar.h>
43 #include <sys/time.h>
44 
45 #include <net/ethernet.h>
46 #include <net/if.h>
47 #include <net/if_var.h>
48 #include <net/if_dl.h>
49 #include <net/if_types.h>
50 #include <net/radix.h>
51 #define	_WANT_RTENTRY
52 #include <net/route.h>
53 
54 #include <netinet/in.h>
55 #include <netatalk/at.h>
56 #include <netgraph/ng_socket.h>
57 
58 #include <sys/sysctl.h>
59 
60 #include <arpa/inet.h>
61 #include <ifaddrs.h>
62 #include <libutil.h>
63 #include <netdb.h>
64 #include <nlist.h>
65 #include <stdint.h>
66 #include <stdio.h>
67 #include <stdlib.h>
68 #include <string.h>
69 #include <sysexits.h>
70 #include <unistd.h>
71 #include <err.h>
72 #include "netstat.h"
73 
74 #define	kget(p, d) (kread((u_long)(p), (char *)&(d), sizeof (d)))
75 
76 /*
77  * Definitions for showing gateway flags.
78  */
79 struct bits {
80 	u_long	b_mask;
81 	char	b_val;
82 } bits[] = {
83 	{ RTF_UP,	'U' },
84 	{ RTF_GATEWAY,	'G' },
85 	{ RTF_HOST,	'H' },
86 	{ RTF_REJECT,	'R' },
87 	{ RTF_DYNAMIC,	'D' },
88 	{ RTF_MODIFIED,	'M' },
89 	{ RTF_DONE,	'd' }, /* Completed -- for routing messages only */
90 	{ RTF_XRESOLVE,	'X' },
91 	{ RTF_STATIC,	'S' },
92 	{ RTF_PROTO1,	'1' },
93 	{ RTF_PROTO2,	'2' },
94 	{ RTF_PRCLONING,'c' },
95 	{ RTF_PROTO3,	'3' },
96 	{ RTF_BLACKHOLE,'B' },
97 	{ RTF_BROADCAST,'b' },
98 #ifdef RTF_LLINFO
99 	{ RTF_LLINFO,	'L' },
100 #endif
101 #ifdef RTF_WASCLONED
102 	{ RTF_WASCLONED,'W' },
103 #endif
104 #ifdef RTF_CLONING
105 	{ RTF_CLONING,	'C' },
106 #endif
107 	{ 0 , 0 }
108 };
109 
110 /*
111  * kvm(3) bindings for every needed symbol
112  */
113 static struct nlist rl[] = {
114 #define	N_RTSTAT	0
115 	{ .n_name = "_rtstat" },
116 #define	N_RTREE		1
117 	{ .n_name = "_rt_tables"},
118 #define	N_RTTRASH	2
119 	{ .n_name = "_rttrash" },
120 	{ .n_name = NULL },
121 };
122 
123 typedef union {
124 	long	dummy;		/* Helps align structure. */
125 	struct	sockaddr u_sa;
126 	u_short	u_data[128];
127 } sa_u;
128 
129 static sa_u pt_u;
130 
131 struct ifmap_entry {
132 	char ifname[IFNAMSIZ];
133 };
134 
135 static struct ifmap_entry *ifmap;
136 static int ifmap_size;
137 
138 int	do_rtent = 0;
139 struct	rtentry rtentry;
140 struct	radix_node rnode;
141 struct	radix_mask rmask;
142 
143 int	NewTree = 1;
144 
145 struct	timespec uptime;
146 
147 static struct sockaddr *kgetsa(struct sockaddr *);
148 static void size_cols(int ef, struct radix_node *rn);
149 static void size_cols_tree(struct radix_node *rn);
150 static void size_cols_rtentry(struct rtentry *rt);
151 static void p_rtnode_kvm(void);
152 static void p_rtable_sysctl(int, int);
153 static void p_rtable_kvm(int, int );
154 static void p_rtree_kvm(struct radix_node *);
155 static void p_rtentry_sysctl(struct rt_msghdr *);
156 static void p_sockaddr(struct sockaddr *, struct sockaddr *, int, int);
157 static const char *fmt_sockaddr(struct sockaddr *sa, struct sockaddr *mask,
158     int flags);
159 static void p_flags(int, const char *);
160 static const char *fmt_flags(int f);
161 static void p_rtentry_kvm(struct rtentry *);
162 static void domask(char *, in_addr_t, u_long);
163 
164 /*
165  * Print routing tables.
166  */
167 void
168 routepr(int fibnum, int af)
169 {
170 	size_t intsize;
171 	int numfibs;
172 
173 	intsize = sizeof(int);
174 	if (fibnum == -1 &&
175 	    sysctlbyname("net.my_fibnum", &fibnum, &intsize, NULL, 0) == -1)
176 		fibnum = 0;
177 	if (sysctlbyname("net.fibs", &numfibs, &intsize, NULL, 0) == -1)
178 		numfibs = 1;
179 	if (fibnum < 0 || fibnum > numfibs - 1)
180 		errx(EX_USAGE, "%d: invalid fib", fibnum);
181 	/*
182 	 * Since kernel & userland use different timebase
183 	 * (time_uptime vs time_second) and we are reading kernel memory
184 	 * directly we should do rt_expire --> expire_time conversion.
185 	 */
186 	if (clock_gettime(CLOCK_UPTIME, &uptime) < 0)
187 		err(EX_OSERR, "clock_gettime() failed");
188 
189 	printf("Routing tables");
190 	if (fibnum)
191 		printf(" (fib: %d)", fibnum);
192 	printf("\n");
193 
194 	if (Aflag == 0 && live != 0 && NewTree)
195 		p_rtable_sysctl(fibnum, af);
196 	else
197 		p_rtable_kvm(fibnum, af);
198 }
199 
200 
201 /*
202  * Print address family header before a section of the routing table.
203  */
204 void
205 pr_family(int af1)
206 {
207 	const char *afname;
208 
209 	switch (af1) {
210 	case AF_INET:
211 		afname = "Internet";
212 		break;
213 #ifdef INET6
214 	case AF_INET6:
215 		afname = "Internet6";
216 		break;
217 #endif /*INET6*/
218 	case AF_ISO:
219 		afname = "ISO";
220 		break;
221 	case AF_APPLETALK:
222 		afname = "AppleTalk";
223 		break;
224 	case AF_CCITT:
225 		afname = "X.25";
226 		break;
227 	case AF_NETGRAPH:
228 		afname = "Netgraph";
229 		break;
230 	default:
231 		afname = NULL;
232 		break;
233 	}
234 	if (afname)
235 		printf("\n%s:\n", afname);
236 	else
237 		printf("\nProtocol Family %d:\n", af1);
238 }
239 
240 /* column widths; each followed by one space */
241 #ifndef INET6
242 #define	WID_DST_DEFAULT(af) 	18	/* width of destination column */
243 #define	WID_GW_DEFAULT(af)	18	/* width of gateway column */
244 #define	WID_IF_DEFAULT(af)	(Wflag ? 8 : 6)	/* width of netif column */
245 #else
246 #define	WID_DST_DEFAULT(af) \
247 	((af) == AF_INET6 ? (numeric_addr ? 33: 18) : 18)
248 #define	WID_GW_DEFAULT(af) \
249 	((af) == AF_INET6 ? (numeric_addr ? 29 : 18) : 18)
250 #define	WID_IF_DEFAULT(af)	((af) == AF_INET6 ? 8 : (Wflag ? 8 : 6))
251 #endif /*INET6*/
252 
253 static int wid_dst;
254 static int wid_gw;
255 static int wid_flags;
256 static int wid_pksent;
257 static int wid_mtu;
258 static int wid_if;
259 static int wid_expire;
260 
261 static void
262 size_cols(int ef, struct radix_node *rn)
263 {
264 	wid_dst = WID_DST_DEFAULT(ef);
265 	wid_gw = WID_GW_DEFAULT(ef);
266 	wid_flags = 6;
267 	wid_pksent = 8;
268 	wid_mtu = 6;
269 	wid_if = WID_IF_DEFAULT(ef);
270 	wid_expire = 6;
271 
272 	if (Wflag && rn != NULL)
273 		size_cols_tree(rn);
274 }
275 
276 static void
277 size_cols_tree(struct radix_node *rn)
278 {
279 again:
280 	if (kget(rn, rnode) != 0)
281 		return;
282 	if (!(rnode.rn_flags & RNF_ACTIVE))
283 		return;
284 	if (rnode.rn_bit < 0) {
285 		if ((rnode.rn_flags & RNF_ROOT) == 0) {
286 			if (kget(rn, rtentry) != 0)
287 				return;
288 			size_cols_rtentry(&rtentry);
289 		}
290 		if ((rn = rnode.rn_dupedkey))
291 			goto again;
292 	} else {
293 		rn = rnode.rn_right;
294 		size_cols_tree(rnode.rn_left);
295 		size_cols_tree(rn);
296 	}
297 }
298 
299 static void
300 size_cols_rtentry(struct rtentry *rt)
301 {
302 	static struct ifnet ifnet, *lastif;
303 	static char buffer[100];
304 	const char *bp;
305 	struct sockaddr *sa;
306 	sa_u addr, mask;
307 	int len;
308 
309 	bzero(&addr, sizeof(addr));
310 	if ((sa = kgetsa(rt_key(rt))))
311 		bcopy(sa, &addr, sa->sa_len);
312 	bzero(&mask, sizeof(mask));
313 	if (rt_mask(rt) && (sa = kgetsa(rt_mask(rt))))
314 		bcopy(sa, &mask, sa->sa_len);
315 	bp = fmt_sockaddr(&addr.u_sa, &mask.u_sa, rt->rt_flags);
316 	len = strlen(bp);
317 	wid_dst = MAX(len, wid_dst);
318 
319 	bp = fmt_sockaddr(kgetsa(rt->rt_gateway), NULL, RTF_HOST);
320 	len = strlen(bp);
321 	wid_gw = MAX(len, wid_gw);
322 
323 	bp = fmt_flags(rt->rt_flags);
324 	len = strlen(bp);
325 	wid_flags = MAX(len, wid_flags);
326 
327 	if (Wflag) {
328 		len = snprintf(buffer, sizeof(buffer), "%ju",
329 		    (uintmax_t )kread_counter((u_long )rt->rt_pksent));
330 		wid_pksent = MAX(len, wid_pksent);
331 	}
332 	if (rt->rt_ifp) {
333 		if (rt->rt_ifp != lastif) {
334 			if (kget(rt->rt_ifp, ifnet) == 0)
335 				len = strlen(ifnet.if_xname);
336 			else
337 				len = strlen("---");
338 			lastif = rt->rt_ifp;
339 			wid_if = MAX(len, wid_if);
340 		}
341 		if (rt->rt_expire) {
342 			time_t expire_time;
343 
344 			if ((expire_time =
345 			    rt->rt_expire - uptime.tv_sec) > 0) {
346 				len = snprintf(buffer, sizeof(buffer), "%d",
347 					       (int)expire_time);
348 				wid_expire = MAX(len, wid_expire);
349 			}
350 		}
351 	}
352 }
353 
354 
355 /*
356  * Print header for routing table columns.
357  */
358 void
359 pr_rthdr(int af1)
360 {
361 
362 	if (Aflag)
363 		printf("%-8.8s ","Address");
364 	if (Wflag) {
365 		printf("%-*.*s %-*.*s %-*.*s %*.*s %*.*s %*.*s %*s\n",
366 			wid_dst,	wid_dst,	"Destination",
367 			wid_gw,		wid_gw,		"Gateway",
368 			wid_flags,	wid_flags,	"Flags",
369 			wid_pksent,	wid_pksent,	"Use",
370 			wid_mtu,	wid_mtu,	"Mtu",
371 			wid_if,		wid_if,		"Netif",
372 			wid_expire,			"Expire");
373 	} else {
374 		printf("%-*.*s %-*.*s %-*.*s  %*.*s %*s\n",
375 			wid_dst,	wid_dst,	"Destination",
376 			wid_gw,		wid_gw,		"Gateway",
377 			wid_flags,	wid_flags,	"Flags",
378 			wid_if,		wid_if,		"Netif",
379 			wid_expire,			"Expire");
380 	}
381 }
382 
383 static struct sockaddr *
384 kgetsa(struct sockaddr *dst)
385 {
386 
387 	if (kget(dst, pt_u.u_sa) != 0)
388 		return (NULL);
389 	if (pt_u.u_sa.sa_len > sizeof (pt_u.u_sa))
390 		kread((u_long)dst, (char *)pt_u.u_data, pt_u.u_sa.sa_len);
391 	return (&pt_u.u_sa);
392 }
393 
394 /*
395  * Print kernel routing tables for given fib
396  * using debugging kvm(3) interface.
397  */
398 static void
399 p_rtable_kvm(int fibnum, int af)
400 {
401 	struct radix_node_head **rnhp, *rnh, head;
402 	struct radix_node_head **rt_tables;
403 	u_long rtree;
404 	int fam, af_size;
405 
406 	kresolve_list(rl);
407 	if ((rtree = rl[N_RTREE].n_value) == 0) {
408 		printf("rt_tables: symbol not in namelist\n");
409 		return;
410 	}
411 
412 	af_size = (AF_MAX + 1) * sizeof(struct radix_node_head *);
413 	rt_tables = calloc(1, af_size);
414 	if (rt_tables == NULL)
415 		err(EX_OSERR, "memory allocation failed");
416 
417 	if (kread((u_long)(rtree), (char *)(rt_tables) + fibnum * af_size,
418 	    af_size) != 0)
419 		err(EX_OSERR, "error retrieving radix pointers");
420 	for (fam = 0; fam <= AF_MAX; fam++) {
421 		int tmpfib;
422 
423 		switch (fam) {
424 		case AF_INET6:
425 		case AF_INET:
426 			tmpfib = fibnum;
427 			break;
428 		default:
429 			tmpfib = 0;
430 		}
431 		rnhp = (struct radix_node_head **)*rt_tables;
432 		/* Calculate the in-kernel address. */
433 		rnhp += tmpfib * (AF_MAX + 1) + fam;
434 		/* Read the in kernel rhn pointer. */
435 		if (kget(rnhp, rnh) != 0)
436 			continue;
437 		if (rnh == NULL)
438 			continue;
439 		/* Read the rnh data. */
440 		if (kget(rnh, head) != 0)
441 			continue;
442 		if (fam == AF_UNSPEC) {
443 			if (Aflag && af == 0) {
444 				printf("Netmasks:\n");
445 				p_rtree_kvm(head.rnh_treetop);
446 			}
447 		} else if (af == AF_UNSPEC || af == fam) {
448 			size_cols(fam, head.rnh_treetop);
449 			pr_family(fam);
450 			do_rtent = 1;
451 			pr_rthdr(fam);
452 			p_rtree_kvm(head.rnh_treetop);
453 		}
454 	}
455 
456 	free(rt_tables);
457 }
458 
459 /*
460  * Print given kernel radix tree using
461  * debugging kvm(3) interface.
462  */
463 static void
464 p_rtree_kvm(struct radix_node *rn)
465 {
466 
467 again:
468 	if (kget(rn, rnode) != 0)
469 		return;
470 	if (!(rnode.rn_flags & RNF_ACTIVE))
471 		return;
472 	if (rnode.rn_bit < 0) {
473 		if (Aflag)
474 			printf("%-8.8lx ", (u_long)rn);
475 		if (rnode.rn_flags & RNF_ROOT) {
476 			if (Aflag)
477 				printf("(root node)%s",
478 				    rnode.rn_dupedkey ? " =>\n" : "\n");
479 		} else if (do_rtent) {
480 			if (kget(rn, rtentry) == 0) {
481 				p_rtentry_kvm(&rtentry);
482 				if (Aflag)
483 					p_rtnode_kvm();
484 			}
485 		} else {
486 			p_sockaddr(kgetsa((struct sockaddr *)rnode.rn_key),
487 				   NULL, 0, 44);
488 			putchar('\n');
489 		}
490 		if ((rn = rnode.rn_dupedkey))
491 			goto again;
492 	} else {
493 		if (Aflag && do_rtent) {
494 			printf("%-8.8lx ", (u_long)rn);
495 			p_rtnode_kvm();
496 		}
497 		rn = rnode.rn_right;
498 		p_rtree_kvm(rnode.rn_left);
499 		p_rtree_kvm(rn);
500 	}
501 }
502 
503 char	nbuf[20];
504 
505 static void
506 p_rtnode_kvm(void)
507 {
508 	struct radix_mask *rm = rnode.rn_mklist;
509 
510 	if (rnode.rn_bit < 0) {
511 		if (rnode.rn_mask) {
512 			printf("\t  mask ");
513 			p_sockaddr(kgetsa((struct sockaddr *)rnode.rn_mask),
514 				   NULL, 0, -1);
515 		} else if (rm == 0)
516 			return;
517 	} else {
518 		sprintf(nbuf, "(%d)", rnode.rn_bit);
519 		printf("%6.6s %8.8lx : %8.8lx", nbuf, (u_long)rnode.rn_left, (u_long)rnode.rn_right);
520 	}
521 	while (rm) {
522 		if (kget(rm, rmask) != 0)
523 			break;
524 		sprintf(nbuf, " %d refs, ", rmask.rm_refs);
525 		printf(" mk = %8.8lx {(%d),%s",
526 			(u_long)rm, -1 - rmask.rm_bit, rmask.rm_refs ? nbuf : " ");
527 		if (rmask.rm_flags & RNF_NORMAL) {
528 			struct radix_node rnode_aux;
529 			printf(" <normal>, ");
530 			if (kget(rmask.rm_leaf, rnode_aux) == 0)
531 				p_sockaddr(kgetsa((struct sockaddr *)rnode_aux.rn_mask),
532 				    NULL, 0, -1);
533 			else
534 				p_sockaddr(NULL, NULL, 0, -1);
535 		} else
536 		    p_sockaddr(kgetsa((struct sockaddr *)rmask.rm_mask),
537 				NULL, 0, -1);
538 		putchar('}');
539 		if ((rm = rmask.rm_mklist))
540 			printf(" ->");
541 	}
542 	putchar('\n');
543 }
544 
545 static void
546 p_rtable_sysctl(int fibnum, int af)
547 {
548 	size_t needed;
549 	int mib[7];
550 	char *buf, *next, *lim;
551 	struct rt_msghdr *rtm;
552 	struct sockaddr *sa;
553 	int fam = 0, ifindex = 0, size;
554 
555 	struct ifaddrs *ifap, *ifa;
556 	struct sockaddr_dl *sdl;
557 
558 	/*
559 	 * Retrieve interface list at first
560 	 * since we need #ifindex -> if_xname match
561 	 */
562 	if (getifaddrs(&ifap) != 0)
563 		err(EX_OSERR, "getifaddrs");
564 
565 	for (ifa = ifap; ifa; ifa = ifa->ifa_next) {
566 
567 		if (ifa->ifa_addr->sa_family != AF_LINK)
568 			continue;
569 
570 		sdl = (struct sockaddr_dl *)ifa->ifa_addr;
571 		ifindex = sdl->sdl_index;
572 
573 		if (ifindex >= ifmap_size) {
574 			size = roundup(ifindex + 1, 32) *
575 			    sizeof(struct ifmap_entry);
576 			if ((ifmap = realloc(ifmap, size)) == NULL)
577 				errx(2, "realloc(%d) failed", size);
578 			memset(&ifmap[ifmap_size], 0,
579 			    size - ifmap_size *
580 			     sizeof(struct ifmap_entry));
581 
582 			ifmap_size = roundup(ifindex + 1, 32);
583 		}
584 
585 		if (*ifmap[ifindex].ifname != '\0')
586 			continue;
587 
588 		strlcpy(ifmap[ifindex].ifname, ifa->ifa_name, IFNAMSIZ);
589 	}
590 
591 	freeifaddrs(ifap);
592 
593 	mib[0] = CTL_NET;
594 	mib[1] = PF_ROUTE;
595 	mib[2] = 0;
596 	mib[3] = af;
597 	mib[4] = NET_RT_DUMP;
598 	mib[5] = 0;
599 	mib[6] = fibnum;
600 	if (sysctl(mib, 7, NULL, &needed, NULL, 0) < 0) {
601 		err(1, "sysctl: net.route.0.%d.dump.%d estimate", af, fibnum);
602 	}
603 
604 	if ((buf = malloc(needed)) == 0) {
605 		errx(2, "malloc(%lu)", (unsigned long)needed);
606 	}
607 	if (sysctl(mib, 6, buf, &needed, NULL, 0) < 0) {
608 		err(1, "sysctl: net.route.0.%d.dump.%d", af, fibnum);
609 	}
610 	lim  = buf + needed;
611 	for (next = buf; next < lim; next += rtm->rtm_msglen) {
612 		rtm = (struct rt_msghdr *)next;
613 		/*
614 		 * Peek inside header to determine AF
615 		 */
616 		sa = (struct sockaddr *)(rtm + 1);
617 		if (fam != sa->sa_family) {
618 			fam = sa->sa_family;
619 			size_cols(fam, NULL);
620 			pr_family(fam);
621 			pr_rthdr(fam);
622 		}
623 		p_rtentry_sysctl(rtm);
624 	}
625 }
626 
627 static void
628 p_rtentry_sysctl(struct rt_msghdr *rtm)
629 {
630 	struct sockaddr *sa = (struct sockaddr *)(rtm + 1);
631 	char buffer[128];
632 	char prettyname[128];
633 	sa_u addr, mask, gw;
634 	unsigned int l;
635 
636 #define	GETSA(_s, _f)	{ \
637 	bzero(&(_s), sizeof(_s)); \
638 	if (rtm->rtm_addrs & _f) { \
639 		l = roundup(sa->sa_len, sizeof(long)); \
640 		memcpy(&(_s), sa, (l > sizeof(_s)) ? sizeof(_s) : l); \
641 		sa = (struct sockaddr *)((char *)sa + l); \
642 	} \
643 }
644 
645 	GETSA(addr, RTA_DST);
646 	GETSA(gw, RTA_GATEWAY);
647 	GETSA(mask, RTA_NETMASK);
648 	p_sockaddr(&addr.u_sa, &mask.u_sa, rtm->rtm_flags, wid_dst);
649 	p_sockaddr(&gw.u_sa, NULL, RTF_HOST, wid_gw);
650 
651 	snprintf(buffer, sizeof(buffer), "%%-%d.%ds ", wid_flags, wid_flags);
652 	p_flags(rtm->rtm_flags, buffer);
653 	if (Wflag) {
654 		printf("%*lu ", wid_pksent, rtm->rtm_rmx.rmx_pksent);
655 
656 		if (rtm->rtm_rmx.rmx_mtu != 0)
657 			printf("%*lu ", wid_mtu, rtm->rtm_rmx.rmx_mtu);
658 		else
659 			printf("%*s ", wid_mtu, "");
660 	}
661 
662 	memset(prettyname, 0, sizeof(prettyname));
663 	if (rtm->rtm_index < ifmap_size) {
664 		strlcpy(prettyname, ifmap[rtm->rtm_index].ifname,
665 		    sizeof(prettyname));
666 		if (*prettyname == '\0')
667 			strlcpy(prettyname, "---", sizeof(prettyname));
668 	}
669 
670 	printf("%*.*s", wid_if, wid_if, prettyname);
671 	if (rtm->rtm_rmx.rmx_expire) {
672 		time_t expire_time;
673 
674 		if ((expire_time =
675 		    rtm->rtm_rmx.rmx_expire - uptime.tv_sec) > 0)
676 			printf(" %*d", wid_expire, (int)expire_time);
677 	}
678 
679 	putchar('\n');
680 }
681 
682 static void
683 p_sockaddr(struct sockaddr *sa, struct sockaddr *mask, int flags, int width)
684 {
685 	const char *cp;
686 
687 	cp = fmt_sockaddr(sa, mask, flags);
688 
689 	if (width < 0 )
690 		printf("%s ", cp);
691 	else {
692 		if (numeric_addr)
693 			printf("%-*s ", width, cp);
694 		else
695 			printf("%-*.*s ", width, width, cp);
696 	}
697 }
698 
699 static const char *
700 fmt_sockaddr(struct sockaddr *sa, struct sockaddr *mask, int flags)
701 {
702 	static char workbuf[128];
703 	const char *cp;
704 
705 	if (sa == NULL)
706 		return ("null");
707 
708 	switch(sa->sa_family) {
709 	case AF_INET:
710 	    {
711 		struct sockaddr_in *sockin = (struct sockaddr_in *)sa;
712 
713 		if ((sockin->sin_addr.s_addr == INADDR_ANY) &&
714 			mask &&
715 			ntohl(((struct sockaddr_in *)mask)->sin_addr.s_addr)
716 				==0L)
717 				cp = "default" ;
718 		else if (flags & RTF_HOST)
719 			cp = routename(sockin->sin_addr.s_addr);
720 		else if (mask)
721 			cp = netname(sockin->sin_addr.s_addr,
722 			    ((struct sockaddr_in *)mask)->sin_addr.s_addr);
723 		else
724 			cp = netname(sockin->sin_addr.s_addr, INADDR_ANY);
725 		break;
726 	    }
727 
728 #ifdef INET6
729 	case AF_INET6:
730 	    {
731 		struct sockaddr_in6 *sa6 = (struct sockaddr_in6 *)sa;
732 
733 		/*
734 		 * The sa6->sin6_scope_id must be filled here because
735 		 * this sockaddr is extracted from kmem(4) directly
736 		 * and has KAME-specific embedded scope id in
737 		 * sa6->sin6_addr.s6_addr[2].
738 		 */
739 		in6_fillscopeid(sa6);
740 
741 		if (flags & RTF_HOST)
742 		    cp = routename6(sa6);
743 		else if (mask)
744 		    cp = netname6(sa6,
745 				  &((struct sockaddr_in6 *)mask)->sin6_addr);
746 		else {
747 		    cp = netname6(sa6, NULL);
748 		}
749 		break;
750 	    }
751 #endif /*INET6*/
752 
753 	case AF_APPLETALK:
754 	    {
755 		if (!(flags & RTF_HOST) && mask)
756 			cp = atalk_print2(sa,mask,9);
757 		else
758 			cp = atalk_print(sa,11);
759 		break;
760 	    }
761 	case AF_NETGRAPH:
762 	    {
763 		strlcpy(workbuf, ((struct sockaddr_ng *)sa)->sg_data,
764 		        sizeof(workbuf));
765 		cp = workbuf;
766 		break;
767 	    }
768 
769 	case AF_LINK:
770 	    {
771 		struct sockaddr_dl *sdl = (struct sockaddr_dl *)sa;
772 
773 		if (sdl->sdl_nlen == 0 && sdl->sdl_alen == 0 &&
774 		    sdl->sdl_slen == 0) {
775 			(void) sprintf(workbuf, "link#%d", sdl->sdl_index);
776 			cp = workbuf;
777 		} else
778 			switch (sdl->sdl_type) {
779 
780 			case IFT_ETHER:
781 			case IFT_L2VLAN:
782 			case IFT_BRIDGE:
783 				if (sdl->sdl_alen == ETHER_ADDR_LEN) {
784 					cp = ether_ntoa((struct ether_addr *)
785 					    (sdl->sdl_data + sdl->sdl_nlen));
786 					break;
787 				}
788 				/* FALLTHROUGH */
789 			default:
790 				cp = link_ntoa(sdl);
791 				break;
792 			}
793 		break;
794 	    }
795 
796 	default:
797 	    {
798 		u_char *s = (u_char *)sa->sa_data, *slim;
799 		char *cq, *cqlim;
800 
801 		cq = workbuf;
802 		slim =  sa->sa_len + (u_char *) sa;
803 		cqlim = cq + sizeof(workbuf) - 6;
804 		cq += sprintf(cq, "(%d)", sa->sa_family);
805 		while (s < slim && cq < cqlim) {
806 			cq += sprintf(cq, " %02x", *s++);
807 			if (s < slim)
808 			    cq += sprintf(cq, "%02x", *s++);
809 		}
810 		cp = workbuf;
811 	    }
812 	}
813 
814 	return (cp);
815 }
816 
817 static void
818 p_flags(int f, const char *format)
819 {
820 	printf(format, fmt_flags(f));
821 }
822 
823 static const char *
824 fmt_flags(int f)
825 {
826 	static char name[33];
827 	char *flags;
828 	struct bits *p = bits;
829 
830 	for (flags = name; p->b_mask; p++)
831 		if (p->b_mask & f)
832 			*flags++ = p->b_val;
833 	*flags = '\0';
834 	return (name);
835 }
836 
837 static void
838 p_rtentry_kvm(struct rtentry *rt)
839 {
840 	static struct ifnet ifnet, *lastif;
841 	static char buffer[128];
842 	static char prettyname[128];
843 	struct sockaddr *sa;
844 	sa_u addr, mask;
845 
846 	bzero(&addr, sizeof(addr));
847 	if ((sa = kgetsa(rt_key(rt))))
848 		bcopy(sa, &addr, sa->sa_len);
849 	bzero(&mask, sizeof(mask));
850 	if (rt_mask(rt) && (sa = kgetsa(rt_mask(rt))))
851 		bcopy(sa, &mask, sa->sa_len);
852 	p_sockaddr(&addr.u_sa, &mask.u_sa, rt->rt_flags, wid_dst);
853 	p_sockaddr(kgetsa(rt->rt_gateway), NULL, RTF_HOST, wid_gw);
854 	snprintf(buffer, sizeof(buffer), "%%-%d.%ds ", wid_flags, wid_flags);
855 	p_flags(rt->rt_flags, buffer);
856 	if (Wflag) {
857 		printf("%*ju ", wid_pksent,
858 		    (uintmax_t )kread_counter((u_long )rt->rt_pksent));
859 
860 		if (rt->rt_mtu != 0)
861 			printf("%*lu ", wid_mtu, rt->rt_mtu);
862 		else
863 			printf("%*s ", wid_mtu, "");
864 	}
865 	if (rt->rt_ifp) {
866 		if (rt->rt_ifp != lastif) {
867 			if (kget(rt->rt_ifp, ifnet) == 0)
868 				strlcpy(prettyname, ifnet.if_xname,
869 				    sizeof(prettyname));
870 			else
871 				strlcpy(prettyname, "---", sizeof(prettyname));
872 			lastif = rt->rt_ifp;
873 		}
874 		printf("%*.*s", wid_if, wid_if, prettyname);
875 		if (rt->rt_expire) {
876 			time_t expire_time;
877 
878 			if ((expire_time =
879 			    rt->rt_expire - uptime.tv_sec) > 0)
880 				printf(" %*d", wid_expire, (int)expire_time);
881 		}
882 		if (rt->rt_nodes[0].rn_dupedkey)
883 			printf(" =>");
884 	}
885 	putchar('\n');
886 }
887 
888 char *
889 routename(in_addr_t in)
890 {
891 	char *cp;
892 	static char line[MAXHOSTNAMELEN];
893 	struct hostent *hp;
894 
895 	cp = 0;
896 	if (!numeric_addr) {
897 		hp = gethostbyaddr(&in, sizeof (struct in_addr), AF_INET);
898 		if (hp) {
899 			cp = hp->h_name;
900 			trimdomain(cp, strlen(cp));
901 		}
902 	}
903 	if (cp) {
904 		strlcpy(line, cp, sizeof(line));
905 	} else {
906 #define	C(x)	((x) & 0xff)
907 		in = ntohl(in);
908 		sprintf(line, "%u.%u.%u.%u",
909 		    C(in >> 24), C(in >> 16), C(in >> 8), C(in));
910 	}
911 	return (line);
912 }
913 
914 #define	NSHIFT(m) (							\
915 	(m) == IN_CLASSA_NET ? IN_CLASSA_NSHIFT :			\
916 	(m) == IN_CLASSB_NET ? IN_CLASSB_NSHIFT :			\
917 	(m) == IN_CLASSC_NET ? IN_CLASSC_NSHIFT :			\
918 	0)
919 
920 static void
921 domask(char *dst, in_addr_t addr __unused, u_long mask)
922 {
923 	int b, i;
924 
925 	if (mask == 0 || (!numeric_addr && NSHIFT(mask) != 0)) {
926 		*dst = '\0';
927 		return;
928 	}
929 	i = 0;
930 	for (b = 0; b < 32; b++)
931 		if (mask & (1 << b)) {
932 			int bb;
933 
934 			i = b;
935 			for (bb = b+1; bb < 32; bb++)
936 				if (!(mask & (1 << bb))) {
937 					i = -1;	/* noncontig */
938 					break;
939 				}
940 			break;
941 		}
942 	if (i == -1)
943 		sprintf(dst, "&0x%lx", mask);
944 	else
945 		sprintf(dst, "/%d", 32-i);
946 }
947 
948 /*
949  * Return the name of the network whose address is given.
950  */
951 char *
952 netname(in_addr_t in, in_addr_t mask)
953 {
954 	char *cp = 0;
955 	static char line[MAXHOSTNAMELEN];
956 	struct netent *np = 0;
957 	in_addr_t i;
958 
959 	/* It is ok to supply host address. */
960 	in &= mask;
961 
962 	i = ntohl(in);
963 	if (!numeric_addr && i) {
964 		np = getnetbyaddr(i >> NSHIFT(ntohl(mask)), AF_INET);
965 		if (np != NULL) {
966 			cp = np->n_name;
967 			trimdomain(cp, strlen(cp));
968 		}
969 	}
970 	if (cp != NULL) {
971 		strlcpy(line, cp, sizeof(line));
972 	} else {
973 		inet_ntop(AF_INET, &in, line, sizeof(line) - 1);
974 	}
975 	domask(line + strlen(line), i, ntohl(mask));
976 	return (line);
977 }
978 
979 #undef NSHIFT
980 
981 #ifdef INET6
982 void
983 in6_fillscopeid(struct sockaddr_in6 *sa6)
984 {
985 #if defined(__KAME__)
986 	/*
987 	 * XXX: This is a special workaround for KAME kernels.
988 	 * sin6_scope_id field of SA should be set in the future.
989 	 */
990 	if (IN6_IS_ADDR_LINKLOCAL(&sa6->sin6_addr) ||
991 	    IN6_IS_ADDR_MC_NODELOCAL(&sa6->sin6_addr) ||
992 	    IN6_IS_ADDR_MC_LINKLOCAL(&sa6->sin6_addr)) {
993 		/* XXX: override is ok? */
994 		sa6->sin6_scope_id =
995 		    ntohs(*(u_int16_t *)&sa6->sin6_addr.s6_addr[2]);
996 		sa6->sin6_addr.s6_addr[2] = sa6->sin6_addr.s6_addr[3] = 0;
997 	}
998 #endif
999 }
1000 
1001 const char *
1002 netname6(struct sockaddr_in6 *sa6, struct in6_addr *mask)
1003 {
1004 	static char line[MAXHOSTNAMELEN];
1005 	u_char *p = (u_char *)mask;
1006 	u_char *lim;
1007 	int masklen, illegal = 0, flag = 0;
1008 
1009 	if (mask) {
1010 		for (masklen = 0, lim = p + 16; p < lim; p++) {
1011 			switch (*p) {
1012 			 case 0xff:
1013 				 masklen += 8;
1014 				 break;
1015 			 case 0xfe:
1016 				 masklen += 7;
1017 				 break;
1018 			 case 0xfc:
1019 				 masklen += 6;
1020 				 break;
1021 			 case 0xf8:
1022 				 masklen += 5;
1023 				 break;
1024 			 case 0xf0:
1025 				 masklen += 4;
1026 				 break;
1027 			 case 0xe0:
1028 				 masklen += 3;
1029 				 break;
1030 			 case 0xc0:
1031 				 masklen += 2;
1032 				 break;
1033 			 case 0x80:
1034 				 masklen += 1;
1035 				 break;
1036 			 case 0x00:
1037 				 break;
1038 			 default:
1039 				 illegal ++;
1040 				 break;
1041 			}
1042 		}
1043 		if (illegal)
1044 			fprintf(stderr, "illegal prefixlen\n");
1045 	}
1046 	else
1047 		masklen = 128;
1048 
1049 	if (masklen == 0 && IN6_IS_ADDR_UNSPECIFIED(&sa6->sin6_addr))
1050 		return("default");
1051 
1052 	if (numeric_addr)
1053 		flag |= NI_NUMERICHOST;
1054 	getnameinfo((struct sockaddr *)sa6, sa6->sin6_len, line, sizeof(line),
1055 		    NULL, 0, flag);
1056 
1057 	if (numeric_addr)
1058 		sprintf(&line[strlen(line)], "/%d", masklen);
1059 
1060 	return line;
1061 }
1062 
1063 char *
1064 routename6(struct sockaddr_in6 *sa6)
1065 {
1066 	static char line[MAXHOSTNAMELEN];
1067 	int flag = 0;
1068 	/* use local variable for safety */
1069 	struct sockaddr_in6 sa6_local;
1070 
1071 	sa6_local.sin6_family = AF_INET6;
1072 	sa6_local.sin6_len = sizeof(sa6_local);
1073 	sa6_local.sin6_addr = sa6->sin6_addr;
1074 	sa6_local.sin6_scope_id = sa6->sin6_scope_id;
1075 
1076 	if (numeric_addr)
1077 		flag |= NI_NUMERICHOST;
1078 
1079 	getnameinfo((struct sockaddr *)&sa6_local, sa6_local.sin6_len,
1080 		    line, sizeof(line), NULL, 0, flag);
1081 
1082 	return line;
1083 }
1084 #endif /*INET6*/
1085 
1086 /*
1087  * Print routing statistics
1088  */
1089 void
1090 rt_stats(void)
1091 {
1092 	struct rtstat rtstat;
1093 	u_long rtsaddr, rttaddr;
1094 	int rttrash;
1095 
1096 	kresolve_list(rl);
1097 
1098 	if ((rtsaddr = rl[N_RTSTAT].n_value) == 0) {
1099 		printf("rtstat: symbol not in namelist\n");
1100 		return;
1101 	}
1102 	if ((rttaddr = rl[N_RTTRASH].n_value) == 0) {
1103 		printf("rttrash: symbol not in namelist\n");
1104 		return;
1105 	}
1106 	kread(rtsaddr, (char *)&rtstat, sizeof (rtstat));
1107 	kread(rttaddr, (char *)&rttrash, sizeof (rttrash));
1108 	printf("routing:\n");
1109 
1110 #define	p(f, m) if (rtstat.f || sflag <= 1) \
1111 	printf(m, rtstat.f, plural(rtstat.f))
1112 
1113 	p(rts_badredirect, "\t%hu bad routing redirect%s\n");
1114 	p(rts_dynamic, "\t%hu dynamically created route%s\n");
1115 	p(rts_newgateway, "\t%hu new gateway%s due to redirects\n");
1116 	p(rts_unreach, "\t%hu destination%s found unreachable\n");
1117 	p(rts_wildcard, "\t%hu use%s of a wildcard route\n");
1118 #undef p
1119 
1120 	if (rttrash || sflag <= 1)
1121 		printf("\t%u route%s not in table but not freed\n",
1122 		    rttrash, plural(rttrash));
1123 }
1124