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