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