xref: /freebsd/usr.bin/netstat/route.c (revision 86390f9444433b00296741d03d069a587ad8e4bf)
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 #include <net/route.h>
52 
53 #include <netinet/in.h>
54 #include <netipx/ipx.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_rmx.rmx_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_IPX:
219 		afname = "IPX";
220 		break;
221 	case AF_ISO:
222 		afname = "ISO";
223 		break;
224 	case AF_APPLETALK:
225 		afname = "AppleTalk";
226 		break;
227 	case AF_CCITT:
228 		afname = "X.25";
229 		break;
230 	case AF_NETGRAPH:
231 		afname = "Netgraph";
232 		break;
233 	default:
234 		afname = NULL;
235 		break;
236 	}
237 	if (afname)
238 		printf("\n%s:\n", afname);
239 	else
240 		printf("\nProtocol Family %d:\n", af1);
241 }
242 
243 /* column widths; each followed by one space */
244 #ifndef INET6
245 #define	WID_DST_DEFAULT(af) 	18	/* width of destination column */
246 #define	WID_GW_DEFAULT(af)	18	/* width of gateway column */
247 #define	WID_IF_DEFAULT(af)	(Wflag ? 8 : 6)	/* width of netif column */
248 #else
249 #define	WID_DST_DEFAULT(af) \
250 	((af) == AF_INET6 ? (numeric_addr ? 33: 18) : 18)
251 #define	WID_GW_DEFAULT(af) \
252 	((af) == AF_INET6 ? (numeric_addr ? 29 : 18) : 18)
253 #define	WID_IF_DEFAULT(af)	((af) == AF_INET6 ? 8 : (Wflag ? 8 : 6))
254 #endif /*INET6*/
255 
256 static int wid_dst;
257 static int wid_gw;
258 static int wid_flags;
259 static int wid_refs;
260 static int wid_use;
261 static int wid_mtu;
262 static int wid_if;
263 static int wid_expire;
264 
265 static void
266 size_cols(int ef, struct radix_node *rn)
267 {
268 	wid_dst = WID_DST_DEFAULT(ef);
269 	wid_gw = WID_GW_DEFAULT(ef);
270 	wid_flags = 6;
271 	wid_refs = 6;
272 	wid_use = 8;
273 	wid_mtu = 6;
274 	wid_if = WID_IF_DEFAULT(ef);
275 	wid_expire = 6;
276 
277 	if (Wflag && rn != NULL)
278 		size_cols_tree(rn);
279 }
280 
281 static void
282 size_cols_tree(struct radix_node *rn)
283 {
284 again:
285 	if (kget(rn, rnode) != 0)
286 		return;
287 	if (!(rnode.rn_flags & RNF_ACTIVE))
288 		return;
289 	if (rnode.rn_bit < 0) {
290 		if ((rnode.rn_flags & RNF_ROOT) == 0) {
291 			if (kget(rn, rtentry) != 0)
292 				return;
293 			size_cols_rtentry(&rtentry);
294 		}
295 		if ((rn = rnode.rn_dupedkey))
296 			goto again;
297 	} else {
298 		rn = rnode.rn_right;
299 		size_cols_tree(rnode.rn_left);
300 		size_cols_tree(rn);
301 	}
302 }
303 
304 static void
305 size_cols_rtentry(struct rtentry *rt)
306 {
307 	static struct ifnet ifnet, *lastif;
308 	static char buffer[100];
309 	const char *bp;
310 	struct sockaddr *sa;
311 	sa_u addr, mask;
312 	int len;
313 
314 	bzero(&addr, sizeof(addr));
315 	if ((sa = kgetsa(rt_key(rt))))
316 		bcopy(sa, &addr, sa->sa_len);
317 	bzero(&mask, sizeof(mask));
318 	if (rt_mask(rt) && (sa = kgetsa(rt_mask(rt))))
319 		bcopy(sa, &mask, sa->sa_len);
320 	bp = fmt_sockaddr(&addr.u_sa, &mask.u_sa, rt->rt_flags);
321 	len = strlen(bp);
322 	wid_dst = MAX(len, wid_dst);
323 
324 	bp = fmt_sockaddr(kgetsa(rt->rt_gateway), NULL, RTF_HOST);
325 	len = strlen(bp);
326 	wid_gw = MAX(len, wid_gw);
327 
328 	bp = fmt_flags(rt->rt_flags);
329 	len = strlen(bp);
330 	wid_flags = MAX(len, wid_flags);
331 
332 	if (addr.u_sa.sa_family == AF_INET || Wflag) {
333 		len = snprintf(buffer, sizeof(buffer), "%d", rt->rt_refcnt);
334 		wid_refs = MAX(len, wid_refs);
335 		len = snprintf(buffer, sizeof(buffer), "%lu", rt->rt_use);
336 		wid_use = MAX(len, wid_use);
337 		if (Wflag && rt->rt_rmx.rmx_mtu != 0) {
338 			len = snprintf(buffer, sizeof(buffer),
339 				       "%lu", rt->rt_rmx.rmx_mtu);
340 			wid_mtu = MAX(len, wid_mtu);
341 		}
342 	}
343 	if (rt->rt_ifp) {
344 		if (rt->rt_ifp != lastif) {
345 			if (kget(rt->rt_ifp, ifnet) == 0)
346 				len = strlen(ifnet.if_xname);
347 			else
348 				len = strlen("---");
349 			lastif = rt->rt_ifp;
350 			wid_if = MAX(len, wid_if);
351 		}
352 		if (rt->rt_rmx.rmx_expire) {
353 			time_t expire_time;
354 
355 			if ((expire_time =
356 			    rt->rt_rmx.rmx_expire - uptime.tv_sec) > 0) {
357 				len = snprintf(buffer, sizeof(buffer), "%d",
358 					       (int)expire_time);
359 				wid_expire = MAX(len, wid_expire);
360 			}
361 		}
362 	}
363 }
364 
365 
366 /*
367  * Print header for routing table columns.
368  */
369 void
370 pr_rthdr(int af1)
371 {
372 
373 	if (Aflag)
374 		printf("%-8.8s ","Address");
375 	if (Wflag) {
376 		printf("%-*.*s %-*.*s %-*.*s %*.*s %*.*s %*s\n",
377 			wid_dst,	wid_dst,	"Destination",
378 			wid_gw,		wid_gw,		"Gateway",
379 			wid_flags,	wid_flags,	"Flags",
380 			wid_mtu,	wid_mtu,	"Mtu",
381 			wid_if,		wid_if,		"Netif",
382 			wid_expire,			"Expire");
383 	} else {
384 		printf("%-*.*s %-*.*s %-*.*s  %*.*s %*s\n",
385 			wid_dst,	wid_dst,	"Destination",
386 			wid_gw,		wid_gw,		"Gateway",
387 			wid_flags,	wid_flags,	"Flags",
388 			wid_if,		wid_if,		"Netif",
389 			wid_expire,			"Expire");
390 	}
391 }
392 
393 static struct sockaddr *
394 kgetsa(struct sockaddr *dst)
395 {
396 
397 	if (kget(dst, pt_u.u_sa) != 0)
398 		return (NULL);
399 	if (pt_u.u_sa.sa_len > sizeof (pt_u.u_sa))
400 		kread((u_long)dst, (char *)pt_u.u_data, pt_u.u_sa.sa_len);
401 	return (&pt_u.u_sa);
402 }
403 
404 /*
405  * Print kernel routing tables for given fib
406  * using debugging kvm(3) interface.
407  */
408 static void
409 p_rtable_kvm(int fibnum, int af)
410 {
411 	struct radix_node_head **rnhp, *rnh, head;
412 	struct radix_node_head **rt_tables;
413 	u_long rtree;
414 	int fam, af_size;
415 
416 	kresolve_list(rl);
417 	if ((rtree = rl[N_RTREE].n_value) == 0) {
418 		printf("rt_tables: symbol not in namelist\n");
419 		return;
420 	}
421 
422 	af_size = (AF_MAX + 1) * sizeof(struct radix_node_head *);
423 	rt_tables = calloc(1, af_size);
424 	if (rt_tables == NULL)
425 		err(EX_OSERR, "memory allocation failed");
426 
427 	if (kread((u_long)(rtree), (char *)(rt_tables) + fibnum * af_size,
428 	    af_size) != 0)
429 		return;
430 	for (fam = 0; fam <= AF_MAX; fam++) {
431 		int tmpfib;
432 
433 		switch (fam) {
434 		case AF_INET6:
435 		case AF_INET:
436 			tmpfib = fibnum;
437 			break;
438 		default:
439 			tmpfib = 0;
440 		}
441 		rnhp = (struct radix_node_head **)*rt_tables;
442 		/* Calculate the in-kernel address. */
443 		rnhp += tmpfib * (AF_MAX + 1) + fam;
444 		/* Read the in kernel rhn pointer. */
445 		if (kget(rnhp, rnh) != 0)
446 			continue;
447 		if (rnh == NULL)
448 			continue;
449 		/* Read the rnh data. */
450 		if (kget(rnh, head) != 0)
451 			continue;
452 		if (fam == AF_UNSPEC) {
453 			if (Aflag && af == 0) {
454 				printf("Netmasks:\n");
455 				p_rtree_kvm(head.rnh_treetop);
456 			}
457 		} else if (af == AF_UNSPEC || af == fam) {
458 			size_cols(fam, head.rnh_treetop);
459 			pr_family(fam);
460 			do_rtent = 1;
461 			pr_rthdr(fam);
462 			p_rtree_kvm(head.rnh_treetop);
463 		}
464 	}
465 }
466 
467 /*
468  * Print given kernel radix tree using
469  * debugging kvm(3) interface.
470  */
471 static void
472 p_rtree_kvm(struct radix_node *rn)
473 {
474 
475 again:
476 	if (kget(rn, rnode) != 0)
477 		return;
478 	if (!(rnode.rn_flags & RNF_ACTIVE))
479 		return;
480 	if (rnode.rn_bit < 0) {
481 		if (Aflag)
482 			printf("%-8.8lx ", (u_long)rn);
483 		if (rnode.rn_flags & RNF_ROOT) {
484 			if (Aflag)
485 				printf("(root node)%s",
486 				    rnode.rn_dupedkey ? " =>\n" : "\n");
487 		} else if (do_rtent) {
488 			if (kget(rn, rtentry) == 0) {
489 				p_rtentry_kvm(&rtentry);
490 				if (Aflag)
491 					p_rtnode_kvm();
492 			}
493 		} else {
494 			p_sockaddr(kgetsa((struct sockaddr *)rnode.rn_key),
495 				   NULL, 0, 44);
496 			putchar('\n');
497 		}
498 		if ((rn = rnode.rn_dupedkey))
499 			goto again;
500 	} else {
501 		if (Aflag && do_rtent) {
502 			printf("%-8.8lx ", (u_long)rn);
503 			p_rtnode_kvm();
504 		}
505 		rn = rnode.rn_right;
506 		p_rtree_kvm(rnode.rn_left);
507 		p_rtree_kvm(rn);
508 	}
509 }
510 
511 char	nbuf[20];
512 
513 static void
514 p_rtnode_kvm(void)
515 {
516 	struct radix_mask *rm = rnode.rn_mklist;
517 
518 	if (rnode.rn_bit < 0) {
519 		if (rnode.rn_mask) {
520 			printf("\t  mask ");
521 			p_sockaddr(kgetsa((struct sockaddr *)rnode.rn_mask),
522 				   NULL, 0, -1);
523 		} else if (rm == 0)
524 			return;
525 	} else {
526 		sprintf(nbuf, "(%d)", rnode.rn_bit);
527 		printf("%6.6s %8.8lx : %8.8lx", nbuf, (u_long)rnode.rn_left, (u_long)rnode.rn_right);
528 	}
529 	while (rm) {
530 		if (kget(rm, rmask) != 0)
531 			break;
532 		sprintf(nbuf, " %d refs, ", rmask.rm_refs);
533 		printf(" mk = %8.8lx {(%d),%s",
534 			(u_long)rm, -1 - rmask.rm_bit, rmask.rm_refs ? nbuf : " ");
535 		if (rmask.rm_flags & RNF_NORMAL) {
536 			struct radix_node rnode_aux;
537 			printf(" <normal>, ");
538 			if (kget(rmask.rm_leaf, rnode_aux) == 0)
539 				p_sockaddr(kgetsa((struct sockaddr *)rnode_aux.rn_mask),
540 				    NULL, 0, -1);
541 			else
542 				p_sockaddr(NULL, NULL, 0, -1);
543 		} else
544 		    p_sockaddr(kgetsa((struct sockaddr *)rmask.rm_mask),
545 				NULL, 0, -1);
546 		putchar('}');
547 		if ((rm = rmask.rm_mklist))
548 			printf(" ->");
549 	}
550 	putchar('\n');
551 }
552 
553 static void
554 p_rtable_sysctl(int fibnum, int af)
555 {
556 	size_t needed;
557 	int mib[7];
558 	char *buf, *next, *lim;
559 	struct rt_msghdr *rtm;
560 	struct sockaddr *sa;
561 	int fam = 0, ifindex = 0, size;
562 
563 	struct ifaddrs *ifap, *ifa;
564 	struct sockaddr_dl *sdl;
565 
566 	/*
567 	 * Retrieve interface list at first
568 	 * since we need #ifindex -> if_xname match
569 	 */
570 	if (getifaddrs(&ifap) != 0)
571 		err(EX_OSERR, "getifaddrs");
572 
573 	for (ifa = ifap; ifa; ifa = ifa->ifa_next) {
574 
575 		if (ifa->ifa_addr->sa_family != AF_LINK)
576 			continue;
577 
578 		sdl = (struct sockaddr_dl *)ifa->ifa_addr;
579 		ifindex = sdl->sdl_index;
580 
581 		if (ifindex >= ifmap_size) {
582 			size = roundup(ifindex + 1, 32) *
583 			    sizeof(struct ifmap_entry);
584 			if ((ifmap = realloc(ifmap, size)) == NULL)
585 				errx(2, "realloc(%d) failed", size);
586 			memset(&ifmap[ifmap_size], 0,
587 			    size - ifmap_size *
588 			     sizeof(struct ifmap_entry));
589 
590 			ifmap_size = roundup(ifindex + 1, 32);
591 		}
592 
593 		if (*ifmap[ifindex].ifname != '\0')
594 			continue;
595 
596 		strlcpy(ifmap[ifindex].ifname, ifa->ifa_name, IFNAMSIZ);
597 	}
598 
599 	freeifaddrs(ifap);
600 
601 	mib[0] = CTL_NET;
602 	mib[1] = PF_ROUTE;
603 	mib[2] = 0;
604 	mib[3] = af;
605 	mib[4] = NET_RT_DUMP;
606 	mib[5] = 0;
607 	mib[6] = fibnum;
608 	if (sysctl(mib, 7, NULL, &needed, NULL, 0) < 0) {
609 		err(1, "sysctl: net.route.0.%d.dump.%d estimate", af, fibnum);
610 	}
611 
612 	if ((buf = malloc(needed)) == 0) {
613 		errx(2, "malloc(%lu)", (unsigned long)needed);
614 	}
615 	if (sysctl(mib, 6, buf, &needed, NULL, 0) < 0) {
616 		err(1, "sysctl: net.route.0.%d.dump.%d", af, fibnum);
617 	}
618 	lim  = buf + needed;
619 	for (next = buf; next < lim; next += rtm->rtm_msglen) {
620 		rtm = (struct rt_msghdr *)next;
621 		/*
622 		 * Peek inside header to determine AF
623 		 */
624 		sa = (struct sockaddr *)(rtm + 1);
625 		if (fam != sa->sa_family) {
626 			fam = sa->sa_family;
627 			size_cols(fam, NULL);
628 			pr_family(fam);
629 			pr_rthdr(fam);
630 		}
631 		p_rtentry_sysctl(rtm);
632 	}
633 }
634 
635 static void
636 p_rtentry_sysctl(struct rt_msghdr *rtm)
637 {
638 	struct sockaddr *sa = (struct sockaddr *)(rtm + 1);
639 	char buffer[128];
640 	char prettyname[128];
641 	sa_u addr, mask, gw;
642 	unsigned int l;
643 
644 #define	GETSA(_s, _f)	{ \
645 	bzero(&(_s), sizeof(_s)); \
646 	if (rtm->rtm_addrs & _f) { \
647 		l = roundup(sa->sa_len, sizeof(long)); \
648 		memcpy(&(_s), sa, (l > sizeof(_s)) ? sizeof(_s) : l); \
649 		sa = (struct sockaddr *)((char *)sa + l); \
650 	} \
651 }
652 
653 	GETSA(addr, RTA_DST);
654 	GETSA(gw, RTA_GATEWAY);
655 	GETSA(mask, RTA_NETMASK);
656 	p_sockaddr(&addr.u_sa, &mask.u_sa, rtm->rtm_flags, wid_dst);
657 	p_sockaddr(&gw.u_sa, NULL, RTF_HOST, wid_gw);
658 
659 	snprintf(buffer, sizeof(buffer), "%%-%d.%ds ", wid_flags, wid_flags);
660 	p_flags(rtm->rtm_flags, buffer);
661 	if (Wflag) {
662 		if (rtm->rtm_rmx.rmx_mtu != 0)
663 			printf("%*lu ", wid_mtu, rtm->rtm_rmx.rmx_mtu);
664 		else
665 			printf("%*s ", wid_mtu, "");
666 	}
667 
668 	memset(prettyname, 0, sizeof(prettyname));
669 	if (rtm->rtm_index < ifmap_size) {
670 		strlcpy(prettyname, ifmap[rtm->rtm_index].ifname,
671 		    sizeof(prettyname));
672 		if (*prettyname == '\0')
673 			strlcpy(prettyname, "---", sizeof(prettyname));
674 	}
675 
676 	printf("%*.*s", wid_if, wid_if, prettyname);
677 	if (rtm->rtm_rmx.rmx_expire) {
678 		time_t expire_time;
679 
680 		if ((expire_time =
681 		    rtm->rtm_rmx.rmx_expire - uptime.tv_sec) > 0)
682 			printf(" %*d", wid_expire, (int)expire_time);
683 	}
684 
685 	putchar('\n');
686 }
687 
688 static void
689 p_sockaddr(struct sockaddr *sa, struct sockaddr *mask, int flags, int width)
690 {
691 	const char *cp;
692 
693 	cp = fmt_sockaddr(sa, mask, flags);
694 
695 	if (width < 0 )
696 		printf("%s ", cp);
697 	else {
698 		if (numeric_addr)
699 			printf("%-*s ", width, cp);
700 		else
701 			printf("%-*.*s ", width, width, cp);
702 	}
703 }
704 
705 static const char *
706 fmt_sockaddr(struct sockaddr *sa, struct sockaddr *mask, int flags)
707 {
708 	static char workbuf[128];
709 	const char *cp;
710 
711 	if (sa == NULL)
712 		return ("null");
713 
714 	switch(sa->sa_family) {
715 	case AF_INET:
716 	    {
717 		struct sockaddr_in *sockin = (struct sockaddr_in *)sa;
718 
719 		if ((sockin->sin_addr.s_addr == INADDR_ANY) &&
720 			mask &&
721 			ntohl(((struct sockaddr_in *)mask)->sin_addr.s_addr)
722 				==0L)
723 				cp = "default" ;
724 		else if (flags & RTF_HOST)
725 			cp = routename(sockin->sin_addr.s_addr);
726 		else if (mask)
727 			cp = netname(sockin->sin_addr.s_addr,
728 			    ((struct sockaddr_in *)mask)->sin_addr.s_addr);
729 		else
730 			cp = netname(sockin->sin_addr.s_addr, INADDR_ANY);
731 		break;
732 	    }
733 
734 #ifdef INET6
735 	case AF_INET6:
736 	    {
737 		struct sockaddr_in6 *sa6 = (struct sockaddr_in6 *)sa;
738 
739 		/*
740 		 * The sa6->sin6_scope_id must be filled here because
741 		 * this sockaddr is extracted from kmem(4) directly
742 		 * and has KAME-specific embedded scope id in
743 		 * sa6->sin6_addr.s6_addr[2].
744 		 */
745 		in6_fillscopeid(sa6);
746 
747 		if (flags & RTF_HOST)
748 		    cp = routename6(sa6);
749 		else if (mask)
750 		    cp = netname6(sa6,
751 				  &((struct sockaddr_in6 *)mask)->sin6_addr);
752 		else {
753 		    cp = netname6(sa6, NULL);
754 		}
755 		break;
756 	    }
757 #endif /*INET6*/
758 
759 	case AF_IPX:
760 	    {
761 		struct ipx_addr work = ((struct sockaddr_ipx *)sa)->sipx_addr;
762 		if (ipx_nullnet(satoipx_addr(work)))
763 			cp = "default";
764 		else
765 			cp = ipx_print(sa);
766 		break;
767 	    }
768 	case AF_APPLETALK:
769 	    {
770 		if (!(flags & RTF_HOST) && mask)
771 			cp = atalk_print2(sa,mask,9);
772 		else
773 			cp = atalk_print(sa,11);
774 		break;
775 	    }
776 	case AF_NETGRAPH:
777 	    {
778 		strlcpy(workbuf, ((struct sockaddr_ng *)sa)->sg_data,
779 		        sizeof(workbuf));
780 		cp = workbuf;
781 		break;
782 	    }
783 
784 	case AF_LINK:
785 	    {
786 		struct sockaddr_dl *sdl = (struct sockaddr_dl *)sa;
787 
788 		if (sdl->sdl_nlen == 0 && sdl->sdl_alen == 0 &&
789 		    sdl->sdl_slen == 0) {
790 			(void) sprintf(workbuf, "link#%d", sdl->sdl_index);
791 			cp = workbuf;
792 		} else
793 			switch (sdl->sdl_type) {
794 
795 			case IFT_ETHER:
796 			case IFT_L2VLAN:
797 			case IFT_BRIDGE:
798 				if (sdl->sdl_alen == ETHER_ADDR_LEN) {
799 					cp = ether_ntoa((struct ether_addr *)
800 					    (sdl->sdl_data + sdl->sdl_nlen));
801 					break;
802 				}
803 				/* FALLTHROUGH */
804 			default:
805 				cp = link_ntoa(sdl);
806 				break;
807 			}
808 		break;
809 	    }
810 
811 	default:
812 	    {
813 		u_char *s = (u_char *)sa->sa_data, *slim;
814 		char *cq, *cqlim;
815 
816 		cq = workbuf;
817 		slim =  sa->sa_len + (u_char *) sa;
818 		cqlim = cq + sizeof(workbuf) - 6;
819 		cq += sprintf(cq, "(%d)", sa->sa_family);
820 		while (s < slim && cq < cqlim) {
821 			cq += sprintf(cq, " %02x", *s++);
822 			if (s < slim)
823 			    cq += sprintf(cq, "%02x", *s++);
824 		}
825 		cp = workbuf;
826 	    }
827 	}
828 
829 	return (cp);
830 }
831 
832 static void
833 p_flags(int f, const char *format)
834 {
835 	printf(format, fmt_flags(f));
836 }
837 
838 static const char *
839 fmt_flags(int f)
840 {
841 	static char name[33];
842 	char *flags;
843 	struct bits *p = bits;
844 
845 	for (flags = name; p->b_mask; p++)
846 		if (p->b_mask & f)
847 			*flags++ = p->b_val;
848 	*flags = '\0';
849 	return (name);
850 }
851 
852 static void
853 p_rtentry_kvm(struct rtentry *rt)
854 {
855 	static struct ifnet ifnet, *lastif;
856 	static char buffer[128];
857 	static char prettyname[128];
858 	struct sockaddr *sa;
859 	sa_u addr, mask;
860 
861 	bzero(&addr, sizeof(addr));
862 	if ((sa = kgetsa(rt_key(rt))))
863 		bcopy(sa, &addr, sa->sa_len);
864 	bzero(&mask, sizeof(mask));
865 	if (rt_mask(rt) && (sa = kgetsa(rt_mask(rt))))
866 		bcopy(sa, &mask, sa->sa_len);
867 	p_sockaddr(&addr.u_sa, &mask.u_sa, rt->rt_flags, wid_dst);
868 	p_sockaddr(kgetsa(rt->rt_gateway), NULL, RTF_HOST, wid_gw);
869 	snprintf(buffer, sizeof(buffer), "%%-%d.%ds ", wid_flags, wid_flags);
870 	p_flags(rt->rt_flags, buffer);
871 	if (addr.u_sa.sa_family == AF_INET || Wflag) {
872 #if 0
873 		printf("%*d %*lu ", wid_refs, rt->rt_refcnt,
874 				     wid_use, rt->rt_use);
875 #endif
876 		if (Wflag) {
877 			if (rt->rt_rmx.rmx_mtu != 0)
878 				printf("%*lu ", wid_mtu, rt->rt_rmx.rmx_mtu);
879 			else
880 				printf("%*s ", wid_mtu, "");
881 		}
882 	}
883 	if (rt->rt_ifp) {
884 		if (rt->rt_ifp != lastif) {
885 			if (kget(rt->rt_ifp, ifnet) == 0)
886 				strlcpy(prettyname, ifnet.if_xname,
887 				    sizeof(prettyname));
888 			else
889 				strlcpy(prettyname, "---", sizeof(prettyname));
890 			lastif = rt->rt_ifp;
891 		}
892 		printf("%*.*s", wid_if, wid_if, prettyname);
893 		if (rt->rt_rmx.rmx_expire) {
894 			time_t expire_time;
895 
896 			if ((expire_time =
897 			    rt->rt_rmx.rmx_expire - uptime.tv_sec) > 0)
898 				printf(" %*d", wid_expire, (int)expire_time);
899 		}
900 		if (rt->rt_nodes[0].rn_dupedkey)
901 			printf(" =>");
902 	}
903 	putchar('\n');
904 }
905 
906 char *
907 routename(in_addr_t in)
908 {
909 	char *cp;
910 	static char line[MAXHOSTNAMELEN];
911 	struct hostent *hp;
912 
913 	cp = 0;
914 	if (!numeric_addr) {
915 		hp = gethostbyaddr(&in, sizeof (struct in_addr), AF_INET);
916 		if (hp) {
917 			cp = hp->h_name;
918 			trimdomain(cp, strlen(cp));
919 		}
920 	}
921 	if (cp) {
922 		strlcpy(line, cp, sizeof(line));
923 	} else {
924 #define	C(x)	((x) & 0xff)
925 		in = ntohl(in);
926 		sprintf(line, "%u.%u.%u.%u",
927 		    C(in >> 24), C(in >> 16), C(in >> 8), C(in));
928 	}
929 	return (line);
930 }
931 
932 #define	NSHIFT(m) (							\
933 	(m) == IN_CLASSA_NET ? IN_CLASSA_NSHIFT :			\
934 	(m) == IN_CLASSB_NET ? IN_CLASSB_NSHIFT :			\
935 	(m) == IN_CLASSC_NET ? IN_CLASSC_NSHIFT :			\
936 	0)
937 
938 static void
939 domask(char *dst, in_addr_t addr __unused, u_long mask)
940 {
941 	int b, i;
942 
943 	if (mask == 0 || (!numeric_addr && NSHIFT(mask) != 0)) {
944 		*dst = '\0';
945 		return;
946 	}
947 	i = 0;
948 	for (b = 0; b < 32; b++)
949 		if (mask & (1 << b)) {
950 			int bb;
951 
952 			i = b;
953 			for (bb = b+1; bb < 32; bb++)
954 				if (!(mask & (1 << bb))) {
955 					i = -1;	/* noncontig */
956 					break;
957 				}
958 			break;
959 		}
960 	if (i == -1)
961 		sprintf(dst, "&0x%lx", mask);
962 	else
963 		sprintf(dst, "/%d", 32-i);
964 }
965 
966 /*
967  * Return the name of the network whose address is given.
968  */
969 char *
970 netname(in_addr_t in, in_addr_t mask)
971 {
972 	char *cp = 0;
973 	static char line[MAXHOSTNAMELEN];
974 	struct netent *np = 0;
975 	in_addr_t i;
976 
977 	/* It is ok to supply host address. */
978 	in &= mask;
979 
980 	i = ntohl(in);
981 	if (!numeric_addr && i) {
982 		np = getnetbyaddr(i >> NSHIFT(ntohl(mask)), AF_INET);
983 		if (np != NULL) {
984 			cp = np->n_name;
985 			trimdomain(cp, strlen(cp));
986 		}
987 	}
988 	if (cp != NULL) {
989 		strlcpy(line, cp, sizeof(line));
990 	} else {
991 		inet_ntop(AF_INET, &in, line, sizeof(line) - 1);
992 	}
993 	domask(line + strlen(line), i, ntohl(mask));
994 	return (line);
995 }
996 
997 #undef NSHIFT
998 
999 #ifdef INET6
1000 void
1001 in6_fillscopeid(struct sockaddr_in6 *sa6)
1002 {
1003 #if defined(__KAME__)
1004 	/*
1005 	 * XXX: This is a special workaround for KAME kernels.
1006 	 * sin6_scope_id field of SA should be set in the future.
1007 	 */
1008 	if (IN6_IS_ADDR_LINKLOCAL(&sa6->sin6_addr) ||
1009 	    IN6_IS_ADDR_MC_NODELOCAL(&sa6->sin6_addr) ||
1010 	    IN6_IS_ADDR_MC_LINKLOCAL(&sa6->sin6_addr)) {
1011 		/* XXX: override is ok? */
1012 		sa6->sin6_scope_id =
1013 		    ntohs(*(u_int16_t *)&sa6->sin6_addr.s6_addr[2]);
1014 		sa6->sin6_addr.s6_addr[2] = sa6->sin6_addr.s6_addr[3] = 0;
1015 	}
1016 #endif
1017 }
1018 
1019 const char *
1020 netname6(struct sockaddr_in6 *sa6, struct in6_addr *mask)
1021 {
1022 	static char line[MAXHOSTNAMELEN];
1023 	u_char *p = (u_char *)mask;
1024 	u_char *lim;
1025 	int masklen, illegal = 0, flag = 0;
1026 
1027 	if (mask) {
1028 		for (masklen = 0, lim = p + 16; p < lim; p++) {
1029 			switch (*p) {
1030 			 case 0xff:
1031 				 masklen += 8;
1032 				 break;
1033 			 case 0xfe:
1034 				 masklen += 7;
1035 				 break;
1036 			 case 0xfc:
1037 				 masklen += 6;
1038 				 break;
1039 			 case 0xf8:
1040 				 masklen += 5;
1041 				 break;
1042 			 case 0xf0:
1043 				 masklen += 4;
1044 				 break;
1045 			 case 0xe0:
1046 				 masklen += 3;
1047 				 break;
1048 			 case 0xc0:
1049 				 masklen += 2;
1050 				 break;
1051 			 case 0x80:
1052 				 masklen += 1;
1053 				 break;
1054 			 case 0x00:
1055 				 break;
1056 			 default:
1057 				 illegal ++;
1058 				 break;
1059 			}
1060 		}
1061 		if (illegal)
1062 			fprintf(stderr, "illegal prefixlen\n");
1063 	}
1064 	else
1065 		masklen = 128;
1066 
1067 	if (masklen == 0 && IN6_IS_ADDR_UNSPECIFIED(&sa6->sin6_addr))
1068 		return("default");
1069 
1070 	if (numeric_addr)
1071 		flag |= NI_NUMERICHOST;
1072 	getnameinfo((struct sockaddr *)sa6, sa6->sin6_len, line, sizeof(line),
1073 		    NULL, 0, flag);
1074 
1075 	if (numeric_addr)
1076 		sprintf(&line[strlen(line)], "/%d", masklen);
1077 
1078 	return line;
1079 }
1080 
1081 char *
1082 routename6(struct sockaddr_in6 *sa6)
1083 {
1084 	static char line[MAXHOSTNAMELEN];
1085 	int flag = 0;
1086 	/* use local variable for safety */
1087 	struct sockaddr_in6 sa6_local;
1088 
1089 	sa6_local.sin6_family = AF_INET6;
1090 	sa6_local.sin6_len = sizeof(sa6_local);
1091 	sa6_local.sin6_addr = sa6->sin6_addr;
1092 	sa6_local.sin6_scope_id = sa6->sin6_scope_id;
1093 
1094 	if (numeric_addr)
1095 		flag |= NI_NUMERICHOST;
1096 
1097 	getnameinfo((struct sockaddr *)&sa6_local, sa6_local.sin6_len,
1098 		    line, sizeof(line), NULL, 0, flag);
1099 
1100 	return line;
1101 }
1102 #endif /*INET6*/
1103 
1104 /*
1105  * Print routing statistics
1106  */
1107 void
1108 rt_stats(void)
1109 {
1110 	struct rtstat rtstat;
1111 	u_long rtsaddr, rttaddr;
1112 	int rttrash;
1113 
1114 	kresolve_list(rl);
1115 
1116 	if ((rtsaddr = rl[N_RTSTAT].n_value) == 0) {
1117 		printf("rtstat: symbol not in namelist\n");
1118 		return;
1119 	}
1120 	if ((rttaddr = rl[N_RTTRASH].n_value) == 0) {
1121 		printf("rttrash: symbol not in namelist\n");
1122 		return;
1123 	}
1124 	kread(rtsaddr, (char *)&rtstat, sizeof (rtstat));
1125 	kread(rttaddr, (char *)&rttrash, sizeof (rttrash));
1126 	printf("routing:\n");
1127 
1128 #define	p(f, m) if (rtstat.f || sflag <= 1) \
1129 	printf(m, rtstat.f, plural(rtstat.f))
1130 
1131 	p(rts_badredirect, "\t%hu bad routing redirect%s\n");
1132 	p(rts_dynamic, "\t%hu dynamically created route%s\n");
1133 	p(rts_newgateway, "\t%hu new gateway%s due to redirects\n");
1134 	p(rts_unreach, "\t%hu destination%s found unreachable\n");
1135 	p(rts_wildcard, "\t%hu use%s of a wildcard route\n");
1136 #undef p
1137 
1138 	if (rttrash || sflag <= 1)
1139 		printf("\t%u route%s not in table but not freed\n",
1140 		    rttrash, plural(rttrash));
1141 }
1142 
1143 char *
1144 ipx_print(struct sockaddr *sa)
1145 {
1146 	u_short port;
1147 	struct servent *sp = 0;
1148 	const char *net = "", *host = "";
1149 	char *p;
1150 	u_char *q;
1151 	struct ipx_addr work = ((struct sockaddr_ipx *)sa)->sipx_addr;
1152 	static char mybuf[50];
1153 	char cport[10], chost[15], cnet[15];
1154 
1155 	port = ntohs(work.x_port);
1156 
1157 	if (ipx_nullnet(work) && ipx_nullhost(work)) {
1158 
1159 		if (port) {
1160 			if (sp)
1161 				sprintf(mybuf, "*.%s", sp->s_name);
1162 			else
1163 				sprintf(mybuf, "*.%x", port);
1164 		} else
1165 			sprintf(mybuf, "*.*");
1166 
1167 		return (mybuf);
1168 	}
1169 
1170 	if (ipx_wildnet(work))
1171 		net = "any";
1172 	else if (ipx_nullnet(work))
1173 		net = "*";
1174 	else {
1175 		q = work.x_net.c_net;
1176 		sprintf(cnet, "%02x%02x%02x%02x",
1177 			q[0], q[1], q[2], q[3]);
1178 		for (p = cnet; *p == '0' && p < cnet + 8; p++)
1179 			continue;
1180 		net = p;
1181 	}
1182 
1183 	if (ipx_wildhost(work))
1184 		host = "any";
1185 	else if (ipx_nullhost(work))
1186 		host = "*";
1187 	else {
1188 		q = work.x_host.c_host;
1189 		sprintf(chost, "%02x%02x%02x%02x%02x%02x",
1190 			q[0], q[1], q[2], q[3], q[4], q[5]);
1191 		for (p = chost; *p == '0' && p < chost + 12; p++)
1192 			continue;
1193 		host = p;
1194 	}
1195 
1196 	if (port) {
1197 		if (strcmp(host, "*") == 0)
1198 			host = "";
1199 		if (sp)
1200 			snprintf(cport, sizeof(cport),
1201 				"%s%s", *host ? "." : "", sp->s_name);
1202 		else
1203 			snprintf(cport, sizeof(cport),
1204 				"%s%x", *host ? "." : "", port);
1205 	} else
1206 		*cport = 0;
1207 
1208 	snprintf(mybuf, sizeof(mybuf), "%s.%s%s", net, host, cport);
1209 	return(mybuf);
1210 }
1211 
1212 char *
1213 ipx_phost(struct sockaddr *sa)
1214 {
1215 	struct sockaddr_ipx *sipx = (struct sockaddr_ipx *)sa;
1216 	struct sockaddr_ipx work;
1217 	static union ipx_net ipx_zeronet;
1218 	char *p;
1219 
1220 	work = *sipx;
1221 
1222 	work.sipx_addr.x_port = 0;
1223 	work.sipx_addr.x_net = ipx_zeronet;
1224 	p = ipx_print((struct sockaddr *)&work);
1225 	if (strncmp("*.", p, 2) == 0) p += 2;
1226 
1227 	return(p);
1228 }
1229 
1230 void
1231 upHex(char *p0)
1232 {
1233 	char *p = p0;
1234 
1235 	for (; *p; p++)
1236 		switch (*p) {
1237 
1238 		case 'a':
1239 		case 'b':
1240 		case 'c':
1241 		case 'd':
1242 		case 'e':
1243 		case 'f':
1244 			*p += ('A' - 'a');
1245 			break;
1246 		}
1247 }
1248