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