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>
73 * Definitions for showing gateway flags.
80 { RTF_UP, 'U', "up" },
81 { RTF_GATEWAY, 'G', "gateway" },
82 { RTF_HOST, 'H', "host" },
83 { RTF_REJECT, 'R', "reject" },
84 { RTF_DYNAMIC, 'D', "dynamic" },
85 { RTF_MODIFIED, 'M', "modified" },
86 { RTF_DONE, 'd', "done" }, /* Completed -- for routing msgs only */
87 { RTF_XRESOLVE, 'X', "xresolve" },
88 { RTF_STATIC, 'S', "static" },
89 { RTF_PROTO1, '1', "proto1" },
90 { RTF_PROTO2, '2', "proto2" },
91 { RTF_PROTO3, '3', "proto3" },
92 { RTF_BLACKHOLE,'B', "blackhole" },
93 { RTF_BROADCAST,'b', "broadcast" },
95 { RTF_LLINFO, 'L', "llinfo" },
101 char ifname[IFNAMSIZ];
103 static struct ifmap_entry *ifmap;
104 static int ifmap_size;
105 static struct timespec uptime;
107 static const char *netname4(in_addr_t, in_addr_t);
109 static const char *netname6(struct sockaddr_in6 *, struct sockaddr_in6 *);
111 static void p_rtable_sysctl(int, int);
112 static void p_rtentry_sysctl(const char *name, struct rt_msghdr *);
113 static int p_sockaddr(const char *name, struct sockaddr *, struct sockaddr *,
115 static const char *fmt_sockaddr(struct sockaddr *sa, struct sockaddr *mask,
117 static void p_flags(int, const char *);
118 static const char *fmt_flags(int f);
119 static void domask(char *, size_t, u_long);
123 * Print routing tables.
126 routepr(int fibnum, int af)
134 intsize = sizeof(int);
136 sysctlbyname("net.my_fibnum", &fibnum, &intsize, NULL, 0) == -1)
138 if (sysctlbyname("net.fibs", &numfibs, &intsize, NULL, 0) == -1)
140 if (fibnum < 0 || fibnum > numfibs - 1)
141 errx(EX_USAGE, "%d: invalid fib", fibnum);
143 * Since kernel & userland use different timebase
144 * (time_uptime vs time_second) and we are reading kernel memory
145 * directly we should do rt_expire --> expire_time conversion.
147 if (clock_gettime(CLOCK_UPTIME, &uptime) < 0)
148 err(EX_OSERR, "clock_gettime() failed");
150 xo_open_container("route-information");
151 xo_emit("{T:Routing tables}");
153 xo_emit(" ({L:fib}: {:fib/%d})", fibnum);
155 p_rtable_sysctl(fibnum, af);
156 xo_close_container("route-information");
161 * Print address family header before a section of the routing table.
174 afname = "Internet6";
191 xo_emit("\n{k:address-family/%s}:\n", afname);
193 xo_emit("\n{L:Protocol Family} {k:address-family/%d}:\n", af1);
196 /* column widths; each followed by one space */
198 #define WID_DST_DEFAULT(af) 18 /* width of destination column */
199 #define WID_GW_DEFAULT(af) 18 /* width of gateway column */
200 #define WID_IF_DEFAULT(af) (Wflag ? 10 : 8) /* width of netif column */
202 #define WID_DST_DEFAULT(af) \
203 ((af) == AF_INET6 ? (numeric_addr ? 33: 18) : 18)
204 #define WID_GW_DEFAULT(af) \
205 ((af) == AF_INET6 ? (numeric_addr ? 29 : 18) : 18)
206 #define WID_IF_DEFAULT(af) ((af) == AF_INET6 ? 8 : (Wflag ? 10 : 8))
211 static int wid_flags;
212 static int wid_pksent;
215 static int wid_expire;
218 * Print header for routing table columns.
221 pr_rthdr(int af1 __unused)
225 xo_emit("{T:/%-*.*s} {T:/%-*.*s} {T:/%-*.*s} {T:/%*.*s} "
226 "{T:/%*.*s} {T:/%*.*s} {T:/%*s}\n",
227 wid_dst, wid_dst, "Destination",
228 wid_gw, wid_gw, "Gateway",
229 wid_flags, wid_flags, "Flags",
230 wid_pksent, wid_pksent, "Use",
231 wid_mtu, wid_mtu, "Mtu",
232 wid_if, wid_if, "Netif",
233 wid_expire, "Expire");
235 xo_emit("{T:/%-*.*s} {T:/%-*.*s} {T:/%-*.*s} {T:/%*.*s} "
237 wid_dst, wid_dst, "Destination",
238 wid_gw, wid_gw, "Gateway",
239 wid_flags, wid_flags, "Flags",
240 wid_if, wid_if, "Netif",
241 wid_expire, "Expire");
246 p_rtable_sysctl(int fibnum, int af)
250 char *buf, *next, *lim;
251 struct rt_msghdr *rtm;
253 int fam = AF_UNSPEC, ifindex = 0, size;
254 int need_table_close = false;
256 struct ifaddrs *ifap, *ifa;
257 struct sockaddr_dl *sdl;
260 * Retrieve interface list at first
261 * since we need #ifindex -> if_xname match
263 if (getifaddrs(&ifap) != 0)
264 err(EX_OSERR, "getifaddrs");
266 for (ifa = ifap; ifa; ifa = ifa->ifa_next) {
268 if (ifa->ifa_addr->sa_family != AF_LINK)
271 sdl = (struct sockaddr_dl *)ifa->ifa_addr;
272 ifindex = sdl->sdl_index;
274 if (ifindex >= ifmap_size) {
275 size = roundup(ifindex + 1, 32) *
276 sizeof(struct ifmap_entry);
277 if ((ifmap = realloc(ifmap, size)) == NULL)
278 errx(2, "realloc(%d) failed", size);
279 memset(&ifmap[ifmap_size], 0,
281 sizeof(struct ifmap_entry));
283 ifmap_size = roundup(ifindex + 1, 32);
286 if (*ifmap[ifindex].ifname != '\0')
289 strlcpy(ifmap[ifindex].ifname, ifa->ifa_name, IFNAMSIZ);
298 mib[4] = NET_RT_DUMP;
301 if (sysctl(mib, nitems(mib), NULL, &needed, NULL, 0) < 0)
302 err(EX_OSERR, "sysctl: net.route.0.%d.dump.%d estimate", af,
304 if ((buf = malloc(needed)) == NULL)
305 errx(2, "malloc(%lu)", (unsigned long)needed);
306 if (sysctl(mib, nitems(mib), buf, &needed, NULL, 0) < 0)
307 err(1, "sysctl: net.route.0.%d.dump.%d", af, fibnum);
309 xo_open_container("route-table");
310 xo_open_list("rt-family");
311 for (next = buf; next < lim; next += rtm->rtm_msglen) {
312 rtm = (struct rt_msghdr *)next;
313 if (rtm->rtm_version != RTM_VERSION)
316 * Peek inside header to determine AF
318 sa = (struct sockaddr *)(rtm + 1);
319 /* Only print family first time. */
320 if (fam != sa->sa_family) {
321 if (need_table_close) {
322 xo_close_list("rt-entry");
323 xo_close_instance("rt-family");
325 need_table_close = true;
328 wid_dst = WID_DST_DEFAULT(fam);
329 wid_gw = WID_GW_DEFAULT(fam);
333 wid_if = WID_IF_DEFAULT(fam);
335 xo_open_instance("rt-family");
337 xo_open_list("rt-entry");
341 p_rtentry_sysctl("rt-entry", rtm);
343 if (need_table_close) {
344 xo_close_list("rt-entry");
345 xo_close_instance("rt-family");
347 xo_close_list("rt-family");
348 xo_close_container("route-table");
353 p_rtentry_sysctl(const char *name, struct rt_msghdr *rtm)
355 struct sockaddr *sa, *addr[RTAX_MAX];
357 char prettyname[128];
360 xo_open_instance(name);
361 sa = (struct sockaddr *)(rtm + 1);
362 for (i = 0; i < RTAX_MAX; i++) {
363 if (rtm->rtm_addrs & (1 << i))
365 sa = (struct sockaddr *)((char *)sa + SA_SIZE(sa));
368 protrusion = p_sockaddr("destination", addr[RTAX_DST],
370 rtm->rtm_flags, wid_dst);
371 protrusion = p_sockaddr("gateway", addr[RTAX_GATEWAY], NULL, RTF_HOST,
372 wid_gw - protrusion);
373 snprintf(buffer, sizeof(buffer), "{[:-%d}{:flags/%%s}{]:} ",
374 wid_flags - protrusion);
375 p_flags(rtm->rtm_flags, buffer);
377 xo_emit("{t:use/%*lu} ", wid_pksent, rtm->rtm_rmx.rmx_pksent);
379 if (rtm->rtm_rmx.rmx_mtu != 0)
380 xo_emit("{t:mtu/%*lu} ", wid_mtu, rtm->rtm_rmx.rmx_mtu);
382 xo_emit("{P:/%*s} ", wid_mtu, "");
385 memset(prettyname, 0, sizeof(prettyname));
386 if (rtm->rtm_index < ifmap_size) {
387 strlcpy(prettyname, ifmap[rtm->rtm_index].ifname,
389 if (*prettyname == '\0')
390 strlcpy(prettyname, "---", sizeof(prettyname));
394 xo_emit("{t:interface-name/%*s}", wid_if, prettyname);
396 xo_emit("{t:interface-name/%*.*s}", wid_if, wid_if,
398 if (rtm->rtm_rmx.rmx_expire) {
401 if ((expire_time = rtm->rtm_rmx.rmx_expire - uptime.tv_sec) > 0)
402 xo_emit(" {:expire-time/%*d}", wid_expire,
407 xo_close_instance(name);
411 p_sockaddr(const char *name, struct sockaddr *sa, struct sockaddr *mask,
412 int flags, int width)
418 cp = fmt_sockaddr(sa, mask, flags);
421 snprintf(buf, sizeof(buf), "{:%s/%%s} ", name);
425 if (Wflag != 0 || numeric_addr) {
426 snprintf(buf, sizeof(buf), "{[:%d}{:%s/%%s}{]:} ",
429 protrusion = strlen(cp) - width;
433 snprintf(buf, sizeof(buf), "{[:%d}{:%s/%%-.*s}{]:} ",
435 xo_emit(buf, width, cp);
443 fmt_sockaddr(struct sockaddr *sa, struct sockaddr *mask, int flags)
445 static char buf[128];
451 switch(sa->sa_family) {
455 * The sa6->sin6_scope_id must be filled here because
456 * this sockaddr is extracted from kmem(4) directly
457 * and has KAME-specific embedded scope id in
458 * sa6->sin6_addr.s6_addr[2].
460 in6_fillscopeid(satosin6(sa));
464 if (flags & RTF_HOST)
465 cp = routename(sa, numeric_addr);
467 cp = netname(sa, mask);
469 cp = netname(sa, NULL);
473 strlcpy(buf, ((struct sockaddr_ng *)sa)->sg_data,
481 struct sockaddr_dl *sdl = (struct sockaddr_dl *)sa;
483 /* Interface route. */
488 cp = routename(sa, 1);
493 u_char *s = (u_char *)sa->sa_data, *slim;
497 slim = sa->sa_len + (u_char *) sa;
498 cqlim = cq + sizeof(buf) - sizeof(" ffff");
499 snprintf(cq, sizeof(buf), "(%d)", sa->sa_family);
501 while (s < slim && cq < cqlim) {
502 snprintf(cq, sizeof(" ff"), " %02x", *s++);
505 snprintf(cq, sizeof("ff"), "%02x", *s++);
517 p_flags(int f, const char *format)
521 xo_emit(format, fmt_flags(f));
523 xo_open_list("flags_pretty");
524 for (p = bits; p->b_mask; p++)
526 xo_emit("{le:flags_pretty/%s}", p->b_name);
527 xo_close_list("flags_pretty");
533 static char name[33];
535 struct bits *p = bits;
537 for (flags = name; p->b_mask; p++)
545 routename(struct sockaddr *sa, int flags)
547 static char line[NI_MAXHOST];
550 f = (flags) ? NI_NUMERICHOST : 0;
551 error = getnameinfo(sa, sa->sa_len, line, sizeof(line),
555 switch (sa->sa_family) {
558 src = &satosin(sa)->sin_addr;
563 src = &satosin6(sa)->sin6_addr;
569 inet_ntop(sa->sa_family, src, line, sizeof(line) - 1);
572 trimdomain(line, strlen(line));
577 #define NSHIFT(m) ( \
578 (m) == IN_CLASSA_NET ? IN_CLASSA_NSHIFT : \
579 (m) == IN_CLASSB_NET ? IN_CLASSB_NSHIFT : \
580 (m) == IN_CLASSC_NET ? IN_CLASSC_NSHIFT : \
584 domask(char *dst, size_t buflen, u_long mask)
593 for (b = 0; b < 32; b++)
594 if (mask & (1 << b)) {
598 for (bb = b+1; bb < 32; bb++)
599 if (!(mask & (1 << bb))) {
600 i = -1; /* noncontig */
606 snprintf(dst, buflen, "&0x%lx", mask);
608 snprintf(dst, buflen, "/%d", 32-i);
612 * Return the name of the network whose address is given.
615 netname(struct sockaddr *sa, struct sockaddr *mask)
617 switch (sa->sa_family) {
620 return (netname4(satosin(sa)->sin_addr.s_addr,
621 satosin(mask)->sin_addr.s_addr));
623 return (netname4(satosin(sa)->sin_addr.s_addr,
628 return (netname6(satosin6(sa), satosin6(mask)));
636 netname4(in_addr_t in, in_addr_t mask)
639 static char line[MAXHOSTNAMELEN + sizeof("&0xffffffff")];
640 char nline[INET_ADDRSTRLEN];
641 struct netent *np = 0;
644 if (in == INADDR_ANY && mask == 0) {
645 strlcpy(line, "default", sizeof(line));
649 /* It is ok to supply host address. */
653 if (!numeric_addr && i) {
654 np = getnetbyaddr(i >> NSHIFT(ntohl(mask)), AF_INET);
657 trimdomain(cp, strlen(cp));
661 strlcpy(line, cp, sizeof(line));
663 inet_ntop(AF_INET, &in, nline, sizeof(nline));
664 strlcpy(line, nline, sizeof(line));
665 domask(line + strlen(line), sizeof(line) - strlen(line), ntohl(mask));
675 in6_fillscopeid(struct sockaddr_in6 *sa6)
677 #if defined(__KAME__)
679 * XXX: This is a special workaround for KAME kernels.
680 * sin6_scope_id field of SA should be set in the future.
682 if (IN6_IS_ADDR_LINKLOCAL(&sa6->sin6_addr) ||
683 IN6_IS_ADDR_MC_NODELOCAL(&sa6->sin6_addr) ||
684 IN6_IS_ADDR_MC_LINKLOCAL(&sa6->sin6_addr)) {
685 if (sa6->sin6_scope_id == 0)
687 ntohs(*(u_int16_t *)&sa6->sin6_addr.s6_addr[2]);
688 sa6->sin6_addr.s6_addr[2] = sa6->sin6_addr.s6_addr[3] = 0;
693 /* Mask to length table. To check an invalid value, (length + 1) is used. */
694 static const u_char masktolen[256] = {
707 netname6(struct sockaddr_in6 *sa6, struct sockaddr_in6 *mask)
709 static char line[NI_MAXHOST + sizeof("/xxx") - 1];
710 struct sockaddr_in6 addr;
711 char nline[NI_MAXHOST];
712 char maskbuf[sizeof("/xxx")];
716 bool illegal = false;
719 p = (u_char *)&mask->sin6_addr;
720 for (masklen = 0, lim = p + 16; p < lim; p++) {
721 if (masktolen[*p] > 0) {
722 /* -1 is required. */
723 masklen += (masktolen[*p] - 1);
728 xo_error("illegal prefixlen\n");
730 memcpy(&addr, sa6, sizeof(addr));
731 for (i = 0; i < 16; ++i)
732 addr.sin6_addr.s6_addr[i] &=
733 mask->sin6_addr.s6_addr[i];
739 if (masklen == 0 && IN6_IS_ADDR_UNSPECIFIED(&sa6->sin6_addr))
742 getnameinfo((struct sockaddr *)sa6, sa6->sin6_len, nline, sizeof(nline),
743 NULL, 0, NI_NUMERICHOST);
745 strlcpy(line, nline, sizeof(line));
747 getnameinfo((struct sockaddr *)sa6, sa6->sin6_len, line,
748 sizeof(line), NULL, 0, 0);
749 if (numeric_addr || strcmp(line, nline) == 0) {
750 snprintf(maskbuf, sizeof(maskbuf), "/%d", masklen);
751 strlcat(line, maskbuf, sizeof(line));
759 * Print routing statistics
764 struct rtstat rtstat;
765 u_long rtsaddr, rttaddr;
768 if ((rtsaddr = nl[N_RTSTAT].n_value) == 0) {
769 xo_emit("{W:rtstat: symbol not in namelist}\n");
772 if ((rttaddr = nl[N_RTTRASH].n_value) == 0) {
773 xo_emit("{W:rttrash: symbol not in namelist}\n");
776 kread(rtsaddr, (char *)&rtstat, sizeof (rtstat));
777 kread(rttaddr, (char *)&rttrash, sizeof (rttrash));
778 xo_emit("{T:routing}:\n");
780 #define p(f, m) if (rtstat.f || sflag <= 1) \
781 xo_emit(m, rtstat.f, plural(rtstat.f))
783 p(rts_badredirect, "\t{:bad-redirects/%hu} "
784 "{N:/bad routing redirect%s}\n");
785 p(rts_dynamic, "\t{:dynamically-created/%hu} "
786 "{N:/dynamically created route%s}\n");
787 p(rts_newgateway, "\t{:new-gateways/%hu} "
788 "{N:/new gateway%s due to redirects}\n");
789 p(rts_unreach, "\t{:unreachable-destination/%hu} "
790 "{N:/destination%s found unreachable}\n");
791 p(rts_wildcard, "\t{:wildcard-uses/%hu} "
792 "{N:/use%s of a wildcard route}\n");
795 if (rttrash || sflag <= 1)
796 xo_emit("\t{:unused-but-not-freed/%u} "
797 "{N:/route%s not in table but not freed}\n",
798 rttrash, plural(rttrash));