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