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