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