xref: /freebsd/sbin/route/route.c (revision 52f72944b8f5abb2386eae924357dee8aea17d5b)
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 	return (error);
527 }
528 
529 static const char *
530 routename(struct sockaddr *sa)
531 {
532 	struct sockaddr_dl *sdl;
533 	const char *cp;
534 	int n;
535 
536 	if (!domain_initialized) {
537 		domain_initialized = true;
538 		if (gethostname(domain, MAXHOSTNAMELEN) == 0 &&
539 		    (cp = strchr(domain, '.'))) {
540 			domain[MAXHOSTNAMELEN] = '\0';
541 			(void)strcpy(domain, cp + 1);
542 		} else
543 			domain[0] = '\0';
544 	}
545 
546 	/* If the address is zero-filled, use "default". */
547 	if (sa->sa_len == 0 && nflag == 0)
548 		return ("default");
549 #if defined(INET) || defined(INET6)
550 	switch (sa->sa_family) {
551 #ifdef INET
552 	case AF_INET:
553 		/* If the address is zero-filled, use "default". */
554 		if (nflag == 0 &&
555 		    ((struct sockaddr_in *)(void *)sa)->sin_addr.s_addr ==
556 		    INADDR_ANY)
557 			return("default");
558 		break;
559 #endif
560 #ifdef INET6
561 	case AF_INET6:
562 		/* If the address is zero-filled, use "default". */
563 		if (nflag == 0 &&
564 		    IN6_IS_ADDR_UNSPECIFIED(&((struct sockaddr_in6 *)(void *)sa)->sin6_addr))
565 			return("default");
566 		break;
567 #endif
568 	}
569 #endif
570 
571 	switch (sa->sa_family) {
572 #if defined(INET) || defined(INET6)
573 #ifdef INET
574 	case AF_INET:
575 #endif
576 #ifdef INET6
577 	case AF_INET6:
578 #endif
579 	{
580 		struct sockaddr_storage ss;
581 		int error;
582 		char *p;
583 
584 		memset(&ss, 0, sizeof(ss));
585 		if (sa->sa_len == 0)
586 			ss.ss_family = sa->sa_family;
587 		else
588 			memcpy(&ss, sa, sa->sa_len);
589 		/* Expand sa->sa_len because it could be shortened. */
590 		if (sa->sa_family == AF_INET)
591 			ss.ss_len = sizeof(struct sockaddr_in);
592 		else if (sa->sa_family == AF_INET6)
593 			ss.ss_len = sizeof(struct sockaddr_in6);
594 		error = getnameinfo((struct sockaddr *)&ss, ss.ss_len,
595 		    rt_line, sizeof(rt_line), NULL, 0,
596 		    (nflag == 0) ? 0 : NI_NUMERICHOST);
597 		if (error) {
598 			warnx("getnameinfo(): %s", gai_strerror(error));
599 			strncpy(rt_line, "invalid", sizeof(rt_line));
600 		}
601 
602 		/* Remove the domain part if any. */
603 		p = strchr(rt_line, '.');
604 		if (p != NULL && strcmp(p + 1, domain) == 0)
605 			*p = '\0';
606 
607 		return (rt_line);
608 		break;
609 	}
610 #endif
611 	case AF_LINK:
612 		sdl = (struct sockaddr_dl *)(void *)sa;
613 
614 		if (sdl->sdl_nlen == 0 &&
615 		    sdl->sdl_alen == 0 &&
616 		    sdl->sdl_slen == 0) {
617 			n = snprintf(rt_line, sizeof(rt_line), "link#%d",
618 			    sdl->sdl_index);
619 			if (n > (int)sizeof(rt_line))
620 			    rt_line[0] = '\0';
621 			return (rt_line);
622 		} else
623 			return (link_ntoa(sdl));
624 		break;
625 
626 	default:
627 	    {
628 		u_short *sp = (u_short *)(void *)sa;
629 		u_short *splim = sp + ((sa->sa_len + 1) >> 1);
630 		char *cps = rt_line + sprintf(rt_line, "(%d)", sa->sa_family);
631 		char *cpe = rt_line + sizeof(rt_line);
632 
633 		while (++sp < splim && cps < cpe) /* start with sa->sa_data */
634 			if ((n = snprintf(cps, cpe - cps, " %x", *sp)) > 0)
635 				cps += n;
636 			else
637 				*cps = '\0';
638 		break;
639 	    }
640 	}
641 	return (rt_line);
642 }
643 
644 /*
645  * Return the name of the network whose address is given.
646  * The address is assumed to be that of a net, not a host.
647  */
648 static const char *
649 netname(struct sockaddr *sa)
650 {
651 	struct sockaddr_dl *sdl;
652 	int n;
653 #ifdef INET
654 	struct netent *np = NULL;
655 	const char *cp = NULL;
656 	u_long i;
657 #endif
658 
659 	switch (sa->sa_family) {
660 #ifdef INET
661 	case AF_INET:
662 	{
663 		struct in_addr in;
664 
665 		in = ((struct sockaddr_in *)(void *)sa)->sin_addr;
666 		i = in.s_addr = ntohl(in.s_addr);
667 		if (in.s_addr == 0)
668 			cp = "default";
669 		else if (!nflag) {
670 			np = getnetbyaddr(i, AF_INET);
671 			if (np != NULL)
672 				cp = np->n_name;
673 		}
674 #define C(x)	(unsigned)((x) & 0xff)
675 		if (cp != NULL)
676 			strncpy(net_line, cp, sizeof(net_line));
677 		else if ((in.s_addr & 0xffffff) == 0)
678 			(void)sprintf(net_line, "%u", C(in.s_addr >> 24));
679 		else if ((in.s_addr & 0xffff) == 0)
680 			(void)sprintf(net_line, "%u.%u", C(in.s_addr >> 24),
681 			    C(in.s_addr >> 16));
682 		else if ((in.s_addr & 0xff) == 0)
683 			(void)sprintf(net_line, "%u.%u.%u", C(in.s_addr >> 24),
684 			    C(in.s_addr >> 16), C(in.s_addr >> 8));
685 		else
686 			(void)sprintf(net_line, "%u.%u.%u.%u", C(in.s_addr >> 24),
687 			    C(in.s_addr >> 16), C(in.s_addr >> 8),
688 			    C(in.s_addr));
689 #undef C
690 		break;
691 	}
692 #endif
693 #ifdef INET6
694 	case AF_INET6:
695 	{
696 		struct sockaddr_in6 sin6;
697 		int niflags = 0;
698 
699 		memset(&sin6, 0, sizeof(sin6));
700 		memcpy(&sin6, sa, sa->sa_len);
701 		sin6.sin6_len = sizeof(sin6);
702 		sin6.sin6_family = AF_INET6;
703 		if (nflag)
704 			niflags |= NI_NUMERICHOST;
705 		if (getnameinfo((struct sockaddr *)&sin6, sin6.sin6_len,
706 		    net_line, sizeof(net_line), NULL, 0, niflags) != 0)
707 			strncpy(net_line, "invalid", sizeof(net_line));
708 
709 		return(net_line);
710 	}
711 #endif
712 	case AF_LINK:
713 		sdl = (struct sockaddr_dl *)(void *)sa;
714 
715 		if (sdl->sdl_nlen == 0 &&
716 		    sdl->sdl_alen == 0 &&
717 		    sdl->sdl_slen == 0) {
718 			n = snprintf(net_line, sizeof(net_line), "link#%d",
719 			    sdl->sdl_index);
720 			if (n > (int)sizeof(net_line))
721 			    net_line[0] = '\0';
722 			return (net_line);
723 		} else
724 			return (link_ntoa(sdl));
725 		break;
726 
727 	default:
728 	    {
729 		u_short *sp = (u_short *)(void *)sa->sa_data;
730 		u_short *splim = sp + ((sa->sa_len + 1)>>1);
731 		char *cps = net_line + sprintf(net_line, "af %d:", sa->sa_family);
732 		char *cpe = net_line + sizeof(net_line);
733 
734 		while (sp < splim && cps < cpe)
735 			if ((n = snprintf(cps, cpe - cps, " %x", *sp++)) > 0)
736 				cps += n;
737 			else
738 				*cps = '\0';
739 		break;
740 	    }
741 	}
742 	return (net_line);
743 }
744 
745 static void
746 set_metric(char *value, int key)
747 {
748 	int flag = 0;
749 	char *endptr;
750 	u_long noval, *valp = &noval;
751 
752 	switch (key) {
753 #define caseof(x, y, z)	case x: valp = &rt_metrics.z; flag = y; break
754 	caseof(K_MTU, RTV_MTU, rmx_mtu);
755 	caseof(K_HOPCOUNT, RTV_HOPCOUNT, rmx_hopcount);
756 	caseof(K_EXPIRE, RTV_EXPIRE, rmx_expire);
757 	caseof(K_RECVPIPE, RTV_RPIPE, rmx_recvpipe);
758 	caseof(K_SENDPIPE, RTV_SPIPE, rmx_sendpipe);
759 	caseof(K_SSTHRESH, RTV_SSTHRESH, rmx_ssthresh);
760 	caseof(K_RTT, RTV_RTT, rmx_rtt);
761 	caseof(K_RTTVAR, RTV_RTTVAR, rmx_rttvar);
762 	caseof(K_WEIGHT, RTV_WEIGHT, rmx_weight);
763 	}
764 	rtm_inits |= flag;
765 	if (lockrest || locking)
766 		rt_metrics.rmx_locks |= flag;
767 	if (locking)
768 		locking = 0;
769 	errno = 0;
770 	*valp = strtol(value, &endptr, 0);
771 	if (errno == 0 && *endptr != '\0')
772 		errno = EINVAL;
773 	if (errno)
774 		err(EX_USAGE, "%s", value);
775 	if (flag & RTV_EXPIRE && (value[0] == '+' || value[0] == '-')) {
776 		struct timespec ts;
777 
778 		clock_gettime(CLOCK_REALTIME_FAST, &ts);
779 		*valp += ts.tv_sec;
780 	}
781 }
782 
783 #define	F_ISHOST	0x01
784 #define	F_FORCENET	0x02
785 #define	F_FORCEHOST	0x04
786 #define	F_PROXY		0x08
787 #define	F_INTERFACE	0x10
788 
789 static void
790 newroute(int argc, char **argv)
791 {
792 	struct sigaction sa;
793 	struct hostent *hp;
794 	struct fibl *fl;
795 	char *cmd;
796 	const char *dest, *gateway, *errmsg;
797 	int key, error, flags, nrflags, fibnum;
798 
799 	if (uid != 0 && !debugonly && !tflag)
800 		errx(EX_NOPERM, "must be root to alter routing table");
801 	dest = NULL;
802 	gateway = NULL;
803 	flags = RTF_STATIC;
804 	nrflags = 0;
805 	hp = NULL;
806 	TAILQ_INIT(&fibl_head);
807 
808 	sigemptyset(&sa.sa_mask);
809 	sa.sa_flags = 0;
810 	sa.sa_handler = stopit;
811 	if (sigaction(SIGALRM, &sa, 0) == -1)
812 		warn("sigaction SIGALRM");
813 
814 	cmd = argv[0];
815 	if (*cmd != 'g' && *cmd != 's')
816 		shutdown(s, SHUT_RD); /* Don't want to read back our messages */
817 	while (--argc > 0) {
818 		if (**(++argv)== '-') {
819 			switch (key = keyword(1 + *argv)) {
820 			case K_LINK:
821 				af = AF_LINK;
822 				aflen = sizeof(struct sockaddr_dl);
823 				break;
824 #ifdef INET
825 			case K_4:
826 			case K_INET:
827 				af = AF_INET;
828 				aflen = sizeof(struct sockaddr_in);
829 				break;
830 #endif
831 #ifdef INET6
832 			case K_6:
833 			case K_INET6:
834 				af = AF_INET6;
835 				aflen = sizeof(struct sockaddr_in6);
836 				break;
837 #endif
838 			case K_SA:
839 				af = PF_ROUTE;
840 				aflen = sizeof(struct sockaddr_storage);
841 				break;
842 			case K_IFACE:
843 			case K_INTERFACE:
844 				nrflags |= F_INTERFACE;
845 				break;
846 			case K_NOSTATIC:
847 				flags &= ~RTF_STATIC;
848 				break;
849 			case K_LOCK:
850 				locking = 1;
851 				break;
852 			case K_LOCKREST:
853 				lockrest = 1;
854 				break;
855 			case K_HOST:
856 				nrflags |= F_FORCEHOST;
857 				break;
858 			case K_REJECT:
859 				flags |= RTF_REJECT;
860 				break;
861 			case K_BLACKHOLE:
862 				flags |= RTF_BLACKHOLE;
863 				break;
864 			case K_PROTO1:
865 				flags |= RTF_PROTO1;
866 				break;
867 			case K_PROTO2:
868 				flags |= RTF_PROTO2;
869 				break;
870 			case K_PROXY:
871 				nrflags |= F_PROXY;
872 				break;
873 			case K_XRESOLVE:
874 				flags |= RTF_XRESOLVE;
875 				break;
876 			case K_STATIC:
877 				flags |= RTF_STATIC;
878 				break;
879 			case K_STICKY:
880 				flags |= RTF_STICKY;
881 				break;
882 			case K_NOSTICK:
883 				flags &= ~RTF_STICKY;
884 				break;
885 			case K_FIB:
886 				if (!--argc)
887 					usage(NULL);
888 				error = fiboptlist_csv(*++argv, &fibl_head);
889 				if (error)
890 					errx(EX_USAGE,
891 					    "invalid fib number: %s", *argv);
892 				break;
893 			case K_IFA:
894 				if (!--argc)
895 					usage(NULL);
896 				getaddr(RTAX_IFA, *++argv, 0, nrflags);
897 				break;
898 			case K_IFP:
899 				if (!--argc)
900 					usage(NULL);
901 				getaddr(RTAX_IFP, *++argv, 0, nrflags);
902 				break;
903 			case K_GENMASK:
904 				if (!--argc)
905 					usage(NULL);
906 				getaddr(RTAX_GENMASK, *++argv, 0, nrflags);
907 				break;
908 			case K_GATEWAY:
909 				if (!--argc)
910 					usage(NULL);
911 				getaddr(RTAX_GATEWAY, *++argv, 0, nrflags);
912 				gateway = *argv;
913 				break;
914 			case K_DST:
915 				if (!--argc)
916 					usage(NULL);
917 				if (getaddr(RTAX_DST, *++argv, &hp, nrflags))
918 					nrflags |= F_ISHOST;
919 				dest = *argv;
920 				break;
921 			case K_NETMASK:
922 				if (!--argc)
923 					usage(NULL);
924 				getaddr(RTAX_NETMASK, *++argv, 0, nrflags);
925 				/* FALLTHROUGH */
926 			case K_NET:
927 				nrflags |= F_FORCENET;
928 				break;
929 			case K_PREFIXLEN:
930 				if (!--argc)
931 					usage(NULL);
932 				if (prefixlen(*++argv) == -1) {
933 					nrflags &= ~F_FORCENET;
934 					nrflags |= F_ISHOST;
935 				} else {
936 					nrflags |= F_FORCENET;
937 					nrflags &= ~F_ISHOST;
938 				}
939 				break;
940 			case K_MTU:
941 			case K_HOPCOUNT:
942 			case K_EXPIRE:
943 			case K_RECVPIPE:
944 			case K_SENDPIPE:
945 			case K_SSTHRESH:
946 			case K_RTT:
947 			case K_RTTVAR:
948 			case K_WEIGHT:
949 				if (!--argc)
950 					usage(NULL);
951 				set_metric(*++argv, key);
952 				break;
953 			default:
954 				usage(1+*argv);
955 			}
956 		} else {
957 			if ((rtm_addrs & RTA_DST) == 0) {
958 				dest = *argv;
959 				if (getaddr(RTAX_DST, *argv, &hp, nrflags))
960 					nrflags |= F_ISHOST;
961 			} else if ((rtm_addrs & RTA_GATEWAY) == 0) {
962 				gateway = *argv;
963 				getaddr(RTAX_GATEWAY, *argv, &hp, nrflags);
964 			} else {
965 				getaddr(RTAX_NETMASK, *argv, 0, nrflags);
966 				nrflags |= F_FORCENET;
967 			}
968 		}
969 	}
970 
971 	/* Do some sanity checks on resulting request */
972 	if (so[RTAX_DST].ss_len == 0) {
973 		warnx("destination parameter required");
974 		usage(NULL);
975 	}
976 
977 	if (so[RTAX_NETMASK].ss_len != 0 &&
978 	    so[RTAX_DST].ss_family != so[RTAX_NETMASK].ss_family) {
979 		warnx("destination and netmask family need to be the same");
980 		usage(NULL);
981 	}
982 
983 	if (nrflags & F_FORCEHOST) {
984 		nrflags |= F_ISHOST;
985 #ifdef INET6
986 		if (af == AF_INET6) {
987 			rtm_addrs &= ~RTA_NETMASK;
988 			memset(&so[RTAX_NETMASK], 0, sizeof(so[RTAX_NETMASK]));
989 		}
990 #endif
991 	}
992 	if (nrflags & F_FORCENET)
993 		nrflags &= ~F_ISHOST;
994 	flags |= RTF_UP;
995 	if (nrflags & F_ISHOST)
996 		flags |= RTF_HOST;
997 	if ((nrflags & F_INTERFACE) == 0)
998 		flags |= RTF_GATEWAY;
999 	if (nrflags & F_PROXY)
1000 		flags |= RTF_ANNOUNCE;
1001 	if (dest == NULL)
1002 		dest = "";
1003 	if (gateway == NULL)
1004 		gateway = "";
1005 
1006 	if (TAILQ_EMPTY(&fibl_head)) {
1007 		error = fiboptlist_csv("default", &fibl_head);
1008 		if (error)
1009 			errx(EX_OSERR, "fiboptlist_csv failed.");
1010 	}
1011 	error = 0;
1012 	TAILQ_FOREACH(fl, &fibl_head, fl_next) {
1013 		fl->fl_error = newroute_fib(fl->fl_num, cmd, flags);
1014 		if (fl->fl_error)
1015 			fl->fl_errno = errno;
1016 		error += fl->fl_error;
1017 	}
1018 	if (*cmd == 'g' || *cmd == 's')
1019 		exit(error);
1020 
1021 	error = 0;
1022 	if (!qflag) {
1023 		fibnum = 0;
1024 		TAILQ_FOREACH(fl, &fibl_head, fl_next) {
1025 			if (fl->fl_error == 0)
1026 				fibnum++;
1027 		}
1028 		if (fibnum > 0) {
1029 			int firstfib = 1;
1030 
1031 			printf("%s %s %s", cmd,
1032 			    (nrflags & F_ISHOST) ? "host" : "net", dest);
1033 			if (*gateway)
1034 				printf(": gateway %s", gateway);
1035 
1036 			if (numfibs > 1) {
1037 				TAILQ_FOREACH(fl, &fibl_head, fl_next) {
1038 					if (fl->fl_error == 0
1039 					    && fl->fl_num >= 0) {
1040 						if (firstfib) {
1041 							printf(" fib ");
1042 							firstfib = 0;
1043 						}
1044 						printf("%d", fl->fl_num);
1045 						if (fibnum-- > 1)
1046 							printf(",");
1047 					}
1048 				}
1049 			}
1050 			printf("\n");
1051 		}
1052 
1053 		fibnum = 0;
1054 		TAILQ_FOREACH(fl, &fibl_head, fl_next) {
1055 			if (fl->fl_error != 0) {
1056 				printf("%s %s %s", cmd, (nrflags & F_ISHOST)
1057 				    ? "host" : "net", dest);
1058 				if (*gateway)
1059 					printf(": gateway %s", gateway);
1060 
1061 				if (fl->fl_num >= 0)
1062 					printf(" fib %d", fl->fl_num);
1063 
1064 				switch (fl->fl_errno) {
1065 				case ESRCH:
1066 					errmsg = "not in table";
1067 					break;
1068 				case EBUSY:
1069 					errmsg = "entry in use";
1070 					break;
1071 				case ENOBUFS:
1072 					errmsg = "not enough memory";
1073 					break;
1074 				case EADDRINUSE:
1075 					/*
1076 					 * handle recursion avoidance
1077 					 * in rt_setgate()
1078 					 */
1079 					errmsg = "gateway uses the same route";
1080 					break;
1081 				case EEXIST:
1082 					errmsg = "route already in table";
1083 					break;
1084 				default:
1085 					errmsg = strerror(fl->fl_errno);
1086 					break;
1087 				}
1088 				printf(": %s\n", errmsg);
1089 				error = 1;
1090 			}
1091 		}
1092 	}
1093 	exit(error);
1094 }
1095 
1096 static int
1097 newroute_fib(int fib, char *cmd, int flags)
1098 {
1099 	int error;
1100 
1101 	error = set_sofib(fib);
1102 	if (error) {
1103 		warn("fib number %d is ignored", fib);
1104 		return (error);
1105 	}
1106 
1107 	error = rtmsg(*cmd, flags, fib);
1108 	return (error);
1109 }
1110 
1111 #ifdef INET
1112 static void
1113 inet_makenetandmask(u_long net, struct sockaddr_in *sin,
1114     struct sockaddr_in *sin_mask, u_long bits)
1115 {
1116 	u_long mask = 0;
1117 
1118 	rtm_addrs |= RTA_NETMASK;
1119 
1120 	/*
1121 	 * MSB of net should be meaningful. 0/0 is exception.
1122 	 */
1123 	if (net > 0)
1124 		while ((net & 0xff000000) == 0)
1125 			net <<= 8;
1126 
1127 	/*
1128 	 * If no /xx was specified we must calculate the
1129 	 * CIDR address.
1130 	 */
1131 	if ((bits == 0) && (net != 0)) {
1132 		u_long i, j;
1133 
1134 		for(i = 0, j = 0xff; i < 4; i++)  {
1135 			if (net & j) {
1136 				break;
1137 			}
1138 			j <<= 8;
1139 		}
1140 		/* i holds the first non zero bit */
1141 		bits = 32 - (i*8);
1142 	}
1143 	if (bits != 0)
1144 		mask = 0xffffffff << (32 - bits);
1145 
1146 	sin->sin_addr.s_addr = htonl(net);
1147 	sin_mask->sin_addr.s_addr = htonl(mask);
1148 	sin_mask->sin_len = sizeof(struct sockaddr_in);
1149 	sin_mask->sin_family = AF_INET;
1150 }
1151 #endif
1152 
1153 #ifdef INET6
1154 /*
1155  * XXX the function may need more improvement...
1156  */
1157 static int
1158 inet6_makenetandmask(struct sockaddr_in6 *sin6, const char *plen)
1159 {
1160 
1161 	if (plen == NULL) {
1162 		if (IN6_IS_ADDR_UNSPECIFIED(&sin6->sin6_addr) &&
1163 		    sin6->sin6_scope_id == 0)
1164 			plen = "0";
1165 	}
1166 
1167 	if (plen == NULL || strcmp(plen, "128") == 0)
1168 		return (1);
1169 	rtm_addrs |= RTA_NETMASK;
1170 	prefixlen(plen);
1171 	return (0);
1172 }
1173 #endif
1174 
1175 /*
1176  * Interpret an argument as a network address of some kind,
1177  * returning 1 if a host address, 0 if a network address.
1178  */
1179 static int
1180 getaddr(int idx, char *str, struct hostent **hpp, int nrflags)
1181 {
1182 	struct sockaddr *sa;
1183 #if defined(INET)
1184 	struct sockaddr_in *sin;
1185 	struct hostent *hp;
1186 	struct netent *np;
1187 	u_long val;
1188 	char *q;
1189 #elif defined(INET6)
1190 	char *q;
1191 #endif
1192 
1193 	if (idx < 0 || idx >= RTAX_MAX)
1194 		usage("internal error");
1195 	if (af == 0) {
1196 #if defined(INET)
1197 		af = AF_INET;
1198 		aflen = sizeof(struct sockaddr_in);
1199 #elif defined(INET6)
1200 		af = AF_INET6;
1201 		aflen = sizeof(struct sockaddr_in6);
1202 #else
1203 		af = AF_LINK;
1204 		aflen = sizeof(struct sockaddr_dl);
1205 #endif
1206 	}
1207 #ifndef INET
1208 	hpp = NULL;
1209 #endif
1210 	rtm_addrs |= (1 << idx);
1211 	sa = (struct sockaddr *)&so[idx];
1212 	sa->sa_family = af;
1213 	sa->sa_len = aflen;
1214 
1215 	switch (idx) {
1216 	case RTAX_GATEWAY:
1217 		if (nrflags & F_INTERFACE) {
1218 			struct ifaddrs *ifap, *ifa;
1219 			struct sockaddr_dl *sdl0 = (struct sockaddr_dl *)(void *)sa;
1220 			struct sockaddr_dl *sdl = NULL;
1221 
1222 			if (getifaddrs(&ifap))
1223 				err(EX_OSERR, "getifaddrs");
1224 
1225 			for (ifa = ifap; ifa != NULL; ifa = ifa->ifa_next) {
1226 				if (ifa->ifa_addr->sa_family != AF_LINK)
1227 					continue;
1228 
1229 				if (strcmp(str, ifa->ifa_name) != 0)
1230 					continue;
1231 
1232 				sdl = (struct sockaddr_dl *)(void *)ifa->ifa_addr;
1233 			}
1234 			/* If we found it, then use it */
1235 			if (sdl != NULL) {
1236 				/*
1237 				 * Note that we need to copy before calling
1238 				 * freeifaddrs().
1239 				 */
1240 				memcpy(sdl0, sdl, sdl->sdl_len);
1241 			}
1242 			freeifaddrs(ifap);
1243 			if (sdl != NULL)
1244 				return(1);
1245 			else
1246 				errx(EX_DATAERR,
1247 				    "interface '%s' does not exist", str);
1248 		}
1249 		break;
1250 	case RTAX_IFP:
1251 		sa->sa_family = AF_LINK;
1252 		break;
1253 	}
1254 	if (strcmp(str, "default") == 0) {
1255 		/*
1256 		 * Default is net 0.0.0.0/0
1257 		 */
1258 		switch (idx) {
1259 		case RTAX_DST:
1260 			nrflags |= F_FORCENET;
1261 			getaddr(RTAX_NETMASK, str, 0, nrflags);
1262 			break;
1263 		}
1264 		return (0);
1265 	}
1266 	switch (sa->sa_family) {
1267 #ifdef INET6
1268 	case AF_INET6:
1269 	{
1270 		struct addrinfo hints, *res;
1271 		int ecode;
1272 
1273 		q = NULL;
1274 		if (idx == RTAX_DST && (q = strchr(str, '/')) != NULL)
1275 			*q = '\0';
1276 		memset(&hints, 0, sizeof(hints));
1277 		hints.ai_family = sa->sa_family;
1278 		hints.ai_socktype = SOCK_DGRAM;
1279 		ecode = getaddrinfo(str, NULL, &hints, &res);
1280 		if (ecode != 0 || res->ai_family != AF_INET6 ||
1281 		    res->ai_addrlen != sizeof(struct sockaddr_in6))
1282 			errx(EX_OSERR, "%s: %s", str, gai_strerror(ecode));
1283 		memcpy(sa, res->ai_addr, res->ai_addrlen);
1284 		freeaddrinfo(res);
1285 		if (q != NULL)
1286 			*q++ = '/';
1287 		if (idx == RTAX_DST)
1288 			return (inet6_makenetandmask((struct sockaddr_in6 *)(void *)sa, q));
1289 		return (0);
1290 	}
1291 #endif /* INET6 */
1292 	case AF_LINK:
1293 		link_addr(str, (struct sockaddr_dl *)(void *)sa);
1294 		return (1);
1295 
1296 	case PF_ROUTE:
1297 		sockaddr(str, sa, sizeof(struct sockaddr_storage));
1298 		return (1);
1299 #ifdef INET
1300 	case AF_INET:
1301 #endif
1302 	default:
1303 		break;
1304 	}
1305 
1306 #ifdef INET
1307 	sin = (struct sockaddr_in *)(void *)sa;
1308 	if (hpp == NULL)
1309 		hpp = &hp;
1310 	*hpp = NULL;
1311 
1312 	q = strchr(str,'/');
1313 	if (q != NULL && idx == RTAX_DST) {
1314 		*q = '\0';
1315 		if ((val = inet_network(str)) != INADDR_NONE) {
1316 			inet_makenetandmask(val, sin,
1317 			    (struct sockaddr_in *)&so[RTAX_NETMASK],
1318 			    strtoul(q+1, 0, 0));
1319 			return (0);
1320 		}
1321 		*q = '/';
1322 	}
1323 	if ((idx != RTAX_DST || (nrflags & F_FORCENET) == 0) &&
1324 	    inet_aton(str, &sin->sin_addr)) {
1325 		val = sin->sin_addr.s_addr;
1326 		if (idx != RTAX_DST || nrflags & F_FORCEHOST ||
1327 		    inet_lnaof(sin->sin_addr) != INADDR_ANY)
1328 			return (1);
1329 		else {
1330 			val = ntohl(val);
1331 			goto netdone;
1332 		}
1333 	}
1334 	if (idx == RTAX_DST && (nrflags & F_FORCEHOST) == 0 &&
1335 	    ((val = inet_network(str)) != INADDR_NONE ||
1336 	    ((np = getnetbyname(str)) != NULL && (val = np->n_net) != 0))) {
1337 netdone:
1338 		inet_makenetandmask(val, sin,
1339 		    (struct sockaddr_in *)&so[RTAX_NETMASK], 0);
1340 		return (0);
1341 	}
1342 	hp = gethostbyname(str);
1343 	if (hp != NULL) {
1344 		*hpp = hp;
1345 		sin->sin_family = hp->h_addrtype;
1346 		memmove((char *)&sin->sin_addr, hp->h_addr,
1347 		    MIN((size_t)hp->h_length, sizeof(sin->sin_addr)));
1348 		return (1);
1349 	}
1350 #endif
1351 	errx(EX_NOHOST, "bad address: %s", str);
1352 }
1353 
1354 static int
1355 prefixlen(const char *str)
1356 {
1357 	int len = atoi(str), q, r;
1358 	int max;
1359 	char *p;
1360 
1361 	rtm_addrs |= RTA_NETMASK;
1362 	switch (af) {
1363 #ifdef INET6
1364 	case AF_INET6:
1365 	{
1366 		struct sockaddr_in6 *sin6 =
1367 		    (struct sockaddr_in6 *)&so[RTAX_NETMASK];
1368 
1369 		max = 128;
1370 		p = (char *)&sin6->sin6_addr;
1371 		sin6->sin6_family = AF_INET6;
1372 		sin6->sin6_len = sizeof(*sin6);
1373 		break;
1374 	}
1375 #endif
1376 #ifdef INET
1377 	case AF_INET:
1378 	{
1379 		struct sockaddr_in *sin =
1380 		    (struct sockaddr_in *)&so[RTAX_NETMASK];
1381 
1382 		max = 32;
1383 		p = (char *)&sin->sin_addr;
1384 		sin->sin_family = AF_INET;
1385 		sin->sin_len = sizeof(*sin);
1386 		break;
1387 	}
1388 #endif
1389 	default:
1390 		errx(EX_OSERR, "prefixlen not supported in this af");
1391 	}
1392 
1393 	if (len < 0 || max < len)
1394 		errx(EX_USAGE, "%s: invalid prefixlen", str);
1395 
1396 	q = len >> 3;
1397 	r = len & 7;
1398 	memset((void *)p, 0, max / 8);
1399 	if (q > 0)
1400 		memset((void *)p, 0xff, q);
1401 	if (r > 0)
1402 		*((u_char *)p + q) = (0xff00 >> r) & 0xff;
1403 	if (len == max)
1404 		return (-1);
1405 	else
1406 		return (len);
1407 }
1408 
1409 static void
1410 interfaces(void)
1411 {
1412 	size_t needed;
1413 	int mib[6];
1414 	char *buf, *lim, *next, count = 0;
1415 	struct rt_msghdr *rtm;
1416 
1417 retry2:
1418 	mib[0] = CTL_NET;
1419 	mib[1] = PF_ROUTE;
1420 	mib[2] = 0;		/* protocol */
1421 	mib[3] = AF_UNSPEC;
1422 	mib[4] = NET_RT_IFLIST;
1423 	mib[5] = 0;		/* no flags */
1424 	if (sysctl(mib, nitems(mib), NULL, &needed, NULL, 0) < 0)
1425 		err(EX_OSERR, "route-sysctl-estimate");
1426 	if ((buf = malloc(needed)) == NULL)
1427 		errx(EX_OSERR, "malloc failed");
1428 	if (sysctl(mib, nitems(mib), buf, &needed, NULL, 0) < 0) {
1429 		if (errno == ENOMEM && count++ < 10) {
1430 			warnx("Routing table grew, retrying");
1431 			sleep(1);
1432 			free(buf);
1433 			goto retry2;
1434 		}
1435 		err(EX_OSERR, "actual retrieval of interface table");
1436 	}
1437 	lim = buf + needed;
1438 	for (next = buf; next < lim; next += rtm->rtm_msglen) {
1439 		rtm = (struct rt_msghdr *)(void *)next;
1440 		print_rtmsg(rtm, rtm->rtm_msglen);
1441 	}
1442 }
1443 
1444 static void
1445 monitor(int argc, char *argv[])
1446 {
1447 	int n, fib, error;
1448 	char msg[2048], *endptr;
1449 
1450 	fib = defaultfib;
1451 	while (argc > 1) {
1452 		argc--;
1453 		argv++;
1454 		if (**argv != '-')
1455 			usage(*argv);
1456 		switch (keyword(*argv + 1)) {
1457 		case K_FIB:
1458 			if (!--argc)
1459 				usage(*argv);
1460 			errno = 0;
1461 			fib = strtol(*++argv, &endptr, 0);
1462 			if (errno == 0) {
1463 				if (*endptr != '\0' ||
1464 				    fib < 0 ||
1465 				    (numfibs != -1 && fib > numfibs - 1))
1466 					errno = EINVAL;
1467 			}
1468 			if (errno)
1469 				errx(EX_USAGE, "invalid fib number: %s", *argv);
1470 			break;
1471 		default:
1472 			usage(*argv);
1473 		}
1474 	}
1475 	error = set_sofib(fib);
1476 	if (error)
1477 		errx(EX_USAGE, "invalid fib number: %d", fib);
1478 
1479 	verbose = 1;
1480 	if (debugonly) {
1481 		interfaces();
1482 		exit(0);
1483 	}
1484 	for (;;) {
1485 		time_t now;
1486 		n = read(s, msg, 2048);
1487 		now = time(NULL);
1488 		(void)printf("\ngot message of size %d on %s", n, ctime(&now));
1489 		print_rtmsg((struct rt_msghdr *)(void *)msg, n);
1490 	}
1491 }
1492 
1493 static int
1494 rtmsg(int cmd, int flags, int fib)
1495 {
1496 	int rlen;
1497 	char *cp = m_rtmsg.m_space;
1498 	int l;
1499 
1500 #define NEXTADDR(w, u)							\
1501 	if (rtm_addrs & (w)) {						\
1502 		l = SA_SIZE(&(u));					\
1503 		memmove(cp, (char *)&(u), l);				\
1504 		cp += l;						\
1505 		if (verbose)						\
1506 			sodump((struct sockaddr *)&(u), #w);		\
1507 	}
1508 
1509 	errno = 0;
1510 	memset(&m_rtmsg, 0, sizeof(m_rtmsg));
1511 	if (cmd == 'a')
1512 		cmd = RTM_ADD;
1513 	else if (cmd == 'c')
1514 		cmd = RTM_CHANGE;
1515 	else if (cmd == 'g' || cmd == 's') {
1516 		cmd = RTM_GET;
1517 		if (so[RTAX_IFP].ss_family == 0) {
1518 			so[RTAX_IFP].ss_family = AF_LINK;
1519 			so[RTAX_IFP].ss_len = sizeof(struct sockaddr_dl);
1520 			rtm_addrs |= RTA_IFP;
1521 		}
1522 	} else {
1523 		cmd = RTM_DELETE;
1524 		flags |= RTF_PINNED;
1525 	}
1526 #define rtm m_rtmsg.m_rtm
1527 	rtm.rtm_type = cmd;
1528 	rtm.rtm_flags = flags;
1529 	rtm.rtm_version = RTM_VERSION;
1530 	rtm.rtm_seq = ++rtm_seq;
1531 	rtm.rtm_addrs = rtm_addrs;
1532 	rtm.rtm_rmx = rt_metrics;
1533 	rtm.rtm_inits = rtm_inits;
1534 
1535 	NEXTADDR(RTA_DST, so[RTAX_DST]);
1536 	NEXTADDR(RTA_GATEWAY, so[RTAX_GATEWAY]);
1537 	NEXTADDR(RTA_NETMASK, so[RTAX_NETMASK]);
1538 	NEXTADDR(RTA_GENMASK, so[RTAX_GENMASK]);
1539 	NEXTADDR(RTA_IFP, so[RTAX_IFP]);
1540 	NEXTADDR(RTA_IFA, so[RTAX_IFA]);
1541 	rtm.rtm_msglen = l = cp - (char *)&m_rtmsg;
1542 	if (verbose)
1543 		print_rtmsg(&rtm, l);
1544 	if (debugonly)
1545 		return (0);
1546 	if ((rlen = write(s, (char *)&m_rtmsg, l)) < 0) {
1547 		switch (errno) {
1548 		case EPERM:
1549 			err(1, "writing to routing socket");
1550 			break;
1551 		case ESRCH:
1552 			warnx("route has not been found");
1553 			break;
1554 		case EEXIST:
1555 			/* Handled by newroute() */
1556 			break;
1557 		default:
1558 			warn("writing to routing socket");
1559 		}
1560 		return (-1);
1561 	}
1562 	if (cmd == RTM_GET) {
1563 		stop_read = 0;
1564 		alarm(READ_TIMEOUT);
1565 		do {
1566 			l = read(s, (char *)&m_rtmsg, sizeof(m_rtmsg));
1567 		} while (l > 0 && stop_read == 0 &&
1568 		    (rtm.rtm_type != RTM_GET || rtm.rtm_seq != rtm_seq ||
1569 			rtm.rtm_pid != pid));
1570 		if (stop_read != 0) {
1571 			warnx("read from routing socket timed out");
1572 			return (-1);
1573 		} else
1574 			alarm(0);
1575 		if (l < 0)
1576 			warn("read from routing socket");
1577 		else
1578 			print_getmsg(&rtm, l, fib);
1579 	}
1580 #undef rtm
1581 	return (0);
1582 }
1583 
1584 static const char *const msgtypes[] = {
1585 	"",
1586 	"RTM_ADD: Add Route",
1587 	"RTM_DELETE: Delete Route",
1588 	"RTM_CHANGE: Change Metrics or flags",
1589 	"RTM_GET: Report Metrics",
1590 	"RTM_LOSING: Kernel Suspects Partitioning",
1591 	"RTM_REDIRECT: Told to use different route",
1592 	"RTM_MISS: Lookup failed on this address",
1593 	"RTM_LOCK: fix specified metrics",
1594 	"RTM_OLDADD: caused by SIOCADDRT",
1595 	"RTM_OLDDEL: caused by SIOCDELRT",
1596 	"RTM_RESOLVE: Route created by cloning",
1597 	"RTM_NEWADDR: address being added to iface",
1598 	"RTM_DELADDR: address being removed from iface",
1599 	"RTM_IFINFO: iface status change",
1600 	"RTM_NEWMADDR: new multicast group membership on iface",
1601 	"RTM_DELMADDR: multicast group membership removed from iface",
1602 	"RTM_IFANNOUNCE: interface arrival/departure",
1603 	"RTM_IEEE80211: IEEE 802.11 wireless event",
1604 };
1605 
1606 static const char metricnames[] =
1607     "\011weight\010rttvar\7rtt\6ssthresh\5sendpipe\4recvpipe\3expire"
1608     "\1mtu";
1609 static const char routeflags[] =
1610     "\1UP\2GATEWAY\3HOST\4REJECT\5DYNAMIC\6MODIFIED\7DONE"
1611     "\012XRESOLVE\013LLINFO\014STATIC\015BLACKHOLE"
1612     "\017PROTO2\020PROTO1\021PRCLONING\022WASCLONED\023PROTO3"
1613     "\024FIXEDMTU\025PINNED\026LOCAL\027BROADCAST\030MULTICAST\035STICKY";
1614 static const char ifnetflags[] =
1615     "\1UP\2BROADCAST\3DEBUG\4LOOPBACK\5PTP\6b6\7RUNNING\010NOARP"
1616     "\011PPROMISC\012ALLMULTI\013OACTIVE\014SIMPLEX\015LINK0\016LINK1"
1617     "\017LINK2\020MULTICAST";
1618 static const char addrnames[] =
1619     "\1DST\2GATEWAY\3NETMASK\4GENMASK\5IFP\6IFA\7AUTHOR\010BRD";
1620 
1621 static const char errfmt[] =
1622     "\n%s: truncated route message, only %zu bytes left\n";
1623 
1624 static void
1625 print_rtmsg(struct rt_msghdr *rtm, size_t msglen)
1626 {
1627 	struct if_msghdr *ifm;
1628 	struct ifa_msghdr *ifam;
1629 #ifdef RTM_NEWMADDR
1630 	struct ifma_msghdr *ifmam;
1631 #endif
1632 	struct if_announcemsghdr *ifan;
1633 	const char *state;
1634 
1635 	if (verbose == 0)
1636 		return;
1637 	if (rtm->rtm_version != RTM_VERSION) {
1638 		(void)printf("routing message version %d not understood\n",
1639 		    rtm->rtm_version);
1640 		return;
1641 	}
1642 	if (rtm->rtm_type < nitems(msgtypes))
1643 		(void)printf("%s: ", msgtypes[rtm->rtm_type]);
1644 	else
1645 		(void)printf("unknown type %d: ", rtm->rtm_type);
1646 	(void)printf("len %d, ", rtm->rtm_msglen);
1647 
1648 #define	REQUIRE(x)	do {		\
1649 	if (msglen < sizeof(x))		\
1650 		goto badlen;		\
1651 	else				\
1652 		msglen -= sizeof(x);	\
1653 	} while (0)
1654 
1655 	switch (rtm->rtm_type) {
1656 	case RTM_IFINFO:
1657 		REQUIRE(struct if_msghdr);
1658 		ifm = (struct if_msghdr *)rtm;
1659 		(void)printf("if# %d, ", ifm->ifm_index);
1660 		switch (ifm->ifm_data.ifi_link_state) {
1661 		case LINK_STATE_DOWN:
1662 			state = "down";
1663 			break;
1664 		case LINK_STATE_UP:
1665 			state = "up";
1666 			break;
1667 		default:
1668 			state = "unknown";
1669 			break;
1670 		}
1671 		(void)printf("link: %s, flags:", state);
1672 		printb(ifm->ifm_flags, ifnetflags);
1673 		pmsg_addrs((char *)(ifm + 1), ifm->ifm_addrs, msglen);
1674 		break;
1675 	case RTM_NEWADDR:
1676 	case RTM_DELADDR:
1677 		REQUIRE(struct ifa_msghdr);
1678 		ifam = (struct ifa_msghdr *)rtm;
1679 		(void)printf("metric %d, flags:", ifam->ifam_metric);
1680 		printb(ifam->ifam_flags, routeflags);
1681 		pmsg_addrs((char *)(ifam + 1), ifam->ifam_addrs, msglen);
1682 		break;
1683 #ifdef RTM_NEWMADDR
1684 	case RTM_NEWMADDR:
1685 	case RTM_DELMADDR:
1686 		REQUIRE(struct ifma_msghdr);
1687 		ifmam = (struct ifma_msghdr *)rtm;
1688 		pmsg_addrs((char *)(ifmam + 1), ifmam->ifmam_addrs, msglen);
1689 		break;
1690 #endif
1691 	case RTM_IFANNOUNCE:
1692 		REQUIRE(struct if_announcemsghdr);
1693 		ifan = (struct if_announcemsghdr *)rtm;
1694 		(void)printf("if# %d, what: ", ifan->ifan_index);
1695 		switch (ifan->ifan_what) {
1696 		case IFAN_ARRIVAL:
1697 			(void)printf("arrival");
1698 			break;
1699 		case IFAN_DEPARTURE:
1700 			printf("departure");
1701 			break;
1702 		default:
1703 			printf("#%d", ifan->ifan_what);
1704 			break;
1705 		}
1706 		printf("\n");
1707 		fflush(stdout);
1708 		break;
1709 
1710 	default:
1711 		if (rtm->rtm_type <= RTM_RESOLVE) {
1712 			printf("pid: %ld, seq %d, errno %d, flags:",
1713 			    (long)rtm->rtm_pid, rtm->rtm_seq, rtm->rtm_errno);
1714 			printb(rtm->rtm_flags, routeflags);
1715 			pmsg_common(rtm, msglen);
1716 		} else
1717 			printf("type: %u, len: %zu\n", rtm->rtm_type, msglen);
1718 	}
1719 
1720 	return;
1721 
1722 badlen:
1723 	(void)printf(errfmt, __func__, msglen);
1724 #undef	REQUIRE
1725 }
1726 
1727 static void
1728 print_getmsg(struct rt_msghdr *rtm, int msglen, int fib)
1729 {
1730 	struct sockaddr *sp[RTAX_MAX];
1731 	struct timespec ts;
1732 	char *cp;
1733 	int i;
1734 
1735 	memset(sp, 0, sizeof(sp));
1736 	(void)printf("   route to: %s\n",
1737 	    routename((struct sockaddr *)&so[RTAX_DST]));
1738 	if (rtm->rtm_version != RTM_VERSION) {
1739 		warnx("routing message version %d not understood",
1740 		     rtm->rtm_version);
1741 		return;
1742 	}
1743 	if (rtm->rtm_msglen > msglen) {
1744 		warnx("message length mismatch, in packet %d, returned %d",
1745 		      rtm->rtm_msglen, msglen);
1746 		return;
1747 	}
1748 	if (rtm->rtm_errno)  {
1749 		errno = rtm->rtm_errno;
1750 		warn("message indicates error %d", errno);
1751 		return;
1752 	}
1753 	cp = ((char *)(rtm + 1));
1754 	for (i = 0; i < RTAX_MAX; i++)
1755 		if (rtm->rtm_addrs & (1 << i)) {
1756 			sp[i] = (struct sockaddr *)cp;
1757 			cp += SA_SIZE((struct sockaddr *)cp);
1758 		}
1759 	if ((rtm->rtm_addrs & RTA_IFP) &&
1760 	    (sp[RTAX_IFP]->sa_family != AF_LINK ||
1761 	     ((struct sockaddr_dl *)(void *)sp[RTAX_IFP])->sdl_nlen == 0))
1762 			sp[RTAX_IFP] = NULL;
1763 	if (sp[RTAX_DST])
1764 		(void)printf("destination: %s\n", routename(sp[RTAX_DST]));
1765 	if (sp[RTAX_NETMASK])
1766 		(void)printf("       mask: %s\n", routename(sp[RTAX_NETMASK]));
1767 	if (sp[RTAX_GATEWAY] && (rtm->rtm_flags & RTF_GATEWAY))
1768 		(void)printf("    gateway: %s\n", routename(sp[RTAX_GATEWAY]));
1769 	if (fib >= 0)
1770 		(void)printf("        fib: %u\n", (unsigned int)fib);
1771 	if (sp[RTAX_IFP])
1772 		(void)printf("  interface: %.*s\n",
1773 		    ((struct sockaddr_dl *)(void *)sp[RTAX_IFP])->sdl_nlen,
1774 		    ((struct sockaddr_dl *)(void *)sp[RTAX_IFP])->sdl_data);
1775 	(void)printf("      flags: ");
1776 	printb(rtm->rtm_flags, routeflags);
1777 
1778 #define lock(f)	((rtm->rtm_rmx.rmx_locks & __CONCAT(RTV_,f)) ? 'L' : ' ')
1779 #define msec(u)	(((u) + 500) / 1000)		/* usec to msec */
1780 	printf("\n%9s %9s %9s %9s %9s %10s %9s\n", "recvpipe",
1781 	    "sendpipe", "ssthresh", "rtt,msec", "mtu   ", "weight", "expire");
1782 	printf("%8lu%c ", rtm->rtm_rmx.rmx_recvpipe, lock(RPIPE));
1783 	printf("%8lu%c ", rtm->rtm_rmx.rmx_sendpipe, lock(SPIPE));
1784 	printf("%8lu%c ", rtm->rtm_rmx.rmx_ssthresh, lock(SSTHRESH));
1785 	printf("%8lu%c ", msec(rtm->rtm_rmx.rmx_rtt), lock(RTT));
1786 	printf("%8lu%c ", rtm->rtm_rmx.rmx_mtu, lock(MTU));
1787 	printf("%8lu%c ", rtm->rtm_rmx.rmx_weight, lock(WEIGHT));
1788 	if (rtm->rtm_rmx.rmx_expire > 0)
1789 		clock_gettime(CLOCK_REALTIME_FAST, &ts);
1790 	else
1791 		ts.tv_sec = 0;
1792 	printf("%8ld%c\n", (long)(rtm->rtm_rmx.rmx_expire - ts.tv_sec),
1793 	    lock(EXPIRE));
1794 #undef lock
1795 #undef msec
1796 #define	RTA_IGN	(RTA_DST|RTA_GATEWAY|RTA_NETMASK|RTA_IFP|RTA_IFA|RTA_BRD)
1797 	if (verbose)
1798 		pmsg_common(rtm, msglen);
1799 	else if (rtm->rtm_addrs &~ RTA_IGN) {
1800 		(void)printf("sockaddrs: ");
1801 		printb(rtm->rtm_addrs, addrnames);
1802 		putchar('\n');
1803 	}
1804 #undef	RTA_IGN
1805 }
1806 
1807 static void
1808 pmsg_common(struct rt_msghdr *rtm, size_t msglen)
1809 {
1810 
1811 	(void)printf("\nlocks: ");
1812 	printb(rtm->rtm_rmx.rmx_locks, metricnames);
1813 	(void)printf(" inits: ");
1814 	printb(rtm->rtm_inits, metricnames);
1815 	if (msglen > sizeof(struct rt_msghdr))
1816 		pmsg_addrs(((char *)(rtm + 1)), rtm->rtm_addrs,
1817 		    msglen - sizeof(struct rt_msghdr));
1818 	else
1819 		(void)fflush(stdout);
1820 }
1821 
1822 static void
1823 pmsg_addrs(char *cp, int addrs, size_t len)
1824 {
1825 	struct sockaddr *sa;
1826 	int i;
1827 
1828 	if (addrs == 0) {
1829 		(void)putchar('\n');
1830 		return;
1831 	}
1832 	(void)printf("\nsockaddrs: ");
1833 	printb(addrs, addrnames);
1834 	putchar('\n');
1835 	for (i = 0; i < RTAX_MAX; i++)
1836 		if (addrs & (1 << i)) {
1837 			sa = (struct sockaddr *)cp;
1838 			if (len == 0 || len < SA_SIZE(sa)) {
1839 				(void)printf(errfmt, __func__, len);
1840 				break;
1841 			}
1842 			(void)printf(" %s", routename(sa));
1843 			len -= SA_SIZE(sa);
1844 			cp += SA_SIZE(sa);
1845 		}
1846 	(void)putchar('\n');
1847 	(void)fflush(stdout);
1848 }
1849 
1850 static void
1851 printb(int b, const char *str)
1852 {
1853 	int i;
1854 	int gotsome = 0;
1855 
1856 	if (b == 0)
1857 		return;
1858 	while ((i = *str++) != 0) {
1859 		if (b & (1 << (i-1))) {
1860 			if (gotsome == 0)
1861 				i = '<';
1862 			else
1863 				i = ',';
1864 			putchar(i);
1865 			gotsome = 1;
1866 			for (; (i = *str) > 32; str++)
1867 				putchar(i);
1868 		} else
1869 			while (*str > 32)
1870 				str++;
1871 	}
1872 	if (gotsome)
1873 		putchar('>');
1874 }
1875 
1876 int
1877 keyword(const char *cp)
1878 {
1879 	const struct keytab *kt = keywords;
1880 
1881 	while (kt->kt_cp != NULL && strcmp(kt->kt_cp, cp) != 0)
1882 		kt++;
1883 	return (kt->kt_i);
1884 }
1885 
1886 static void
1887 sodump(struct sockaddr *sa, const char *which)
1888 {
1889 #ifdef INET6
1890 	char nbuf[INET6_ADDRSTRLEN];
1891 #endif
1892 
1893 	switch (sa->sa_family) {
1894 	case AF_LINK:
1895 		(void)printf("%s: link %s; ", which,
1896 		    link_ntoa((struct sockaddr_dl *)(void *)sa));
1897 		break;
1898 #ifdef INET
1899 	case AF_INET:
1900 		(void)printf("%s: inet %s; ", which,
1901 		    inet_ntoa(((struct sockaddr_in *)(void *)sa)->sin_addr));
1902 		break;
1903 #endif
1904 #ifdef INET6
1905 	case AF_INET6:
1906 		(void)printf("%s: inet6 %s; ", which, inet_ntop(sa->sa_family,
1907 		    &((struct sockaddr_in6 *)(void *)sa)->sin6_addr, nbuf,
1908 		    sizeof(nbuf)));
1909 		break;
1910 #endif
1911 	}
1912 	(void)fflush(stdout);
1913 }
1914 
1915 /* States*/
1916 #define VIRGIN	0
1917 #define GOTONE	1
1918 #define GOTTWO	2
1919 /* Inputs */
1920 #define	DIGIT	(4*0)
1921 #define	END	(4*1)
1922 #define DELIM	(4*2)
1923 
1924 static void
1925 sockaddr(char *addr, struct sockaddr *sa, size_t size)
1926 {
1927 	char *cp = (char *)sa;
1928 	char *cplim = cp + size;
1929 	int byte = 0, state = VIRGIN, new = 0 /* foil gcc */;
1930 
1931 	memset(cp, 0, size);
1932 	cp++;
1933 	do {
1934 		if ((*addr >= '0') && (*addr <= '9')) {
1935 			new = *addr - '0';
1936 		} else if ((*addr >= 'a') && (*addr <= 'f')) {
1937 			new = *addr - 'a' + 10;
1938 		} else if ((*addr >= 'A') && (*addr <= 'F')) {
1939 			new = *addr - 'A' + 10;
1940 		} else if (*addr == '\0')
1941 			state |= END;
1942 		else
1943 			state |= DELIM;
1944 		addr++;
1945 		switch (state /* | INPUT */) {
1946 		case GOTTWO | DIGIT:
1947 			*cp++ = byte; /*FALLTHROUGH*/
1948 		case VIRGIN | DIGIT:
1949 			state = GOTONE; byte = new; continue;
1950 		case GOTONE | DIGIT:
1951 			state = GOTTWO; byte = new + (byte << 4); continue;
1952 		default: /* | DELIM */
1953 			state = VIRGIN; *cp++ = byte; byte = 0; continue;
1954 		case GOTONE | END:
1955 		case GOTTWO | END:
1956 			*cp++ = byte; /* FALLTHROUGH */
1957 		case VIRGIN | END:
1958 			break;
1959 		}
1960 		break;
1961 	} while (cp < cplim);
1962 	sa->sa_len = cp - (char *)sa;
1963 }
1964