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