xref: /netbsd-src/usr.bin/netstat/route.c (revision 76dfffe33547c37f8bdd446e3e4ab0f3c16cea4b)
1 /*	$NetBSD: route.c,v 1.15 1996/05/07 02:55:06 thorpej Exp $	*/
2 
3 /*
4  * Copyright (c) 1983, 1988, 1993
5  *	The Regents of the University of California.  All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. All advertising materials mentioning features or use of this software
16  *    must display the following acknowledgement:
17  *	This product includes software developed by the University of
18  *	California, Berkeley and its contributors.
19  * 4. Neither the name of the University nor the names of its contributors
20  *    may be used to endorse or promote products derived from this software
21  *    without specific prior written permission.
22  *
23  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
24  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
25  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
27  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
28  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
29  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
30  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
31  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
32  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33  * SUCH DAMAGE.
34  */
35 
36 #ifndef lint
37 #if 0
38 static char sccsid[] = "from: @(#)route.c	8.3 (Berkeley) 3/9/94";
39 #else
40 static char *rcsid = "$NetBSD: route.c,v 1.15 1996/05/07 02:55:06 thorpej Exp $";
41 #endif
42 #endif /* not lint */
43 
44 #include <sys/param.h>
45 #include <sys/protosw.h>
46 #include <sys/socket.h>
47 #include <sys/mbuf.h>
48 
49 #include <net/if.h>
50 #include <net/if_dl.h>
51 #include <net/if_types.h>
52 #define _KERNEL
53 #include <net/route.h>
54 #undef _KERNEL
55 #include <netinet/in.h>
56 
57 #include <netns/ns.h>
58 
59 #include <sys/sysctl.h>
60 
61 #include <netdb.h>
62 #include <stdio.h>
63 #include <stdlib.h>
64 #include <string.h>
65 #include <unistd.h>
66 #include "netstat.h"
67 
68 #define kget(p, d) (kread((u_long)(p), (char *)&(d), sizeof (d)))
69 
70 /*
71  * Definitions for showing gateway flags.
72  */
73 struct bits {
74 	short	b_mask;
75 	char	b_val;
76 } bits[] = {
77 	{ RTF_UP,	'U' },
78 	{ RTF_GATEWAY,	'G' },
79 	{ RTF_HOST,	'H' },
80 	{ RTF_REJECT,	'R' },
81 	{ RTF_DYNAMIC,	'D' },
82 	{ RTF_MODIFIED,	'M' },
83 	{ RTF_DONE,	'd' }, /* Completed -- for routing messages only */
84 	{ RTF_MASK,	'm' }, /* Mask Present -- for routing messages only */
85 	{ RTF_CLONING,	'C' },
86 	{ RTF_XRESOLVE,	'X' },
87 	{ RTF_LLINFO,	'L' },
88 	{ RTF_STATIC,	'S' },
89 	{ RTF_PROTO1,	'1' },
90 	{ RTF_PROTO2,	'2' },
91 	{ 0 }
92 };
93 
94 static union {
95 	struct	sockaddr u_sa;
96 	u_short	u_data[128];
97 } pt_u;
98 
99 int	do_rtent = 0;
100 struct	rtentry rtentry;
101 struct	radix_node rnode;
102 struct	radix_mask rmask;
103 
104 int	NewTree = 0;
105 
106 static struct sockaddr *kgetsa __P((struct sockaddr *));
107 static void p_tree __P((struct radix_node *));
108 static void p_rtnode __P(());
109 static void ntreestuff __P(());
110 static void np_rtentry __P((struct rt_msghdr *));
111 static void p_sockaddr __P((struct sockaddr *, int, int));
112 static void p_flags __P((int, char *));
113 static void p_rtentry __P((struct rtentry *));
114 
115 /*
116  * Print routing tables.
117  */
118 void
119 routepr(rtree)
120 	u_long rtree;
121 {
122 	struct radix_node_head *rnh, head;
123 	int i;
124 
125 	printf("Routing tables\n");
126 
127 	if (Aflag == 0 && NewTree)
128 		ntreestuff();
129 	else {
130 		if (rtree == 0) {
131 			printf("rt_tables: symbol not in namelist\n");
132 			return;
133 		}
134 
135 		kget(rtree, rt_tables);
136 		for (i = 0; i <= AF_MAX; i++) {
137 			if ((rnh = rt_tables[i]) == 0)
138 				continue;
139 			kget(rnh, head);
140 			if (i == AF_UNSPEC) {
141 				if (Aflag && af == 0) {
142 					printf("Netmasks:\n");
143 					p_tree(head.rnh_treetop);
144 				}
145 			} else if (af == AF_UNSPEC || af == i) {
146 				pr_family(i);
147 				do_rtent = 1;
148 				pr_rthdr();
149 				p_tree(head.rnh_treetop);
150 			}
151 		}
152 	}
153 }
154 
155 /*
156  * Print address family header before a section of the routing table.
157  */
158 void
159 pr_family(af)
160 	int af;
161 {
162 	char *afname;
163 
164 	switch (af) {
165 	case AF_INET:
166 		afname = "Internet";
167 		break;
168 	case AF_NS:
169 		afname = "XNS";
170 		break;
171 	case AF_ISO:
172 		afname = "ISO";
173 		break;
174 	case AF_CCITT:
175 		afname = "X.25";
176 		break;
177 	default:
178 		afname = NULL;
179 		break;
180 	}
181 	if (afname)
182 		printf("\n%s:\n", afname);
183 	else
184 		printf("\nProtocol Family %d:\n", af);
185 }
186 
187 /* column widths; each followed by one space */
188 #define	WID_DST		16	/* width of destination column */
189 #define	WID_GW		18	/* width of gateway column */
190 
191 /*
192  * Print header for routing table columns.
193  */
194 void
195 pr_rthdr()
196 {
197 
198 	if (Aflag)
199 		printf("%-8.8s ","Address");
200 	printf("%-*.*s %-*.*s %-6.6s  %6.6s%8.8s %6.6s  %s\n",
201 		WID_DST, WID_DST, "Destination",
202 		WID_GW, WID_GW, "Gateway",
203 		"Flags", "Refs", "Use", "Mtu", "Interface");
204 }
205 
206 static struct sockaddr *
207 kgetsa(dst)
208 	register struct sockaddr *dst;
209 {
210 
211 	kget(dst, pt_u.u_sa);
212 	if (pt_u.u_sa.sa_len > sizeof (pt_u.u_sa))
213 		kread((u_long)dst, (char *)pt_u.u_data, pt_u.u_sa.sa_len);
214 	return (&pt_u.u_sa);
215 }
216 
217 static void
218 p_tree(rn)
219 	struct radix_node *rn;
220 {
221 
222 again:
223 	kget(rn, rnode);
224 	if (rnode.rn_b < 0) {
225 		if (Aflag)
226 			printf("%-8.8x ", rn);
227 		if (rnode.rn_flags & RNF_ROOT) {
228 			if (Aflag)
229 				printf("(root node)%s",
230 				    rnode.rn_dupedkey ? " =>\n" : "\n");
231 		} else if (do_rtent) {
232 			kget(rn, rtentry);
233 			p_rtentry(&rtentry);
234 			if (Aflag)
235 				p_rtnode();
236 		} else {
237 			p_sockaddr(kgetsa((struct sockaddr *)rnode.rn_key),
238 			    0, 44);
239 			putchar('\n');
240 		}
241 		if (rn = rnode.rn_dupedkey)
242 			goto again;
243 	} else {
244 		if (Aflag && do_rtent) {
245 			printf("%-8.8x ", rn);
246 			p_rtnode();
247 		}
248 		rn = rnode.rn_r;
249 		p_tree(rnode.rn_l);
250 		p_tree(rn);
251 	}
252 }
253 
254 char	nbuf[20];
255 
256 static void
257 p_rtnode()
258 {
259 	struct radix_mask *rm = rnode.rn_mklist;
260 
261 	if (rnode.rn_b < 0) {
262 		if (rnode.rn_mask) {
263 			printf("\t  mask ");
264 			p_sockaddr(kgetsa((struct sockaddr *)rnode.rn_mask),
265 				    0, -1);
266 		} else if (rm == 0)
267 			return;
268 	} else {
269 		sprintf(nbuf, "(%d)", rnode.rn_b);
270 		printf("%6.6s %8.8x : %8.8x", nbuf, rnode.rn_l, rnode.rn_r);
271 	}
272 	while (rm) {
273 		kget(rm, rmask);
274 		sprintf(nbuf, " %d refs, ", rmask.rm_refs);
275 		printf(" mk = %8.8x {(%d),%s",
276 			rm, -1 - rmask.rm_b, rmask.rm_refs ? nbuf : " ");
277 		p_sockaddr(kgetsa((struct sockaddr *)rmask.rm_mask), 0, -1);
278 		putchar('}');
279 		if (rm = rmask.rm_mklist)
280 			printf(" ->");
281 	}
282 	putchar('\n');
283 }
284 
285 static void
286 ntreestuff()
287 {
288 	size_t needed;
289 	int mib[6];
290 	char *buf, *next, *lim;
291 	register struct rt_msghdr *rtm;
292 
293         mib[0] = CTL_NET;
294         mib[1] = PF_ROUTE;
295         mib[2] = 0;
296         mib[3] = 0;
297         mib[4] = NET_RT_DUMP;
298         mib[5] = 0;
299         if (sysctl(mib, 6, NULL, &needed, NULL, 0) < 0)
300 		{ perror("route-sysctl-estimate"); exit(1);}
301 	if ((buf = malloc(needed)) == 0)
302 		{ printf("out of space\n"); exit(1);}
303         if (sysctl(mib, 6, buf, &needed, NULL, 0) < 0)
304 		{ perror("sysctl of routing table"); exit(1);}
305 	lim  = buf + needed;
306 	for (next = buf; next < lim; next += rtm->rtm_msglen) {
307 		rtm = (struct rt_msghdr *)next;
308 		np_rtentry(rtm);
309 	}
310 }
311 
312 static void
313 np_rtentry(rtm)
314 	register struct rt_msghdr *rtm;
315 {
316 	register struct sockaddr *sa = (struct sockaddr *)(rtm + 1);
317 #ifdef notdef
318 	static int masks_done, banner_printed;
319 #endif
320 	static int old_af;
321 	int af = 0, interesting = RTF_UP | RTF_GATEWAY | RTF_HOST;
322 
323 #ifdef notdef
324 	/* for the moment, netmasks are skipped over */
325 	if (!banner_printed) {
326 		printf("Netmasks:\n");
327 		banner_printed = 1;
328 	}
329 	if (masks_done == 0) {
330 		if (rtm->rtm_addrs != RTA_DST ) {
331 			masks_done = 1;
332 			af = sa->sa_family;
333 		}
334 	} else
335 #endif
336 		af = sa->sa_family;
337 	if (af != old_af) {
338 		pr_family(af);
339 		old_af = af;
340 	}
341 	if (rtm->rtm_addrs == RTA_DST)
342 		p_sockaddr(sa, 0, 36);
343 	else {
344 		p_sockaddr(sa, rtm->rtm_flags, 16);
345 		if (sa->sa_len == 0)
346 			sa->sa_len = sizeof(long);
347 		sa = (struct sockaddr *)(sa->sa_len + (char *)sa);
348 		p_sockaddr(sa, 0, 18);
349 	}
350 	p_flags(rtm->rtm_flags & interesting, "%-6.6s ");
351 	putchar('\n');
352 }
353 
354 static void
355 p_sockaddr(sa, flags, width)
356 	struct sockaddr *sa;
357 	int flags, width;
358 {
359 	char workbuf[128], *cplim;
360 	register char *cp = workbuf;
361 
362 	switch(sa->sa_family) {
363 	case AF_INET:
364 	    {
365 		register struct sockaddr_in *sin = (struct sockaddr_in *)sa;
366 
367 		cp = (sin->sin_addr.s_addr == 0) ? "default" :
368 		      ((flags & RTF_HOST) ?
369 			routename(sin->sin_addr.s_addr) :
370 			netname(sin->sin_addr.s_addr, INADDR_ANY));
371 		break;
372 	    }
373 
374 	case AF_NS:
375 		cp = ns_print(sa);
376 		break;
377 
378 	case AF_LINK:
379 	    {
380 		register struct sockaddr_dl *sdl = (struct sockaddr_dl *)sa;
381 
382 		if (sdl->sdl_nlen == 0 && sdl->sdl_alen == 0 &&
383 		    sdl->sdl_slen == 0)
384 			(void) sprintf(workbuf, "link#%d", sdl->sdl_index);
385 		else switch (sdl->sdl_type) {
386 		case IFT_ETHER:
387 		    {
388 			register int i;
389 			register u_char *lla = (u_char *)sdl->sdl_data +
390 			    sdl->sdl_nlen;
391 
392 			cplim = "";
393 			for (i = 0; i < sdl->sdl_alen; i++, lla++) {
394 				cp += sprintf(cp, "%s%x", cplim, *lla);
395 				cplim = ":";
396 			}
397 			cp = workbuf;
398 			break;
399 		    }
400 		default:
401 			cp = link_ntoa(sdl);
402 			break;
403 		}
404 		break;
405 	    }
406 
407 	default:
408 	    {
409 		register u_char *s = (u_char *)sa->sa_data, *slim;
410 
411 		slim =  sa->sa_len + (u_char *) sa;
412 		cplim = cp + sizeof(workbuf) - 6;
413 		cp += sprintf(cp, "(%d)", sa->sa_family);
414 		while (s < slim && cp < cplim) {
415 			cp += sprintf(cp, " %02x", *s++);
416 			if (s < slim)
417 			    cp += sprintf(cp, "%02x", *s++);
418 		}
419 		cp = workbuf;
420 	    }
421 	}
422 	if (width < 0 )
423 		printf("%s ", cp);
424 	else {
425 		if (nflag)
426 			printf("%-*s ", width, cp);
427 		else
428 			printf("%-*.*s ", width, width, cp);
429 	}
430 }
431 
432 static void
433 p_flags(f, format)
434 	register int f;
435 	char *format;
436 {
437 	char name[33], *flags;
438 	register struct bits *p = bits;
439 
440 	for (flags = name; p->b_mask; p++)
441 		if (p->b_mask & f)
442 			*flags++ = p->b_val;
443 	*flags = '\0';
444 	printf(format, name);
445 }
446 
447 static void
448 p_rtentry(rt)
449 	register struct rtentry *rt;
450 {
451 	static struct ifnet ifnet, *lastif;
452 
453 	p_sockaddr(kgetsa(rt_key(rt)), rt->rt_flags, WID_DST);
454 	p_sockaddr(kgetsa(rt->rt_gateway), RTF_HOST, WID_GW);
455 	p_flags(rt->rt_flags, "%-6.6s ");
456 	printf("%6d %8d ", rt->rt_refcnt, rt->rt_use);
457 	if (rt->rt_rmx.rmx_mtu)
458 		printf("%6d ", rt->rt_rmx.rmx_mtu);
459 	else
460 		printf("%6s ", "-");
461 	if (rt->rt_ifp) {
462 		if (rt->rt_ifp != lastif) {
463 			kget(rt->rt_ifp, ifnet);
464 			lastif = rt->rt_ifp;
465 		}
466 		printf(" %.16s%s", ifnet.if_xname,
467 			rt->rt_nodes[0].rn_dupedkey ? " =>" : "");
468 	}
469 	putchar('\n');
470 }
471 
472 char *
473 routename(in)
474 	u_int32_t in;
475 {
476 	register char *cp;
477 	static char line[MAXHOSTNAMELEN + 1];
478 	struct hostent *hp;
479 	static char domain[MAXHOSTNAMELEN + 1];
480 	static int first = 1;
481 
482 	if (first) {
483 		first = 0;
484 		if (gethostname(domain, MAXHOSTNAMELEN) == 0 &&
485 		    (cp = index(domain, '.')))
486 			(void) strcpy(domain, cp + 1);
487 		else
488 			domain[0] = 0;
489 	}
490 	cp = 0;
491 	if (!nflag) {
492 		hp = gethostbyaddr((char *)&in, sizeof (struct in_addr),
493 			AF_INET);
494 		if (hp) {
495 			if ((cp = index(hp->h_name, '.')) &&
496 			    !strcmp(cp + 1, domain))
497 				*cp = 0;
498 			cp = hp->h_name;
499 		}
500 	}
501 	if (cp)
502 		strncpy(line, cp, sizeof(line) - 1);
503 	else {
504 #define C(x)	((x) & 0xff)
505 		in = ntohl(in);
506 		sprintf(line, "%u.%u.%u.%u",
507 		    C(in >> 24), C(in >> 16), C(in >> 8), C(in));
508 	}
509 	return (line);
510 }
511 
512 /*
513  * Return the name of the network whose address is given.
514  * The address is assumed to be that of a net or subnet, not a host.
515  */
516 char *
517 netname(in, mask)
518 	u_int32_t in, mask;
519 {
520 	char *cp = 0;
521 	static char line[MAXHOSTNAMELEN + 1];
522 	struct netent *np = 0;
523 	u_int32_t net;
524 	int subnetshift;
525 
526 	in = ntohl(in);
527 	mask = ntohl(mask);
528 	if (!nflag && in != INADDR_ANY) {
529 		if (mask == INADDR_ANY) {
530 			if (IN_CLASSA(in)) {
531 				mask = IN_CLASSA_NET;
532 				subnetshift = 8;
533 			} else if (IN_CLASSB(in)) {
534 				mask = IN_CLASSB_NET;
535 				subnetshift = 8;
536 			} else {
537 				mask = IN_CLASSC_NET;
538 				subnetshift = 4;
539 			}
540 			/*
541 			 * If there are more bits than the standard mask
542 			 * would suggest, subnets must be in use.
543 			 * Guess at the subnet mask, assuming reasonable
544 			 * width subnet fields.
545 			 */
546 			while (in &~ mask)
547 				mask = (long)mask >> subnetshift;
548 		}
549 		net = in & mask;
550 		while ((mask & 1) == 0)
551 			mask >>= 1, net >>= 1;
552 		np = getnetbyaddr(net, AF_INET);
553 		if (np)
554 			cp = np->n_name;
555 	}
556 	if (cp)
557 		strncpy(line, cp, sizeof(line) - 1);
558 	else if ((in & 0xffffff) == 0)
559 		sprintf(line, "%u", C(in >> 24));
560 	else if ((in & 0xffff) == 0)
561 		sprintf(line, "%u.%u", C(in >> 24) , C(in >> 16));
562 	else if ((in & 0xff) == 0)
563 		sprintf(line, "%u.%u.%u", C(in >> 24), C(in >> 16), C(in >> 8));
564 	else
565 		sprintf(line, "%u.%u.%u.%u", C(in >> 24),
566 			C(in >> 16), C(in >> 8), C(in));
567 	return (line);
568 }
569 
570 /*
571  * Print routing statistics
572  */
573 void
574 rt_stats(off)
575 	u_long off;
576 {
577 	struct rtstat rtstat;
578 
579 	if (off == 0) {
580 		printf("rtstat: symbol not in namelist\n");
581 		return;
582 	}
583 	kread(off, (char *)&rtstat, sizeof (rtstat));
584 	printf("routing:\n");
585 	printf("\t%u bad routing redirect%s\n",
586 		rtstat.rts_badredirect, plural(rtstat.rts_badredirect));
587 	printf("\t%u dynamically created route%s\n",
588 		rtstat.rts_dynamic, plural(rtstat.rts_dynamic));
589 	printf("\t%u new gateway%s due to redirects\n",
590 		rtstat.rts_newgateway, plural(rtstat.rts_newgateway));
591 	printf("\t%u destination%s found unreachable\n",
592 		rtstat.rts_unreach, plural(rtstat.rts_unreach));
593 	printf("\t%u use%s of a wildcard route\n",
594 		rtstat.rts_wildcard, plural(rtstat.rts_wildcard));
595 }
596 short ns_nullh[] = {0,0,0};
597 short ns_bh[] = {-1,-1,-1};
598 
599 char *
600 ns_print(sa)
601 	register struct sockaddr *sa;
602 {
603 	register struct sockaddr_ns *sns = (struct sockaddr_ns*)sa;
604 	struct ns_addr work;
605 	union { union ns_net net_e; u_long long_e; } net;
606 	u_short port;
607 	static char mybuf[50], cport[10], chost[25];
608 	char *host = "";
609 	register char *p; register u_char *q;
610 
611 	work = sns->sns_addr;
612 	port = ntohs(work.x_port);
613 	work.x_port = 0;
614 	net.net_e  = work.x_net;
615 	if (ns_nullhost(work) && net.long_e == 0) {
616 		if (port ) {
617 			sprintf(mybuf, "*.%xH", port);
618 			upHex(mybuf);
619 		} else
620 			sprintf(mybuf, "*.*");
621 		return (mybuf);
622 	}
623 
624 	if (bcmp(ns_bh, work.x_host.c_host, 6) == 0) {
625 		host = "any";
626 	} else if (bcmp(ns_nullh, work.x_host.c_host, 6) == 0) {
627 		host = "*";
628 	} else {
629 		q = work.x_host.c_host;
630 		sprintf(chost, "%02x%02x%02x%02x%02x%02xH",
631 			q[0], q[1], q[2], q[3], q[4], q[5]);
632 		for (p = chost; *p == '0' && p < chost + 12; p++)
633 			continue;
634 		host = p;
635 	}
636 	if (port)
637 		sprintf(cport, ".%xH", htons(port));
638 	else
639 		*cport = 0;
640 
641 	sprintf(mybuf,"%xH.%s%s", ntohl(net.long_e), host, cport);
642 	upHex(mybuf);
643 	return(mybuf);
644 }
645 
646 char *
647 ns_phost(sa)
648 	struct sockaddr *sa;
649 {
650 	register struct sockaddr_ns *sns = (struct sockaddr_ns *)sa;
651 	struct sockaddr_ns work;
652 	static union ns_net ns_zeronet;
653 	char *p;
654 
655 	work = *sns;
656 	work.sns_addr.x_port = 0;
657 	work.sns_addr.x_net = ns_zeronet;
658 
659 	p = ns_print((struct sockaddr *)&work);
660 	if (strncmp("0H.", p, 3) == 0) p += 3;
661 	return(p);
662 }
663 
664 void
665 upHex(p0)
666 	char *p0;
667 {
668 	register char *p = p0;
669 	for (; *p; p++) switch (*p) {
670 
671 	case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
672 		*p += ('A' - 'a');
673 	}
674 }
675