xref: /freebsd/sbin/route/route.c (revision 445ed7b40948c160f2f7d363d2d0ae1ffac4aabd)
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 	struct in6_addr in6;
1141 
1142 	if (plen == NULL) {
1143 		if (IN6_IS_ADDR_UNSPECIFIED(&sin6->sin6_addr) &&
1144 		    sin6->sin6_scope_id == 0) {
1145 			plen = "0";
1146 		} else if ((sin6->sin6_addr.s6_addr[0] & 0xe0) == 0x20) {
1147 			/* aggregatable global unicast - RFC2374 */
1148 			memset(&in6, 0, sizeof(in6));
1149 			if (!memcmp(&sin6->sin6_addr.s6_addr[8],
1150 				    &in6.s6_addr[8], 8))
1151 				plen = "64";
1152 		}
1153 	}
1154 
1155 	if (plen == NULL || strcmp(plen, "128") == 0)
1156 		return (1);
1157 	rtm_addrs |= RTA_NETMASK;
1158 	prefixlen(plen);
1159 	return (0);
1160 }
1161 #endif
1162 
1163 /*
1164  * Interpret an argument as a network address of some kind,
1165  * returning 1 if a host address, 0 if a network address.
1166  */
1167 static int
1168 getaddr(int idx, char *str, struct hostent **hpp, int nrflags)
1169 {
1170 	struct sockaddr *sa;
1171 #if defined(INET)
1172 	struct sockaddr_in *sin;
1173 	struct hostent *hp;
1174 	struct netent *np;
1175 	u_long val;
1176 	char *q;
1177 #elif defined(INET6)
1178 	char *q;
1179 #endif
1180 
1181 	if (idx < 0 || idx >= RTAX_MAX)
1182 		usage("internal error");
1183 	if (af == 0) {
1184 #if defined(INET)
1185 		af = AF_INET;
1186 		aflen = sizeof(struct sockaddr_in);
1187 #elif defined(INET6)
1188 		af = AF_INET6;
1189 		aflen = sizeof(struct sockaddr_in6);
1190 #else
1191 		af = AF_LINK;
1192 		aflen = sizeof(struct sockaddr_dl);
1193 #endif
1194 	}
1195 #ifndef INET
1196 	hpp = NULL;
1197 #endif
1198 	rtm_addrs |= (1 << idx);
1199 	sa = (struct sockaddr *)&so[idx];
1200 	sa->sa_family = af;
1201 	sa->sa_len = aflen;
1202 
1203 	switch (idx) {
1204 	case RTAX_GATEWAY:
1205 		if (nrflags & F_INTERFACE) {
1206 			struct ifaddrs *ifap, *ifa;
1207 			struct sockaddr_dl *sdl0 = (struct sockaddr_dl *)(void *)sa;
1208 			struct sockaddr_dl *sdl = NULL;
1209 
1210 			if (getifaddrs(&ifap))
1211 				err(EX_OSERR, "getifaddrs");
1212 
1213 			for (ifa = ifap; ifa != NULL; ifa = ifa->ifa_next) {
1214 				if (ifa->ifa_addr->sa_family != AF_LINK)
1215 					continue;
1216 
1217 				if (strcmp(str, ifa->ifa_name) != 0)
1218 					continue;
1219 
1220 				sdl = (struct sockaddr_dl *)(void *)ifa->ifa_addr;
1221 			}
1222 			/* If we found it, then use it */
1223 			if (sdl != NULL) {
1224 				/*
1225 				 * Note that we need to copy before calling
1226 				 * freeifaddrs().
1227 				 */
1228 				memcpy(sdl0, sdl, sdl->sdl_len);
1229 			}
1230 			freeifaddrs(ifap);
1231 			if (sdl != NULL)
1232 				return(1);
1233 		}
1234 		break;
1235 	case RTAX_IFP:
1236 		sa->sa_family = AF_LINK;
1237 		break;
1238 	}
1239 	if (strcmp(str, "default") == 0) {
1240 		/*
1241 		 * Default is net 0.0.0.0/0
1242 		 */
1243 		switch (idx) {
1244 		case RTAX_DST:
1245 			nrflags |= F_FORCENET;
1246 			getaddr(RTAX_NETMASK, str, 0, nrflags);
1247 			break;
1248 		}
1249 		return (0);
1250 	}
1251 	switch (sa->sa_family) {
1252 #ifdef INET6
1253 	case AF_INET6:
1254 	{
1255 		struct addrinfo hints, *res;
1256 		int ecode;
1257 
1258 		q = NULL;
1259 		if (idx == RTAX_DST && (q = strchr(str, '/')) != NULL)
1260 			*q = '\0';
1261 		memset(&hints, 0, sizeof(hints));
1262 		hints.ai_family = sa->sa_family;
1263 		hints.ai_socktype = SOCK_DGRAM;
1264 		ecode = getaddrinfo(str, NULL, &hints, &res);
1265 		if (ecode != 0 || res->ai_family != AF_INET6 ||
1266 		    res->ai_addrlen != sizeof(struct sockaddr_in6))
1267 			errx(EX_OSERR, "%s: %s", str, gai_strerror(ecode));
1268 		memcpy(sa, res->ai_addr, res->ai_addrlen);
1269 		freeaddrinfo(res);
1270 		if (q != NULL)
1271 			*q++ = '/';
1272 		if (idx == RTAX_DST)
1273 			return (inet6_makenetandmask((struct sockaddr_in6 *)(void *)sa, q));
1274 		return (0);
1275 	}
1276 #endif /* INET6 */
1277 	case AF_LINK:
1278 		link_addr(str, (struct sockaddr_dl *)(void *)sa);
1279 		return (1);
1280 
1281 	case PF_ROUTE:
1282 		sockaddr(str, sa, sizeof(struct sockaddr_storage));
1283 		return (1);
1284 #ifdef INET
1285 	case AF_INET:
1286 #endif
1287 	default:
1288 		break;
1289 	}
1290 
1291 #ifdef INET
1292 	sin = (struct sockaddr_in *)(void *)sa;
1293 	if (hpp == NULL)
1294 		hpp = &hp;
1295 	*hpp = NULL;
1296 
1297 	q = strchr(str,'/');
1298 	if (q != NULL && idx == RTAX_DST) {
1299 		*q = '\0';
1300 		if ((val = inet_network(str)) != INADDR_NONE) {
1301 			inet_makenetandmask(val, sin,
1302 			    (struct sockaddr_in *)&so[RTAX_NETMASK],
1303 			    strtoul(q+1, 0, 0));
1304 			return (0);
1305 		}
1306 		*q = '/';
1307 	}
1308 	if ((idx != RTAX_DST || (nrflags & F_FORCENET) == 0) &&
1309 	    inet_aton(str, &sin->sin_addr)) {
1310 		val = sin->sin_addr.s_addr;
1311 		if (idx != RTAX_DST || nrflags & F_FORCEHOST ||
1312 		    inet_lnaof(sin->sin_addr) != INADDR_ANY)
1313 			return (1);
1314 		else {
1315 			val = ntohl(val);
1316 			goto netdone;
1317 		}
1318 	}
1319 	if (idx == RTAX_DST && (nrflags & F_FORCEHOST) == 0 &&
1320 	    ((val = inet_network(str)) != INADDR_NONE ||
1321 	    ((np = getnetbyname(str)) != NULL && (val = np->n_net) != 0))) {
1322 netdone:
1323 		inet_makenetandmask(val, sin,
1324 		    (struct sockaddr_in *)&so[RTAX_NETMASK], 0);
1325 		return (0);
1326 	}
1327 	hp = gethostbyname(str);
1328 	if (hp != NULL) {
1329 		*hpp = hp;
1330 		sin->sin_family = hp->h_addrtype;
1331 		memmove((char *)&sin->sin_addr, hp->h_addr,
1332 		    MIN((size_t)hp->h_length, sizeof(sin->sin_addr)));
1333 		return (1);
1334 	}
1335 #endif
1336 	errx(EX_NOHOST, "bad address: %s", str);
1337 }
1338 
1339 static int
1340 prefixlen(const char *str)
1341 {
1342 	int len = atoi(str), q, r;
1343 	int max;
1344 	char *p;
1345 
1346 	rtm_addrs |= RTA_NETMASK;
1347 	switch (af) {
1348 #ifdef INET6
1349 	case AF_INET6:
1350 	{
1351 		struct sockaddr_in6 *sin6 =
1352 		    (struct sockaddr_in6 *)&so[RTAX_NETMASK];
1353 
1354 		max = 128;
1355 		p = (char *)&sin6->sin6_addr;
1356 		sin6->sin6_family = AF_INET6;
1357 		sin6->sin6_len = sizeof(*sin6);
1358 		break;
1359 	}
1360 #endif
1361 #ifdef INET
1362 	case AF_INET:
1363 	{
1364 		struct sockaddr_in *sin =
1365 		    (struct sockaddr_in *)&so[RTAX_NETMASK];
1366 
1367 		max = 32;
1368 		p = (char *)&sin->sin_addr;
1369 		sin->sin_family = AF_INET;
1370 		sin->sin_len = sizeof(*sin);
1371 		break;
1372 	}
1373 #endif
1374 	default:
1375 		errx(EX_OSERR, "prefixlen not supported in this af");
1376 	}
1377 
1378 	if (len < 0 || max < len)
1379 		errx(EX_USAGE, "%s: invalid prefixlen", str);
1380 
1381 	q = len >> 3;
1382 	r = len & 7;
1383 	memset((void *)p, 0, max / 8);
1384 	if (q > 0)
1385 		memset((void *)p, 0xff, q);
1386 	if (r > 0)
1387 		*((u_char *)p + q) = (0xff00 >> r) & 0xff;
1388 	if (len == max)
1389 		return (-1);
1390 	else
1391 		return (len);
1392 }
1393 
1394 static void
1395 interfaces(void)
1396 {
1397 	size_t needed;
1398 	int mib[6];
1399 	char *buf, *lim, *next, count = 0;
1400 	struct rt_msghdr *rtm;
1401 
1402 retry2:
1403 	mib[0] = CTL_NET;
1404 	mib[1] = PF_ROUTE;
1405 	mib[2] = 0;		/* protocol */
1406 	mib[3] = AF_UNSPEC;
1407 	mib[4] = NET_RT_IFLIST;
1408 	mib[5] = 0;		/* no flags */
1409 	if (sysctl(mib, nitems(mib), NULL, &needed, NULL, 0) < 0)
1410 		err(EX_OSERR, "route-sysctl-estimate");
1411 	if ((buf = malloc(needed)) == NULL)
1412 		errx(EX_OSERR, "malloc failed");
1413 	if (sysctl(mib, nitems(mib), buf, &needed, NULL, 0) < 0) {
1414 		if (errno == ENOMEM && count++ < 10) {
1415 			warnx("Routing table grew, retrying");
1416 			sleep(1);
1417 			free(buf);
1418 			goto retry2;
1419 		}
1420 		err(EX_OSERR, "actual retrieval of interface table");
1421 	}
1422 	lim = buf + needed;
1423 	for (next = buf; next < lim; next += rtm->rtm_msglen) {
1424 		rtm = (struct rt_msghdr *)(void *)next;
1425 		print_rtmsg(rtm, rtm->rtm_msglen);
1426 	}
1427 }
1428 
1429 static void
1430 monitor(int argc, char *argv[])
1431 {
1432 	int n, fib, error;
1433 	char msg[2048], *endptr;
1434 
1435 	fib = defaultfib;
1436 	while (argc > 1) {
1437 		argc--;
1438 		argv++;
1439 		if (**argv != '-')
1440 			usage(*argv);
1441 		switch (keyword(*argv + 1)) {
1442 		case K_FIB:
1443 			if (!--argc)
1444 				usage(*argv);
1445 			errno = 0;
1446 			fib = strtol(*++argv, &endptr, 0);
1447 			if (errno == 0) {
1448 				if (*endptr != '\0' ||
1449 				    fib < 0 ||
1450 				    (numfibs != -1 && fib > numfibs - 1))
1451 					errno = EINVAL;
1452 			}
1453 			if (errno)
1454 				errx(EX_USAGE, "invalid fib number: %s", *argv);
1455 			break;
1456 		default:
1457 			usage(*argv);
1458 		}
1459 	}
1460 	error = set_sofib(fib);
1461 	if (error)
1462 		errx(EX_USAGE, "invalid fib number: %d", fib);
1463 
1464 	verbose = 1;
1465 	if (debugonly) {
1466 		interfaces();
1467 		exit(0);
1468 	}
1469 	for (;;) {
1470 		time_t now;
1471 		n = read(s, msg, 2048);
1472 		now = time(NULL);
1473 		(void)printf("\ngot message of size %d on %s", n, ctime(&now));
1474 		print_rtmsg((struct rt_msghdr *)(void *)msg, n);
1475 	}
1476 }
1477 
1478 static int
1479 rtmsg(int cmd, int flags, int fib)
1480 {
1481 	int rlen;
1482 	char *cp = m_rtmsg.m_space;
1483 	int l;
1484 
1485 #define NEXTADDR(w, u)							\
1486 	if (rtm_addrs & (w)) {						\
1487 		l = (((struct sockaddr *)&(u))->sa_len == 0) ?		\
1488 		    sizeof(long) :					\
1489 		    1 + ((((struct sockaddr *)&(u))->sa_len - 1)	\
1490 			| (sizeof(long) - 1));				\
1491 		memmove(cp, (char *)&(u), l);				\
1492 		cp += l;						\
1493 		if (verbose)						\
1494 			sodump((struct sockaddr *)&(u), #w);		\
1495 	}
1496 
1497 	errno = 0;
1498 	memset(&m_rtmsg, 0, sizeof(m_rtmsg));
1499 	if (cmd == 'a')
1500 		cmd = RTM_ADD;
1501 	else if (cmd == 'c')
1502 		cmd = RTM_CHANGE;
1503 	else if (cmd == 'g' || cmd == 's') {
1504 		cmd = RTM_GET;
1505 		if (so[RTAX_IFP].ss_family == 0) {
1506 			so[RTAX_IFP].ss_family = AF_LINK;
1507 			so[RTAX_IFP].ss_len = sizeof(struct sockaddr_dl);
1508 			rtm_addrs |= RTA_IFP;
1509 		}
1510 	} else
1511 		cmd = RTM_DELETE;
1512 #define rtm m_rtmsg.m_rtm
1513 	rtm.rtm_type = cmd;
1514 	rtm.rtm_flags = flags;
1515 	rtm.rtm_version = RTM_VERSION;
1516 	rtm.rtm_seq = ++rtm_seq;
1517 	rtm.rtm_addrs = rtm_addrs;
1518 	rtm.rtm_rmx = rt_metrics;
1519 	rtm.rtm_inits = rtm_inits;
1520 
1521 	NEXTADDR(RTA_DST, so[RTAX_DST]);
1522 	NEXTADDR(RTA_GATEWAY, so[RTAX_GATEWAY]);
1523 	NEXTADDR(RTA_NETMASK, so[RTAX_NETMASK]);
1524 	NEXTADDR(RTA_GENMASK, so[RTAX_GENMASK]);
1525 	NEXTADDR(RTA_IFP, so[RTAX_IFP]);
1526 	NEXTADDR(RTA_IFA, so[RTAX_IFA]);
1527 	rtm.rtm_msglen = l = cp - (char *)&m_rtmsg;
1528 	if (verbose)
1529 		print_rtmsg(&rtm, l);
1530 	if (debugonly)
1531 		return (0);
1532 	if ((rlen = write(s, (char *)&m_rtmsg, l)) < 0) {
1533 		switch (errno) {
1534 		case EPERM:
1535 			err(1, "writing to routing socket");
1536 			break;
1537 		case ESRCH:
1538 			warnx("route has not been found");
1539 			break;
1540 		case EEXIST:
1541 			/* Handled by newroute() */
1542 			break;
1543 		default:
1544 			warn("writing to routing socket");
1545 		}
1546 		return (-1);
1547 	}
1548 	if (cmd == RTM_GET) {
1549 		do {
1550 			l = read(s, (char *)&m_rtmsg, sizeof(m_rtmsg));
1551 		} while (l > 0 && (rtm.rtm_seq != rtm_seq || rtm.rtm_pid != pid));
1552 		if (l < 0)
1553 			warn("read from routing socket");
1554 		else
1555 			print_getmsg(&rtm, l, fib);
1556 	}
1557 #undef rtm
1558 	return (0);
1559 }
1560 
1561 static const char *const msgtypes[] = {
1562 	"",
1563 	"RTM_ADD: Add Route",
1564 	"RTM_DELETE: Delete Route",
1565 	"RTM_CHANGE: Change Metrics or flags",
1566 	"RTM_GET: Report Metrics",
1567 	"RTM_LOSING: Kernel Suspects Partitioning",
1568 	"RTM_REDIRECT: Told to use different route",
1569 	"RTM_MISS: Lookup failed on this address",
1570 	"RTM_LOCK: fix specified metrics",
1571 	"RTM_OLDADD: caused by SIOCADDRT",
1572 	"RTM_OLDDEL: caused by SIOCDELRT",
1573 	"RTM_RESOLVE: Route created by cloning",
1574 	"RTM_NEWADDR: address being added to iface",
1575 	"RTM_DELADDR: address being removed from iface",
1576 	"RTM_IFINFO: iface status change",
1577 	"RTM_NEWMADDR: new multicast group membership on iface",
1578 	"RTM_DELMADDR: multicast group membership removed from iface",
1579 	"RTM_IFANNOUNCE: interface arrival/departure",
1580 	"RTM_IEEE80211: IEEE 802.11 wireless event",
1581 };
1582 
1583 static const char metricnames[] =
1584     "\011weight\010rttvar\7rtt\6ssthresh\5sendpipe\4recvpipe\3expire"
1585     "\1mtu";
1586 static const char routeflags[] =
1587     "\1UP\2GATEWAY\3HOST\4REJECT\5DYNAMIC\6MODIFIED\7DONE"
1588     "\012XRESOLVE\013LLINFO\014STATIC\015BLACKHOLE"
1589     "\017PROTO2\020PROTO1\021PRCLONING\022WASCLONED\023PROTO3"
1590     "\024FIXEDMTU\025PINNED\026LOCAL\027BROADCAST\030MULTICAST\035STICKY";
1591 static const char ifnetflags[] =
1592     "\1UP\2BROADCAST\3DEBUG\4LOOPBACK\5PTP\6b6\7RUNNING\010NOARP"
1593     "\011PPROMISC\012ALLMULTI\013OACTIVE\014SIMPLEX\015LINK0\016LINK1"
1594     "\017LINK2\020MULTICAST";
1595 static const char addrnames[] =
1596     "\1DST\2GATEWAY\3NETMASK\4GENMASK\5IFP\6IFA\7AUTHOR\010BRD";
1597 
1598 static const char errfmt[] =
1599     "\n%s: truncated route message, only %zu bytes left\n";
1600 
1601 static void
1602 print_rtmsg(struct rt_msghdr *rtm, size_t msglen)
1603 {
1604 	struct if_msghdr *ifm;
1605 	struct ifa_msghdr *ifam;
1606 #ifdef RTM_NEWMADDR
1607 	struct ifma_msghdr *ifmam;
1608 #endif
1609 	struct if_announcemsghdr *ifan;
1610 	const char *state;
1611 
1612 	if (verbose == 0)
1613 		return;
1614 	if (rtm->rtm_version != RTM_VERSION) {
1615 		(void)printf("routing message version %d not understood\n",
1616 		    rtm->rtm_version);
1617 		return;
1618 	}
1619 	if (rtm->rtm_type < nitems(msgtypes))
1620 		(void)printf("%s: ", msgtypes[rtm->rtm_type]);
1621 	else
1622 		(void)printf("unknown type %d: ", rtm->rtm_type);
1623 	(void)printf("len %d, ", rtm->rtm_msglen);
1624 
1625 #define	REQUIRE(x)	do {		\
1626 	if (msglen < sizeof(x))		\
1627 		goto badlen;		\
1628 	else				\
1629 		msglen -= sizeof(x);	\
1630 	} while (0)
1631 
1632 	switch (rtm->rtm_type) {
1633 	case RTM_IFINFO:
1634 		REQUIRE(struct if_msghdr);
1635 		ifm = (struct if_msghdr *)rtm;
1636 		(void)printf("if# %d, ", ifm->ifm_index);
1637 		switch (ifm->ifm_data.ifi_link_state) {
1638 		case LINK_STATE_DOWN:
1639 			state = "down";
1640 			break;
1641 		case LINK_STATE_UP:
1642 			state = "up";
1643 			break;
1644 		default:
1645 			state = "unknown";
1646 			break;
1647 		}
1648 		(void)printf("link: %s, flags:", state);
1649 		printb(ifm->ifm_flags, ifnetflags);
1650 		pmsg_addrs((char *)(ifm + 1), ifm->ifm_addrs, msglen);
1651 		break;
1652 	case RTM_NEWADDR:
1653 	case RTM_DELADDR:
1654 		REQUIRE(struct ifa_msghdr);
1655 		ifam = (struct ifa_msghdr *)rtm;
1656 		(void)printf("metric %d, flags:", ifam->ifam_metric);
1657 		printb(ifam->ifam_flags, routeflags);
1658 		pmsg_addrs((char *)(ifam + 1), ifam->ifam_addrs, msglen);
1659 		break;
1660 #ifdef RTM_NEWMADDR
1661 	case RTM_NEWMADDR:
1662 	case RTM_DELMADDR:
1663 		REQUIRE(struct ifma_msghdr);
1664 		ifmam = (struct ifma_msghdr *)rtm;
1665 		pmsg_addrs((char *)(ifmam + 1), ifmam->ifmam_addrs, msglen);
1666 		break;
1667 #endif
1668 	case RTM_IFANNOUNCE:
1669 		REQUIRE(struct if_announcemsghdr);
1670 		ifan = (struct if_announcemsghdr *)rtm;
1671 		(void)printf("if# %d, what: ", ifan->ifan_index);
1672 		switch (ifan->ifan_what) {
1673 		case IFAN_ARRIVAL:
1674 			(void)printf("arrival");
1675 			break;
1676 		case IFAN_DEPARTURE:
1677 			printf("departure");
1678 			break;
1679 		default:
1680 			printf("#%d", ifan->ifan_what);
1681 			break;
1682 		}
1683 		printf("\n");
1684 		fflush(stdout);
1685 		break;
1686 
1687 	default:
1688 		printf("pid: %ld, seq %d, errno %d, flags:",
1689 			(long)rtm->rtm_pid, rtm->rtm_seq, rtm->rtm_errno);
1690 		printb(rtm->rtm_flags, routeflags);
1691 		pmsg_common(rtm, msglen);
1692 	}
1693 
1694 	return;
1695 
1696 badlen:
1697 	(void)printf(errfmt, __func__, msglen);
1698 #undef	REQUIRE
1699 }
1700 
1701 static void
1702 print_getmsg(struct rt_msghdr *rtm, int msglen, int fib)
1703 {
1704 	struct sockaddr *sp[RTAX_MAX];
1705 	struct timespec ts;
1706 	char *cp;
1707 	int i;
1708 
1709 	memset(sp, 0, sizeof(sp));
1710 	(void)printf("   route to: %s\n",
1711 	    routename((struct sockaddr *)&so[RTAX_DST]));
1712 	if (rtm->rtm_version != RTM_VERSION) {
1713 		warnx("routing message version %d not understood",
1714 		     rtm->rtm_version);
1715 		return;
1716 	}
1717 	if (rtm->rtm_msglen > msglen) {
1718 		warnx("message length mismatch, in packet %d, returned %d",
1719 		      rtm->rtm_msglen, msglen);
1720 		return;
1721 	}
1722 	if (rtm->rtm_errno)  {
1723 		errno = rtm->rtm_errno;
1724 		warn("message indicates error %d", errno);
1725 		return;
1726 	}
1727 	cp = ((char *)(rtm + 1));
1728 	for (i = 0; i < RTAX_MAX; i++)
1729 		if (rtm->rtm_addrs & (1 << i)) {
1730 			sp[i] = (struct sockaddr *)cp;
1731 			cp += SA_SIZE((struct sockaddr *)cp);
1732 		}
1733 	if ((rtm->rtm_addrs & RTA_IFP) &&
1734 	    (sp[RTAX_IFP]->sa_family != AF_LINK ||
1735 	     ((struct sockaddr_dl *)(void *)sp[RTAX_IFP])->sdl_nlen == 0))
1736 			sp[RTAX_IFP] = NULL;
1737 	if (sp[RTAX_DST])
1738 		(void)printf("destination: %s\n", routename(sp[RTAX_DST]));
1739 	if (sp[RTAX_NETMASK])
1740 		(void)printf("       mask: %s\n", routename(sp[RTAX_NETMASK]));
1741 	if (sp[RTAX_GATEWAY] && (rtm->rtm_flags & RTF_GATEWAY))
1742 		(void)printf("    gateway: %s\n", routename(sp[RTAX_GATEWAY]));
1743 	if (fib >= 0)
1744 		(void)printf("        fib: %u\n", (unsigned int)fib);
1745 	if (sp[RTAX_IFP])
1746 		(void)printf("  interface: %.*s\n",
1747 		    ((struct sockaddr_dl *)(void *)sp[RTAX_IFP])->sdl_nlen,
1748 		    ((struct sockaddr_dl *)(void *)sp[RTAX_IFP])->sdl_data);
1749 	(void)printf("      flags: ");
1750 	printb(rtm->rtm_flags, routeflags);
1751 
1752 #define lock(f)	((rtm->rtm_rmx.rmx_locks & __CONCAT(RTV_,f)) ? 'L' : ' ')
1753 #define msec(u)	(((u) + 500) / 1000)		/* usec to msec */
1754 	printf("\n%9s %9s %9s %9s %9s %10s %9s\n", "recvpipe",
1755 	    "sendpipe", "ssthresh", "rtt,msec", "mtu   ", "weight", "expire");
1756 	printf("%8lu%c ", rtm->rtm_rmx.rmx_recvpipe, lock(RPIPE));
1757 	printf("%8lu%c ", rtm->rtm_rmx.rmx_sendpipe, lock(SPIPE));
1758 	printf("%8lu%c ", rtm->rtm_rmx.rmx_ssthresh, lock(SSTHRESH));
1759 	printf("%8lu%c ", msec(rtm->rtm_rmx.rmx_rtt), lock(RTT));
1760 	printf("%8lu%c ", rtm->rtm_rmx.rmx_mtu, lock(MTU));
1761 	printf("%8lu%c ", rtm->rtm_rmx.rmx_weight, lock(WEIGHT));
1762 	if (rtm->rtm_rmx.rmx_expire > 0)
1763 		clock_gettime(CLOCK_REALTIME_FAST, &ts);
1764 	else
1765 		ts.tv_sec = 0;
1766 	printf("%8ld%c\n", (long)(rtm->rtm_rmx.rmx_expire - ts.tv_sec),
1767 	    lock(EXPIRE));
1768 #undef lock
1769 #undef msec
1770 #define	RTA_IGN	(RTA_DST|RTA_GATEWAY|RTA_NETMASK|RTA_IFP|RTA_IFA|RTA_BRD)
1771 	if (verbose)
1772 		pmsg_common(rtm, msglen);
1773 	else if (rtm->rtm_addrs &~ RTA_IGN) {
1774 		(void)printf("sockaddrs: ");
1775 		printb(rtm->rtm_addrs, addrnames);
1776 		putchar('\n');
1777 	}
1778 #undef	RTA_IGN
1779 }
1780 
1781 static void
1782 pmsg_common(struct rt_msghdr *rtm, size_t msglen)
1783 {
1784 
1785 	(void)printf("\nlocks: ");
1786 	printb(rtm->rtm_rmx.rmx_locks, metricnames);
1787 	(void)printf(" inits: ");
1788 	printb(rtm->rtm_inits, metricnames);
1789 	if (msglen > sizeof(struct rt_msghdr))
1790 		pmsg_addrs(((char *)(rtm + 1)), rtm->rtm_addrs,
1791 		    msglen - sizeof(struct rt_msghdr));
1792 	else
1793 		(void)fflush(stdout);
1794 }
1795 
1796 static void
1797 pmsg_addrs(char *cp, int addrs, size_t len)
1798 {
1799 	struct sockaddr *sa;
1800 	int i;
1801 
1802 	if (addrs == 0) {
1803 		(void)putchar('\n');
1804 		return;
1805 	}
1806 	(void)printf("\nsockaddrs: ");
1807 	printb(addrs, addrnames);
1808 	putchar('\n');
1809 	for (i = 0; i < RTAX_MAX; i++)
1810 		if (addrs & (1 << i)) {
1811 			sa = (struct sockaddr *)cp;
1812 			if (len == 0 || len < SA_SIZE(sa)) {
1813 				(void)printf(errfmt, __func__, len);
1814 				break;
1815 			}
1816 			(void)printf(" %s", routename(sa));
1817 			len -= SA_SIZE(sa);
1818 			cp += SA_SIZE(sa);
1819 		}
1820 	(void)putchar('\n');
1821 	(void)fflush(stdout);
1822 }
1823 
1824 static void
1825 printb(int b, const char *str)
1826 {
1827 	int i;
1828 	int gotsome = 0;
1829 
1830 	if (b == 0)
1831 		return;
1832 	while ((i = *str++) != 0) {
1833 		if (b & (1 << (i-1))) {
1834 			if (gotsome == 0)
1835 				i = '<';
1836 			else
1837 				i = ',';
1838 			putchar(i);
1839 			gotsome = 1;
1840 			for (; (i = *str) > 32; str++)
1841 				putchar(i);
1842 		} else
1843 			while (*str > 32)
1844 				str++;
1845 	}
1846 	if (gotsome)
1847 		putchar('>');
1848 }
1849 
1850 int
1851 keyword(const char *cp)
1852 {
1853 	const struct keytab *kt = keywords;
1854 
1855 	while (kt->kt_cp != NULL && strcmp(kt->kt_cp, cp) != 0)
1856 		kt++;
1857 	return (kt->kt_i);
1858 }
1859 
1860 static void
1861 sodump(struct sockaddr *sa, const char *which)
1862 {
1863 #ifdef INET6
1864 	char nbuf[INET6_ADDRSTRLEN];
1865 #endif
1866 
1867 	switch (sa->sa_family) {
1868 	case AF_LINK:
1869 		(void)printf("%s: link %s; ", which,
1870 		    link_ntoa((struct sockaddr_dl *)(void *)sa));
1871 		break;
1872 #ifdef INET
1873 	case AF_INET:
1874 		(void)printf("%s: inet %s; ", which,
1875 		    inet_ntoa(((struct sockaddr_in *)(void *)sa)->sin_addr));
1876 		break;
1877 #endif
1878 #ifdef INET6
1879 	case AF_INET6:
1880 		(void)printf("%s: inet6 %s; ", which, inet_ntop(sa->sa_family,
1881 		    &((struct sockaddr_in6 *)(void *)sa)->sin6_addr, nbuf,
1882 		    sizeof(nbuf)));
1883 		break;
1884 #endif
1885 	}
1886 	(void)fflush(stdout);
1887 }
1888 
1889 /* States*/
1890 #define VIRGIN	0
1891 #define GOTONE	1
1892 #define GOTTWO	2
1893 /* Inputs */
1894 #define	DIGIT	(4*0)
1895 #define	END	(4*1)
1896 #define DELIM	(4*2)
1897 
1898 static void
1899 sockaddr(char *addr, struct sockaddr *sa, size_t size)
1900 {
1901 	char *cp = (char *)sa;
1902 	char *cplim = cp + size;
1903 	int byte = 0, state = VIRGIN, new = 0 /* foil gcc */;
1904 
1905 	memset(cp, 0, size);
1906 	cp++;
1907 	do {
1908 		if ((*addr >= '0') && (*addr <= '9')) {
1909 			new = *addr - '0';
1910 		} else if ((*addr >= 'a') && (*addr <= 'f')) {
1911 			new = *addr - 'a' + 10;
1912 		} else if ((*addr >= 'A') && (*addr <= 'F')) {
1913 			new = *addr - 'A' + 10;
1914 		} else if (*addr == '\0')
1915 			state |= END;
1916 		else
1917 			state |= DELIM;
1918 		addr++;
1919 		switch (state /* | INPUT */) {
1920 		case GOTTWO | DIGIT:
1921 			*cp++ = byte; /*FALLTHROUGH*/
1922 		case VIRGIN | DIGIT:
1923 			state = GOTONE; byte = new; continue;
1924 		case GOTONE | DIGIT:
1925 			state = GOTTWO; byte = new + (byte << 4); continue;
1926 		default: /* | DELIM */
1927 			state = VIRGIN; *cp++ = byte; byte = 0; continue;
1928 		case GOTONE | END:
1929 		case GOTTWO | END:
1930 			*cp++ = byte; /* FALLTHROUGH */
1931 		case VIRGIN | END:
1932 			break;
1933 		}
1934 		break;
1935 	} while (cp < cplim);
1936 	sa->sa_len = cp - (char *)sa;
1937 }
1938