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