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