xref: /dragonfly/sbin/route/route.c (revision 25a2db75)
1 /*
2  * Copyright (c) 1983, 1989, 1991, 1993
3  *	The Regents of the University of California.  All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 4. Neither the name of the University nor the names of its contributors
14  *    may be used to endorse or promote products derived from this software
15  *    without specific prior written permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  *
29  * @(#) Copyright (c) 1983, 1989, 1991, 1993 The Regents of the University of California.  All rights reserved.
30  * @(#)route.c	8.6 (Berkeley) 4/28/95
31  * $FreeBSD: src/sbin/route/route.c,v 1.40.2.11 2003/02/27 23:10:10 ru Exp $
32  */
33 
34 #include <sys/param.h>
35 #include <sys/file.h>
36 #include <sys/socket.h>
37 #include <sys/ioctl.h>
38 #include <sys/sysctl.h>
39 #include <sys/types.h>
40 
41 #include <net/if.h>
42 #include <net/route.h>
43 #include <net/if_dl.h>
44 #include <netinet/in.h>
45 #include <netinet/if_ether.h>
46 #include <arpa/inet.h>
47 #include <netdb.h>
48 
49 #include <netproto/mpls/mpls.h>
50 
51 #include <ctype.h>
52 #include <err.h>
53 #include <errno.h>
54 #include <paths.h>
55 #include <stdio.h>
56 #include <stdlib.h>
57 #include <string.h>
58 #include <sysexits.h>
59 #include <unistd.h>
60 #include <ifaddrs.h>
61 
62 #include "extern.h"
63 #include "keywords.h"
64 
65 union	sockunion {
66 	struct	sockaddr sa;
67 	struct	sockaddr_in sin;
68 #ifdef INET6
69 	struct	sockaddr_in6 sin6;
70 #endif
71 	struct	sockaddr_mpls smpls;
72 	struct	sockaddr_dl sdl;
73 	struct	sockaddr_inarp sinarp;
74 	struct	sockaddr_storage ss; /* added to avoid memory overrun */
75 } so_dst, so_gate, so_mask, so_genmask, so_ifa, so_ifp, so_mpls1,
76 	so_mpls2, so_mpls3;
77 
78 typedef union sockunion *sup;
79 
80 int	nflag, wflag;
81 int	cpuflag = -1;
82 
83 static struct ortentry route;
84 static struct rt_metrics rt_metrics;
85 static int	pid, rtm_addrs;
86 static int	s;
87 static int	forcehost, forcenet, af, qflag, tflag;
88 static int	iflag, verbose, aflen = sizeof(struct sockaddr_in);
89 static int	locking, lockrest, debugonly;
90 static int	mplsop, popcount, pushcount, swapcount;
91 static u_long	rtm_inits;
92 static uid_t	uid;
93 
94 static void	 flushroutes(int, char **);
95 static void	 set_metric(char *, int);
96 static void	 newroute(int, char **);
97 static void	 inet_makenetandmask(u_long, struct sockaddr_in *, u_long);
98 static void	 interfaces(void);
99 static void	 monitor(void);
100 static void	 sockaddr(const char *, struct sockaddr *);
101 static void	 sodump(sup, const char *);
102 static void	 bprintf(FILE *, int, u_char *);
103 static void	 print_getmsg(struct rt_msghdr *, int);
104 static void	 print_rtmsg(struct rt_msghdr *, int);
105 static void	 pmsg_common(struct rt_msghdr *);
106 static void	 pmsg_addrs(char *, int);
107 static void	 mask_addr(void);
108 static int	 getaddr(int, const char *, struct hostent **);
109 static int	 rtmsg(int, int);
110 static int	 prefixlen(const char *);
111 #ifdef INET6
112 static int	 inet6_makenetandmask(struct sockaddr_in6 *, const char *);
113 #endif
114 
115 void
116 usage(const char *cp)
117 {
118 	if (cp != NULL)
119 		warnx("bad keyword: %s", cp);
120 	fprintf(stderr, "usage: route [-dnqtv] command [[modifiers] args]\n");
121 	exit(EX_USAGE);
122 	/* NOTREACHED */
123 }
124 
125 #define ROUNDUP(a) \
126 	((a) > 0 ? (1 + (((a) - 1) | (sizeof(long) - 1))) : sizeof(long))
127 #define ADVANCE(x, n) (x += ROUNDUP((n)->sa_len))
128 
129 int
130 main(int argc, char **argv)
131 {
132 	int ch;
133 
134 	if (argc < 2)
135 		usage(NULL);
136 
137 	while ((ch = getopt(argc, argv, "c:wnqdtv")) != -1)
138 		switch(ch) {
139 		case 'c':
140 			cpuflag = strtol(optarg, NULL, 0);
141 			break;
142 		case 'w':
143 			wflag = 1;
144 			break;
145 		case 'n':
146 			nflag = 1;
147 			break;
148 		case 'q':
149 			qflag = 1;
150 			break;
151 		case 'v':
152 			verbose = 1;
153 			break;
154 		case 't':
155 			tflag = 1;
156 			break;
157 		case 'd':
158 			debugonly = 1;
159 			break;
160 		case '?':
161 		default:
162 			usage(NULL);
163 		}
164 	argc -= optind;
165 	argv += optind;
166 
167 	pid = getpid();
168 	uid = geteuid();
169 	if (tflag)
170 		s = open(_PATH_DEVNULL, O_WRONLY, 0);
171 	else
172 		s = socket(PF_ROUTE, SOCK_RAW, 0);
173 	if (s < 0)
174 		err(EX_OSERR, "socket");
175 	if (*argv != NULL)
176 		switch (keyword(*argv)) {
177 		case K_GET:
178 			uid = 0;
179 			/* FALLTHROUGH */
180 
181 		case K_CHANGE:
182 		case K_ADD:
183 		case K_DELETE:
184 			newroute(argc, argv);
185 			/* NOTREACHED */
186 
187 		case K_SHOW:
188 			show(argc, argv);
189 			return(0);
190 
191 		case K_MONITOR:
192 			monitor();
193 			/* NOTREACHED */
194 
195 		case K_FLUSH:
196 			flushroutes(argc, argv);
197 			exit(0);
198 			/* NOTREACHED */
199 		}
200 	usage(*argv);
201 	/* NOTREACHED */
202 }
203 
204 /*
205  * Purge all entries in the routing tables not
206  * associated with network interfaces.
207  */
208 static void
209 flushroutes(int argc, char **argv)
210 {
211 	size_t needed;
212 	int mib[7], rlen, seqno;
213 	int miblen;
214 	char *buf, *next, *lim;
215 	struct rt_msghdr *rtm;
216 
217 	if (uid != 0) {
218 		errx(EX_NOPERM, "must be root to alter routing table");
219 	}
220 	shutdown(s, SHUT_RD); /* Don't want to read back our messages */
221 	if (argc > 1) {
222 		argv++;
223 		if (argc == 2 && **argv == '-')
224 		    switch (keyword(*argv + 1)) {
225 			case K_INET:
226 				af = AF_INET;
227 				break;
228 #ifdef INET6
229 			case K_INET6:
230 				af = AF_INET6;
231 				break;
232 #endif
233 			case K_LINK:
234 				af = AF_LINK;
235 				break;
236 			case K_MPLS:
237 				af = AF_MPLS;
238 				break;
239 			default:
240 				goto bad;
241 		} else
242 bad:			usage(*argv);
243 	}
244 	mib[0] = CTL_NET;
245 	mib[1] = PF_ROUTE;
246 	mib[2] = 0;		/* protocol */
247 	mib[3] = 0;		/* wildcard address family */
248 	mib[4] = NET_RT_DUMP;
249 	mib[5] = 0;		/* no flags */
250 	if (cpuflag >= 0) {
251 		mib[6] = cpuflag;
252 		miblen = 7;
253 	} else {
254 		miblen = 6;
255 	}
256 	if (sysctl(mib, miblen, NULL, &needed, NULL, 0) < 0)
257 		err(EX_OSERR, "route-sysctl-estimate");
258 	if ((buf = malloc(needed)) == NULL)
259 		errx(EX_OSERR, "malloc failed");
260 	if (sysctl(mib, miblen, buf, &needed, NULL, 0) < 0)
261 		err(EX_OSERR, "route-sysctl-get");
262 	lim = buf + needed;
263 	if (verbose)
264 		printf("Examining routing table from sysctl\n");
265 	seqno = 0;		/* ??? */
266 	for (next = buf; next < lim; next += rtm->rtm_msglen) {
267 		rtm = (struct rt_msghdr *)next;
268 		if (verbose)
269 			print_rtmsg(rtm, rtm->rtm_msglen);
270 		if ((rtm->rtm_flags & RTF_GATEWAY) == 0)
271 			continue;
272 		if (af != 0) {
273 			struct sockaddr *sa = (struct sockaddr *)(rtm + 1);
274 
275 			if (sa->sa_family != af)
276 				continue;
277 		}
278 		if (debugonly)
279 			continue;
280 		rtm->rtm_type = RTM_DELETE;
281 		rtm->rtm_seq = seqno;
282 		rlen = write(s, next, rtm->rtm_msglen);
283 		if (rlen < (int)rtm->rtm_msglen) {
284 			warn("write to routing socket");
285 			printf("got only %d for rlen\n", rlen);
286 			break;
287 		}
288 		seqno++;
289 		if (qflag)
290 			continue;
291 		if (verbose) {
292 			print_rtmsg(rtm, rlen);
293 		} else {
294 			struct sockaddr *sa = (struct sockaddr *)(rtm + 1);
295 			if (wflag) {
296 			    printf("%-20s ", rtm->rtm_flags & RTF_HOST ?
297 				routename(sa) : netname(sa));
298 			} else {
299 			    printf("%-20.20s ", rtm->rtm_flags & RTF_HOST ?
300 				routename(sa) : netname(sa));
301 			}
302 			sa = (struct sockaddr *)(ROUNDUP(sa->sa_len) +
303 			    (char *)sa);
304 			if (wflag) {
305 			    printf("%-20s ", routename(sa));
306 			} else {
307 			    printf("%-20.20s ", routename(sa));
308 			}
309 			printf("done\n");
310 		}
311 	}
312 }
313 
314 char *
315 routename(struct sockaddr *sa)
316 {
317 	const char *cp;
318 	static char line[MAXHOSTNAMELEN + 1];
319 	struct hostent *hp;
320 	static char domain[MAXHOSTNAMELEN + 1];
321 	static int first = 1;
322 
323 	if (first) {
324 		first = 0;
325 		if (gethostname(domain, MAXHOSTNAMELEN) == 0 &&
326 		    (cp = strchr(domain, '.'))) {
327 			domain[MAXHOSTNAMELEN] = '\0';
328 			strcpy(domain, cp + 1);
329 		} else
330 			domain[0] = 0;
331 	}
332 
333 	if (sa->sa_len == 0)
334 		strcpy(line, "default");
335 	else switch (sa->sa_family) {
336 
337 	case AF_INET:
338 	    {	struct in_addr in;
339 		in = ((struct sockaddr_in *)sa)->sin_addr;
340 
341 		cp = NULL;
342 		if (in.s_addr == INADDR_ANY || sa->sa_len < 4)
343 			cp = "default";
344 		if (cp == NULL && !nflag) {
345 			hp = gethostbyaddr(&in, sizeof(struct in_addr),
346 				AF_INET);
347 			if (hp != NULL) {
348 				char *cptr;
349 				cptr = strchr(hp->h_name, '.');
350 				if (cptr != NULL && !wflag &&
351 				    strcmp(cptr + 1, domain) == 0)
352 					*cptr = '\0';
353 				cp = hp->h_name;
354 			}
355 		}
356 		if (cp != NULL) {
357 			strncpy(line, cp, sizeof(line) - 1);
358 			line[sizeof(line) - 1] = '\0';
359 		} else
360 			sprintf(line, "%s", inet_ntoa(in));
361 		break;
362 	    }
363 
364 #ifdef INET6
365 	case AF_INET6:
366 	{
367 		struct sockaddr_in6 sin6; /* use static var for safety */
368 		int niflags = 0;
369 #ifdef NI_WITHSCOPEID
370 		niflags = NI_WITHSCOPEID;
371 #endif
372 
373 		memset(&sin6, 0, sizeof(sin6));
374 		memcpy(&sin6, sa, sa->sa_len);
375 		sin6.sin6_len = sizeof(struct sockaddr_in6);
376 		sin6.sin6_family = AF_INET6;
377 #ifdef __KAME__
378 		if (sa->sa_len == sizeof(struct sockaddr_in6) &&
379 		    (IN6_IS_ADDR_LINKLOCAL(&sin6.sin6_addr) ||
380 		     IN6_IS_ADDR_MC_LINKLOCAL(&sin6.sin6_addr)) &&
381 		    sin6.sin6_scope_id == 0) {
382 			sin6.sin6_scope_id =
383 			    ntohs(*(u_int16_t *)&sin6.sin6_addr.s6_addr[2]);
384 			sin6.sin6_addr.s6_addr[2] = 0;
385 			sin6.sin6_addr.s6_addr[3] = 0;
386 		}
387 #endif
388 		if (nflag)
389 			niflags |= NI_NUMERICHOST;
390 		if (getnameinfo((struct sockaddr *)&sin6, sin6.sin6_len,
391 		    line, sizeof(line), NULL, 0, niflags) != 0)
392 			strncpy(line, "invalid", sizeof(line));
393 
394 		return(line);
395 	}
396 #endif
397 
398 	case AF_LINK:
399 		return(link_ntoa((struct sockaddr_dl *)sa));
400 
401 	default:
402 	    {
403 		/*
404 		 * Unknown address family; just render the raw
405 		 * data in sa->sa_data as hex values.
406 		 */
407 		uint8_t *sp = (uint8_t *)sa->sa_data;
408 		uint8_t *splim = (uint8_t *)sa + sa->sa_len;
409 		char *cps = line + sprintf(line, "(%d)", sa->sa_family);
410 		char *cpe = line + sizeof(line);
411 
412 		while (sp < splim && cps < cpe)
413 			cps += snprintf(cps, cpe - cps, " %02x", *sp++);
414 		break;
415 	    }
416 	}
417 	return(line);
418 }
419 
420 /*
421  * Return the name of the network whose address is given.
422  * The address is assumed to be that of a net or subnet, not a host.
423  */
424 char *
425 netname(struct sockaddr *sa)
426 {
427 	const char *cp = NULL;
428 	static char line[MAXHOSTNAMELEN + 1];
429 	struct netent *np = NULL;
430 	u_long net, mask;
431 	u_long i;
432 	int subnetshift;
433 
434 	switch (sa->sa_family) {
435 
436 	case AF_INET:
437 	    {	struct in_addr in;
438 		in = ((struct sockaddr_in *)sa)->sin_addr;
439 
440 		i = in.s_addr = ntohl(in.s_addr);
441 		if (in.s_addr == 0)
442 			cp = "default";
443 		else if (!nflag) {
444 			if (IN_CLASSA(i)) {
445 				mask = IN_CLASSA_NET;
446 				subnetshift = 8;
447 			} else if (IN_CLASSB(i)) {
448 				mask = IN_CLASSB_NET;
449 				subnetshift = 8;
450 			} else {
451 				mask = IN_CLASSC_NET;
452 				subnetshift = 4;
453 			}
454 			/*
455 			 * If there are more bits than the standard mask
456 			 * would suggest, subnets must be in use.
457 			 * Guess at the subnet mask, assuming reasonable
458 			 * width subnet fields.
459 			 */
460 			while (in.s_addr &~ mask)
461 				mask |= mask >> subnetshift;
462 			net = in.s_addr & mask;
463 			while ((mask & 1) == 0)
464 				mask >>= 1, net >>= 1;
465 			np = getnetbyaddr(net, AF_INET);
466 			if (np != NULL)
467 				cp = np->n_name;
468 		}
469 #define C(x)	(unsigned)((x) & 0xff)
470 		if (cp != NULL)
471 			strncpy(line, cp, sizeof(line));
472 		else if ((in.s_addr & 0xffffff) == 0)
473 			sprintf(line, "%u", C(in.s_addr >> 24));
474 		else if ((in.s_addr & 0xffff) == 0)
475 			sprintf(line, "%u.%u", C(in.s_addr >> 24),
476 			    C(in.s_addr >> 16));
477 		else if ((in.s_addr & 0xff) == 0)
478 			sprintf(line, "%u.%u.%u", C(in.s_addr >> 24),
479 			    C(in.s_addr >> 16), C(in.s_addr >> 8));
480 		else
481 			sprintf(line, "%u.%u.%u.%u", C(in.s_addr >> 24),
482 			    C(in.s_addr >> 16), C(in.s_addr >> 8),
483 			    C(in.s_addr));
484 #undef C
485 		break;
486 	    }
487 
488 #ifdef INET6
489 	case AF_INET6:
490 	{
491 		struct sockaddr_in6 sin6; /* use static var for safety */
492 		int niflags = 0;
493 #ifdef NI_WITHSCOPEID
494 		niflags = NI_WITHSCOPEID;
495 #endif
496 
497 		memset(&sin6, 0, sizeof(sin6));
498 		memcpy(&sin6, sa, sa->sa_len);
499 		sin6.sin6_len = sizeof(struct sockaddr_in6);
500 		sin6.sin6_family = AF_INET6;
501 #ifdef __KAME__
502 		if (sa->sa_len == sizeof(struct sockaddr_in6) &&
503 		    (IN6_IS_ADDR_LINKLOCAL(&sin6.sin6_addr) ||
504 		     IN6_IS_ADDR_MC_LINKLOCAL(&sin6.sin6_addr)) &&
505 		    sin6.sin6_scope_id == 0) {
506 			sin6.sin6_scope_id =
507 			    ntohs(*(u_int16_t *)&sin6.sin6_addr.s6_addr[2]);
508 			sin6.sin6_addr.s6_addr[2] = 0;
509 			sin6.sin6_addr.s6_addr[3] = 0;
510 		}
511 #endif
512 		if (nflag)
513 			niflags |= NI_NUMERICHOST;
514 		if (getnameinfo((struct sockaddr *)&sin6, sin6.sin6_len,
515 		    line, sizeof(line), NULL, 0, niflags) != 0)
516 			strncpy(line, "invalid", sizeof(line));
517 
518 		return(line);
519 	}
520 #endif
521 
522 	case AF_LINK:
523 		return(link_ntoa((struct sockaddr_dl *)sa));
524 
525 
526 	default:
527 	    {
528 		/*
529 		 * Unknown address family; just render the raw
530 		 * data in sa->sa_data as hex values.
531 		 */
532 		uint8_t *sp = (uint8_t *)sa->sa_data;
533 		uint8_t *splim = (uint8_t *)sa + sa->sa_len;
534 		char *cps = line + sprintf(line, "af %d:", sa->sa_family);
535 		char *cpe = line + sizeof(line);
536 
537 		while (sp < splim && cps < cpe)
538 			cps += snprintf(cps, cpe - cps, " %02x", *sp++);
539 		break;
540 	    }
541 	}
542 	return(line);
543 }
544 
545 static void
546 set_metric(char *value, int key)
547 {
548 	int flag = 0;
549 	u_long noval, *valp = &noval;
550 
551 	switch (key) {
552 #define caseof(x, y, z)	case x: valp = &rt_metrics.z; flag = y; break
553 	caseof(K_MTU, RTV_MTU, rmx_mtu);
554 	caseof(K_HOPCOUNT, RTV_HOPCOUNT, rmx_hopcount);
555 	caseof(K_EXPIRE, RTV_EXPIRE, rmx_expire);
556 	caseof(K_RECVPIPE, RTV_RPIPE, rmx_recvpipe);
557 	caseof(K_SENDPIPE, RTV_SPIPE, rmx_sendpipe);
558 	caseof(K_SSTHRESH, RTV_SSTHRESH, rmx_ssthresh);
559 	caseof(K_RTT, RTV_RTT, rmx_rtt);
560 	caseof(K_RTTVAR, RTV_RTTVAR, rmx_rttvar);
561 	caseof(K_MSL, RTV_MSL, rmx_msl);
562 	caseof(K_IWMAX, RTV_IWMAXSEGS, rmx_iwmaxsegs);
563 	caseof(K_IW, RTV_IWCAPSEGS, rmx_iwcapsegs);
564 	}
565 	rtm_inits |= flag;
566 	if (lockrest || locking)
567 		rt_metrics.rmx_locks |= flag;
568 	if (locking)
569 		locking = 0;
570 	*valp = atoi(value);
571 }
572 
573 static void
574 newroute(int argc, char **argv)
575 {
576 	char *cmd;
577 	const char *err_str, *dest = "", *gateway = "";
578 	int ishost = 0, proxy = 0, ret, attempts, oerrno, flags = RTF_STATIC;
579 	int key;
580 	struct hostent *hp = NULL;
581 
582 	if (uid != 0) {
583 		errx(EX_NOPERM, "must be root to alter routing table");
584 	}
585 	cmd = argv[0];
586 	if (*cmd != 'g')
587 		shutdown(s, SHUT_RD); /* Don't want to read back our messages */
588 	while (--argc > 0) {
589 		if (**(++argv)== '-') {
590 			switch (key = keyword(1 + *argv)) {
591 			case K_LINK:
592 				af = AF_LINK;
593 				aflen = sizeof(struct sockaddr_dl);
594 				break;
595 			case K_INET:
596 				af = AF_INET;
597 				aflen = sizeof(struct sockaddr_in);
598 				break;
599 #ifdef INET6
600 			case K_INET6:
601 				af = AF_INET6;
602 				aflen = sizeof(struct sockaddr_in6);
603 				break;
604 #endif
605 			case K_SA:
606 				af = PF_ROUTE;
607 				aflen = sizeof(union sockunion);
608 				break;
609 			case K_IFACE:
610 			case K_INTERFACE:
611 				iflag++;
612 				break;
613 			case K_NOSTATIC:
614 				flags &= ~RTF_STATIC;
615 				break;
616 			case K_LLINFO:
617 				flags |= RTF_LLINFO;
618 				break;
619 			case K_LOCK:
620 				locking = 1;
621 				break;
622 			case K_LOCKREST:
623 				lockrest = 1;
624 				break;
625 			case K_HOST:
626 				forcehost++;
627 				break;
628 			case K_REJECT:
629 				flags |= RTF_REJECT;
630 				break;
631 			case K_BLACKHOLE:
632 				flags |= RTF_BLACKHOLE;
633 				break;
634 			case K_PROTO1:
635 				flags |= RTF_PROTO1;
636 				break;
637 			case K_PROTO2:
638 				flags |= RTF_PROTO2;
639 				break;
640 			case K_PROXY:
641 				proxy = 1;
642 				break;
643 			case K_CLONING:
644 				flags |= RTF_CLONING;
645 				break;
646 			case K_XRESOLVE:
647 				flags |= RTF_XRESOLVE;
648 				break;
649 			case K_STATIC:
650 				flags |= RTF_STATIC;
651 				break;
652 			case K_IFA:
653 				if (--argc == 0)
654 					usage(NULL);
655 				getaddr(RTA_IFA, *++argv, 0);
656 				break;
657 			case K_IFP:
658 				if (--argc == 0)
659 					usage(NULL);
660 				getaddr(RTA_IFP, *++argv, 0);
661 				break;
662 			case K_GENMASK:
663 				if (--argc == 0)
664 					usage(NULL);
665 				getaddr(RTA_GENMASK, *++argv, 0);
666 				break;
667 			case K_GATEWAY:
668 				if (--argc == 0)
669 					usage(NULL);
670 				getaddr(RTA_GATEWAY, *++argv, 0);
671 				break;
672 			case K_DST:
673 				if (--argc == 0)
674 					usage(NULL);
675 				ishost = getaddr(RTA_DST, *++argv, &hp);
676 				dest = *argv;
677 				break;
678 			case K_NETMASK:
679 				if (--argc == 0)
680 					usage(NULL);
681 				getaddr(RTA_NETMASK, *++argv, 0);
682 				/* FALLTHROUGH */
683 			case K_NET:
684 				forcenet++;
685 				break;
686 			case K_PREFIXLEN:
687 				if (--argc == 0)
688 					usage(NULL);
689 				if (prefixlen(*++argv) == -1) {
690 					forcenet = 0;
691 					ishost = 1;
692 				} else {
693 					forcenet = 1;
694 					ishost = 0;
695 				}
696 				break;
697 			case K_MPLS:
698 				af = AF_MPLS;
699 				aflen = sizeof(struct sockaddr_mpls);
700 				break;
701 			case K_POP:
702 				flags |= RTF_MPLSOPS;
703 				af = AF_MPLS;
704 				mplsop = MPLSLOP_POP;
705 				switch(++popcount){
706 					case 1:
707 						getaddr(RTA_MPLS1, "", 0);
708 						break;
709 					case 2:
710 						getaddr(RTA_MPLS2, "", 0);
711 						break;
712 					case 3:
713 						getaddr(RTA_MPLS3, "", 0);
714 						break;
715 				}
716 				break;
717 			case K_PUSH:
718 			case K_SWAP:
719 				if (popcount > 0) {
720 					warnx("Push or swap after pop. Ignoring.");
721 					break;
722 				}
723 				if (key == K_PUSH) {
724 					mplsop = MPLSLOP_PUSH;
725 					++pushcount;
726 				} else {
727 					if (pushcount > 0) {
728 						warnx("Swap after push. Ignoring.");
729 						break;
730 					}
731 					if (swapcount > 0) {
732 						warnx("Too many swaps. Ignoring.");
733 						break;
734 					}
735 					mplsop = MPLSLOP_SWAP;
736 					++swapcount;
737 				}
738 				flags |= RTF_MPLSOPS;
739 				af = AF_MPLS;
740 				aflen = sizeof(struct sockaddr_mpls);
741 				if (--argc == 0)
742 					usage(NULL);
743 				switch(pushcount + swapcount){
744 					case 1:
745 						getaddr(RTA_MPLS1, *++argv, 0);
746 						break;
747 					case 2:
748 						getaddr(RTA_MPLS2, *++argv, 0);
749 						break;
750 					case 3:
751 						getaddr(RTA_MPLS3, *++argv, 0);
752 						break;
753 				}
754 				break;
755 			case K_MTU:
756 			case K_HOPCOUNT:
757 			case K_EXPIRE:
758 			case K_RECVPIPE:
759 			case K_SENDPIPE:
760 			case K_SSTHRESH:
761 			case K_RTT:
762 			case K_RTTVAR:
763 			case K_MSL:
764 			case K_IWMAX:
765 			case K_IW:
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 "\013iw\012iwmax\011msl\010rttvar\7rtt\6ssthresh\5sendpipe\4recvpipe\3expire"
1380 "\2hopcount\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 iwmax iw");
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 ", rtm->rtm_rmx.rmx_msl);
1544 	printf("%5ld ", rtm->rtm_rmx.rmx_iwmaxsegs);
1545 	printf("%3ld\n", rtm->rtm_rmx.rmx_iwcapsegs);
1546 #undef lock
1547 #undef msec
1548 #define	RTA_IGN	(RTA_DST|RTA_GATEWAY|RTA_NETMASK|RTA_IFP|RTA_IFA|RTA_BRD)
1549 	if (verbose)
1550 		pmsg_common(rtm);
1551 	else if (rtm->rtm_addrs &~ RTA_IGN) {
1552 		printf("sockaddrs: ");
1553 		bprintf(stdout, rtm->rtm_addrs, addrnames);
1554 		putchar('\n');
1555 	}
1556 #undef	RTA_IGN
1557 }
1558 
1559 static void
1560 pmsg_common(struct rt_msghdr *rtm)
1561 {
1562 	printf("\nlocks: ");
1563 	bprintf(stdout, rtm->rtm_rmx.rmx_locks, metricnames);
1564 	printf(" inits: ");
1565 	bprintf(stdout, rtm->rtm_inits, metricnames);
1566 	pmsg_addrs(((char *)(rtm + 1)), rtm->rtm_addrs);
1567 }
1568 
1569 static void
1570 pmsg_addrs(char *cp, int addrs)
1571 {
1572 	struct sockaddr *sa;
1573 	int i;
1574 
1575 	if (addrs == 0) {
1576 		putchar('\n');
1577 		return;
1578 	}
1579 	printf("\nsockaddrs: ");
1580 	bprintf(stdout, addrs, addrnames);
1581 	putchar('\n');
1582 	for (i = 1; i != 0; i <<= 1)
1583 		if (i & addrs) {
1584 			sa = (struct sockaddr *)cp;
1585 			printf(" %s", routename(sa));
1586 			ADVANCE(cp, sa);
1587 		}
1588 	putchar('\n');
1589 	fflush(stdout);
1590 }
1591 
1592 static void
1593 bprintf(FILE *fp, int b, u_char *str)
1594 {
1595 	int i;
1596 	int gotsome = 0;
1597 
1598 	if (b == 0)
1599 		return;
1600 	while ((i = *str++) != 0) {
1601 		if (b & (1 << (i-1))) {
1602 			if (!gotsome)
1603 				i = '<';
1604 			else
1605 				i = ',';
1606 			putc(i, fp);
1607 			gotsome = 1;
1608 			for (; (i = *str) > 32; str++)
1609 				putc(i, fp);
1610 		} else
1611 			while (*str > 32)
1612 				str++;
1613 	}
1614 	if (gotsome)
1615 		putc('>', fp);
1616 }
1617 
1618 int
1619 keyword(const char *cp)
1620 {
1621 	struct keytab *kt = keywords;
1622 
1623 	while (kt->kt_cp != NULL && strcmp(kt->kt_cp, cp) != 0)
1624 		kt++;
1625 	return(kt->kt_i);
1626 }
1627 
1628 static void
1629 sodump(sup su, const char *which)
1630 {
1631 	switch (su->sa.sa_family) {
1632 	case AF_LINK:
1633 		printf("%s: link %s; ",
1634 		    which, link_ntoa(&su->sdl));
1635 		break;
1636 	case AF_INET:
1637 		printf("%s: inet %s; ",
1638 		    which, inet_ntoa(su->sin.sin_addr));
1639 		break;
1640 	}
1641 	fflush(stdout);
1642 }
1643 
1644 /* States*/
1645 #define VIRGIN	0
1646 #define GOTONE	1
1647 #define GOTTWO	2
1648 /* Inputs */
1649 #define	DIGIT	(4*0)
1650 #define	END	(4*1)
1651 #define DELIM	(4*2)
1652 
1653 static void
1654 sockaddr(const char *addr, struct sockaddr *sa)
1655 {
1656 	char *cp = (char *)sa;
1657 	int size = sa->sa_len;
1658 	char *cplim = cp + size;
1659 	int byte = 0, state = VIRGIN, new = 0 /* foil gcc */;
1660 
1661 	memset(cp, 0, size);
1662 	cp++;
1663 	do {
1664 		if ((*addr >= '0') && (*addr <= '9')) {
1665 			new = *addr - '0';
1666 		} else if ((*addr >= 'a') && (*addr <= 'f')) {
1667 			new = *addr - 'a' + 10;
1668 		} else if ((*addr >= 'A') && (*addr <= 'F')) {
1669 			new = *addr - 'A' + 10;
1670 		} else if (*addr == '\0')
1671 			state |= END;
1672 		else
1673 			state |= DELIM;
1674 		addr++;
1675 		switch (state /* | INPUT */) {
1676 		case GOTTWO | DIGIT:
1677 			*cp++ = byte; /*FALLTHROUGH*/
1678 		case VIRGIN | DIGIT:
1679 			state = GOTONE; byte = new; continue;
1680 		case GOTONE | DIGIT:
1681 			state = GOTTWO; byte = new + (byte << 4); continue;
1682 		default: /* | DELIM */
1683 			state = VIRGIN; *cp++ = byte; byte = 0; continue;
1684 		case GOTONE | END:
1685 		case GOTTWO | END:
1686 			*cp++ = byte; /* FALLTHROUGH */
1687 		case VIRGIN | END:
1688 			break;
1689 		}
1690 		break;
1691 	} while (cp < cplim);
1692 	sa->sa_len = cp - (char *)sa;
1693 }
1694