2 * Copyright (c) 1983, 1988, 1993
3 * The Regents of the University of California. All rights reserved.
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
13 * 4. Neither the name of the University nor the names of its contributors
14 * may be used to endorse or promote products derived from this software
15 * without specific prior written permission.
17 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
18 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
21 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32 static char sccsid[] = "From: @(#)route.c 8.6 (Berkeley) 4/28/95";
36 #include <sys/cdefs.h>
37 __FBSDID("$FreeBSD$");
39 #include <sys/param.h>
40 #include <sys/protosw.h>
41 #include <sys/socket.h>
42 #include <sys/socketvar.h>
43 #include <sys/sysctl.h>
46 #include <net/ethernet.h>
48 #include <net/if_dl.h>
49 #include <net/if_types.h>
50 #include <net/route.h>
52 #include <netinet/in.h>
53 #include <netgraph/ng_socket.h>
55 #include <arpa/inet.h>
72 * Definitions for showing gateway flags.
79 { RTF_UP, 'U', "up" },
80 { RTF_GATEWAY, 'G', "gateway" },
81 { RTF_HOST, 'H', "host" },
82 { RTF_REJECT, 'R', "reject" },
83 { RTF_DYNAMIC, 'D', "dynamic" },
84 { RTF_MODIFIED, 'M', "modified" },
85 { RTF_DONE, 'd', "done" }, /* Completed -- for routing msgs only */
86 { RTF_XRESOLVE, 'X', "xresolve" },
87 { RTF_STATIC, 'S', "static" },
88 { RTF_PROTO1, '1', "proto1" },
89 { RTF_PROTO2, '2', "proto2" },
90 { RTF_PROTO3, '3', "proto3" },
91 { RTF_BLACKHOLE,'B', "blackhole" },
92 { RTF_BROADCAST,'b', "broadcast" },
94 { RTF_LLINFO, 'L', "llinfo" },
100 char ifname[IFNAMSIZ];
102 static struct ifmap_entry *ifmap;
103 static int ifmap_size;
104 static struct timespec uptime;
106 static const char *netname4(in_addr_t, in_addr_t);
107 static const char *netname6(struct sockaddr_in6 *, struct sockaddr_in6 *);
108 static void p_rtable_sysctl(int, int);
109 static void p_rtentry_sysctl(const char *name, struct rt_msghdr *);
110 static int p_sockaddr(const char *name, struct sockaddr *, struct sockaddr *,
112 static const char *fmt_sockaddr(struct sockaddr *sa, struct sockaddr *mask,
114 static void p_flags(int, const char *);
115 static const char *fmt_flags(int f);
116 static void domask(char *, in_addr_t, u_long);
120 * Print routing tables.
123 routepr(int fibnum, int af)
131 intsize = sizeof(int);
133 sysctlbyname("net.my_fibnum", &fibnum, &intsize, NULL, 0) == -1)
135 if (sysctlbyname("net.fibs", &numfibs, &intsize, NULL, 0) == -1)
137 if (fibnum < 0 || fibnum > numfibs - 1)
138 errx(EX_USAGE, "%d: invalid fib", fibnum);
140 * Since kernel & userland use different timebase
141 * (time_uptime vs time_second) and we are reading kernel memory
142 * directly we should do rt_expire --> expire_time conversion.
144 if (clock_gettime(CLOCK_UPTIME, &uptime) < 0)
145 err(EX_OSERR, "clock_gettime() failed");
147 xo_open_container("route-information");
148 xo_emit("{T:Routing tables}");
150 xo_emit(" ({L:fib}: {:fib/%d})", fibnum);
152 p_rtable_sysctl(fibnum, af);
153 xo_close_container("route-information");
158 * Print address family header before a section of the routing table.
171 afname = "Internet6";
188 xo_emit("\n{k:address-family/%s}:\n", afname);
190 xo_emit("\n{L:Protocol Family} {k:address-family/%d}:\n", af1);
193 /* column widths; each followed by one space */
195 #define WID_DST_DEFAULT(af) 18 /* width of destination column */
196 #define WID_GW_DEFAULT(af) 18 /* width of gateway column */
197 #define WID_IF_DEFAULT(af) (Wflag ? 10 : 8) /* width of netif column */
199 #define WID_DST_DEFAULT(af) \
200 ((af) == AF_INET6 ? (numeric_addr ? 33: 18) : 18)
201 #define WID_GW_DEFAULT(af) \
202 ((af) == AF_INET6 ? (numeric_addr ? 29 : 18) : 18)
203 #define WID_IF_DEFAULT(af) ((af) == AF_INET6 ? 8 : (Wflag ? 10 : 8))
208 static int wid_flags;
209 static int wid_pksent;
212 static int wid_expire;
215 * Print header for routing table columns.
218 pr_rthdr(int af1 __unused)
222 xo_emit("{T:/%-*.*s} {T:/%-*.*s} {T:/%-*.*s} {T:/%*.*s} "
223 "{T:/%*.*s} {T:/%*.*s} {T:/%*s}\n",
224 wid_dst, wid_dst, "Destination",
225 wid_gw, wid_gw, "Gateway",
226 wid_flags, wid_flags, "Flags",
227 wid_pksent, wid_pksent, "Use",
228 wid_mtu, wid_mtu, "Mtu",
229 wid_if, wid_if, "Netif",
230 wid_expire, "Expire");
232 xo_emit("{T:/%-*.*s} {T:/%-*.*s} {T:/%-*.*s} {T:/%*.*s} "
234 wid_dst, wid_dst, "Destination",
235 wid_gw, wid_gw, "Gateway",
236 wid_flags, wid_flags, "Flags",
237 wid_if, wid_if, "Netif",
238 wid_expire, "Expire");
243 p_rtable_sysctl(int fibnum, int af)
247 char *buf, *next, *lim;
248 struct rt_msghdr *rtm;
250 int fam = AF_UNSPEC, ifindex = 0, size;
251 int need_table_close = false;
253 struct ifaddrs *ifap, *ifa;
254 struct sockaddr_dl *sdl;
257 * Retrieve interface list at first
258 * since we need #ifindex -> if_xname match
260 if (getifaddrs(&ifap) != 0)
261 err(EX_OSERR, "getifaddrs");
263 for (ifa = ifap; ifa; ifa = ifa->ifa_next) {
265 if (ifa->ifa_addr->sa_family != AF_LINK)
268 sdl = (struct sockaddr_dl *)ifa->ifa_addr;
269 ifindex = sdl->sdl_index;
271 if (ifindex >= ifmap_size) {
272 size = roundup(ifindex + 1, 32) *
273 sizeof(struct ifmap_entry);
274 if ((ifmap = realloc(ifmap, size)) == NULL)
275 errx(2, "realloc(%d) failed", size);
276 memset(&ifmap[ifmap_size], 0,
278 sizeof(struct ifmap_entry));
280 ifmap_size = roundup(ifindex + 1, 32);
283 if (*ifmap[ifindex].ifname != '\0')
286 strlcpy(ifmap[ifindex].ifname, ifa->ifa_name, IFNAMSIZ);
295 mib[4] = NET_RT_DUMP;
298 if (sysctl(mib, nitems(mib), NULL, &needed, NULL, 0) < 0)
299 err(EX_OSERR, "sysctl: net.route.0.%d.dump.%d estimate", af,
301 if ((buf = malloc(needed)) == NULL)
302 errx(2, "malloc(%lu)", (unsigned long)needed);
303 if (sysctl(mib, nitems(mib), buf, &needed, NULL, 0) < 0)
304 err(1, "sysctl: net.route.0.%d.dump.%d", af, fibnum);
306 xo_open_container("route-table");
307 xo_open_list("rt-family");
308 for (next = buf; next < lim; next += rtm->rtm_msglen) {
309 rtm = (struct rt_msghdr *)next;
310 if (rtm->rtm_version != RTM_VERSION)
313 * Peek inside header to determine AF
315 sa = (struct sockaddr *)(rtm + 1);
316 /* Only print family first time. */
317 if (fam != sa->sa_family) {
318 if (need_table_close) {
319 xo_close_list("rt-entry");
320 xo_close_instance("rt-family");
322 need_table_close = true;
325 wid_dst = WID_DST_DEFAULT(fam);
326 wid_gw = WID_GW_DEFAULT(fam);
330 wid_if = WID_IF_DEFAULT(fam);
332 xo_open_instance("rt-family");
334 xo_open_list("rt-entry");
338 p_rtentry_sysctl("rt-entry", rtm);
340 if (need_table_close) {
341 xo_close_list("rt-entry");
342 xo_close_instance("rt-family");
344 xo_close_list("rt-family");
345 xo_close_container("route-table");
350 p_rtentry_sysctl(const char *name, struct rt_msghdr *rtm)
352 struct sockaddr *sa, *addr[RTAX_MAX];
354 char prettyname[128];
357 xo_open_instance(name);
358 sa = (struct sockaddr *)(rtm + 1);
359 for (i = 0; i < RTAX_MAX; i++) {
360 if (rtm->rtm_addrs & (1 << i))
362 sa = (struct sockaddr *)((char *)sa + SA_SIZE(sa));
365 protrusion = p_sockaddr("destination", addr[RTAX_DST],
367 rtm->rtm_flags, wid_dst);
368 protrusion = p_sockaddr("gateway", addr[RTAX_GATEWAY], NULL, RTF_HOST,
369 wid_gw - protrusion);
370 snprintf(buffer, sizeof(buffer), "{[:-%d}{:flags/%%s}{]:} ",
371 wid_flags - protrusion);
372 p_flags(rtm->rtm_flags, buffer);
374 xo_emit("{t:use/%*lu} ", wid_pksent, rtm->rtm_rmx.rmx_pksent);
376 if (rtm->rtm_rmx.rmx_mtu != 0)
377 xo_emit("{t:mtu/%*lu} ", wid_mtu, rtm->rtm_rmx.rmx_mtu);
379 xo_emit("{P:/%*s} ", wid_mtu, "");
382 memset(prettyname, 0, sizeof(prettyname));
383 if (rtm->rtm_index < ifmap_size) {
384 strlcpy(prettyname, ifmap[rtm->rtm_index].ifname,
386 if (*prettyname == '\0')
387 strlcpy(prettyname, "---", sizeof(prettyname));
391 xo_emit("{t:interface-name/%*s}", wid_if, prettyname);
393 xo_emit("{t:interface-name/%*.*s}", wid_if, wid_if,
395 if (rtm->rtm_rmx.rmx_expire) {
398 if ((expire_time = rtm->rtm_rmx.rmx_expire - uptime.tv_sec) > 0)
399 xo_emit(" {:expire-time/%*d}", wid_expire,
404 xo_close_instance(name);
408 p_sockaddr(const char *name, struct sockaddr *sa, struct sockaddr *mask,
409 int flags, int width)
415 cp = fmt_sockaddr(sa, mask, flags);
418 snprintf(buf, sizeof(buf), "{:%s/%%s} ", name);
421 if (Wflag != 0 || numeric_addr) {
422 snprintf(buf, sizeof(buf), "{[:%d}{:%s/%%s}{]:} ",
425 protrusion = strlen(cp) - width;
429 snprintf(buf, sizeof(buf), "{[:%d}{:%s/%%-.*s}{]:} ",
431 xo_emit(buf, width, cp);
439 fmt_sockaddr(struct sockaddr *sa, struct sockaddr *mask, int flags)
441 static char buf[128];
447 switch(sa->sa_family) {
451 * The sa6->sin6_scope_id must be filled here because
452 * this sockaddr is extracted from kmem(4) directly
453 * and has KAME-specific embedded scope id in
454 * sa6->sin6_addr.s6_addr[2].
456 in6_fillscopeid(satosin6(sa));
460 if (flags & RTF_HOST)
461 cp = routename(sa, numeric_addr);
463 cp = netname(sa, mask);
465 cp = netname(sa, NULL);
469 strlcpy(buf, ((struct sockaddr_ng *)sa)->sg_data,
477 struct sockaddr_dl *sdl = (struct sockaddr_dl *)sa;
479 /* Interface route. */
484 cp = routename(sa, 1);
489 u_char *s = (u_char *)sa->sa_data, *slim;
493 slim = sa->sa_len + (u_char *) sa;
494 cqlim = cq + sizeof(buf) - 6;
495 cq += sprintf(cq, "(%d)", sa->sa_family);
496 while (s < slim && cq < cqlim) {
497 cq += sprintf(cq, " %02x", *s++);
499 cq += sprintf(cq, "%02x", *s++);
509 p_flags(int f, const char *format)
513 xo_emit(format, fmt_flags(f));
515 xo_open_list("flags_pretty");
516 for (p = bits; p->b_mask; p++)
518 xo_emit("{le:flags_pretty/%s}", p->b_name);
519 xo_close_list("flags_pretty");
525 static char name[33];
527 struct bits *p = bits;
529 for (flags = name; p->b_mask; p++)
537 routename(struct sockaddr *sa, int flags)
539 static char line[NI_MAXHOST];
542 f = (flags) ? NI_NUMERICHOST : 0;
543 error = getnameinfo(sa, sa->sa_len, line, sizeof(line),
547 switch (sa->sa_family) {
550 src = &satosin(sa)->sin_addr;
555 src = &satosin6(sa)->sin6_addr;
561 inet_ntop(sa->sa_family, src, line, sizeof(line) - 1);
564 trimdomain(line, strlen(line));
569 #define NSHIFT(m) ( \
570 (m) == IN_CLASSA_NET ? IN_CLASSA_NSHIFT : \
571 (m) == IN_CLASSB_NET ? IN_CLASSB_NSHIFT : \
572 (m) == IN_CLASSC_NET ? IN_CLASSC_NSHIFT : \
576 domask(char *dst, in_addr_t addr __unused, u_long mask)
585 for (b = 0; b < 32; b++)
586 if (mask & (1 << b)) {
590 for (bb = b+1; bb < 32; bb++)
591 if (!(mask & (1 << bb))) {
592 i = -1; /* noncontig */
598 sprintf(dst, "&0x%lx", mask);
600 sprintf(dst, "/%d", 32-i);
604 * Return the name of the network whose address is given.
607 netname(struct sockaddr *sa, struct sockaddr *mask)
609 switch (sa->sa_family) {
612 return (netname4(satosin(sa)->sin_addr.s_addr,
613 satosin(mask)->sin_addr.s_addr));
615 return (netname4(satosin(sa)->sin_addr.s_addr,
620 return (netname6(satosin6(sa), satosin6(mask)));
628 netname4(in_addr_t in, in_addr_t mask)
631 static char line[MAXHOSTNAMELEN + sizeof("/xx")];
632 char nline[INET_ADDRSTRLEN];
633 struct netent *np = 0;
636 if (in == INADDR_ANY && mask == 0) {
637 strlcpy(line, "default", sizeof(line));
641 /* It is ok to supply host address. */
645 if (!numeric_addr && i) {
646 np = getnetbyaddr(i >> NSHIFT(ntohl(mask)), AF_INET);
649 trimdomain(cp, strlen(cp));
653 strlcpy(line, cp, sizeof(line));
655 inet_ntop(AF_INET, &in, nline, sizeof(nline));
656 strlcpy(line, nline, sizeof(line));
657 domask(line + strlen(line), i, ntohl(mask));
667 in6_fillscopeid(struct sockaddr_in6 *sa6)
669 #if defined(__KAME__)
671 * XXX: This is a special workaround for KAME kernels.
672 * sin6_scope_id field of SA should be set in the future.
674 if (IN6_IS_ADDR_LINKLOCAL(&sa6->sin6_addr) ||
675 IN6_IS_ADDR_MC_NODELOCAL(&sa6->sin6_addr) ||
676 IN6_IS_ADDR_MC_LINKLOCAL(&sa6->sin6_addr)) {
677 if (sa6->sin6_scope_id == 0)
679 ntohs(*(u_int16_t *)&sa6->sin6_addr.s6_addr[2]);
680 sa6->sin6_addr.s6_addr[2] = sa6->sin6_addr.s6_addr[3] = 0;
685 /* Mask to length table. To check an invalid value, (length + 1) is used. */
686 static int masktolen[256] = {
699 netname6(struct sockaddr_in6 *sa6, struct sockaddr_in6 *mask)
701 static char line[NI_MAXHOST + sizeof("/xxx") - 1];
702 struct sockaddr_in6 addr;
703 char nline[NI_MAXHOST];
705 int masklen, illegal = 0, i;
708 p = (u_char *)&mask->sin6_addr;
709 for (masklen = 0, lim = p + 16; p < lim; p++) {
710 if (masktolen[*p] > 0)
711 /* -1 is required. */
712 masklen += masktolen[*p] - 1;
717 xo_error("illegal prefixlen\n");
719 memcpy(&addr, sa6, sizeof(addr));
720 for (i = 0; i < 16; ++i)
721 addr.sin6_addr.s6_addr[i] &=
722 mask->sin6_addr.s6_addr[i];
728 if (masklen == 0 && IN6_IS_ADDR_UNSPECIFIED(&sa6->sin6_addr))
731 getnameinfo((struct sockaddr *)sa6, sa6->sin6_len, nline, sizeof(nline),
732 NULL, 0, NI_NUMERICHOST);
734 strlcpy(line, nline, sizeof(line));
736 getnameinfo((struct sockaddr *)sa6, sa6->sin6_len, line,
737 sizeof(line), NULL, 0, 0);
738 if (numeric_addr || strcmp(line, nline) == 0)
739 sprintf(&line[strlen(line)], "/%d", masklen);
746 * Print routing statistics
751 struct rtstat rtstat;
752 u_long rtsaddr, rttaddr;
755 if ((rtsaddr = nl[N_RTSTAT].n_value) == 0) {
756 xo_emit("{W:rtstat: symbol not in namelist}\n");
759 if ((rttaddr = nl[N_RTTRASH].n_value) == 0) {
760 xo_emit("{W:rttrash: symbol not in namelist}\n");
763 kread(rtsaddr, (char *)&rtstat, sizeof (rtstat));
764 kread(rttaddr, (char *)&rttrash, sizeof (rttrash));
765 xo_emit("{T:routing}:\n");
767 #define p(f, m) if (rtstat.f || sflag <= 1) \
768 xo_emit(m, rtstat.f, plural(rtstat.f))
770 p(rts_badredirect, "\t{:bad-redirects/%hu} "
771 "{N:/bad routing redirect%s}\n");
772 p(rts_dynamic, "\t{:dynamically-created/%hu} "
773 "{N:/dynamically created route%s}\n");
774 p(rts_newgateway, "\t{:new-gateways/%hu} "
775 "{N:/new gateway%s due to redirects}\n");
776 p(rts_unreach, "\t{:unreachable-destination/%hu} "
777 "{N:/destination%s found unreachable}\n");
778 p(rts_wildcard, "\t{:wildcard-uses/%hu} "
779 "{N:/use%s of a wildcard route}\n");
782 if (rttrash || sflag <= 1)
783 xo_emit("\t{:unused-but-not-freed/%u} "
784 "{N:/route%s not in table but not freed}\n",
785 rttrash, plural(rttrash));