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