xref: /freebsd/sbin/route/route.c (revision 23f282aa31e9b6fceacd449020e936e98d6f2298)
1 /*
2  * Copyright (c) 1983, 1989, 1991, 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. All advertising materials mentioning features or use of this software
14  *    must display the following acknowledgement:
15  *	This product includes software developed by the University of
16  *	California, Berkeley and its contributors.
17  * 4. Neither the name of the University nor the names of its contributors
18  *    may be used to endorse or promote products derived from this software
19  *    without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  */
33 
34 #ifndef lint
35 static const char copyright[] =
36 "@(#) Copyright (c) 1983, 1989, 1991, 1993\n\
37 	The Regents of the University of California.  All rights reserved.\n";
38 #endif /* not lint */
39 
40 #ifndef lint
41 #if 0
42 static char sccsid[] = "@(#)route.c	8.3 (Berkeley) 3/19/94";
43 #endif
44 static const char rcsid[] =
45   "$FreeBSD$";
46 #endif /* not lint */
47 
48 #include <sys/param.h>
49 #include <sys/file.h>
50 #include <sys/socket.h>
51 #include <sys/ioctl.h>
52 #include <sys/sysctl.h>
53 #include <sys/types.h>
54 
55 #include <net/if.h>
56 #include <net/route.h>
57 #include <net/if_dl.h>
58 #include <netinet/in.h>
59 #include <netatalk/at.h>
60 #ifdef NS
61 #include <netns/ns.h>
62 #endif
63 #include <arpa/inet.h>
64 #include <netdb.h>
65 
66 #include <ctype.h>
67 #include <err.h>
68 #include <errno.h>
69 #include <stdio.h>
70 #include <stdlib.h>
71 #include <string.h>
72 #include <sysexits.h>
73 #include <unistd.h>
74 
75 /* wrapper for KAME-special getnameinfo() */
76 #ifndef NI_WITHSCOPEID
77 #define	NI_WITHSCOPEID	0
78 #endif
79 
80 struct keytab {
81 	char	*kt_cp;
82 	int	kt_i;
83 } keywords[] = {
84 #include "keywords.h"
85 	{0, 0}
86 };
87 
88 struct	ortentry route;
89 union	sockunion {
90 	struct	sockaddr sa;
91 	struct	sockaddr_in sin;
92 #ifdef INET6
93 	struct	sockaddr_in6 sin6;
94 #endif
95 	struct	sockaddr_at sat;
96 #ifdef NS
97 	struct	sockaddr_ns sns;
98 #endif
99 	struct	sockaddr_dl sdl;
100 } so_dst, so_gate, so_mask, so_genmask, so_ifa, so_ifp;
101 
102 typedef union sockunion *sup;
103 int	pid, rtm_addrs, uid;
104 int	s;
105 int	forcehost, forcenet, doflush, nflag, af, qflag, tflag, keyword();
106 int	iflag, verbose, aflen = sizeof (struct sockaddr_in);
107 int	locking, lockrest, debugonly;
108 struct	rt_metrics rt_metrics;
109 u_long  rtm_inits;
110 int	atalk_aton __P((const char *, struct at_addr *));
111 char	*atalk_ntoa __P((struct at_addr));
112 #ifdef INET6
113 char	*inet6_ntoa __P((struct sockaddr *sa));
114 #endif
115 char	*routename(), *netname();
116 void	flushroutes(), newroute(), monitor(), sockaddr(), sodump(), bprintf();
117 void	print_getmsg(), print_rtmsg(), pmsg_common(), pmsg_addrs(), mask_addr();
118 int	getaddr(), rtmsg(), x25_makemask();
119 int	prefixlen();
120 extern	char *iso_ntoa();
121 
122 void usage __P((const char *)) __dead2;
123 
124 #ifdef INET6
125 char name_buf[MAXHOSTNAMELEN * 2 + 1];	/*for getnameinfo()*/
126 #endif
127 
128 void
129 usage(cp)
130 	const char *cp;
131 {
132 	if (cp)
133 		warnx("bad keyword: %s", cp);
134 	(void) fprintf(stderr,
135 	    "usage: route [-dnqtv] command [[modifiers] args]\n");
136 	exit(EX_USAGE);
137 	/* NOTREACHED */
138 }
139 
140 #define ROUNDUP(a) \
141 	((a) > 0 ? (1 + (((a) - 1) | (sizeof(long) - 1))) : sizeof(long))
142 #define ADVANCE(x, n) (x += ROUNDUP((n)->sa_len))
143 
144 int
145 main(argc, argv)
146 	int argc;
147 	char **argv;
148 {
149 	int ch;
150 
151 	if (argc < 2)
152 		usage((char *)NULL);
153 
154 	while ((ch = getopt(argc, argv, "nqdtv")) != -1)
155 		switch(ch) {
156 		case 'n':
157 			nflag = 1;
158 			break;
159 		case 'q':
160 			qflag = 1;
161 			break;
162 		case 'v':
163 			verbose = 1;
164 			break;
165 		case 't':
166 			tflag = 1;
167 			break;
168 		case 'd':
169 			debugonly = 1;
170 			break;
171 		case '?':
172 		default:
173 			usage((char *)NULL);
174 		}
175 	argc -= optind;
176 	argv += optind;
177 
178 	pid = getpid();
179 	uid = getuid();
180 	if (tflag)
181 		s = open("/dev/null", O_WRONLY, 0);
182 	else
183 		s = socket(PF_ROUTE, SOCK_RAW, 0);
184 	if (s < 0)
185 		err(EX_OSERR, "socket");
186 	setuid(uid);
187 	if (*argv)
188 		switch (keyword(*argv)) {
189 		case K_GET:
190 			uid = 0;
191 			/* FALLTHROUGH */
192 
193 		case K_CHANGE:
194 		case K_ADD:
195 		case K_DELETE:
196 			newroute(argc, argv);
197 			exit(0);
198 			/* NOTREACHED */
199 
200 		case K_MONITOR:
201 			monitor();
202 			/* NOTREACHED */
203 
204 		case K_FLUSH:
205 			flushroutes(argc, argv);
206 			exit(0);
207 			/* NOTREACHED */
208 		}
209 	usage(*argv);
210 	/* NOTREACHED */
211 }
212 
213 /*
214  * Purge all entries in the routing tables not
215  * associated with network interfaces.
216  */
217 void
218 flushroutes(argc, argv)
219 	int argc;
220 	char *argv[];
221 {
222 	size_t needed;
223 	int mib[6], rlen, seqno;
224 	char *buf, *next, *lim;
225 	register struct rt_msghdr *rtm;
226 
227 	if (uid) {
228 		errx(EX_NOPERM, "must be root to alter routing table");
229 	}
230 	shutdown(s, 0); /* Don't want to read back our messages */
231 	if (argc > 1) {
232 		argv++;
233 		if (argc == 2 && **argv == '-')
234 		    switch (keyword(*argv + 1)) {
235 			case K_INET:
236 				af = AF_INET;
237 				break;
238 #ifdef INET6
239 			case K_INET6:
240 				af = AF_INET6;
241 				break;
242 #endif
243 			case K_ATALK:
244 				af = AF_APPLETALK;
245 				break;
246 #ifdef NS
247 			case K_XNS:
248 				af = AF_NS;
249 				break;
250 #endif
251 			case K_LINK:
252 				af = AF_LINK;
253 				break;
254 			default:
255 				goto bad;
256 		} else
257 bad:			usage(*argv);
258 	}
259 	mib[0] = CTL_NET;
260 	mib[1] = PF_ROUTE;
261 	mib[2] = 0;		/* protocol */
262 	mib[3] = 0;		/* wildcard address family */
263 	mib[4] = NET_RT_DUMP;
264 	mib[5] = 0;		/* no flags */
265 	if (sysctl(mib, 6, NULL, &needed, NULL, 0) < 0)
266 		err(EX_OSERR, "route-sysctl-estimate");
267 	if ((buf = malloc(needed)) == NULL)
268 		errx(EX_OSERR, "malloc failed");
269 	if (sysctl(mib, 6, buf, &needed, NULL, 0) < 0)
270 		err(EX_OSERR, "route-sysctl-get");
271 	lim = buf + needed;
272 	if (verbose)
273 		(void) printf("Examining routing table from sysctl\n");
274 	seqno = 0;		/* ??? */
275 	for (next = buf; next < lim; next += rtm->rtm_msglen) {
276 		rtm = (struct rt_msghdr *)next;
277 		if (verbose)
278 			print_rtmsg(rtm, rtm->rtm_msglen);
279 		if ((rtm->rtm_flags & RTF_GATEWAY) == 0)
280 			continue;
281 		if (af) {
282 			struct sockaddr *sa = (struct sockaddr *)(rtm + 1);
283 
284 			if (sa->sa_family != af)
285 				continue;
286 		}
287 		if (debugonly)
288 			continue;
289 		rtm->rtm_type = RTM_DELETE;
290 		rtm->rtm_seq = seqno;
291 		rlen = write(s, next, rtm->rtm_msglen);
292 		if (rlen < (int)rtm->rtm_msglen) {
293 			warn("write to routing socket");
294 			(void) printf("got only %d for rlen\n", rlen);
295 			break;
296 		}
297 		seqno++;
298 		if (qflag)
299 			continue;
300 		if (verbose)
301 			print_rtmsg(rtm, rlen);
302 		else {
303 			struct sockaddr *sa = (struct sockaddr *)(rtm + 1);
304 			(void) printf("%-20.20s ", rtm->rtm_flags & RTF_HOST ?
305 			    routename(sa) : netname(sa));
306 			sa = (struct sockaddr *)(sa->sa_len + (char *)sa);
307 			(void) printf("%-20.20s ", routename(sa));
308 			(void) printf("done\n");
309 		}
310 	}
311 }
312 
313 char *
314 routename(sa)
315 	struct sockaddr *sa;
316 {
317 	register char *cp;
318 	static char line[MAXHOSTNAMELEN + 1];
319 	struct hostent *hp;
320 	static char domain[MAXHOSTNAMELEN + 1];
321 	static int first = 1;
322 #ifdef NS
323 	char *ns_print();
324 #endif
325 
326 	if (first) {
327 		first = 0;
328 		if (gethostname(domain, MAXHOSTNAMELEN) == 0 &&
329 		    (cp = index(domain, '.'))) {
330 			domain[MAXHOSTNAMELEN] = '\0';
331 			(void) strcpy(domain, cp + 1);
332 		} else
333 			domain[0] = 0;
334 	}
335 
336 	if (sa->sa_len == 0)
337 		strcpy(line, "default");
338 	else switch (sa->sa_family) {
339 
340 	case AF_INET:
341 	    {	struct in_addr in;
342 		in = ((struct sockaddr_in *)sa)->sin_addr;
343 
344 		cp = 0;
345 		if (in.s_addr == INADDR_ANY || sa->sa_len < 4)
346 			cp = "default";
347 		if (cp == 0 && !nflag) {
348 			hp = gethostbyaddr((char *)&in, sizeof (struct in_addr),
349 				AF_INET);
350 			if (hp) {
351 				if ((cp = index(hp->h_name, '.')) &&
352 				    !strcmp(cp + 1, domain))
353 					*cp = 0;
354 				cp = hp->h_name;
355 			}
356 		}
357 		if (cp) {
358 			strncpy(line, cp, sizeof(line) - 1);
359 			line[sizeof(line) - 1] = '\0';
360 		} else {
361 			/* XXX - why not inet_ntoa()? */
362 #define C(x)	(unsigned)((x) & 0xff)
363 			in.s_addr = ntohl(in.s_addr);
364 			(void) sprintf(line, "%u.%u.%u.%u", C(in.s_addr >> 24),
365 			   C(in.s_addr >> 16), C(in.s_addr >> 8), C(in.s_addr));
366 		}
367 		break;
368 	    }
369 
370 #ifdef INET6
371 	case AF_INET6:
372 		(void) snprintf(line, sizeof(line), "%s", inet6_ntoa(sa));
373 		break;
374 #endif
375 
376 	case AF_APPLETALK:
377 		(void) snprintf(line, sizeof(line), "atalk %s",
378 			atalk_ntoa(((struct sockaddr_at *)sa)->sat_addr));
379 		break;
380 
381 #ifdef NS
382 	case AF_NS:
383 		return (ns_print((struct sockaddr_ns *)sa));
384 #endif
385 
386 	case AF_LINK:
387 		return (link_ntoa((struct sockaddr_dl *)sa));
388 
389 	default:
390 	    {	u_short *s = (u_short *)sa;
391 		u_short *slim = s + ((sa->sa_len + 1) >> 1);
392 		char *cp = line + sprintf(line, "(%d)", sa->sa_family);
393 		char *cpe = line + sizeof(line);
394 
395 		while (++s < slim && cp < cpe) /* start with sa->sa_data */
396 			cp += snprintf(cp, cpe - cp, " %x", *s);
397 		break;
398 	    }
399 	}
400 	return (line);
401 }
402 
403 /*
404  * Return the name of the network whose address is given.
405  * The address is assumed to be that of a net or subnet, not a host.
406  */
407 char *
408 netname(sa)
409 	struct sockaddr *sa;
410 {
411 	char *cp = 0;
412 	static char line[MAXHOSTNAMELEN + 1];
413 	struct netent *np = 0;
414 	u_long net, mask;
415 	register u_long i;
416 	int subnetshift;
417 #ifdef NS
418 	char *ns_print();
419 #endif
420 
421 	switch (sa->sa_family) {
422 
423 	case AF_INET:
424 	    {	struct in_addr in;
425 		in = ((struct sockaddr_in *)sa)->sin_addr;
426 
427 		i = in.s_addr = ntohl(in.s_addr);
428 		if (in.s_addr == 0)
429 			cp = "default";
430 		else if (!nflag) {
431 			if (IN_CLASSA(i)) {
432 				mask = IN_CLASSA_NET;
433 				subnetshift = 8;
434 			} else if (IN_CLASSB(i)) {
435 				mask = IN_CLASSB_NET;
436 				subnetshift = 8;
437 			} else {
438 				mask = IN_CLASSC_NET;
439 				subnetshift = 4;
440 			}
441 			/*
442 			 * If there are more bits than the standard mask
443 			 * would suggest, subnets must be in use.
444 			 * Guess at the subnet mask, assuming reasonable
445 			 * width subnet fields.
446 			 */
447 			while (in.s_addr &~ mask)
448 				mask = (long)mask >> subnetshift;
449 			net = in.s_addr & mask;
450 			while ((mask & 1) == 0)
451 				mask >>= 1, net >>= 1;
452 			np = getnetbyaddr(net, AF_INET);
453 			if (np)
454 				cp = np->n_name;
455 		}
456 		if (cp)
457 			strncpy(line, cp, sizeof(line));
458 		else if ((in.s_addr & 0xffffff) == 0)
459 			(void) sprintf(line, "%u", C(in.s_addr >> 24));
460 		else if ((in.s_addr & 0xffff) == 0)
461 			(void) sprintf(line, "%u.%u", C(in.s_addr >> 24),
462 			    C(in.s_addr >> 16));
463 		else if ((in.s_addr & 0xff) == 0)
464 			(void) sprintf(line, "%u.%u.%u", C(in.s_addr >> 24),
465 			    C(in.s_addr >> 16), C(in.s_addr >> 8));
466 		else
467 			(void) sprintf(line, "%u.%u.%u.%u", C(in.s_addr >> 24),
468 			    C(in.s_addr >> 16), C(in.s_addr >> 8),
469 			    C(in.s_addr));
470 		break;
471 	    }
472 
473 #ifdef INET6
474 	case AF_INET6:
475 		(void) snprintf(line, sizeof(line), "%s", inet6_ntoa(sa));
476 		break;
477 #endif
478 
479 	case AF_APPLETALK:
480 		(void) snprintf(line, sizeof(line), "atalk %s",
481 			atalk_ntoa(((struct sockaddr_at *)sa)->sat_addr));
482 		break;
483 
484 #ifdef NS
485 	case AF_NS:
486 		return (ns_print((struct sockaddr_ns *)sa));
487 		break;
488 #endif
489 
490 	case AF_LINK:
491 		return (link_ntoa((struct sockaddr_dl *)sa));
492 
493 
494 	default:
495 	    {	u_short *s = (u_short *)sa->sa_data;
496 		u_short *slim = s + ((sa->sa_len + 1)>>1);
497 		char *cp = line + sprintf(line, "af %d:", sa->sa_family);
498 		char *cpe = line + sizeof(line);
499 
500 		while (s < slim && cp < cpe)
501 			cp += snprintf(cp, cpe - cp, " %x", *s++);
502 		break;
503 	    }
504 	}
505 	return (line);
506 }
507 
508 void
509 set_metric(value, key)
510 	char *value;
511 	int key;
512 {
513 	int flag = 0;
514 	u_long noval, *valp = &noval;
515 
516 	switch (key) {
517 #define caseof(x, y, z)	case x: valp = &rt_metrics.z; flag = y; break
518 	caseof(K_MTU, RTV_MTU, rmx_mtu);
519 	caseof(K_HOPCOUNT, RTV_HOPCOUNT, rmx_hopcount);
520 	caseof(K_EXPIRE, RTV_EXPIRE, rmx_expire);
521 	caseof(K_RECVPIPE, RTV_RPIPE, rmx_recvpipe);
522 	caseof(K_SENDPIPE, RTV_SPIPE, rmx_sendpipe);
523 	caseof(K_SSTHRESH, RTV_SSTHRESH, rmx_ssthresh);
524 	caseof(K_RTT, RTV_RTT, rmx_rtt);
525 	caseof(K_RTTVAR, RTV_RTTVAR, rmx_rttvar);
526 	}
527 	rtm_inits |= flag;
528 	if (lockrest || locking)
529 		rt_metrics.rmx_locks |= flag;
530 	if (locking)
531 		locking = 0;
532 	*valp = atoi(value);
533 }
534 
535 void
536 newroute(argc, argv)
537 	int argc;
538 	register char **argv;
539 {
540 	char *cmd, *dest = "", *gateway = "", *err;
541 	int ishost = 0, ret, attempts, oerrno, flags = RTF_STATIC;
542 	int key;
543 	struct hostent *hp = 0;
544 
545 	if (uid) {
546 		errx(EX_NOPERM, "must be root to alter routing table");
547 	}
548 	cmd = argv[0];
549 	if (*cmd != 'g')
550 		shutdown(s, 0); /* Don't want to read back our messages */
551 	while (--argc > 0) {
552 		if (**(++argv)== '-') {
553 			switch (key = keyword(1 + *argv)) {
554 			case K_LINK:
555 				af = AF_LINK;
556 				aflen = sizeof(struct sockaddr_dl);
557 				break;
558 			case K_INET:
559 				af = AF_INET;
560 				aflen = sizeof(struct sockaddr_in);
561 				break;
562 #ifdef INET6
563 			case K_INET6:
564 				af = AF_INET6;
565 				aflen = sizeof(struct sockaddr_in6);
566 				break;
567 #endif
568 			case K_ATALK:
569 				af = AF_APPLETALK;
570 				aflen = sizeof(struct sockaddr_at);
571 				break;
572 			case K_SA:
573 				af = PF_ROUTE;
574 				aflen = sizeof(union sockunion);
575 				break;
576 #ifdef NS
577 			case K_XNS:
578 				af = AF_NS;
579 				aflen = sizeof(struct sockaddr_ns);
580 				break;
581 #endif
582 			case K_IFACE:
583 			case K_INTERFACE:
584 				iflag++;
585 				break;
586 			case K_NOSTATIC:
587 				flags &= ~RTF_STATIC;
588 				break;
589 			case K_LLINFO:
590 				flags |= RTF_LLINFO;
591 				break;
592 			case K_LOCK:
593 				locking = 1;
594 				break;
595 			case K_LOCKREST:
596 				lockrest = 1;
597 				break;
598 			case K_HOST:
599 				forcehost++;
600 				break;
601 			case K_REJECT:
602 				flags |= RTF_REJECT;
603 				break;
604 			case K_BLACKHOLE:
605 				flags |= RTF_BLACKHOLE;
606 				break;
607 			case K_PROTO1:
608 				flags |= RTF_PROTO1;
609 				break;
610 			case K_PROTO2:
611 				flags |= RTF_PROTO2;
612 				break;
613 			case K_CLONING:
614 				flags |= RTF_CLONING;
615 				break;
616 			case K_XRESOLVE:
617 				flags |= RTF_XRESOLVE;
618 				break;
619 			case K_STATIC:
620 				flags |= RTF_STATIC;
621 				break;
622 			case K_IFA:
623 				if (!--argc)
624 					usage((char *)NULL);
625 				(void) getaddr(RTA_IFA, *++argv, 0);
626 				break;
627 			case K_IFP:
628 				if (!--argc)
629 					usage((char *)NULL);
630 				(void) getaddr(RTA_IFP, *++argv, 0);
631 				break;
632 			case K_GENMASK:
633 				if (!--argc)
634 					usage((char *)NULL);
635 				(void) getaddr(RTA_GENMASK, *++argv, 0);
636 				break;
637 			case K_GATEWAY:
638 				if (!--argc)
639 					usage((char *)NULL);
640 				(void) getaddr(RTA_GATEWAY, *++argv, 0);
641 				break;
642 			case K_DST:
643 				if (!--argc)
644 					usage((char *)NULL);
645 				ishost = getaddr(RTA_DST, *++argv, &hp);
646 				dest = *argv;
647 				break;
648 			case K_NETMASK:
649 				if (!--argc)
650 					usage((char *)NULL);
651 				(void) getaddr(RTA_NETMASK, *++argv, 0);
652 				/* FALLTHROUGH */
653 			case K_NET:
654 				forcenet++;
655 				break;
656 			case K_PREFIXLEN:
657 				if (!--argc)
658 					usage((char *)NULL);
659 				if (prefixlen(*++argv) == -1) {
660 					forcenet = 0;
661 					ishost = 1;
662 				} else {
663 					forcenet = 1;
664 					ishost = 0;
665 				}
666 				break;
667 			case K_MTU:
668 			case K_HOPCOUNT:
669 			case K_EXPIRE:
670 			case K_RECVPIPE:
671 			case K_SENDPIPE:
672 			case K_SSTHRESH:
673 			case K_RTT:
674 			case K_RTTVAR:
675 				if (!--argc)
676 					usage((char *)NULL);
677 				set_metric(*++argv, key);
678 				break;
679 			default:
680 				usage(1+*argv);
681 			}
682 		} else {
683 			if ((rtm_addrs & RTA_DST) == 0) {
684 				dest = *argv;
685 				ishost = getaddr(RTA_DST, *argv, &hp);
686 			} else if ((rtm_addrs & RTA_GATEWAY) == 0) {
687 				gateway = *argv;
688 				(void) getaddr(RTA_GATEWAY, *argv, &hp);
689 			} else {
690 				(void) getaddr(RTA_NETMASK, *argv, 0);
691 			}
692 		}
693 	}
694 	if (forcehost) {
695 		ishost = 1;
696 #ifdef INET6
697 		if (af == AF_INET6) {
698 			rtm_addrs &= ~RTA_NETMASK;
699 			memset((void *)&so_mask, 0, sizeof(so_mask));
700 		}
701 #endif
702 	}
703 	if (forcenet)
704 		ishost = 0;
705 	flags |= RTF_UP;
706 	if (ishost)
707 		flags |= RTF_HOST;
708 	if (iflag == 0)
709 		flags |= RTF_GATEWAY;
710 	for (attempts = 1; ; attempts++) {
711 		errno = 0;
712 		if ((ret = rtmsg(*cmd, flags)) == 0)
713 			break;
714 		if (errno != ENETUNREACH && errno != ESRCH)
715 			break;
716 		if (af == AF_INET && *gateway && hp && hp->h_addr_list[1]) {
717 			hp->h_addr_list++;
718 			bcopy(hp->h_addr_list[0], &so_gate.sin.sin_addr,
719 			    MIN(hp->h_length, sizeof(so_gate.sin.sin_addr)));
720 		} else
721 			break;
722 	}
723 	if (*cmd == 'g')
724 		exit(0);
725 	oerrno = errno;
726 	(void) printf("%s %s %s", cmd, ishost? "host" : "net", dest);
727 	if (*gateway) {
728 		(void) printf(": gateway %s", gateway);
729 		if (attempts > 1 && ret == 0 && af == AF_INET)
730 		    (void) printf(" (%s)",
731 			inet_ntoa(((struct sockaddr_in *)&route.rt_gateway)->sin_addr));
732 	}
733 	if (ret == 0)
734 		(void) printf("\n");
735 	else {
736 		switch (oerrno) {
737 		case ESRCH:
738 			err = "not in table";
739 			break;
740 		case EBUSY:
741 			err = "entry in use";
742 			break;
743 		case ENOBUFS:
744 			err = "routing table overflow";
745 			break;
746 		default:
747 			err = strerror(oerrno);
748 			break;
749 		}
750 		(void) printf(": %s\n", err);
751 	}
752 }
753 
754 void
755 inet_makenetandmask(net, sin, bits)
756 	u_long net, bits;
757 	register struct sockaddr_in *sin;
758 {
759 	u_long addr, mask = 0;
760 	register char *cp;
761 
762 	rtm_addrs |= RTA_NETMASK;
763 	if (net == 0)
764 		mask = addr = 0;
765 	else if (bits) {
766 		addr = net;
767 		mask = 0xffffffff << (32 - bits);
768 	} else if (net < 128) {
769 		addr = net << IN_CLASSA_NSHIFT;
770 		mask = IN_CLASSA_NET;
771 	} else if (net < 65536) {
772 		addr = net << IN_CLASSB_NSHIFT;
773 		mask = IN_CLASSB_NET;
774 	} else if (net < 16777216L) {
775 		addr = net << IN_CLASSC_NSHIFT;
776 		mask = IN_CLASSC_NET;
777 	} else {
778 		addr = net;
779 		if ((addr & IN_CLASSA_HOST) == 0)
780 			mask =  IN_CLASSA_NET;
781 		else if ((addr & IN_CLASSB_HOST) == 0)
782 			mask =  IN_CLASSB_NET;
783 		else if ((addr & IN_CLASSC_HOST) == 0)
784 			mask =  IN_CLASSC_NET;
785 		else
786 			mask = -1;
787 	}
788 	sin->sin_addr.s_addr = htonl(addr);
789 	sin = &so_mask.sin;
790 	sin->sin_addr.s_addr = htonl(mask);
791 	sin->sin_len = 0;
792 	sin->sin_family = 0;
793 	cp = (char *)(&sin->sin_addr + 1);
794 	while (*--cp == 0 && cp > (char *)sin)
795 		;
796 	sin->sin_len = 1 + cp - (char *)sin;
797 }
798 
799 /*
800  * Interpret an argument as a network address of some kind,
801  * returning 1 if a host address, 0 if a network address.
802  */
803 int
804 getaddr(which, s, hpp)
805 	int which;
806 	char *s;
807 	struct hostent **hpp;
808 {
809 	register sup su;
810 	struct hostent *hp;
811 	struct netent *np;
812 	u_long val;
813 	char *q,qs;
814 	int afamily;  /* local copy of af so we can change it */
815 
816 	if (af == 0) {
817 		af = AF_INET;
818 		aflen = sizeof(struct sockaddr_in);
819 	}
820 	afamily = af;
821 	rtm_addrs |= which;
822 	switch (which) {
823 	case RTA_DST:
824 		su = &so_dst;
825 		break;
826 	case RTA_GATEWAY:
827 		su = &so_gate;
828 		if (iflag) {
829 			#define MAX_IFACES	400
830 			int			sock;
831 			struct ifreq		iflist[MAX_IFACES];
832 			struct ifconf		ifconf;
833 			struct ifreq		*ifr, *ifr_end;
834 			struct sockaddr_dl	*dl, *sdl = NULL;
835 
836 			/* Get socket */
837 			if ((sock = socket(PF_INET, SOCK_DGRAM, 0)) < 0)
838 				err(1, "socket");
839 
840 			/* Get interface list */
841 			ifconf.ifc_req = iflist;
842 			ifconf.ifc_len = sizeof(iflist);
843 			if (ioctl(sock, SIOCGIFCONF, &ifconf) < 0)
844 				err(1, "ioctl(SIOCGIFCONF)");
845 			close(sock);
846 
847 			/* Look for this interface in the list */
848 			for (ifr = ifconf.ifc_req,
849 			    ifr_end = (struct ifreq *)
850 				(ifconf.ifc_buf + ifconf.ifc_len);
851 			    ifr < ifr_end;
852 			    ifr = (struct ifreq *) ((char *) &ifr->ifr_addr
853 				    + MAX(ifr->ifr_addr.sa_len,
854 					sizeof(ifr->ifr_addr)))) {
855 				dl = (struct sockaddr_dl *)&ifr->ifr_addr;
856 				if (ifr->ifr_addr.sa_family == AF_LINK
857 				    && (ifr->ifr_flags & IFF_POINTOPOINT)
858 				    && !strncmp(s, dl->sdl_data, dl->sdl_nlen)
859 				    && s[dl->sdl_nlen] == 0) {
860 					sdl = dl;
861 					break;
862 				}
863 			}
864 
865 			/* If we found it, then use it */
866 			if (sdl) {
867 				su->sdl = *sdl;
868 				return(1);
869 			}
870 		}
871 		break;
872 	case RTA_NETMASK:
873 		su = &so_mask;
874 		break;
875 	case RTA_GENMASK:
876 		su = &so_genmask;
877 		break;
878 	case RTA_IFP:
879 		su = &so_ifp;
880 		afamily = AF_LINK;
881 		break;
882 	case RTA_IFA:
883 		su = &so_ifa;
884 		break;
885 	default:
886 		usage("internal error");
887 		/*NOTREACHED*/
888 	}
889 	su->sa.sa_len = aflen;
890 	su->sa.sa_family = afamily; /* cases that don't want it have left already */
891 	if (strcmp(s, "default") == 0) {
892 		/*
893 		 * Default is net 0.0.0.0/0
894 		 */
895 		switch (which) {
896 		case RTA_DST:
897 			forcenet++;
898 			/* bzero(su, sizeof(*su)); *//* for readability */
899 			(void) getaddr(RTA_NETMASK, s, 0);
900 			break;
901 		case RTA_NETMASK:
902 		case RTA_GENMASK:
903 			/* bzero(su, sizeof(*su)); *//* for readability */
904 		}
905 		return (0);
906 	}
907 	switch (afamily) {
908 #ifdef INET6
909 	case AF_INET6:
910 	  {
911 		struct addrinfo hints, *res;
912 		int error;
913 
914 		bzero(&hints, sizeof(struct addrinfo));
915 		hints.ai_family = AF_INET6;
916 
917 		error = getaddrinfo(s, NULL, &hints, &res);
918 		if (error != 0) {
919 			(void) fprintf(stderr, "%s: bad value\n",
920 				       gai_strerror(error));
921 			if (error == EAI_SYSTEM)
922 				(void) fprintf(stderr, "%s\n",
923 					       strerror(errno));
924 			exit(1);
925 		}
926 		bcopy(res->ai_addr, &su->sa, res->ai_addrlen);
927 		/* XXX: embedded link local addr check */
928 		if (IN6_IS_ADDR_LINKLOCAL(&su->sin6.sin6_addr))
929 			*(u_short *)&su->sin6.sin6_addr.s6_addr[2] =
930 				ntohs(su->sin6.sin6_scope_id);
931 		su->sin6.sin6_scope_id = 0;
932 		return 0;
933 	  }
934 #endif
935 
936 #ifdef NS
937 	case AF_NS:
938 		if (which == RTA_DST) {
939 			extern short ns_bh[3];
940 			struct sockaddr_ns *sms = &(so_mask.sns);
941 			bzero((char *)sms, sizeof(*sms));
942 			sms->sns_family = 0;
943 			sms->sns_len = 6;
944 			sms->sns_addr.x_net = *(union ns_net *)ns_bh;
945 			rtm_addrs |= RTA_NETMASK;
946 		}
947 		su->sns.sns_addr = ns_addr(s);
948 		return (!ns_nullhost(su->sns.sns_addr));
949 #endif
950 
951 
952 	case AF_APPLETALK:
953 		if (!atalk_aton(s, &su->sat.sat_addr))
954 			errx(EX_NOHOST, "bad address: %s", s);
955 		rtm_addrs |= RTA_NETMASK;
956 		return(forcehost || su->sat.sat_addr.s_node != 0);
957 
958 	case AF_LINK:
959 		link_addr(s, &su->sdl);
960 		return (1);
961 
962 
963 	case PF_ROUTE:
964 		su->sa.sa_len = sizeof(*su);
965 		sockaddr(s, &su->sa);
966 		return (1);
967 
968 	case AF_INET:
969 	default:
970 		break;
971 	}
972 
973 	if (hpp == NULL)
974 		hpp = &hp;
975 	*hpp = NULL;
976 
977 	q = strchr(s,'/');
978 	if (q && which == RTA_DST) {
979 		qs = *q;
980 		*q = '\0';
981 		if (((val = inet_addr(s)) != INADDR_NONE)) {
982 			inet_makenetandmask(
983 				htonl(val), &su->sin, strtoul(q+1, 0, 0));
984 			return (0);
985 		}
986 		*q =qs;
987 	}
988 	if (((val = inet_addr(s)) != INADDR_NONE) &&
989 	    (which != RTA_DST || forcenet == 0)) {
990 		su->sin.sin_addr.s_addr = val;
991 		if (inet_lnaof(su->sin.sin_addr) != INADDR_ANY)
992 			return (1);
993 		else {
994 			val = ntohl(val);
995 			goto netdone;
996 		}
997 	}
998 	if ((val = inet_network(s)) != INADDR_NONE ||
999 	    (forcehost == 0 && (np = getnetbyname(s)) != NULL &&
1000 		    (val = np->n_net) != 0)) {
1001 netdone:
1002 		if (which == RTA_DST)
1003 			inet_makenetandmask(val, &su->sin, 0);
1004 		return (0);
1005 	}
1006 	hp = gethostbyname(s);
1007 	if (hp) {
1008 		*hpp = hp;
1009 		su->sin.sin_family = hp->h_addrtype;
1010 		bcopy(hp->h_addr, (char *)&su->sin.sin_addr,
1011 		    MIN(hp->h_length, sizeof(su->sin.sin_addr)));
1012 		return (1);
1013 	}
1014 	errx(EX_NOHOST, "bad address: %s", s);
1015 }
1016 
1017 int
1018 prefixlen(s)
1019 	char *s;
1020 {
1021 	int len = atoi(s), q, r;
1022 	int max;
1023 	char *p;
1024 
1025 	rtm_addrs |= RTA_NETMASK;
1026 	switch (af) {
1027 #ifdef INET6
1028 	case AF_INET6:
1029 		max = 128;
1030 		p = (char *)&so_mask.sin6.sin6_addr;
1031 		break;
1032 #endif
1033 	case AF_INET:
1034 		max = 32;
1035 		p = (char *)&so_mask.sin.sin_addr;
1036 		break;
1037 	default:
1038 		(void) fprintf(stderr, "prefixlen not supported in this af\n");
1039 		exit(1);
1040 		/*NOTREACHED*/
1041 	}
1042 
1043 	if (len < 0 || max < len) {
1044 		(void) fprintf(stderr, "%s: bad value\n", s);
1045 		exit(1);
1046 	}
1047 
1048 	q = len >> 3;
1049 	r = len & 7;
1050 	so_mask.sa.sa_family = af;
1051 	so_mask.sa.sa_len = aflen;
1052 	memset((void *)p, 0, max / 8);
1053 	if (q > 0)
1054 		memset((void *)p, 0xff, q);
1055 	if (r > 0)
1056 		*((u_char *)p + q) = (0xff00 >> r) & 0xff;
1057 	if (len == max)
1058 		return -1;
1059 	else
1060 		return len;
1061 }
1062 
1063 #ifdef NS
1064 short ns_nullh[] = {0,0,0};
1065 short ns_bh[] = {-1,-1,-1};
1066 
1067 char *
1068 ns_print(sns)
1069 	struct sockaddr_ns *sns;
1070 {
1071 	struct ns_addr work;
1072 	union { union ns_net net_e; u_long long_e; } net;
1073 	u_short port;
1074 	static char mybuf[50+MAXHOSTNAMELEN], cport[10], chost[25];
1075 	char *host = "";
1076 	register char *p;
1077 	register u_char *q;
1078 
1079 	work = sns->sns_addr;
1080 	port = ntohs(work.x_port);
1081 	work.x_port = 0;
1082 	net.net_e  = work.x_net;
1083 	if (ns_nullhost(work) && net.long_e == 0) {
1084 		if (!port)
1085 			return ("*.*");
1086 		(void) sprintf(mybuf, "*.%XH", port);
1087 		return (mybuf);
1088 	}
1089 
1090 	if (bcmp((char *)ns_bh, (char *)work.x_host.c_host, 6) == 0)
1091 		host = "any";
1092 	else if (bcmp((char *)ns_nullh, (char *)work.x_host.c_host, 6) == 0)
1093 		host = "*";
1094 	else {
1095 		q = work.x_host.c_host;
1096 		(void) sprintf(chost, "%02X%02X%02X%02X%02X%02XH",
1097 			q[0], q[1], q[2], q[3], q[4], q[5]);
1098 		for (p = chost; *p == '0' && p < chost + 12; p++)
1099 			/* void */;
1100 		host = p;
1101 	}
1102 	if (port)
1103 		(void) sprintf(cport, ".%XH", htons(port));
1104 	else
1105 		*cport = 0;
1106 
1107 	(void) snprintf(mybuf, sizeof(mybuf), "%lxH.%s%s",
1108 			(unsigned long)ntohl(net.long_e),
1109 			host, cport);
1110 	return (mybuf);
1111 }
1112 #endif
1113 
1114 void
1115 interfaces()
1116 {
1117 	size_t needed;
1118 	int mib[6];
1119 	char *buf, *lim, *next;
1120 	register struct rt_msghdr *rtm;
1121 
1122 	mib[0] = CTL_NET;
1123 	mib[1] = PF_ROUTE;
1124 	mib[2] = 0;		/* protocol */
1125 	mib[3] = 0;		/* wildcard address family */
1126 	mib[4] = NET_RT_IFLIST;
1127 	mib[5] = 0;		/* no flags */
1128 	if (sysctl(mib, 6, NULL, &needed, NULL, 0) < 0)
1129 		err(EX_OSERR, "route-sysctl-estimate");
1130 	if ((buf = malloc(needed)) == NULL)
1131 		errx(EX_OSERR, "malloc failed");
1132 	if (sysctl(mib, 6, buf, &needed, NULL, 0) < 0)
1133 		err(EX_OSERR, "actual retrieval of interface table");
1134 	lim = buf + needed;
1135 	for (next = buf; next < lim; next += rtm->rtm_msglen) {
1136 		rtm = (struct rt_msghdr *)next;
1137 		print_rtmsg(rtm, rtm->rtm_msglen);
1138 	}
1139 }
1140 
1141 void
1142 monitor()
1143 {
1144 	int n;
1145 	char msg[2048];
1146 
1147 	verbose = 1;
1148 	if (debugonly) {
1149 		interfaces();
1150 		exit(0);
1151 	}
1152 	for(;;) {
1153 		time_t now;
1154 		n = read(s, msg, 2048);
1155 		now = time(NULL);
1156 		(void) printf("got message of size %d on %s", n, ctime(&now));
1157 		print_rtmsg((struct rt_msghdr *)msg, n);
1158 	}
1159 }
1160 
1161 struct {
1162 	struct	rt_msghdr m_rtm;
1163 	char	m_space[512];
1164 } m_rtmsg;
1165 
1166 int
1167 rtmsg(cmd, flags)
1168 	int cmd, flags;
1169 {
1170 	static int seq;
1171 	int rlen;
1172 	register char *cp = m_rtmsg.m_space;
1173 	register int l;
1174 
1175 #define NEXTADDR(w, u) \
1176 	if (rtm_addrs & (w)) {\
1177 	    l = ROUNDUP(u.sa.sa_len); bcopy((char *)&(u), cp, l); cp += l;\
1178 	    if (verbose) sodump(&(u),"u");\
1179 	}
1180 
1181 	errno = 0;
1182 	bzero((char *)&m_rtmsg, sizeof(m_rtmsg));
1183 	if (cmd == 'a')
1184 		cmd = RTM_ADD;
1185 	else if (cmd == 'c')
1186 		cmd = RTM_CHANGE;
1187 	else if (cmd == 'g') {
1188 		cmd = RTM_GET;
1189 		if (so_ifp.sa.sa_family == 0) {
1190 			so_ifp.sa.sa_family = AF_LINK;
1191 			so_ifp.sa.sa_len = sizeof(struct sockaddr_dl);
1192 			rtm_addrs |= RTA_IFP;
1193 		}
1194 	} else
1195 		cmd = RTM_DELETE;
1196 #define rtm m_rtmsg.m_rtm
1197 	rtm.rtm_type = cmd;
1198 	rtm.rtm_flags = flags;
1199 	rtm.rtm_version = RTM_VERSION;
1200 	rtm.rtm_seq = ++seq;
1201 	rtm.rtm_addrs = rtm_addrs;
1202 	rtm.rtm_rmx = rt_metrics;
1203 	rtm.rtm_inits = rtm_inits;
1204 
1205 	if (rtm_addrs & RTA_NETMASK)
1206 		mask_addr();
1207 	NEXTADDR(RTA_DST, so_dst);
1208 	NEXTADDR(RTA_GATEWAY, so_gate);
1209 	NEXTADDR(RTA_NETMASK, so_mask);
1210 	NEXTADDR(RTA_GENMASK, so_genmask);
1211 	NEXTADDR(RTA_IFP, so_ifp);
1212 	NEXTADDR(RTA_IFA, so_ifa);
1213 	rtm.rtm_msglen = l = cp - (char *)&m_rtmsg;
1214 	if (verbose)
1215 		print_rtmsg(&rtm, l);
1216 	if (debugonly)
1217 		return (0);
1218 	if ((rlen = write(s, (char *)&m_rtmsg, l)) < 0) {
1219 		warn("writing to routing socket");
1220 		return (-1);
1221 	}
1222 	if (cmd == RTM_GET) {
1223 		do {
1224 			l = read(s, (char *)&m_rtmsg, sizeof(m_rtmsg));
1225 		} while (l > 0 && (rtm.rtm_seq != seq || rtm.rtm_pid != pid));
1226 		if (l < 0)
1227 			warn("read from routing socket");
1228 		else
1229 			print_getmsg(&rtm, l);
1230 	}
1231 #undef rtm
1232 	return (0);
1233 }
1234 
1235 void
1236 mask_addr()
1237 {
1238 	int olen = so_mask.sa.sa_len;
1239 	register char *cp1 = olen + (char *)&so_mask, *cp2;
1240 
1241 	for (so_mask.sa.sa_len = 0; cp1 > (char *)&so_mask; )
1242 		if (*--cp1 != 0) {
1243 			so_mask.sa.sa_len = 1 + cp1 - (char *)&so_mask;
1244 			break;
1245 		}
1246 	if ((rtm_addrs & RTA_DST) == 0)
1247 		return;
1248 	switch (so_dst.sa.sa_family) {
1249 #ifdef NS
1250 	case AF_NS:
1251 #endif
1252 	case AF_INET:
1253 #ifdef INET6
1254 	case AF_INET6:
1255 #endif
1256 	case AF_APPLETALK:
1257 	case 0:
1258 		return;
1259 	}
1260 	cp1 = so_mask.sa.sa_len + 1 + (char *)&so_dst;
1261 	cp2 = so_dst.sa.sa_len + 1 + (char *)&so_dst;
1262 	while (cp2 > cp1)
1263 		*--cp2 = 0;
1264 	cp2 = so_mask.sa.sa_len + 1 + (char *)&so_mask;
1265 	while (cp1 > so_dst.sa.sa_data)
1266 		*--cp1 &= *--cp2;
1267 }
1268 
1269 char *msgtypes[] = {
1270 	"",
1271 	"RTM_ADD: Add Route",
1272 	"RTM_DELETE: Delete Route",
1273 	"RTM_CHANGE: Change Metrics or flags",
1274 	"RTM_GET: Report Metrics",
1275 	"RTM_LOSING: Kernel Suspects Partitioning",
1276 	"RTM_REDIRECT: Told to use different route",
1277 	"RTM_MISS: Lookup failed on this address",
1278 	"RTM_LOCK: fix specified metrics",
1279 	"RTM_OLDADD: caused by SIOCADDRT",
1280 	"RTM_OLDDEL: caused by SIOCDELRT",
1281 	"RTM_RESOLVE: Route created by cloning",
1282 	"RTM_NEWADDR: address being added to iface",
1283 	"RTM_DELADDR: address being removed from iface",
1284 	"RTM_IFINFO: iface status change",
1285 	"RTM_NEWMADDR: new multicast group membership on iface",
1286 	"RTM_DELMADDR: multicast group membership removed from iface",
1287 	0,
1288 };
1289 
1290 char metricnames[] =
1291 "\011pksent\010rttvar\7rtt\6ssthresh\5sendpipe\4recvpipe\3expire\2hopcount"
1292 "\1mtu";
1293 char routeflags[] =
1294 "\1UP\2GATEWAY\3HOST\4REJECT\5DYNAMIC\6MODIFIED\7DONE\010MASK_PRESENT"
1295 "\011CLONING\012XRESOLVE\013LLINFO\014STATIC\015BLACKHOLE\016b016"
1296 "\017PROTO2\020PROTO1\021PRCLONING\022WASCLONED\023PROTO3\024CHAINDELETE"
1297 "\025PINNED\026LOCAL\027BROADCAST\030MULTICAST";
1298 char ifnetflags[] =
1299 "\1UP\2BROADCAST\3DEBUG\4LOOPBACK\5PTP\6b6\7RUNNING\010NOARP"
1300 "\011PPROMISC\012ALLMULTI\013OACTIVE\014SIMPLEX\015LINK0\016LINK1"
1301 "\017LINK2\020MULTICAST";
1302 char addrnames[] =
1303 "\1DST\2GATEWAY\3NETMASK\4GENMASK\5IFP\6IFA\7AUTHOR\010BRD";
1304 
1305 void
1306 print_rtmsg(rtm, msglen)
1307 	register struct rt_msghdr *rtm;
1308 	int msglen;
1309 {
1310 	struct if_msghdr *ifm;
1311 	struct ifa_msghdr *ifam;
1312 #ifdef RTM_NEWMADDR
1313 	struct ifma_msghdr *ifmam;
1314 #endif
1315 
1316 	if (verbose == 0)
1317 		return;
1318 	if (rtm->rtm_version != RTM_VERSION) {
1319 		(void) printf("routing message version %d not understood\n",
1320 		    rtm->rtm_version);
1321 		return;
1322 	}
1323 	(void)printf("%s: len %d, ", msgtypes[rtm->rtm_type], rtm->rtm_msglen);
1324 	switch (rtm->rtm_type) {
1325 	case RTM_IFINFO:
1326 		ifm = (struct if_msghdr *)rtm;
1327 		(void) printf("if# %d, flags:", ifm->ifm_index);
1328 		bprintf(stdout, ifm->ifm_flags, ifnetflags);
1329 		pmsg_addrs((char *)(ifm + 1), ifm->ifm_addrs);
1330 		break;
1331 	case RTM_NEWADDR:
1332 	case RTM_DELADDR:
1333 		ifam = (struct ifa_msghdr *)rtm;
1334 		(void) printf("metric %d, flags:", ifam->ifam_metric);
1335 		bprintf(stdout, ifam->ifam_flags, routeflags);
1336 		pmsg_addrs((char *)(ifam + 1), ifam->ifam_addrs);
1337 		break;
1338 #ifdef RTM_NEWMADDR
1339 	case RTM_NEWMADDR:
1340 	case RTM_DELMADDR:
1341 		ifmam = (struct ifma_msghdr *)rtm;
1342 		pmsg_addrs((char *)(ifmam + 1), ifmam->ifmam_addrs);
1343 		break;
1344 #endif
1345 	default:
1346 		(void) printf("pid: %ld, seq %d, errno %d, flags:",
1347 			(long)rtm->rtm_pid, rtm->rtm_seq, rtm->rtm_errno);
1348 		bprintf(stdout, rtm->rtm_flags, routeflags);
1349 		pmsg_common(rtm);
1350 	}
1351 }
1352 
1353 void
1354 print_getmsg(rtm, msglen)
1355 	register struct rt_msghdr *rtm;
1356 	int msglen;
1357 {
1358 	struct sockaddr *dst = NULL, *gate = NULL, *mask = NULL;
1359 	struct sockaddr_dl *ifp = NULL;
1360 	register struct sockaddr *sa;
1361 	register char *cp;
1362 	register int i;
1363 
1364 	(void) printf("   route to: %s\n", routename(&so_dst));
1365 	if (rtm->rtm_version != RTM_VERSION) {
1366 		warnx("routing message version %d not understood",
1367 		     rtm->rtm_version);
1368 		return;
1369 	}
1370 	if (rtm->rtm_msglen > msglen) {
1371 		warnx("message length mismatch, in packet %d, returned %d",
1372 		      rtm->rtm_msglen, msglen);
1373 	}
1374 	if (rtm->rtm_errno)  {
1375 		errno = rtm->rtm_errno;
1376 		warn("message indicates error %d", errno);
1377 		return;
1378 	}
1379 	cp = ((char *)(rtm + 1));
1380 	if (rtm->rtm_addrs)
1381 		for (i = 1; i; i <<= 1)
1382 			if (i & rtm->rtm_addrs) {
1383 				sa = (struct sockaddr *)cp;
1384 				switch (i) {
1385 				case RTA_DST:
1386 					dst = sa;
1387 					break;
1388 				case RTA_GATEWAY:
1389 					gate = sa;
1390 					break;
1391 				case RTA_NETMASK:
1392 					mask = sa;
1393 					break;
1394 				case RTA_IFP:
1395 					if (sa->sa_family == AF_LINK &&
1396 					   ((struct sockaddr_dl *)sa)->sdl_nlen)
1397 						ifp = (struct sockaddr_dl *)sa;
1398 					break;
1399 				}
1400 				ADVANCE(cp, sa);
1401 			}
1402 	if (dst && mask)
1403 		mask->sa_family = dst->sa_family;	/* XXX */
1404 	if (dst)
1405 		(void)printf("destination: %s\n", routename(dst));
1406 	if (mask) {
1407 		int savenflag = nflag;
1408 
1409 		nflag = 1;
1410 		(void)printf("       mask: %s\n", routename(mask));
1411 		nflag = savenflag;
1412 	}
1413 	if (gate && rtm->rtm_flags & RTF_GATEWAY)
1414 		(void)printf("    gateway: %s\n", routename(gate));
1415 	if (ifp)
1416 		(void)printf("  interface: %.*s\n",
1417 		    ifp->sdl_nlen, ifp->sdl_data);
1418 	(void)printf("      flags: ");
1419 	bprintf(stdout, rtm->rtm_flags, routeflags);
1420 
1421 #define lock(f)	((rtm->rtm_rmx.rmx_locks & __CONCAT(RTV_,f)) ? 'L' : ' ')
1422 #define msec(u)	(((u) + 500) / 1000)		/* usec to msec */
1423 
1424 	(void) printf("\n%s\n", "\
1425  recvpipe  sendpipe  ssthresh  rtt,msec    rttvar  hopcount      mtu     expire");
1426 	printf("%8ld%c ", rtm->rtm_rmx.rmx_recvpipe, lock(RPIPE));
1427 	printf("%8ld%c ", rtm->rtm_rmx.rmx_sendpipe, lock(SPIPE));
1428 	printf("%8ld%c ", rtm->rtm_rmx.rmx_ssthresh, lock(SSTHRESH));
1429 	printf("%8ld%c ", msec(rtm->rtm_rmx.rmx_rtt), lock(RTT));
1430 	printf("%8ld%c ", msec(rtm->rtm_rmx.rmx_rttvar), lock(RTTVAR));
1431 	printf("%8ld%c ", rtm->rtm_rmx.rmx_hopcount, lock(HOPCOUNT));
1432 	printf("%8ld%c ", rtm->rtm_rmx.rmx_mtu, lock(MTU));
1433 	if (rtm->rtm_rmx.rmx_expire)
1434 		rtm->rtm_rmx.rmx_expire -= time(0);
1435 	printf("%8ld%c\n", rtm->rtm_rmx.rmx_expire, lock(EXPIRE));
1436 #undef lock
1437 #undef msec
1438 #define	RTA_IGN	(RTA_DST|RTA_GATEWAY|RTA_NETMASK|RTA_IFP|RTA_IFA|RTA_BRD)
1439 	if (verbose)
1440 		pmsg_common(rtm);
1441 	else if (rtm->rtm_addrs &~ RTA_IGN) {
1442 		(void) printf("sockaddrs: ");
1443 		bprintf(stdout, rtm->rtm_addrs, addrnames);
1444 		putchar('\n');
1445 	}
1446 #undef	RTA_IGN
1447 }
1448 
1449 void
1450 pmsg_common(rtm)
1451 	register struct rt_msghdr *rtm;
1452 {
1453 	(void) printf("\nlocks: ");
1454 	bprintf(stdout, rtm->rtm_rmx.rmx_locks, metricnames);
1455 	(void) printf(" inits: ");
1456 	bprintf(stdout, rtm->rtm_inits, metricnames);
1457 	pmsg_addrs(((char *)(rtm + 1)), rtm->rtm_addrs);
1458 }
1459 
1460 void
1461 pmsg_addrs(cp, addrs)
1462 	char	*cp;
1463 	int	addrs;
1464 {
1465 	register struct sockaddr *sa;
1466 	int i;
1467 
1468 	if (addrs == 0)
1469 		return;
1470 	(void) printf("\nsockaddrs: ");
1471 	bprintf(stdout, addrs, addrnames);
1472 	(void) putchar('\n');
1473 	for (i = 1; i; i <<= 1)
1474 		if (i & addrs) {
1475 			sa = (struct sockaddr *)cp;
1476 			(void) printf(" %s", routename(sa));
1477 			ADVANCE(cp, sa);
1478 		}
1479 	(void) putchar('\n');
1480 	(void) fflush(stdout);
1481 }
1482 
1483 void
1484 bprintf(fp, b, s)
1485 	register FILE *fp;
1486 	register int b;
1487 	register u_char *s;
1488 {
1489 	register int i;
1490 	int gotsome = 0;
1491 
1492 	if (b == 0)
1493 		return;
1494 	while ((i = *s++) != 0) {
1495 		if (b & (1 << (i-1))) {
1496 			if (gotsome == 0)
1497 				i = '<';
1498 			else
1499 				i = ',';
1500 			(void) putc(i, fp);
1501 			gotsome = 1;
1502 			for (; (i = *s) > 32; s++)
1503 				(void) putc(i, fp);
1504 		} else
1505 			while (*s > 32)
1506 				s++;
1507 	}
1508 	if (gotsome)
1509 		(void) putc('>', fp);
1510 }
1511 
1512 int
1513 keyword(cp)
1514 	char *cp;
1515 {
1516 	register struct keytab *kt = keywords;
1517 
1518 	while (kt->kt_cp && strcmp(kt->kt_cp, cp))
1519 		kt++;
1520 	return kt->kt_i;
1521 }
1522 
1523 void
1524 sodump(su, which)
1525 	register sup su;
1526 	char *which;
1527 {
1528 	switch (su->sa.sa_family) {
1529 	case AF_LINK:
1530 		(void) printf("%s: link %s; ",
1531 		    which, link_ntoa(&su->sdl));
1532 		break;
1533 	case AF_INET:
1534 		(void) printf("%s: inet %s; ",
1535 		    which, inet_ntoa(su->sin.sin_addr));
1536 		break;
1537 	case AF_APPLETALK:
1538 		(void) printf("%s: atalk %s; ",
1539 		    which, atalk_ntoa(su->sat.sat_addr));
1540 		break;
1541 #ifdef NS
1542 	case AF_NS:
1543 		(void) printf("%s: xns %s; ",
1544 		    which, ns_ntoa(su->sns.sns_addr));
1545 		break;
1546 #endif
1547 	}
1548 	(void) fflush(stdout);
1549 }
1550 
1551 /* States*/
1552 #define VIRGIN	0
1553 #define GOTONE	1
1554 #define GOTTWO	2
1555 /* Inputs */
1556 #define	DIGIT	(4*0)
1557 #define	END	(4*1)
1558 #define DELIM	(4*2)
1559 
1560 void
1561 sockaddr(addr, sa)
1562 	register char *addr;
1563 	register struct sockaddr *sa;
1564 {
1565 	register char *cp = (char *)sa;
1566 	int size = sa->sa_len;
1567 	char *cplim = cp + size;
1568 	register int byte = 0, state = VIRGIN, new = 0 /* foil gcc */;
1569 
1570 	bzero(cp, size);
1571 	cp++;
1572 	do {
1573 		if ((*addr >= '0') && (*addr <= '9')) {
1574 			new = *addr - '0';
1575 		} else if ((*addr >= 'a') && (*addr <= 'f')) {
1576 			new = *addr - 'a' + 10;
1577 		} else if ((*addr >= 'A') && (*addr <= 'F')) {
1578 			new = *addr - 'A' + 10;
1579 		} else if (*addr == 0)
1580 			state |= END;
1581 		else
1582 			state |= DELIM;
1583 		addr++;
1584 		switch (state /* | INPUT */) {
1585 		case GOTTWO | DIGIT:
1586 			*cp++ = byte; /*FALLTHROUGH*/
1587 		case VIRGIN | DIGIT:
1588 			state = GOTONE; byte = new; continue;
1589 		case GOTONE | DIGIT:
1590 			state = GOTTWO; byte = new + (byte << 4); continue;
1591 		default: /* | DELIM */
1592 			state = VIRGIN; *cp++ = byte; byte = 0; continue;
1593 		case GOTONE | END:
1594 		case GOTTWO | END:
1595 			*cp++ = byte; /* FALLTHROUGH */
1596 		case VIRGIN | END:
1597 			break;
1598 		}
1599 		break;
1600 	} while (cp < cplim);
1601 	sa->sa_len = cp - (char *)sa;
1602 }
1603 
1604 int
1605 atalk_aton(const char *text, struct at_addr *addr)
1606 {
1607 	u_int net, node;
1608 
1609 	if (sscanf(text, "%u.%u", &net, &node) != 2
1610 	    || net > 0xffff || node > 0xff)
1611 		return(0);
1612 	addr->s_net = htons(net);
1613 	addr->s_node = node;
1614 	return(1);
1615 }
1616 
1617 char *
1618 atalk_ntoa(struct at_addr at)
1619 {
1620 	static char buf[20];
1621 
1622 	(void) snprintf(buf, sizeof(buf), "%u.%u", ntohs(at.s_net), at.s_node);
1623 	return(buf);
1624 }
1625 
1626 #ifdef INET6
1627 char *
1628 inet6_ntoa(struct sockaddr *sa)
1629 {
1630 	char *cp;
1631 	struct sockaddr_in6 *sin6;
1632 	int error = -1, gap;
1633 
1634 	cp = NULL;
1635 	sin6 = (struct sockaddr_in6 *)sa;
1636 	gap = sizeof(struct sockaddr_in6) - sin6->sin6_len;
1637 	if (gap > 0)
1638 		bzero((char *)(sin6) + sin6->sin6_len, gap);
1639 
1640 	/* XXX: embedded link local addr check */
1641 	if (IN6_IS_ADDR_LINKLOCAL(&sin6->sin6_addr) &&
1642 	    *(u_short *)&sin6->sin6_addr.s6_addr[2] != 0) {
1643 		u_short index;
1644 
1645 		index = *(u_short *)&sin6->sin6_addr.s6_addr[2];
1646 		*(u_short *)&sin6->sin6_addr.s6_addr[2] = 0;
1647 		if (sin6->sin6_scope_id == 0)
1648 			sin6->sin6_scope_id = ntohs(index);
1649 	}
1650 
1651 	if (IN6_IS_ADDR_UNSPECIFIED(&sin6->sin6_addr) || sa->sa_len < 4)
1652 		cp = "default";
1653 	if (cp == 0 && !nflag)
1654 		error = getnameinfo(sa, sa->sa_len, name_buf, sizeof(name_buf),
1655 				    NULL, 0, NI_NAMEREQD);
1656 	if (error != 0)
1657 		error = getnameinfo(sa, sa->sa_len, name_buf,
1658 				    sizeof(name_buf), NULL, 0,
1659 				    NI_NUMERICHOST|NI_WITHSCOPEID);
1660 	if (error != 0)
1661 		inet_ntop(AF_INET6, &sin6->sin6_addr, name_buf,
1662 			  sizeof(name_buf));
1663 
1664 	return (cp != NULL) ? cp : name_buf;
1665 }
1666 #endif
1667