xref: /freebsd/sbin/route/route.c (revision 38f0b757fd84d17d0fc24739a7cda160c4516d81)
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_PROTO3:
851 				flags |= RTF_PROTO3;
852 				break;
853 			case K_PROXY:
854 				nrflags |= F_PROXY;
855 				break;
856 			case K_XRESOLVE:
857 				flags |= RTF_XRESOLVE;
858 				break;
859 			case K_STATIC:
860 				flags |= RTF_STATIC;
861 				break;
862 			case K_STICKY:
863 				flags |= RTF_STICKY;
864 				break;
865 			case K_NOSTICK:
866 				flags &= ~RTF_STICKY;
867 				break;
868 			case K_FIB:
869 				if (!--argc)
870 					usage(NULL);
871 				error = fiboptlist_csv(*++argv, &fibl_head);
872 				if (error)
873 					errx(EX_USAGE,
874 					    "invalid fib number: %s", *argv);
875 				break;
876 			case K_IFA:
877 				if (!--argc)
878 					usage(NULL);
879 				getaddr(RTAX_IFA, *++argv, 0, nrflags);
880 				break;
881 			case K_IFP:
882 				if (!--argc)
883 					usage(NULL);
884 				getaddr(RTAX_IFP, *++argv, 0, nrflags);
885 				break;
886 			case K_GENMASK:
887 				if (!--argc)
888 					usage(NULL);
889 				getaddr(RTAX_GENMASK, *++argv, 0, nrflags);
890 				break;
891 			case K_GATEWAY:
892 				if (!--argc)
893 					usage(NULL);
894 				getaddr(RTAX_GATEWAY, *++argv, 0, nrflags);
895 				gateway = *argv;
896 				break;
897 			case K_DST:
898 				if (!--argc)
899 					usage(NULL);
900 				if (getaddr(RTAX_DST, *++argv, &hp, nrflags))
901 					nrflags |= F_ISHOST;
902 				dest = *argv;
903 				break;
904 			case K_NETMASK:
905 				if (!--argc)
906 					usage(NULL);
907 				getaddr(RTAX_NETMASK, *++argv, 0, nrflags);
908 				/* FALLTHROUGH */
909 			case K_NET:
910 				nrflags |= F_FORCENET;
911 				break;
912 			case K_PREFIXLEN:
913 				if (!--argc)
914 					usage(NULL);
915 				if (prefixlen(*++argv) == -1) {
916 					nrflags &= ~F_FORCENET;
917 					nrflags |= F_ISHOST;
918 				} else {
919 					nrflags |= F_FORCENET;
920 					nrflags &= ~F_ISHOST;
921 				}
922 				break;
923 			case K_MTU:
924 			case K_HOPCOUNT:
925 			case K_EXPIRE:
926 			case K_RECVPIPE:
927 			case K_SENDPIPE:
928 			case K_SSTHRESH:
929 			case K_RTT:
930 			case K_RTTVAR:
931 			case K_WEIGHT:
932 				if (!--argc)
933 					usage(NULL);
934 				set_metric(*++argv, key);
935 				break;
936 			default:
937 				usage(1+*argv);
938 			}
939 		} else {
940 			if ((rtm_addrs & RTA_DST) == 0) {
941 				dest = *argv;
942 				if (getaddr(RTAX_DST, *argv, &hp, nrflags))
943 					nrflags |= F_ISHOST;
944 			} else if ((rtm_addrs & RTA_GATEWAY) == 0) {
945 				gateway = *argv;
946 				getaddr(RTAX_GATEWAY, *argv, &hp, nrflags);
947 			} else {
948 				getaddr(RTAX_NETMASK, *argv, 0, nrflags);
949 				nrflags |= F_FORCENET;
950 			}
951 		}
952 	}
953 
954 	/* Do some sanity checks on resulting request */
955 	if (so[RTAX_DST].ss_len == 0) {
956 		warnx("destination parameter required");
957 		usage(NULL);
958 	}
959 
960 	if (so[RTAX_NETMASK].ss_len != 0 &&
961 	    so[RTAX_DST].ss_family != so[RTAX_NETMASK].ss_family) {
962 		warnx("destination and netmask family need to be the same");
963 		usage(NULL);
964 	}
965 
966 	if (nrflags & F_FORCEHOST) {
967 		nrflags |= F_ISHOST;
968 #ifdef INET6
969 		if (af == AF_INET6) {
970 			rtm_addrs &= ~RTA_NETMASK;
971 			memset(&so[RTAX_NETMASK], 0, sizeof(so[RTAX_NETMASK]));
972 		}
973 #endif
974 	}
975 	if (nrflags & F_FORCENET)
976 		nrflags &= ~F_ISHOST;
977 	flags |= RTF_UP;
978 	if (nrflags & F_ISHOST)
979 		flags |= RTF_HOST;
980 	if ((nrflags & F_INTERFACE) == 0)
981 		flags |= RTF_GATEWAY;
982 	if (nrflags & F_PROXY)
983 		flags |= RTF_ANNOUNCE;
984 	if (dest == NULL)
985 		dest = "";
986 	if (gateway == NULL)
987 		gateway = "";
988 
989 	if (TAILQ_EMPTY(&fibl_head)) {
990 		error = fiboptlist_csv("default", &fibl_head);
991 		if (error)
992 			errx(EX_OSERR, "fiboptlist_csv failed.");
993 	}
994 	error = 0;
995 	TAILQ_FOREACH(fl, &fibl_head, fl_next) {
996 		fl->fl_error = newroute_fib(fl->fl_num, cmd, flags);
997 		if (fl->fl_error)
998 			fl->fl_errno = errno;
999 		error += fl->fl_error;
1000 	}
1001 	if (*cmd == 'g' || *cmd == 's')
1002 		exit(error);
1003 
1004 	error = 0;
1005 	if (!qflag) {
1006 		fibnum = 0;
1007 		TAILQ_FOREACH(fl, &fibl_head, fl_next) {
1008 			if (fl->fl_error == 0)
1009 				fibnum++;
1010 		}
1011 		if (fibnum > 0) {
1012 			int firstfib = 1;
1013 
1014 			printf("%s %s %s", cmd,
1015 			    (nrflags & F_ISHOST) ? "host" : "net", dest);
1016 			if (*gateway)
1017 				printf(": gateway %s", gateway);
1018 
1019 			if (numfibs > 1) {
1020 				TAILQ_FOREACH(fl, &fibl_head, fl_next) {
1021 					if (fl->fl_error == 0
1022 					    && fl->fl_num >= 0) {
1023 						if (firstfib) {
1024 							printf(" fib ");
1025 							firstfib = 0;
1026 						}
1027 						printf("%d", fl->fl_num);
1028 						if (fibnum-- > 1)
1029 							printf(",");
1030 					}
1031 				}
1032 			}
1033 			printf("\n");
1034 		}
1035 
1036 		fibnum = 0;
1037 		TAILQ_FOREACH(fl, &fibl_head, fl_next) {
1038 			if (fl->fl_error != 0) {
1039 				printf("%s %s %s", cmd, (nrflags & F_ISHOST)
1040 				    ? "host" : "net", dest);
1041 				if (*gateway)
1042 					printf(": gateway %s", gateway);
1043 
1044 				if (fl->fl_num >= 0)
1045 					printf(" fib %d", fl->fl_num);
1046 
1047 				switch (fl->fl_errno) {
1048 				case ESRCH:
1049 					errmsg = "not in table";
1050 					break;
1051 				case EBUSY:
1052 					errmsg = "entry in use";
1053 					break;
1054 				case ENOBUFS:
1055 					errmsg = "not enough memory";
1056 					break;
1057 				case EADDRINUSE:
1058 					/*
1059 					 * handle recursion avoidance
1060 					 * in rt_setgate()
1061 					 */
1062 					errmsg = "gateway uses the same route";
1063 					break;
1064 				case EEXIST:
1065 					errmsg = "route already in table";
1066 					break;
1067 				default:
1068 					errmsg = strerror(fl->fl_errno);
1069 					break;
1070 				}
1071 				printf(": %s\n", errmsg);
1072 				error = 1;
1073 			}
1074 		}
1075 	}
1076 	exit(error);
1077 }
1078 
1079 static int
1080 newroute_fib(int fib, char *cmd, int flags)
1081 {
1082 	int error;
1083 
1084 	error = set_sofib(fib);
1085 	if (error) {
1086 		warn("fib number %d is ignored", fib);
1087 		return (error);
1088 	}
1089 
1090 	error = rtmsg(*cmd, flags, fib);
1091 	return (error);
1092 }
1093 
1094 #ifdef INET
1095 static void
1096 inet_makenetandmask(u_long net, struct sockaddr_in *sin,
1097     struct sockaddr_in *sin_mask, u_long bits)
1098 {
1099 	u_long mask = 0;
1100 
1101 	rtm_addrs |= RTA_NETMASK;
1102 
1103 	/*
1104 	 * MSB of net should be meaningful. 0/0 is exception.
1105 	 */
1106 	if (net > 0)
1107 		while ((net & 0xff000000) == 0)
1108 			net <<= 8;
1109 
1110 	/*
1111 	 * If no /xx was specified we must calculate the
1112 	 * CIDR address.
1113 	 */
1114 	if ((bits == 0) && (net != 0)) {
1115 		u_long i, j;
1116 
1117 		for(i = 0, j = 0xff; i < 4; i++)  {
1118 			if (net & j) {
1119 				break;
1120 			}
1121 			j <<= 8;
1122 		}
1123 		/* i holds the first non zero bit */
1124 		bits = 32 - (i*8);
1125 	}
1126 	if (bits != 0)
1127 		mask = 0xffffffff << (32 - bits);
1128 
1129 	sin->sin_addr.s_addr = htonl(net);
1130 	sin_mask->sin_addr.s_addr = htonl(mask);
1131 	sin_mask->sin_len = sizeof(struct sockaddr_in);
1132 	sin_mask->sin_family = AF_INET;
1133 }
1134 #endif
1135 
1136 #ifdef INET6
1137 /*
1138  * XXX the function may need more improvement...
1139  */
1140 static int
1141 inet6_makenetandmask(struct sockaddr_in6 *sin6, const char *plen)
1142 {
1143 	struct in6_addr in6;
1144 
1145 	if (plen == NULL) {
1146 		if (IN6_IS_ADDR_UNSPECIFIED(&sin6->sin6_addr) &&
1147 		    sin6->sin6_scope_id == 0) {
1148 			plen = "0";
1149 		} else if ((sin6->sin6_addr.s6_addr[0] & 0xe0) == 0x20) {
1150 			/* aggregatable global unicast - RFC2374 */
1151 			memset(&in6, 0, sizeof(in6));
1152 			if (!memcmp(&sin6->sin6_addr.s6_addr[8],
1153 				    &in6.s6_addr[8], 8))
1154 				plen = "64";
1155 		}
1156 	}
1157 
1158 	if (plen == NULL || strcmp(plen, "128") == 0)
1159 		return (1);
1160 	rtm_addrs |= RTA_NETMASK;
1161 	prefixlen(plen);
1162 	return (0);
1163 }
1164 #endif
1165 
1166 /*
1167  * Interpret an argument as a network address of some kind,
1168  * returning 1 if a host address, 0 if a network address.
1169  */
1170 static int
1171 getaddr(int idx, char *str, struct hostent **hpp, int nrflags)
1172 {
1173 	struct sockaddr *sa;
1174 #if defined(INET)
1175 	struct sockaddr_in *sin;
1176 	struct hostent *hp;
1177 	struct netent *np;
1178 	u_long val;
1179 	char *q;
1180 #elif defined(INET6)
1181 	char *q;
1182 #endif
1183 
1184 	if (idx < 0 || idx >= RTAX_MAX)
1185 		usage("internal error");
1186 	if (af == 0) {
1187 #if defined(INET)
1188 		af = AF_INET;
1189 		aflen = sizeof(struct sockaddr_in);
1190 #elif defined(INET6)
1191 		af = AF_INET6;
1192 		aflen = sizeof(struct sockaddr_in6);
1193 #else
1194 		af = AF_LINK;
1195 		aflen = sizeof(struct sockaddr_dl);
1196 #endif
1197 	}
1198 #ifndef INET
1199 	hpp = NULL;
1200 #endif
1201 	rtm_addrs |= (1 << idx);
1202 	sa = (struct sockaddr *)&so[idx];
1203 	sa->sa_family = af;
1204 	sa->sa_len = aflen;
1205 
1206 	switch (idx) {
1207 	case RTAX_GATEWAY:
1208 		if (nrflags & F_INTERFACE) {
1209 			struct ifaddrs *ifap, *ifa;
1210 			struct sockaddr_dl *sdl0 = (struct sockaddr_dl *)(void *)sa;
1211 			struct sockaddr_dl *sdl = NULL;
1212 
1213 			if (getifaddrs(&ifap))
1214 				err(EX_OSERR, "getifaddrs");
1215 
1216 			for (ifa = ifap; ifa != NULL; ifa = ifa->ifa_next) {
1217 				if (ifa->ifa_addr->sa_family != AF_LINK)
1218 					continue;
1219 
1220 				if (strcmp(str, ifa->ifa_name) != 0)
1221 					continue;
1222 
1223 				sdl = (struct sockaddr_dl *)(void *)ifa->ifa_addr;
1224 			}
1225 			/* If we found it, then use it */
1226 			if (sdl != NULL) {
1227 				/*
1228 				 * Note that we need to copy before calling
1229 				 * freeifaddrs().
1230 				 */
1231 				memcpy(sdl0, sdl, sdl->sdl_len);
1232 			}
1233 			freeifaddrs(ifap);
1234 			if (sdl != NULL)
1235 				return(1);
1236 		}
1237 		break;
1238 	case RTAX_IFP:
1239 		sa->sa_family = AF_LINK;
1240 		break;
1241 	}
1242 	if (strcmp(str, "default") == 0) {
1243 		/*
1244 		 * Default is net 0.0.0.0/0
1245 		 */
1246 		switch (idx) {
1247 		case RTAX_DST:
1248 			nrflags |= F_FORCENET;
1249 			getaddr(RTAX_NETMASK, str, 0, nrflags);
1250 			break;
1251 		}
1252 		return (0);
1253 	}
1254 	switch (sa->sa_family) {
1255 #ifdef INET6
1256 	case AF_INET6:
1257 	{
1258 		struct addrinfo hints, *res;
1259 		int ecode;
1260 
1261 		q = NULL;
1262 		if (idx == RTAX_DST && (q = strchr(str, '/')) != NULL)
1263 			*q = '\0';
1264 		memset(&hints, 0, sizeof(hints));
1265 		hints.ai_family = sa->sa_family;
1266 		hints.ai_socktype = SOCK_DGRAM;
1267 		ecode = getaddrinfo(str, NULL, &hints, &res);
1268 		if (ecode != 0 || res->ai_family != AF_INET6 ||
1269 		    res->ai_addrlen != sizeof(struct sockaddr_in6))
1270 			errx(EX_OSERR, "%s: %s", str, gai_strerror(ecode));
1271 		memcpy(sa, res->ai_addr, res->ai_addrlen);
1272 		freeaddrinfo(res);
1273 		if (q != NULL)
1274 			*q++ = '/';
1275 		if (idx == RTAX_DST)
1276 			return (inet6_makenetandmask((struct sockaddr_in6 *)(void *)sa, q));
1277 		return (0);
1278 	}
1279 #endif /* INET6 */
1280 	case AF_LINK:
1281 		link_addr(str, (struct sockaddr_dl *)(void *)sa);
1282 		return (1);
1283 
1284 	case PF_ROUTE:
1285 		sockaddr(str, sa, sizeof(struct sockaddr_storage));
1286 		return (1);
1287 #ifdef INET
1288 	case AF_INET:
1289 #endif
1290 	default:
1291 		break;
1292 	}
1293 
1294 #ifdef INET
1295 	sin = (struct sockaddr_in *)(void *)sa;
1296 	if (hpp == NULL)
1297 		hpp = &hp;
1298 	*hpp = NULL;
1299 
1300 	q = strchr(str,'/');
1301 	if (q != NULL && idx == RTAX_DST) {
1302 		*q = '\0';
1303 		if ((val = inet_network(str)) != INADDR_NONE) {
1304 			inet_makenetandmask(val, sin,
1305 			    (struct sockaddr_in *)&so[RTAX_NETMASK],
1306 			    strtoul(q+1, 0, 0));
1307 			return (0);
1308 		}
1309 		*q = '/';
1310 	}
1311 	if ((idx != RTAX_DST || (nrflags & F_FORCENET) == 0) &&
1312 	    inet_aton(str, &sin->sin_addr)) {
1313 		val = sin->sin_addr.s_addr;
1314 		if (idx != RTAX_DST || nrflags & F_FORCEHOST ||
1315 		    inet_lnaof(sin->sin_addr) != INADDR_ANY)
1316 			return (1);
1317 		else {
1318 			val = ntohl(val);
1319 			goto netdone;
1320 		}
1321 	}
1322 	if (idx == RTAX_DST && (nrflags & F_FORCEHOST) == 0 &&
1323 	    ((val = inet_network(str)) != INADDR_NONE ||
1324 	    ((np = getnetbyname(str)) != NULL && (val = np->n_net) != 0))) {
1325 netdone:
1326 		inet_makenetandmask(val, sin,
1327 		    (struct sockaddr_in *)&so[RTAX_NETMASK], 0);
1328 		return (0);
1329 	}
1330 	hp = gethostbyname(str);
1331 	if (hp != NULL) {
1332 		*hpp = hp;
1333 		sin->sin_family = hp->h_addrtype;
1334 		memmove((char *)&sin->sin_addr, hp->h_addr,
1335 		    MIN((size_t)hp->h_length, sizeof(sin->sin_addr)));
1336 		return (1);
1337 	}
1338 #endif
1339 	errx(EX_NOHOST, "bad address: %s", str);
1340 }
1341 
1342 static int
1343 prefixlen(const char *str)
1344 {
1345 	int len = atoi(str), q, r;
1346 	int max;
1347 	char *p;
1348 
1349 	rtm_addrs |= RTA_NETMASK;
1350 	switch (af) {
1351 #ifdef INET6
1352 	case AF_INET6:
1353 	{
1354 		struct sockaddr_in6 *sin6 =
1355 		    (struct sockaddr_in6 *)&so[RTAX_NETMASK];
1356 
1357 		max = 128;
1358 		p = (char *)&sin6->sin6_addr;
1359 		sin6->sin6_family = AF_INET6;
1360 		sin6->sin6_len = sizeof(*sin6);
1361 		break;
1362 	}
1363 #endif
1364 #ifdef INET
1365 	case AF_INET:
1366 	{
1367 		struct sockaddr_in *sin =
1368 		    (struct sockaddr_in *)&so[RTAX_NETMASK];
1369 
1370 		max = 32;
1371 		p = (char *)&sin->sin_addr;
1372 		sin->sin_family = AF_INET;
1373 		sin->sin_len = sizeof(*sin);
1374 		break;
1375 	}
1376 #endif
1377 	default:
1378 		errx(EX_OSERR, "prefixlen not supported in this af");
1379 	}
1380 
1381 	if (len < 0 || max < len)
1382 		errx(EX_USAGE, "%s: invalid prefixlen", str);
1383 
1384 	q = len >> 3;
1385 	r = len & 7;
1386 	memset((void *)p, 0, max / 8);
1387 	if (q > 0)
1388 		memset((void *)p, 0xff, q);
1389 	if (r > 0)
1390 		*((u_char *)p + q) = (0xff00 >> r) & 0xff;
1391 	if (len == max)
1392 		return (-1);
1393 	else
1394 		return (len);
1395 }
1396 
1397 static void
1398 interfaces(void)
1399 {
1400 	size_t needed;
1401 	int mib[6];
1402 	char *buf, *lim, *next, count = 0;
1403 	struct rt_msghdr *rtm;
1404 
1405 retry2:
1406 	mib[0] = CTL_NET;
1407 	mib[1] = PF_ROUTE;
1408 	mib[2] = 0;		/* protocol */
1409 	mib[3] = AF_UNSPEC;
1410 	mib[4] = NET_RT_IFLIST;
1411 	mib[5] = 0;		/* no flags */
1412 	if (sysctl(mib, nitems(mib), NULL, &needed, NULL, 0) < 0)
1413 		err(EX_OSERR, "route-sysctl-estimate");
1414 	if ((buf = malloc(needed)) == NULL)
1415 		errx(EX_OSERR, "malloc failed");
1416 	if (sysctl(mib, nitems(mib), buf, &needed, NULL, 0) < 0) {
1417 		if (errno == ENOMEM && count++ < 10) {
1418 			warnx("Routing table grew, retrying");
1419 			sleep(1);
1420 			free(buf);
1421 			goto retry2;
1422 		}
1423 		err(EX_OSERR, "actual retrieval of interface table");
1424 	}
1425 	lim = buf + needed;
1426 	for (next = buf; next < lim; next += rtm->rtm_msglen) {
1427 		rtm = (struct rt_msghdr *)(void *)next;
1428 		print_rtmsg(rtm, rtm->rtm_msglen);
1429 	}
1430 }
1431 
1432 static void
1433 monitor(int argc, char *argv[])
1434 {
1435 	int n, fib, error;
1436 	char msg[2048], *endptr;
1437 
1438 	fib = defaultfib;
1439 	while (argc > 1) {
1440 		argc--;
1441 		argv++;
1442 		if (**argv != '-')
1443 			usage(*argv);
1444 		switch (keyword(*argv + 1)) {
1445 		case K_FIB:
1446 			if (!--argc)
1447 				usage(*argv);
1448 			errno = 0;
1449 			fib = strtol(*++argv, &endptr, 0);
1450 			if (errno == 0) {
1451 				if (*endptr != '\0' ||
1452 				    fib < 0 ||
1453 				    (numfibs != -1 && fib > numfibs - 1))
1454 					errno = EINVAL;
1455 			}
1456 			if (errno)
1457 				errx(EX_USAGE, "invalid fib number: %s", *argv);
1458 			break;
1459 		default:
1460 			usage(*argv);
1461 		}
1462 	}
1463 	error = set_sofib(fib);
1464 	if (error)
1465 		errx(EX_USAGE, "invalid fib number: %d", fib);
1466 
1467 	verbose = 1;
1468 	if (debugonly) {
1469 		interfaces();
1470 		exit(0);
1471 	}
1472 	for (;;) {
1473 		time_t now;
1474 		n = read(s, msg, 2048);
1475 		now = time(NULL);
1476 		(void)printf("\ngot message of size %d on %s", n, ctime(&now));
1477 		print_rtmsg((struct rt_msghdr *)(void *)msg, n);
1478 	}
1479 }
1480 
1481 static int
1482 rtmsg(int cmd, int flags, int fib)
1483 {
1484 	int rlen;
1485 	char *cp = m_rtmsg.m_space;
1486 	int l;
1487 
1488 #define NEXTADDR(w, u)							\
1489 	if (rtm_addrs & (w)) {						\
1490 		l = (((struct sockaddr *)&(u))->sa_len == 0) ?		\
1491 		    sizeof(long) :					\
1492 		    1 + ((((struct sockaddr *)&(u))->sa_len - 1)	\
1493 			| (sizeof(long) - 1));				\
1494 		memmove(cp, (char *)&(u), l);				\
1495 		cp += l;						\
1496 		if (verbose)						\
1497 			sodump((struct sockaddr *)&(u), #w);		\
1498 	}
1499 
1500 	errno = 0;
1501 	memset(&m_rtmsg, 0, sizeof(m_rtmsg));
1502 	if (cmd == 'a')
1503 		cmd = RTM_ADD;
1504 	else if (cmd == 'c')
1505 		cmd = RTM_CHANGE;
1506 	else if (cmd == 'g' || cmd == 's') {
1507 		cmd = RTM_GET;
1508 		if (so[RTAX_IFP].ss_family == 0) {
1509 			so[RTAX_IFP].ss_family = AF_LINK;
1510 			so[RTAX_IFP].ss_len = sizeof(struct sockaddr_dl);
1511 			rtm_addrs |= RTA_IFP;
1512 		}
1513 	} else
1514 		cmd = RTM_DELETE;
1515 #define rtm m_rtmsg.m_rtm
1516 	rtm.rtm_type = cmd;
1517 	rtm.rtm_flags = flags;
1518 	rtm.rtm_version = RTM_VERSION;
1519 	rtm.rtm_seq = ++rtm_seq;
1520 	rtm.rtm_addrs = rtm_addrs;
1521 	rtm.rtm_rmx = rt_metrics;
1522 	rtm.rtm_inits = rtm_inits;
1523 
1524 	NEXTADDR(RTA_DST, so[RTAX_DST]);
1525 	NEXTADDR(RTA_GATEWAY, so[RTAX_GATEWAY]);
1526 	NEXTADDR(RTA_NETMASK, so[RTAX_NETMASK]);
1527 	NEXTADDR(RTA_GENMASK, so[RTAX_GENMASK]);
1528 	NEXTADDR(RTA_IFP, so[RTAX_IFP]);
1529 	NEXTADDR(RTA_IFA, so[RTAX_IFA]);
1530 	rtm.rtm_msglen = l = cp - (char *)&m_rtmsg;
1531 	if (verbose)
1532 		print_rtmsg(&rtm, l);
1533 	if (debugonly)
1534 		return (0);
1535 	if ((rlen = write(s, (char *)&m_rtmsg, l)) < 0) {
1536 		if (errno == EPERM)
1537 			err(1, "writing to routing socket");
1538 		warn("writing to routing socket");
1539 		return (-1);
1540 	}
1541 	if (cmd == RTM_GET) {
1542 		do {
1543 			l = read(s, (char *)&m_rtmsg, sizeof(m_rtmsg));
1544 		} while (l > 0 && (rtm.rtm_seq != rtm_seq || rtm.rtm_pid != pid));
1545 		if (l < 0)
1546 			warn("read from routing socket");
1547 		else
1548 			print_getmsg(&rtm, l, fib);
1549 	}
1550 #undef rtm
1551 	return (0);
1552 }
1553 
1554 static const char *const msgtypes[] = {
1555 	"",
1556 	"RTM_ADD: Add Route",
1557 	"RTM_DELETE: Delete Route",
1558 	"RTM_CHANGE: Change Metrics or flags",
1559 	"RTM_GET: Report Metrics",
1560 	"RTM_LOSING: Kernel Suspects Partitioning",
1561 	"RTM_REDIRECT: Told to use different route",
1562 	"RTM_MISS: Lookup failed on this address",
1563 	"RTM_LOCK: fix specified metrics",
1564 	"RTM_OLDADD: caused by SIOCADDRT",
1565 	"RTM_OLDDEL: caused by SIOCDELRT",
1566 	"RTM_RESOLVE: Route created by cloning",
1567 	"RTM_NEWADDR: address being added to iface",
1568 	"RTM_DELADDR: address being removed from iface",
1569 	"RTM_IFINFO: iface status change",
1570 	"RTM_NEWMADDR: new multicast group membership on iface",
1571 	"RTM_DELMADDR: multicast group membership removed from iface",
1572 	"RTM_IFANNOUNCE: interface arrival/departure",
1573 	"RTM_IEEE80211: IEEE 802.11 wireless event",
1574 };
1575 
1576 static const char metricnames[] =
1577     "\011weight\010rttvar\7rtt\6ssthresh\5sendpipe\4recvpipe\3expire"
1578     "\1mtu";
1579 static const char routeflags[] =
1580     "\1UP\2GATEWAY\3HOST\4REJECT\5DYNAMIC\6MODIFIED\7DONE"
1581     "\012XRESOLVE\013LLINFO\014STATIC\015BLACKHOLE"
1582     "\017PROTO2\020PROTO1\021PRCLONING\022WASCLONED\023PROTO3"
1583     "\025PINNED\026LOCAL\027BROADCAST\030MULTICAST\035STICKY";
1584 static const char ifnetflags[] =
1585     "\1UP\2BROADCAST\3DEBUG\4LOOPBACK\5PTP\6b6\7RUNNING\010NOARP"
1586     "\011PPROMISC\012ALLMULTI\013OACTIVE\014SIMPLEX\015LINK0\016LINK1"
1587     "\017LINK2\020MULTICAST";
1588 static const char addrnames[] =
1589     "\1DST\2GATEWAY\3NETMASK\4GENMASK\5IFP\6IFA\7AUTHOR\010BRD";
1590 
1591 static const char errfmt[] =
1592     "\n%s: truncated route message, only %zu bytes left\n";
1593 
1594 static void
1595 print_rtmsg(struct rt_msghdr *rtm, size_t msglen)
1596 {
1597 	struct if_msghdr *ifm;
1598 	struct ifa_msghdr *ifam;
1599 #ifdef RTM_NEWMADDR
1600 	struct ifma_msghdr *ifmam;
1601 #endif
1602 	struct if_announcemsghdr *ifan;
1603 	const char *state;
1604 
1605 	if (verbose == 0)
1606 		return;
1607 	if (rtm->rtm_version != RTM_VERSION) {
1608 		(void)printf("routing message version %d not understood\n",
1609 		    rtm->rtm_version);
1610 		return;
1611 	}
1612 	if (rtm->rtm_type < nitems(msgtypes))
1613 		(void)printf("%s: ", msgtypes[rtm->rtm_type]);
1614 	else
1615 		(void)printf("unknown type %d: ", rtm->rtm_type);
1616 	(void)printf("len %d, ", rtm->rtm_msglen);
1617 
1618 #define	REQUIRE(x)	do {		\
1619 	if (msglen < sizeof(x))		\
1620 		goto badlen;		\
1621 	else				\
1622 		msglen -= sizeof(x);	\
1623 	} while (0)
1624 
1625 	switch (rtm->rtm_type) {
1626 	case RTM_IFINFO:
1627 		REQUIRE(struct if_msghdr);
1628 		ifm = (struct if_msghdr *)rtm;
1629 		(void)printf("if# %d, ", ifm->ifm_index);
1630 		switch (ifm->ifm_data.ifi_link_state) {
1631 		case LINK_STATE_DOWN:
1632 			state = "down";
1633 			break;
1634 		case LINK_STATE_UP:
1635 			state = "up";
1636 			break;
1637 		default:
1638 			state = "unknown";
1639 			break;
1640 		}
1641 		(void)printf("link: %s, flags:", state);
1642 		printb(ifm->ifm_flags, ifnetflags);
1643 		pmsg_addrs((char *)(ifm + 1), ifm->ifm_addrs, msglen);
1644 		break;
1645 	case RTM_NEWADDR:
1646 	case RTM_DELADDR:
1647 		REQUIRE(struct ifa_msghdr);
1648 		ifam = (struct ifa_msghdr *)rtm;
1649 		(void)printf("metric %d, flags:", ifam->ifam_metric);
1650 		printb(ifam->ifam_flags, routeflags);
1651 		pmsg_addrs((char *)(ifam + 1), ifam->ifam_addrs, msglen);
1652 		break;
1653 #ifdef RTM_NEWMADDR
1654 	case RTM_NEWMADDR:
1655 	case RTM_DELMADDR:
1656 		REQUIRE(struct ifma_msghdr);
1657 		ifmam = (struct ifma_msghdr *)rtm;
1658 		pmsg_addrs((char *)(ifmam + 1), ifmam->ifmam_addrs, msglen);
1659 		break;
1660 #endif
1661 	case RTM_IFANNOUNCE:
1662 		REQUIRE(struct if_announcemsghdr);
1663 		ifan = (struct if_announcemsghdr *)rtm;
1664 		(void)printf("if# %d, what: ", ifan->ifan_index);
1665 		switch (ifan->ifan_what) {
1666 		case IFAN_ARRIVAL:
1667 			(void)printf("arrival");
1668 			break;
1669 		case IFAN_DEPARTURE:
1670 			printf("departure");
1671 			break;
1672 		default:
1673 			printf("#%d", ifan->ifan_what);
1674 			break;
1675 		}
1676 		printf("\n");
1677 		fflush(stdout);
1678 		break;
1679 
1680 	default:
1681 		printf("pid: %ld, seq %d, errno %d, flags:",
1682 			(long)rtm->rtm_pid, rtm->rtm_seq, rtm->rtm_errno);
1683 		printb(rtm->rtm_flags, routeflags);
1684 		pmsg_common(rtm, msglen);
1685 	}
1686 
1687 	return;
1688 
1689 badlen:
1690 	(void)printf(errfmt, __func__, msglen);
1691 #undef	REQUIRE
1692 }
1693 
1694 static void
1695 print_getmsg(struct rt_msghdr *rtm, int msglen, int fib)
1696 {
1697 	struct sockaddr *sp[RTAX_MAX];
1698 	struct timespec ts;
1699 	char *cp;
1700 	int i;
1701 
1702 	memset(sp, 0, sizeof(sp));
1703 	(void)printf("   route to: %s\n",
1704 	    routename((struct sockaddr *)&so[RTAX_DST]));
1705 	if (rtm->rtm_version != RTM_VERSION) {
1706 		warnx("routing message version %d not understood",
1707 		     rtm->rtm_version);
1708 		return;
1709 	}
1710 	if (rtm->rtm_msglen > msglen) {
1711 		warnx("message length mismatch, in packet %d, returned %d",
1712 		      rtm->rtm_msglen, msglen);
1713 		return;
1714 	}
1715 	if (rtm->rtm_errno)  {
1716 		errno = rtm->rtm_errno;
1717 		warn("message indicates error %d", errno);
1718 		return;
1719 	}
1720 	cp = ((char *)(rtm + 1));
1721 	for (i = 0; i < RTAX_MAX; i++)
1722 		if (rtm->rtm_addrs & (1 << i)) {
1723 			sp[i] = (struct sockaddr *)cp;
1724 			cp += SA_SIZE((struct sockaddr *)cp);
1725 		}
1726 	if ((rtm->rtm_addrs & RTA_IFP) &&
1727 	    (sp[RTAX_IFP]->sa_family != AF_LINK ||
1728 	     ((struct sockaddr_dl *)(void *)sp[RTAX_IFP])->sdl_nlen == 0))
1729 			sp[RTAX_IFP] = NULL;
1730 	if (sp[RTAX_DST] && sp[RTAX_NETMASK])
1731 		sp[RTAX_NETMASK]->sa_family = sp[RTAX_DST]->sa_family; /* XXX */
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