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