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