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