xref: /freebsd/sbin/route/route.c (revision 5bb3134a8c21cb87b30e135ef168483f0333dabb)
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_makemask(struct sockaddr_in *, u_long);
124 #endif
125 #ifdef INET6
126 static int	inet6_makenetandmask(struct sockaddr_in6 *, const char *);
127 #endif
128 static void	interfaces(void);
129 static void	monitor(int, char*[]);
130 static const char	*netname(struct sockaddr *);
131 static void	newroute(int, char **);
132 static int	newroute_fib(int, char *, int);
133 static void	pmsg_addrs(char *, int, size_t);
134 static void	pmsg_common(struct rt_msghdr *, size_t);
135 static int	prefixlen(const char *);
136 static void	print_getmsg(struct rt_msghdr *, int, int);
137 static void	print_rtmsg(struct rt_msghdr *, size_t);
138 static const char	*routename(struct sockaddr *);
139 static int	rtmsg(int, int, int);
140 static void	set_metric(char *, int);
141 static int	set_sofib(int);
142 static void	sockaddr(char *, struct sockaddr *, size_t);
143 static void	sodump(struct sockaddr *, const char *);
144 static int	fiboptlist_csv(const char *, struct fibl_head_t *);
145 static int	fiboptlist_range(const char *, struct fibl_head_t *);
146 
147 static void usage(const char *) __dead2;
148 
149 #define	READ_TIMEOUT	10
150 static volatile sig_atomic_t stop_read;
151 
152 static void
153 stopit(int sig __unused)
154 {
155 
156 	stop_read = 1;
157 }
158 
159 static void
160 usage(const char *cp)
161 {
162 	if (cp != NULL)
163 		warnx("bad keyword: %s", cp);
164 	errx(EX_USAGE, "usage: route [-46dnqtv] command [[modifiers] args]");
165 	/* NOTREACHED */
166 }
167 
168 int
169 main(int argc, char **argv)
170 {
171 	int ch;
172 	size_t len;
173 
174 	if (argc < 2)
175 		usage(NULL);
176 
177 	while ((ch = getopt(argc, argv, "46nqdtv")) != -1)
178 		switch(ch) {
179 		case '4':
180 #ifdef INET
181 			af = AF_INET;
182 			aflen = sizeof(struct sockaddr_in);
183 #else
184 			errx(1, "IPv4 support is not compiled in");
185 #endif
186 			break;
187 		case '6':
188 #ifdef INET6
189 			af = AF_INET6;
190 			aflen = sizeof(struct sockaddr_in6);
191 #else
192 			errx(1, "IPv6 support is not compiled in");
193 #endif
194 			break;
195 		case 'n':
196 			nflag = 1;
197 			break;
198 		case 'q':
199 			qflag = 1;
200 			break;
201 		case 'v':
202 			verbose = 1;
203 			break;
204 		case 't':
205 			tflag = 1;
206 			break;
207 		case 'd':
208 			debugonly = 1;
209 			break;
210 		case '?':
211 		default:
212 			usage(NULL);
213 		}
214 	argc -= optind;
215 	argv += optind;
216 
217 	pid = getpid();
218 	uid = geteuid();
219 	if (tflag)
220 		s = open(_PATH_DEVNULL, O_WRONLY, 0);
221 	else
222 		s = socket(PF_ROUTE, SOCK_RAW, 0);
223 	if (s < 0)
224 		err(EX_OSERR, "socket");
225 
226 	len = sizeof(numfibs);
227 	if (sysctlbyname("net.fibs", (void *)&numfibs, &len, NULL, 0) == -1)
228 		numfibs = -1;
229 
230 	len = sizeof(defaultfib);
231 	if (numfibs != -1 &&
232 	    sysctlbyname("net.my_fibnum", (void *)&defaultfib, &len, NULL,
233 		0) == -1)
234 		defaultfib = -1;
235 
236 	if (*argv != NULL)
237 		switch (keyword(*argv)) {
238 		case K_GET:
239 		case K_SHOW:
240 			uid = 0;
241 			/* FALLTHROUGH */
242 
243 		case K_CHANGE:
244 		case K_ADD:
245 		case K_DEL:
246 		case K_DELETE:
247 			newroute(argc, argv);
248 			/* NOTREACHED */
249 
250 		case K_MONITOR:
251 			monitor(argc, argv);
252 			/* NOTREACHED */
253 
254 		case K_FLUSH:
255 			flushroutes(argc, argv);
256 			exit(0);
257 			/* NOTREACHED */
258 		}
259 	usage(*argv);
260 	/* NOTREACHED */
261 }
262 
263 static int
264 set_sofib(int fib)
265 {
266 
267 	if (fib < 0)
268 		return (0);
269 	return (setsockopt(s, SOL_SOCKET, SO_SETFIB, (void *)&fib,
270 	    sizeof(fib)));
271 }
272 
273 static int
274 fiboptlist_range(const char *arg, struct fibl_head_t *flh)
275 {
276 	struct fibl *fl;
277 	char *str0, *str, *token, *endptr;
278 	int fib[2], i, error;
279 
280 	str0 = str = strdup(arg);
281 	error = 0;
282 	i = 0;
283 	while ((token = strsep(&str, "-")) != NULL) {
284 		switch (i) {
285 		case 0:
286 		case 1:
287 			errno = 0;
288 			fib[i] = strtol(token, &endptr, 0);
289 			if (errno == 0) {
290 				if (*endptr != '\0' ||
291 				    fib[i] < 0 ||
292 				    (numfibs != -1 && fib[i] > numfibs - 1))
293 					errno = EINVAL;
294 			}
295 			if (errno)
296 				error = 1;
297 			break;
298 		default:
299 			error = 1;
300 		}
301 		if (error)
302 			goto fiboptlist_range_ret;
303 		i++;
304 	}
305 	if (fib[0] >= fib[1]) {
306 		error = 1;
307 		goto fiboptlist_range_ret;
308 	}
309 	for (i = fib[0]; i <= fib[1]; i++) {
310 		fl = calloc(1, sizeof(*fl));
311 		if (fl == NULL) {
312 			error = 1;
313 			goto fiboptlist_range_ret;
314 		}
315 		fl->fl_num = i;
316 		TAILQ_INSERT_TAIL(flh, fl, fl_next);
317 	}
318 fiboptlist_range_ret:
319 	free(str0);
320 	return (error);
321 }
322 
323 #define	ALLSTRLEN	64
324 static int
325 fiboptlist_csv(const char *arg, struct fibl_head_t *flh)
326 {
327 	struct fibl *fl;
328 	char *str0, *str, *token, *endptr;
329 	int fib, error;
330 
331 	str0 = str = NULL;
332 	if (strcmp("all", arg) == 0) {
333 		str = calloc(1, ALLSTRLEN);
334 		if (str == NULL) {
335 			error = 1;
336 			goto fiboptlist_csv_ret;
337 		}
338 		if (numfibs > 1)
339 			snprintf(str, ALLSTRLEN - 1, "%d-%d", 0, numfibs - 1);
340 		else
341 			snprintf(str, ALLSTRLEN - 1, "%d", 0);
342 	} else if (strcmp("default", arg) == 0) {
343 		str0 = str = calloc(1, ALLSTRLEN);
344 		if (str == NULL) {
345 			error = 1;
346 			goto fiboptlist_csv_ret;
347 		}
348 		snprintf(str, ALLSTRLEN - 1, "%d", defaultfib);
349 	} else
350 		str0 = str = strdup(arg);
351 
352 	error = 0;
353 	while ((token = strsep(&str, ",")) != NULL) {
354 		if (*token != '-' && strchr(token, '-') != NULL) {
355 			error = fiboptlist_range(token, flh);
356 			if (error)
357 				goto fiboptlist_csv_ret;
358 		} else {
359 			errno = 0;
360 			fib = strtol(token, &endptr, 0);
361 			if (errno == 0) {
362 				if (*endptr != '\0' ||
363 				    fib < 0 ||
364 				    (numfibs != -1 && fib > numfibs - 1))
365 					errno = EINVAL;
366 			}
367 			if (errno) {
368 				error = 1;
369 				goto fiboptlist_csv_ret;
370 			}
371 			fl = calloc(1, sizeof(*fl));
372 			if (fl == NULL) {
373 				error = 1;
374 				goto fiboptlist_csv_ret;
375 			}
376 			fl->fl_num = fib;
377 			TAILQ_INSERT_TAIL(flh, fl, fl_next);
378 		}
379 	}
380 fiboptlist_csv_ret:
381 	if (str0 != NULL)
382 		free(str0);
383 	return (error);
384 }
385 
386 /*
387  * Purge all entries in the routing tables not
388  * associated with network interfaces.
389  */
390 static void
391 flushroutes(int argc, char *argv[])
392 {
393 	struct fibl *fl;
394 	int error;
395 
396 	if (uid != 0 && !debugonly && !tflag)
397 		errx(EX_NOPERM, "must be root to alter routing table");
398 	shutdown(s, SHUT_RD); /* Don't want to read back our messages */
399 
400 	TAILQ_INIT(&fibl_head);
401 	while (argc > 1) {
402 		argc--;
403 		argv++;
404 		if (**argv != '-')
405 			usage(*argv);
406 		switch (keyword(*argv + 1)) {
407 #ifdef INET
408 		case K_4:
409 		case K_INET:
410 			af = AF_INET;
411 			break;
412 #endif
413 #ifdef INET6
414 		case K_6:
415 		case K_INET6:
416 			af = AF_INET6;
417 			break;
418 #endif
419 		case K_LINK:
420 			af = AF_LINK;
421 			break;
422 		case K_FIB:
423 			if (!--argc)
424 				usage(*argv);
425 			error = fiboptlist_csv(*++argv, &fibl_head);
426 			if (error)
427 				errx(EX_USAGE, "invalid fib number: %s", *argv);
428 			break;
429 		default:
430 			usage(*argv);
431 		}
432 	}
433 	if (TAILQ_EMPTY(&fibl_head)) {
434 		error = fiboptlist_csv("default", &fibl_head);
435 		if (error)
436 			errx(EX_OSERR, "fiboptlist_csv failed.");
437 	}
438 	TAILQ_FOREACH(fl, &fibl_head, fl_next)
439 		flushroutes_fib(fl->fl_num);
440 }
441 
442 static int
443 flushroutes_fib(int fib)
444 {
445 	struct rt_msghdr *rtm;
446 	size_t needed;
447 	char *buf, *next, *lim;
448 	int mib[7], rlen, seqno, count = 0;
449 	int error;
450 
451 	error = set_sofib(fib);
452 	if (error) {
453 		warn("fib number %d is ignored", fib);
454 		return (error);
455 	}
456 
457 retry:
458 	mib[0] = CTL_NET;
459 	mib[1] = PF_ROUTE;
460 	mib[2] = 0;		/* protocol */
461 	mib[3] = AF_UNSPEC;
462 	mib[4] = NET_RT_DUMP;
463 	mib[5] = 0;		/* no flags */
464 	mib[6] = fib;
465 	if (sysctl(mib, nitems(mib), NULL, &needed, NULL, 0) < 0)
466 		err(EX_OSERR, "route-sysctl-estimate");
467 	if ((buf = malloc(needed)) == NULL)
468 		errx(EX_OSERR, "malloc failed");
469 	if (sysctl(mib, nitems(mib), buf, &needed, NULL, 0) < 0) {
470 		if (errno == ENOMEM && count++ < 10) {
471 			warnx("Routing table grew, retrying");
472 			sleep(1);
473 			free(buf);
474 			goto retry;
475 		}
476 		err(EX_OSERR, "route-sysctl-get");
477 	}
478 	lim = buf + needed;
479 	if (verbose)
480 		(void)printf("Examining routing table from sysctl\n");
481 	seqno = 0;		/* ??? */
482 	for (next = buf; next < lim; next += rtm->rtm_msglen) {
483 		rtm = (struct rt_msghdr *)(void *)next;
484 		if (verbose)
485 			print_rtmsg(rtm, rtm->rtm_msglen);
486 		if ((rtm->rtm_flags & RTF_GATEWAY) == 0)
487 			continue;
488 		if (af != 0) {
489 			struct sockaddr *sa = (struct sockaddr *)(rtm + 1);
490 
491 			if (sa->sa_family != af)
492 				continue;
493 		}
494 		if (debugonly)
495 			continue;
496 		rtm->rtm_type = RTM_DELETE;
497 		rtm->rtm_seq = seqno;
498 		rlen = write(s, next, rtm->rtm_msglen);
499 		if (rlen < 0 && errno == EPERM)
500 			err(1, "write to routing socket");
501 		if (rlen < (int)rtm->rtm_msglen) {
502 			warn("write to routing socket");
503 			(void)printf("got only %d for rlen\n", rlen);
504 			free(buf);
505 			goto retry;
506 			break;
507 		}
508 		seqno++;
509 		if (qflag)
510 			continue;
511 		if (verbose)
512 			print_rtmsg(rtm, rlen);
513 		else {
514 			struct sockaddr *sa = (struct sockaddr *)(rtm + 1);
515 
516 			printf("%-20.20s ", rtm->rtm_flags & RTF_HOST ?
517 			    routename(sa) : netname(sa));
518 			sa = (struct sockaddr *)(SA_SIZE(sa) + (char *)sa);
519 			printf("%-20.20s ", routename(sa));
520 			if (fib >= 0)
521 				printf("-fib %-3d ", fib);
522 			printf("done\n");
523 		}
524 	}
525 	free(buf);
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 
1054 	fibnum = 0;
1055 	TAILQ_FOREACH(fl, &fibl_head, fl_next) {
1056 		if (fl->fl_error != 0) {
1057 			error = 1;
1058 			if (!qflag) {
1059 				printf("%s %s %s", cmd, (nrflags & F_ISHOST)
1060 				    ? "host" : "net", dest);
1061 				if (*gateway)
1062 					printf(": gateway %s", gateway);
1063 
1064 				if (fl->fl_num >= 0)
1065 					printf(" fib %d", fl->fl_num);
1066 
1067 				switch (fl->fl_errno) {
1068 				case ESRCH:
1069 					errmsg = "not in table";
1070 					break;
1071 				case EBUSY:
1072 					errmsg = "entry in use";
1073 					break;
1074 				case ENOBUFS:
1075 					errmsg = "not enough memory";
1076 					break;
1077 				case EADDRINUSE:
1078 					/*
1079 					 * handle recursion avoidance
1080 					 * in rt_setgate()
1081 					 */
1082 					errmsg = "gateway uses the same route";
1083 					break;
1084 				case EEXIST:
1085 					errmsg = "route already in table";
1086 					break;
1087 				default:
1088 					errmsg = strerror(fl->fl_errno);
1089 					break;
1090 				}
1091 				printf(": %s\n", errmsg);
1092 			}
1093 		}
1094 	}
1095 	exit(error);
1096 }
1097 
1098 static int
1099 newroute_fib(int fib, char *cmd, int flags)
1100 {
1101 	int error;
1102 
1103 	error = set_sofib(fib);
1104 	if (error) {
1105 		warn("fib number %d is ignored", fib);
1106 		return (error);
1107 	}
1108 
1109 	error = rtmsg(*cmd, flags, fib);
1110 	return (error);
1111 }
1112 
1113 #ifdef INET
1114 static void
1115 inet_makemask(struct sockaddr_in *sin_mask, u_long bits)
1116 {
1117 	u_long mask = 0;
1118 
1119 	rtm_addrs |= RTA_NETMASK;
1120 
1121 	if (bits != 0)
1122 		mask = 0xffffffff << (32 - bits);
1123 
1124 	sin_mask->sin_addr.s_addr = htonl(mask);
1125 	sin_mask->sin_len = sizeof(struct sockaddr_in);
1126 	sin_mask->sin_family = AF_INET;
1127 }
1128 #endif
1129 
1130 #ifdef INET6
1131 /*
1132  * XXX the function may need more improvement...
1133  */
1134 static int
1135 inet6_makenetandmask(struct sockaddr_in6 *sin6, const char *plen)
1136 {
1137 
1138 	if (plen == NULL) {
1139 		if (IN6_IS_ADDR_UNSPECIFIED(&sin6->sin6_addr) &&
1140 		    sin6->sin6_scope_id == 0)
1141 			plen = "0";
1142 	}
1143 
1144 	if (plen == NULL || strcmp(plen, "128") == 0)
1145 		return (1);
1146 	rtm_addrs |= RTA_NETMASK;
1147 	prefixlen(plen);
1148 	return (0);
1149 }
1150 #endif
1151 
1152 /*
1153  * Interpret an argument as a network address of some kind,
1154  * returning 1 if a host address, 0 if a network address.
1155  */
1156 static int
1157 getaddr(int idx, char *str, struct hostent **hpp, int nrflags)
1158 {
1159 	struct sockaddr *sa;
1160 #if defined(INET)
1161 	struct sockaddr_in *sin;
1162 	struct hostent *hp;
1163 	char *q;
1164 #elif defined(INET6)
1165 	char *q;
1166 #endif
1167 
1168 	if (idx < 0 || idx >= RTAX_MAX)
1169 		usage("internal error");
1170 	if (af == 0) {
1171 #if defined(INET)
1172 		af = AF_INET;
1173 		aflen = sizeof(struct sockaddr_in);
1174 #elif defined(INET6)
1175 		af = AF_INET6;
1176 		aflen = sizeof(struct sockaddr_in6);
1177 #else
1178 		af = AF_LINK;
1179 		aflen = sizeof(struct sockaddr_dl);
1180 #endif
1181 	}
1182 #ifndef INET
1183 	hpp = NULL;
1184 #endif
1185 	rtm_addrs |= (1 << idx);
1186 	sa = (struct sockaddr *)&so[idx];
1187 	sa->sa_family = af;
1188 	sa->sa_len = aflen;
1189 
1190 	switch (idx) {
1191 	case RTAX_GATEWAY:
1192 		if (nrflags & F_INTERFACE) {
1193 			struct ifaddrs *ifap, *ifa;
1194 			struct sockaddr_dl *sdl0 = (struct sockaddr_dl *)(void *)sa;
1195 			struct sockaddr_dl *sdl = NULL;
1196 
1197 			if (getifaddrs(&ifap))
1198 				err(EX_OSERR, "getifaddrs");
1199 
1200 			for (ifa = ifap; ifa != NULL; ifa = ifa->ifa_next) {
1201 				if (ifa->ifa_addr->sa_family != AF_LINK)
1202 					continue;
1203 
1204 				if (strcmp(str, ifa->ifa_name) != 0)
1205 					continue;
1206 
1207 				sdl = (struct sockaddr_dl *)(void *)ifa->ifa_addr;
1208 			}
1209 			/* If we found it, then use it */
1210 			if (sdl != NULL) {
1211 				/*
1212 				 * Note that we need to copy before calling
1213 				 * freeifaddrs().
1214 				 */
1215 				memcpy(sdl0, sdl, sdl->sdl_len);
1216 			}
1217 			freeifaddrs(ifap);
1218 			if (sdl != NULL)
1219 				return(1);
1220 			else
1221 				errx(EX_DATAERR,
1222 				    "interface '%s' does not exist", str);
1223 		}
1224 		break;
1225 	case RTAX_IFP:
1226 		sa->sa_family = AF_LINK;
1227 		break;
1228 	}
1229 	if (strcmp(str, "default") == 0) {
1230 		/*
1231 		 * Default is net 0.0.0.0/0
1232 		 */
1233 		switch (idx) {
1234 		case RTAX_DST:
1235 			nrflags |= F_FORCENET;
1236 			getaddr(RTAX_NETMASK, str, 0, nrflags);
1237 			break;
1238 		}
1239 		return (0);
1240 	}
1241 	switch (sa->sa_family) {
1242 #ifdef INET6
1243 	case AF_INET6:
1244 	{
1245 		struct addrinfo hints, *res;
1246 		int ecode;
1247 
1248 		q = NULL;
1249 		if (idx == RTAX_DST && (q = strchr(str, '/')) != NULL)
1250 			*q = '\0';
1251 		memset(&hints, 0, sizeof(hints));
1252 		hints.ai_family = sa->sa_family;
1253 		hints.ai_socktype = SOCK_DGRAM;
1254 		ecode = getaddrinfo(str, NULL, &hints, &res);
1255 		if (ecode != 0 || res->ai_family != AF_INET6 ||
1256 		    res->ai_addrlen != sizeof(struct sockaddr_in6))
1257 			errx(EX_OSERR, "%s: %s", str, gai_strerror(ecode));
1258 		memcpy(sa, res->ai_addr, res->ai_addrlen);
1259 		freeaddrinfo(res);
1260 		if (q != NULL)
1261 			*q++ = '/';
1262 		if (idx == RTAX_DST)
1263 			return (inet6_makenetandmask((struct sockaddr_in6 *)(void *)sa, q));
1264 		return (0);
1265 	}
1266 #endif /* INET6 */
1267 	case AF_LINK:
1268 		link_addr(str, (struct sockaddr_dl *)(void *)sa);
1269 		return (1);
1270 
1271 	case PF_ROUTE:
1272 		sockaddr(str, sa, sizeof(struct sockaddr_storage));
1273 		return (1);
1274 #ifdef INET
1275 	case AF_INET:
1276 #endif
1277 	default:
1278 		break;
1279 	}
1280 
1281 #ifdef INET
1282 	sin = (struct sockaddr_in *)(void *)sa;
1283 	if (hpp == NULL)
1284 		hpp = &hp;
1285 	*hpp = NULL;
1286 
1287 	q = strchr(str,'/');
1288 	if (q != NULL && idx == RTAX_DST) {
1289 		/* A.B.C.D/NUM */
1290 		*q = '\0';
1291 		if (inet_aton(str, &sin->sin_addr) == 0)
1292 			errx(EX_NOHOST, "bad address: %s", str);
1293 
1294 		int masklen = strtol(q + 1, NULL, 10);
1295 		if (masklen < 0 || masklen > 32)
1296 			errx(EX_NOHOST, "bad mask length: %s", q + 1);
1297 
1298 		inet_makemask((struct sockaddr_in *)&so[RTAX_NETMASK],masklen);
1299 		return (0);
1300 	}
1301 	if (inet_aton(str, &sin->sin_addr) != 0)
1302 		return (1);
1303 
1304 	hp = gethostbyname(str);
1305 	if (hp != NULL) {
1306 		*hpp = hp;
1307 		sin->sin_family = hp->h_addrtype;
1308 		memmove((char *)&sin->sin_addr, hp->h_addr,
1309 		    MIN((size_t)hp->h_length, sizeof(sin->sin_addr)));
1310 		return (1);
1311 	}
1312 #endif
1313 	errx(EX_NOHOST, "bad address: %s", str);
1314 }
1315 
1316 static int
1317 prefixlen(const char *str)
1318 {
1319 	int len = atoi(str), q, r;
1320 	int max;
1321 	char *p;
1322 
1323 	rtm_addrs |= RTA_NETMASK;
1324 	switch (af) {
1325 #ifdef INET6
1326 	case AF_INET6:
1327 	{
1328 		struct sockaddr_in6 *sin6 =
1329 		    (struct sockaddr_in6 *)&so[RTAX_NETMASK];
1330 
1331 		max = 128;
1332 		p = (char *)&sin6->sin6_addr;
1333 		sin6->sin6_family = AF_INET6;
1334 		sin6->sin6_len = sizeof(*sin6);
1335 		break;
1336 	}
1337 #endif
1338 #ifdef INET
1339 	case AF_INET:
1340 	{
1341 		struct sockaddr_in *sin =
1342 		    (struct sockaddr_in *)&so[RTAX_NETMASK];
1343 
1344 		max = 32;
1345 		p = (char *)&sin->sin_addr;
1346 		sin->sin_family = AF_INET;
1347 		sin->sin_len = sizeof(*sin);
1348 		break;
1349 	}
1350 #endif
1351 	default:
1352 		errx(EX_OSERR, "prefixlen not supported in this af");
1353 	}
1354 
1355 	if (len < 0 || max < len)
1356 		errx(EX_USAGE, "%s: invalid prefixlen", str);
1357 
1358 	q = len >> 3;
1359 	r = len & 7;
1360 	memset((void *)p, 0, max / 8);
1361 	if (q > 0)
1362 		memset((void *)p, 0xff, q);
1363 	if (r > 0)
1364 		*((u_char *)p + q) = (0xff00 >> r) & 0xff;
1365 	if (len == max)
1366 		return (-1);
1367 	else
1368 		return (len);
1369 }
1370 
1371 static void
1372 interfaces(void)
1373 {
1374 	size_t needed;
1375 	int mib[6];
1376 	char *buf, *lim, *next, count = 0;
1377 	struct rt_msghdr *rtm;
1378 
1379 retry2:
1380 	mib[0] = CTL_NET;
1381 	mib[1] = PF_ROUTE;
1382 	mib[2] = 0;		/* protocol */
1383 	mib[3] = AF_UNSPEC;
1384 	mib[4] = NET_RT_IFLIST;
1385 	mib[5] = 0;		/* no flags */
1386 	if (sysctl(mib, nitems(mib), NULL, &needed, NULL, 0) < 0)
1387 		err(EX_OSERR, "route-sysctl-estimate");
1388 	if ((buf = malloc(needed)) == NULL)
1389 		errx(EX_OSERR, "malloc failed");
1390 	if (sysctl(mib, nitems(mib), buf, &needed, NULL, 0) < 0) {
1391 		if (errno == ENOMEM && count++ < 10) {
1392 			warnx("Routing table grew, retrying");
1393 			sleep(1);
1394 			free(buf);
1395 			goto retry2;
1396 		}
1397 		err(EX_OSERR, "actual retrieval of interface table");
1398 	}
1399 	lim = buf + needed;
1400 	for (next = buf; next < lim; next += rtm->rtm_msglen) {
1401 		rtm = (struct rt_msghdr *)(void *)next;
1402 		print_rtmsg(rtm, rtm->rtm_msglen);
1403 	}
1404 	free(buf);
1405 }
1406 
1407 static void
1408 monitor(int argc, char *argv[])
1409 {
1410 	int n, fib, error;
1411 	char msg[2048], *endptr;
1412 
1413 	fib = defaultfib;
1414 	while (argc > 1) {
1415 		argc--;
1416 		argv++;
1417 		if (**argv != '-')
1418 			usage(*argv);
1419 		switch (keyword(*argv + 1)) {
1420 		case K_FIB:
1421 			if (!--argc)
1422 				usage(*argv);
1423 			errno = 0;
1424 			fib = strtol(*++argv, &endptr, 0);
1425 			if (errno == 0) {
1426 				if (*endptr != '\0' ||
1427 				    fib < 0 ||
1428 				    (numfibs != -1 && fib > numfibs - 1))
1429 					errno = EINVAL;
1430 			}
1431 			if (errno)
1432 				errx(EX_USAGE, "invalid fib number: %s", *argv);
1433 			break;
1434 		default:
1435 			usage(*argv);
1436 		}
1437 	}
1438 	error = set_sofib(fib);
1439 	if (error)
1440 		errx(EX_USAGE, "invalid fib number: %d", fib);
1441 
1442 	verbose = 1;
1443 	if (debugonly) {
1444 		interfaces();
1445 		exit(0);
1446 	}
1447 
1448 #ifdef SO_RERROR
1449 	n = 1;
1450 	if (setsockopt(s, SOL_SOCKET, SO_RERROR, &n, sizeof(n)) == -1)
1451 		warn("SO_RERROR");
1452 #endif
1453 
1454 	for (;;) {
1455 		time_t now;
1456 		n = read(s, msg, sizeof(msg));
1457 		if (n == -1) {
1458 			warn("read");
1459 			continue;
1460 		}
1461 		now = time(NULL);
1462 		(void)printf("\ngot message of size %d on %s", n, ctime(&now));
1463 		print_rtmsg((struct rt_msghdr *)(void *)msg, n);
1464 	}
1465 }
1466 
1467 static int
1468 rtmsg(int cmd, int flags, int fib)
1469 {
1470 	int rlen;
1471 	char *cp = m_rtmsg.m_space;
1472 	int l;
1473 
1474 #define NEXTADDR(w, u)							\
1475 	if (rtm_addrs & (w)) {						\
1476 		l = SA_SIZE(&(u));					\
1477 		memmove(cp, (char *)&(u), l);				\
1478 		cp += l;						\
1479 		if (verbose)						\
1480 			sodump((struct sockaddr *)&(u), #w);		\
1481 	}
1482 
1483 	errno = 0;
1484 	memset(&m_rtmsg, 0, sizeof(m_rtmsg));
1485 	if (cmd == 'a')
1486 		cmd = RTM_ADD;
1487 	else if (cmd == 'c')
1488 		cmd = RTM_CHANGE;
1489 	else if (cmd == 'g' || cmd == 's') {
1490 		cmd = RTM_GET;
1491 		if (so[RTAX_IFP].ss_family == 0) {
1492 			so[RTAX_IFP].ss_family = AF_LINK;
1493 			so[RTAX_IFP].ss_len = sizeof(struct sockaddr_dl);
1494 			rtm_addrs |= RTA_IFP;
1495 		}
1496 	} else {
1497 		cmd = RTM_DELETE;
1498 		flags |= RTF_PINNED;
1499 	}
1500 #define rtm m_rtmsg.m_rtm
1501 	rtm.rtm_type = cmd;
1502 	rtm.rtm_flags = flags;
1503 	rtm.rtm_version = RTM_VERSION;
1504 	rtm.rtm_seq = ++rtm_seq;
1505 	rtm.rtm_addrs = rtm_addrs;
1506 	rtm.rtm_rmx = rt_metrics;
1507 	rtm.rtm_inits = rtm_inits;
1508 
1509 	NEXTADDR(RTA_DST, so[RTAX_DST]);
1510 	NEXTADDR(RTA_GATEWAY, so[RTAX_GATEWAY]);
1511 	NEXTADDR(RTA_NETMASK, so[RTAX_NETMASK]);
1512 	NEXTADDR(RTA_GENMASK, so[RTAX_GENMASK]);
1513 	NEXTADDR(RTA_IFP, so[RTAX_IFP]);
1514 	NEXTADDR(RTA_IFA, so[RTAX_IFA]);
1515 	rtm.rtm_msglen = l = cp - (char *)&m_rtmsg;
1516 	if (verbose)
1517 		print_rtmsg(&rtm, l);
1518 	if (debugonly)
1519 		return (0);
1520 	if ((rlen = write(s, (char *)&m_rtmsg, l)) < 0) {
1521 		switch (errno) {
1522 		case EPERM:
1523 			err(1, "writing to routing socket");
1524 			break;
1525 		case ESRCH:
1526 			warnx("route has not been found");
1527 			break;
1528 		case EEXIST:
1529 			/* Handled by newroute() */
1530 			break;
1531 		default:
1532 			warn("writing to routing socket");
1533 		}
1534 		return (-1);
1535 	}
1536 	if (cmd == RTM_GET) {
1537 		stop_read = 0;
1538 		alarm(READ_TIMEOUT);
1539 		do {
1540 			l = read(s, (char *)&m_rtmsg, sizeof(m_rtmsg));
1541 		} while (l > 0 && stop_read == 0 &&
1542 		    (rtm.rtm_type != RTM_GET || rtm.rtm_seq != rtm_seq ||
1543 			rtm.rtm_pid != pid));
1544 		if (stop_read != 0) {
1545 			warnx("read from routing socket timed out");
1546 			return (-1);
1547 		} else
1548 			alarm(0);
1549 		if (l < 0)
1550 			warn("read from routing socket");
1551 		else
1552 			print_getmsg(&rtm, l, fib);
1553 	}
1554 #undef rtm
1555 	return (0);
1556 }
1557 
1558 static const char *const msgtypes[] = {
1559 	"",
1560 	"RTM_ADD: Add Route",
1561 	"RTM_DELETE: Delete Route",
1562 	"RTM_CHANGE: Change Metrics or flags",
1563 	"RTM_GET: Report Metrics",
1564 	"RTM_LOSING: Kernel Suspects Partitioning",
1565 	"RTM_REDIRECT: Told to use different route",
1566 	"RTM_MISS: Lookup failed on this address",
1567 	"RTM_LOCK: fix specified metrics",
1568 	"RTM_OLDADD: caused by SIOCADDRT",
1569 	"RTM_OLDDEL: caused by SIOCDELRT",
1570 	"RTM_RESOLVE: Route created by cloning",
1571 	"RTM_NEWADDR: address being added to iface",
1572 	"RTM_DELADDR: address being removed from iface",
1573 	"RTM_IFINFO: iface status change",
1574 	"RTM_NEWMADDR: new multicast group membership on iface",
1575 	"RTM_DELMADDR: multicast group membership removed from iface",
1576 	"RTM_IFANNOUNCE: interface arrival/departure",
1577 	"RTM_IEEE80211: IEEE 802.11 wireless event",
1578 };
1579 
1580 static const char metricnames[] =
1581     "\011weight\010rttvar\7rtt\6ssthresh\5sendpipe\4recvpipe\3expire"
1582     "\1mtu";
1583 static const char routeflags[] =
1584     "\1UP\2GATEWAY\3HOST\4REJECT\5DYNAMIC\6MODIFIED\7DONE"
1585     "\012XRESOLVE\013LLINFO\014STATIC\015BLACKHOLE"
1586     "\017PROTO2\020PROTO1\021PRCLONING\022WASCLONED\023PROTO3"
1587     "\024FIXEDMTU\025PINNED\026LOCAL\027BROADCAST\030MULTICAST\035STICKY";
1588 static const char ifnetflags[] =
1589     "\1UP\2BROADCAST\3DEBUG\4LOOPBACK\5PTP\6b6\7RUNNING\010NOARP"
1590     "\011PPROMISC\012ALLMULTI\013OACTIVE\014SIMPLEX\015LINK0\016LINK1"
1591     "\017LINK2\020MULTICAST";
1592 static const char addrnames[] =
1593     "\1DST\2GATEWAY\3NETMASK\4GENMASK\5IFP\6IFA\7AUTHOR\010BRD";
1594 
1595 static const char errfmt[] =
1596     "\n%s: truncated route message, only %zu bytes left\n";
1597 
1598 static void
1599 print_rtmsg(struct rt_msghdr *rtm, size_t msglen)
1600 {
1601 	struct if_msghdr *ifm;
1602 	struct ifa_msghdr *ifam;
1603 #ifdef RTM_NEWMADDR
1604 	struct ifma_msghdr *ifmam;
1605 #endif
1606 	struct if_announcemsghdr *ifan;
1607 	const char *state;
1608 
1609 	if (verbose == 0)
1610 		return;
1611 	if (rtm->rtm_version != RTM_VERSION) {
1612 		(void)printf("routing message version %d not understood\n",
1613 		    rtm->rtm_version);
1614 		return;
1615 	}
1616 	if (rtm->rtm_type < nitems(msgtypes))
1617 		(void)printf("%s: ", msgtypes[rtm->rtm_type]);
1618 	else
1619 		(void)printf("unknown type %d: ", rtm->rtm_type);
1620 	(void)printf("len %d, ", rtm->rtm_msglen);
1621 
1622 #define	REQUIRE(x)	do {		\
1623 	if (msglen < sizeof(x))		\
1624 		goto badlen;		\
1625 	else				\
1626 		msglen -= sizeof(x);	\
1627 	} while (0)
1628 
1629 	switch (rtm->rtm_type) {
1630 	case RTM_IFINFO:
1631 		REQUIRE(struct if_msghdr);
1632 		ifm = (struct if_msghdr *)rtm;
1633 		(void)printf("if# %d, ", ifm->ifm_index);
1634 		switch (ifm->ifm_data.ifi_link_state) {
1635 		case LINK_STATE_DOWN:
1636 			state = "down";
1637 			break;
1638 		case LINK_STATE_UP:
1639 			state = "up";
1640 			break;
1641 		default:
1642 			state = "unknown";
1643 			break;
1644 		}
1645 		(void)printf("link: %s, flags:", state);
1646 		printb(ifm->ifm_flags, ifnetflags);
1647 		pmsg_addrs((char *)(ifm + 1), ifm->ifm_addrs, msglen);
1648 		break;
1649 	case RTM_NEWADDR:
1650 	case RTM_DELADDR:
1651 		REQUIRE(struct ifa_msghdr);
1652 		ifam = (struct ifa_msghdr *)rtm;
1653 		(void)printf("metric %d, flags:", ifam->ifam_metric);
1654 		printb(ifam->ifam_flags, routeflags);
1655 		pmsg_addrs((char *)(ifam + 1), ifam->ifam_addrs, msglen);
1656 		break;
1657 #ifdef RTM_NEWMADDR
1658 	case RTM_NEWMADDR:
1659 	case RTM_DELMADDR:
1660 		REQUIRE(struct ifma_msghdr);
1661 		ifmam = (struct ifma_msghdr *)rtm;
1662 		pmsg_addrs((char *)(ifmam + 1), ifmam->ifmam_addrs, msglen);
1663 		break;
1664 #endif
1665 	case RTM_IFANNOUNCE:
1666 		REQUIRE(struct if_announcemsghdr);
1667 		ifan = (struct if_announcemsghdr *)rtm;
1668 		(void)printf("if# %d, what: ", ifan->ifan_index);
1669 		switch (ifan->ifan_what) {
1670 		case IFAN_ARRIVAL:
1671 			(void)printf("arrival");
1672 			break;
1673 		case IFAN_DEPARTURE:
1674 			printf("departure");
1675 			break;
1676 		default:
1677 			printf("#%d", ifan->ifan_what);
1678 			break;
1679 		}
1680 		printf("\n");
1681 		fflush(stdout);
1682 		break;
1683 
1684 	default:
1685 		if (rtm->rtm_type <= RTM_RESOLVE) {
1686 			printf("pid: %ld, seq %d, errno %d, flags:",
1687 			    (long)rtm->rtm_pid, rtm->rtm_seq, rtm->rtm_errno);
1688 			printb(rtm->rtm_flags, routeflags);
1689 			pmsg_common(rtm, msglen);
1690 		} else
1691 			printf("type: %u, len: %zu\n", rtm->rtm_type, msglen);
1692 	}
1693 
1694 	return;
1695 
1696 badlen:
1697 	(void)printf(errfmt, __func__, msglen);
1698 #undef	REQUIRE
1699 }
1700 
1701 static void
1702 print_getmsg(struct rt_msghdr *rtm, int msglen, int fib)
1703 {
1704 	struct sockaddr *sp[RTAX_MAX];
1705 	struct timespec ts;
1706 	char *cp;
1707 	int i;
1708 
1709 	memset(sp, 0, sizeof(sp));
1710 	(void)printf("   route to: %s\n",
1711 	    routename((struct sockaddr *)&so[RTAX_DST]));
1712 	if (rtm->rtm_version != RTM_VERSION) {
1713 		warnx("routing message version %d not understood",
1714 		     rtm->rtm_version);
1715 		return;
1716 	}
1717 	if (rtm->rtm_msglen > msglen) {
1718 		warnx("message length mismatch, in packet %d, returned %d",
1719 		      rtm->rtm_msglen, msglen);
1720 		return;
1721 	}
1722 	if (rtm->rtm_errno)  {
1723 		errno = rtm->rtm_errno;
1724 		warn("message indicates error %d", errno);
1725 		return;
1726 	}
1727 	cp = ((char *)(rtm + 1));
1728 	for (i = 0; i < RTAX_MAX; i++)
1729 		if (rtm->rtm_addrs & (1 << i)) {
1730 			sp[i] = (struct sockaddr *)cp;
1731 			cp += SA_SIZE((struct sockaddr *)cp);
1732 		}
1733 	if ((rtm->rtm_addrs & RTA_IFP) &&
1734 	    (sp[RTAX_IFP]->sa_family != AF_LINK ||
1735 	     ((struct sockaddr_dl *)(void *)sp[RTAX_IFP])->sdl_nlen == 0))
1736 			sp[RTAX_IFP] = NULL;
1737 	if (sp[RTAX_DST])
1738 		(void)printf("destination: %s\n", routename(sp[RTAX_DST]));
1739 	if (sp[RTAX_NETMASK])
1740 		(void)printf("       mask: %s\n", routename(sp[RTAX_NETMASK]));
1741 	if (sp[RTAX_GATEWAY] && (rtm->rtm_flags & RTF_GATEWAY))
1742 		(void)printf("    gateway: %s\n", routename(sp[RTAX_GATEWAY]));
1743 	if (fib >= 0)
1744 		(void)printf("        fib: %u\n", (unsigned int)fib);
1745 	if (sp[RTAX_IFP])
1746 		(void)printf("  interface: %.*s\n",
1747 		    ((struct sockaddr_dl *)(void *)sp[RTAX_IFP])->sdl_nlen,
1748 		    ((struct sockaddr_dl *)(void *)sp[RTAX_IFP])->sdl_data);
1749 	(void)printf("      flags: ");
1750 	printb(rtm->rtm_flags, routeflags);
1751 
1752 #define lock(f)	((rtm->rtm_rmx.rmx_locks & __CONCAT(RTV_,f)) ? 'L' : ' ')
1753 #define msec(u)	(((u) + 500) / 1000)		/* usec to msec */
1754 	printf("\n%9s %9s %9s %9s %9s %10s %9s\n", "recvpipe",
1755 	    "sendpipe", "ssthresh", "rtt,msec", "mtu   ", "weight", "expire");
1756 	printf("%8lu%c ", rtm->rtm_rmx.rmx_recvpipe, lock(RPIPE));
1757 	printf("%8lu%c ", rtm->rtm_rmx.rmx_sendpipe, lock(SPIPE));
1758 	printf("%8lu%c ", rtm->rtm_rmx.rmx_ssthresh, lock(SSTHRESH));
1759 	printf("%8lu%c ", msec(rtm->rtm_rmx.rmx_rtt), lock(RTT));
1760 	printf("%8lu%c ", rtm->rtm_rmx.rmx_mtu, lock(MTU));
1761 	printf("%8lu%c ", rtm->rtm_rmx.rmx_weight, lock(WEIGHT));
1762 	if (rtm->rtm_rmx.rmx_expire > 0)
1763 		clock_gettime(CLOCK_REALTIME_FAST, &ts);
1764 	else
1765 		ts.tv_sec = 0;
1766 	printf("%8ld%c\n", (long)(rtm->rtm_rmx.rmx_expire - ts.tv_sec),
1767 	    lock(EXPIRE));
1768 #undef lock
1769 #undef msec
1770 #define	RTA_IGN	(RTA_DST|RTA_GATEWAY|RTA_NETMASK|RTA_IFP|RTA_IFA|RTA_BRD)
1771 	if (verbose)
1772 		pmsg_common(rtm, msglen);
1773 	else if (rtm->rtm_addrs &~ RTA_IGN) {
1774 		(void)printf("sockaddrs: ");
1775 		printb(rtm->rtm_addrs, addrnames);
1776 		putchar('\n');
1777 	}
1778 #undef	RTA_IGN
1779 }
1780 
1781 static void
1782 pmsg_common(struct rt_msghdr *rtm, size_t msglen)
1783 {
1784 
1785 	(void)printf("\nlocks: ");
1786 	printb(rtm->rtm_rmx.rmx_locks, metricnames);
1787 	(void)printf(" inits: ");
1788 	printb(rtm->rtm_inits, metricnames);
1789 	if (msglen > sizeof(struct rt_msghdr))
1790 		pmsg_addrs(((char *)(rtm + 1)), rtm->rtm_addrs,
1791 		    msglen - sizeof(struct rt_msghdr));
1792 	else
1793 		(void)fflush(stdout);
1794 }
1795 
1796 static void
1797 pmsg_addrs(char *cp, int addrs, size_t len)
1798 {
1799 	struct sockaddr *sa;
1800 	int i;
1801 
1802 	if (addrs == 0) {
1803 		(void)putchar('\n');
1804 		return;
1805 	}
1806 	(void)printf("\nsockaddrs: ");
1807 	printb(addrs, addrnames);
1808 	putchar('\n');
1809 	for (i = 0; i < RTAX_MAX; i++)
1810 		if (addrs & (1 << i)) {
1811 			sa = (struct sockaddr *)cp;
1812 			if (len == 0 || len < SA_SIZE(sa)) {
1813 				(void)printf(errfmt, __func__, len);
1814 				break;
1815 			}
1816 			(void)printf(" %s", routename(sa));
1817 			len -= SA_SIZE(sa);
1818 			cp += SA_SIZE(sa);
1819 		}
1820 	(void)putchar('\n');
1821 	(void)fflush(stdout);
1822 }
1823 
1824 static void
1825 printb(int b, const char *str)
1826 {
1827 	int i;
1828 	int gotsome = 0;
1829 
1830 	if (b == 0)
1831 		return;
1832 	while ((i = *str++) != 0) {
1833 		if (b & (1 << (i-1))) {
1834 			if (gotsome == 0)
1835 				i = '<';
1836 			else
1837 				i = ',';
1838 			putchar(i);
1839 			gotsome = 1;
1840 			for (; (i = *str) > 32; str++)
1841 				putchar(i);
1842 		} else
1843 			while (*str > 32)
1844 				str++;
1845 	}
1846 	if (gotsome)
1847 		putchar('>');
1848 }
1849 
1850 int
1851 keyword(const char *cp)
1852 {
1853 	const struct keytab *kt = keywords;
1854 
1855 	while (kt->kt_cp != NULL && strcmp(kt->kt_cp, cp) != 0)
1856 		kt++;
1857 	return (kt->kt_i);
1858 }
1859 
1860 static void
1861 sodump(struct sockaddr *sa, const char *which)
1862 {
1863 #ifdef INET6
1864 	char nbuf[INET6_ADDRSTRLEN];
1865 #endif
1866 
1867 	switch (sa->sa_family) {
1868 	case AF_LINK:
1869 		(void)printf("%s: link %s; ", which,
1870 		    link_ntoa((struct sockaddr_dl *)(void *)sa));
1871 		break;
1872 #ifdef INET
1873 	case AF_INET:
1874 		(void)printf("%s: inet %s; ", which,
1875 		    inet_ntoa(((struct sockaddr_in *)(void *)sa)->sin_addr));
1876 		break;
1877 #endif
1878 #ifdef INET6
1879 	case AF_INET6:
1880 		(void)printf("%s: inet6 %s; ", which, inet_ntop(sa->sa_family,
1881 		    &((struct sockaddr_in6 *)(void *)sa)->sin6_addr, nbuf,
1882 		    sizeof(nbuf)));
1883 		break;
1884 #endif
1885 	}
1886 	(void)fflush(stdout);
1887 }
1888 
1889 /* States*/
1890 #define VIRGIN	0
1891 #define GOTONE	1
1892 #define GOTTWO	2
1893 /* Inputs */
1894 #define	DIGIT	(4*0)
1895 #define	END	(4*1)
1896 #define DELIM	(4*2)
1897 
1898 static void
1899 sockaddr(char *addr, struct sockaddr *sa, size_t size)
1900 {
1901 	char *cp = (char *)sa;
1902 	char *cplim = cp + size;
1903 	int byte = 0, state = VIRGIN, new = 0 /* foil gcc */;
1904 
1905 	memset(cp, 0, size);
1906 	cp++;
1907 	do {
1908 		if ((*addr >= '0') && (*addr <= '9')) {
1909 			new = *addr - '0';
1910 		} else if ((*addr >= 'a') && (*addr <= 'f')) {
1911 			new = *addr - 'a' + 10;
1912 		} else if ((*addr >= 'A') && (*addr <= 'F')) {
1913 			new = *addr - 'A' + 10;
1914 		} else if (*addr == '\0')
1915 			state |= END;
1916 		else
1917 			state |= DELIM;
1918 		addr++;
1919 		switch (state /* | INPUT */) {
1920 		case GOTTWO | DIGIT:
1921 			*cp++ = byte; /*FALLTHROUGH*/
1922 		case VIRGIN | DIGIT:
1923 			state = GOTONE; byte = new; continue;
1924 		case GOTONE | DIGIT:
1925 			state = GOTTWO; byte = new + (byte << 4); continue;
1926 		default: /* | DELIM */
1927 			state = VIRGIN; *cp++ = byte; byte = 0; continue;
1928 		case GOTONE | END:
1929 		case GOTTWO | END:
1930 			*cp++ = byte; /* FALLTHROUGH */
1931 		case VIRGIN | END:
1932 			break;
1933 		}
1934 		break;
1935 	} while (cp < cplim);
1936 	sa->sa_len = cp - (char *)sa;
1937 }
1938