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