2 * SPDX-License-Identifier: BSD-3-Clause
4 * Copyright (c) 1983, 1988, 1993
5 * The Regents of the University of California. All rights reserved.
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
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.
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
34 static char sccsid[] = "From: @(#)route.c 8.6 (Berkeley) 4/28/95";
38 #include <sys/cdefs.h>
39 __FBSDID("$FreeBSD$");
41 #include <sys/param.h>
42 #include <sys/protosw.h>
43 #include <sys/socket.h>
44 #include <sys/socketvar.h>
45 #include <sys/sysctl.h>
48 #include <net/ethernet.h>
50 #include <net/if_dl.h>
51 #include <net/if_types.h>
52 #include <net/route.h>
54 #include <netinet/in.h>
55 #include <netgraph/ng_socket.h>
57 #include <arpa/inet.h>
76 * Definitions for showing gateway flags.
78 struct bits rt_bits[] = {
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" },
99 static struct ifmap_entry *ifmap;
100 static size_t ifmap_size;
101 static struct timespec uptime;
103 static const char *netname4(in_addr_t, in_addr_t);
105 static const char *netname6(struct sockaddr_in6 *, struct sockaddr_in6 *);
107 static void p_rtable_sysctl(int, int);
108 static void p_rtentry_sysctl(const char *name, struct rt_msghdr *);
109 static void p_flags(int, const char *);
110 static void domask(char *, size_t, u_long);
114 * Print routing tables.
117 routepr(int fibnum, int af)
125 intsize = sizeof(int);
127 sysctlbyname("net.my_fibnum", &fibnum, &intsize, NULL, 0) == -1)
129 if (sysctlbyname("net.fibs", &numfibs, &intsize, NULL, 0) == -1)
131 if (fibnum < 0 || fibnum > numfibs - 1)
132 errx(EX_USAGE, "%d: invalid fib", fibnum);
134 * Since kernel & userland use different timebase
135 * (time_uptime vs time_second) and we are reading kernel memory
136 * directly we should do rt_expire --> expire_time conversion.
138 if (clock_gettime(CLOCK_UPTIME, &uptime) < 0)
139 err(EX_OSERR, "clock_gettime() failed");
141 xo_open_container("route-information");
142 xo_emit("{T:Routing tables}");
144 xo_emit(" ({L:fib}: {:fib/%d})", fibnum);
146 p_rtable_sysctl(fibnum, af);
147 xo_close_container("route-information");
152 * Print address family header before a section of the routing table.
165 afname = "Internet6";
182 xo_emit("\n{k:address-family/%s}:\n", afname);
184 xo_emit("\n{L:Protocol Family} {k:address-family/%d}:\n", af1);
187 /* column widths; each followed by one space */
189 #define WID_DST_DEFAULT(af) 18 /* width of destination column */
190 #define WID_GW_DEFAULT(af) 18 /* width of gateway column */
191 #define WID_IF_DEFAULT(af) (Wflag ? 10 : 8) /* width of netif column */
193 #define WID_DST_DEFAULT(af) \
194 ((af) == AF_INET6 ? (numeric_addr ? 33: 18) : 18)
195 #define WID_GW_DEFAULT(af) \
196 ((af) == AF_INET6 ? (numeric_addr ? 29 : 18) : 18)
197 #define WID_IF_DEFAULT(af) ((af) == AF_INET6 ? 8 : (Wflag ? 10 : 8))
202 static int wid_flags;
203 static int wid_pksent;
206 static int wid_expire;
209 * Print header for routing table columns.
212 pr_rthdr(int af1 __unused)
216 xo_emit("{T:/%-*.*s} {T:/%-*.*s} {T:/%-*.*s} {T:/%*.*s} "
217 "{T:/%*.*s} {T:/%*.*s} {T:/%*s}\n",
218 wid_dst, wid_dst, "Destination",
219 wid_gw, wid_gw, "Gateway",
220 wid_flags, wid_flags, "Flags",
221 wid_mtu, wid_mtu, "Nhop#",
222 wid_mtu, wid_mtu, "Mtu",
223 wid_if, wid_if, "Netif",
224 wid_expire, "Expire");
226 xo_emit("{T:/%-*.*s} {T:/%-*.*s} {T:/%-*.*s} {T:/%*.*s} "
228 wid_dst, wid_dst, "Destination",
229 wid_gw, wid_gw, "Gateway",
230 wid_flags, wid_flags, "Flags",
231 wid_if, wid_if, "Netif",
232 wid_expire, "Expire");
237 p_rtable_sysctl(int fibnum, int af)
241 char *buf, *next, *lim;
242 struct rt_msghdr *rtm;
245 int need_table_close = false;
247 ifmap = prepare_ifmap(&ifmap_size);
253 mib[4] = NET_RT_DUMP;
256 if (sysctl(mib, nitems(mib), NULL, &needed, NULL, 0) < 0)
257 err(EX_OSERR, "sysctl: net.route.0.%d.dump.%d estimate", af,
259 if ((buf = malloc(needed)) == NULL)
260 errx(2, "malloc(%lu)", (unsigned long)needed);
261 if (sysctl(mib, nitems(mib), buf, &needed, NULL, 0) < 0)
262 err(1, "sysctl: net.route.0.%d.dump.%d", af, fibnum);
264 xo_open_container("route-table");
265 xo_open_list("rt-family");
266 for (next = buf; next < lim; next += rtm->rtm_msglen) {
267 rtm = (struct rt_msghdr *)next;
268 if (rtm->rtm_version != RTM_VERSION)
271 * Peek inside header to determine AF
273 sa = (struct sockaddr *)(rtm + 1);
274 /* Only print family first time. */
275 if (fam != sa->sa_family) {
276 if (need_table_close) {
277 xo_close_list("rt-entry");
278 xo_close_instance("rt-family");
280 need_table_close = true;
283 wid_dst = WID_DST_DEFAULT(fam);
284 wid_gw = WID_GW_DEFAULT(fam);
288 wid_if = WID_IF_DEFAULT(fam);
290 xo_open_instance("rt-family");
292 xo_open_list("rt-entry");
296 p_rtentry_sysctl("rt-entry", rtm);
298 if (need_table_close) {
299 xo_close_list("rt-entry");
300 xo_close_instance("rt-family");
302 xo_close_list("rt-family");
303 xo_close_container("route-table");
308 p_rtentry_sysctl(const char *name, struct rt_msghdr *rtm)
310 struct sockaddr *sa, *addr[RTAX_MAX];
312 char prettyname[128];
315 xo_open_instance(name);
316 sa = (struct sockaddr *)(rtm + 1);
317 for (i = 0; i < RTAX_MAX; i++) {
318 if (rtm->rtm_addrs & (1 << i)) {
320 sa = (struct sockaddr *)((char *)sa + SA_SIZE(sa));
324 protrusion = p_sockaddr("destination", addr[RTAX_DST],
326 rtm->rtm_flags, wid_dst);
327 protrusion = p_sockaddr("gateway", addr[RTAX_GATEWAY], NULL, RTF_HOST,
328 wid_gw - protrusion);
329 snprintf(buffer, sizeof(buffer), "{[:-%d}{:flags/%%s}{]:} ",
330 wid_flags - protrusion);
331 p_flags(rtm->rtm_flags, buffer);
334 xo_emit("{t:nhop/%*lu} ", wid_mtu, rtm->rtm_rmx.rmx_nhidx);
336 if (rtm->rtm_rmx.rmx_mtu != 0)
337 xo_emit("{t:mtu/%*lu} ", wid_mtu, rtm->rtm_rmx.rmx_mtu);
339 xo_emit("{P:/%*s} ", wid_mtu, "");
342 memset(prettyname, 0, sizeof(prettyname));
343 if (rtm->rtm_index < ifmap_size) {
344 strlcpy(prettyname, ifmap[rtm->rtm_index].ifname,
346 if (*prettyname == '\0')
347 strlcpy(prettyname, "---", sizeof(prettyname));
351 xo_emit("{t:interface-name/%*s}", wid_if, prettyname);
353 xo_emit("{t:interface-name/%*.*s}", wid_if, wid_if,
355 if (rtm->rtm_rmx.rmx_expire) {
358 if ((expire_time = rtm->rtm_rmx.rmx_expire - uptime.tv_sec) > 0)
359 xo_emit(" {:expire-time/%*d}", wid_expire,
364 xo_close_instance(name);
368 p_sockaddr(const char *name, struct sockaddr *sa, struct sockaddr *mask,
369 int flags, int width)
375 cp = fmt_sockaddr(sa, mask, flags);
378 snprintf(buf, sizeof(buf), "{:%s/%%s} ", name);
382 if (Wflag != 0 || numeric_addr) {
383 snprintf(buf, sizeof(buf), "{[:%d}{:%s/%%s}{]:} ",
386 protrusion = strlen(cp) - width;
390 snprintf(buf, sizeof(buf), "{[:%d}{:%s/%%-.*s}{]:} ",
392 xo_emit(buf, width, cp);
400 fmt_sockaddr(struct sockaddr *sa, struct sockaddr *mask, int flags)
402 static char buf[128];
408 switch(sa->sa_family) {
412 * The sa6->sin6_scope_id must be filled here because
413 * this sockaddr is extracted from kmem(4) directly
414 * and has KAME-specific embedded scope id in
415 * sa6->sin6_addr.s6_addr[2].
417 in6_fillscopeid(satosin6(sa));
421 if (flags & RTF_HOST)
422 cp = routename(sa, numeric_addr);
424 cp = netname(sa, mask);
426 cp = netname(sa, NULL);
430 strlcpy(buf, ((struct sockaddr_ng *)sa)->sg_data,
438 struct sockaddr_dl *sdl = (struct sockaddr_dl *)sa;
440 /* Interface route. */
445 cp = routename(sa, 1);
450 u_char *s = (u_char *)sa->sa_data, *slim;
454 slim = sa->sa_len + (u_char *) sa;
455 cqlim = cq + sizeof(buf) - sizeof(" ffff");
456 snprintf(cq, sizeof(buf), "(%d)", sa->sa_family);
458 while (s < slim && cq < cqlim) {
459 snprintf(cq, sizeof(" ff"), " %02x", *s++);
462 snprintf(cq, sizeof("ff"), "%02x", *s++);
474 p_flags(int f, const char *format)
477 print_flags_generic(f, rt_bits, format, "flags_pretty");
482 routename(struct sockaddr *sa, int flags)
484 static char line[NI_MAXHOST];
487 f = (flags) ? NI_NUMERICHOST : 0;
488 error = getnameinfo(sa, sa->sa_len, line, sizeof(line),
492 switch (sa->sa_family) {
495 src = &satosin(sa)->sin_addr;
500 src = &satosin6(sa)->sin6_addr;
506 inet_ntop(sa->sa_family, src, line, sizeof(line) - 1);
509 trimdomain(line, strlen(line));
514 #define NSHIFT(m) ( \
515 (m) == IN_CLASSA_NET ? IN_CLASSA_NSHIFT : \
516 (m) == IN_CLASSB_NET ? IN_CLASSB_NSHIFT : \
517 (m) == IN_CLASSC_NET ? IN_CLASSC_NSHIFT : \
521 domask(char *dst, size_t buflen, u_long mask)
530 for (b = 0; b < 32; b++)
531 if (mask & (1 << b)) {
535 for (bb = b+1; bb < 32; bb++)
536 if (!(mask & (1 << bb))) {
537 i = -1; /* noncontig */
543 snprintf(dst, buflen, "&0x%lx", mask);
545 snprintf(dst, buflen, "/%d", 32-i);
549 * Return the name of the network whose address is given.
552 netname(struct sockaddr *sa, struct sockaddr *mask)
554 switch (sa->sa_family) {
557 return (netname4(satosin(sa)->sin_addr.s_addr,
558 satosin(mask)->sin_addr.s_addr));
560 return (netname4(satosin(sa)->sin_addr.s_addr,
565 return (netname6(satosin6(sa), satosin6(mask)));
573 netname4(in_addr_t in, in_addr_t mask)
576 static char line[MAXHOSTNAMELEN + sizeof("&0xffffffff")];
577 char nline[INET_ADDRSTRLEN];
578 struct netent *np = 0;
581 if (in == INADDR_ANY && mask == 0) {
582 strlcpy(line, "default", sizeof(line));
586 /* It is ok to supply host address. */
590 if (!numeric_addr && i) {
591 np = getnetbyaddr(i >> NSHIFT(ntohl(mask)), AF_INET);
594 trimdomain(cp, strlen(cp));
598 strlcpy(line, cp, sizeof(line));
600 inet_ntop(AF_INET, &in, nline, sizeof(nline));
601 strlcpy(line, nline, sizeof(line));
602 domask(line + strlen(line), sizeof(line) - strlen(line), ntohl(mask));
612 in6_fillscopeid(struct sockaddr_in6 *sa6)
614 #if defined(__KAME__)
616 * XXX: This is a special workaround for KAME kernels.
617 * sin6_scope_id field of SA should be set in the future.
619 if (IN6_IS_ADDR_LINKLOCAL(&sa6->sin6_addr) ||
620 IN6_IS_ADDR_MC_NODELOCAL(&sa6->sin6_addr) ||
621 IN6_IS_ADDR_MC_LINKLOCAL(&sa6->sin6_addr)) {
622 if (sa6->sin6_scope_id == 0)
624 ntohs(*(u_int16_t *)&sa6->sin6_addr.s6_addr[2]);
625 sa6->sin6_addr.s6_addr[2] = sa6->sin6_addr.s6_addr[3] = 0;
630 /* Mask to length table. To check an invalid value, (length + 1) is used. */
631 static const u_char masktolen[256] = {
644 netname6(struct sockaddr_in6 *sa6, struct sockaddr_in6 *mask)
646 static char line[NI_MAXHOST + sizeof("/xxx") - 1];
647 struct sockaddr_in6 addr;
648 char nline[NI_MAXHOST];
649 char maskbuf[sizeof("/xxx")];
653 bool illegal = false;
656 p = (u_char *)&mask->sin6_addr;
657 for (masklen = 0, lim = p + 16; p < lim; p++) {
658 if (masktolen[*p] > 0) {
659 /* -1 is required. */
660 masklen += (masktolen[*p] - 1);
665 xo_error("illegal prefixlen\n");
667 memcpy(&addr, sa6, sizeof(addr));
668 for (i = 0; i < 16; ++i)
669 addr.sin6_addr.s6_addr[i] &=
670 mask->sin6_addr.s6_addr[i];
676 if (masklen == 0 && IN6_IS_ADDR_UNSPECIFIED(&sa6->sin6_addr))
679 getnameinfo((struct sockaddr *)sa6, sa6->sin6_len, nline, sizeof(nline),
680 NULL, 0, NI_NUMERICHOST);
682 strlcpy(line, nline, sizeof(line));
684 getnameinfo((struct sockaddr *)sa6, sa6->sin6_len, line,
685 sizeof(line), NULL, 0, 0);
686 if (numeric_addr || strcmp(line, nline) == 0) {
687 snprintf(maskbuf, sizeof(maskbuf), "/%d", masklen);
688 strlcat(line, maskbuf, sizeof(line));
696 * Print routing statistics
701 struct rtstat rtstat;
702 u_long rtsaddr, rttaddr;
705 if ((rtsaddr = nl[N_RTSTAT].n_value) == 0) {
706 xo_emit("{W:rtstat: symbol not in namelist}\n");
709 if ((rttaddr = nl[N_RTTRASH].n_value) == 0) {
710 xo_emit("{W:rttrash: symbol not in namelist}\n");
713 kread_counters(rtsaddr, (char *)&rtstat, sizeof (rtstat));
714 kread(rttaddr, (char *)&rttrash, sizeof (rttrash));
715 xo_emit("{T:routing}:\n");
717 #define p(f, m) if (rtstat.f || sflag <= 1) \
718 xo_emit(m, rtstat.f, plural(rtstat.f))
720 p(rts_badredirect, "\t{:bad-redirects/%ju} "
721 "{N:/bad routing redirect%s}\n");
722 p(rts_dynamic, "\t{:dynamically-created/%ju} "
723 "{N:/dynamically created route%s}\n");
724 p(rts_newgateway, "\t{:new-gateways/%ju} "
725 "{N:/new gateway%s due to redirects}\n");
726 p(rts_unreach, "\t{:unreachable-destination/%ju} "
727 "{N:/destination%s found unreachable}\n");
728 p(rts_wildcard, "\t{:wildcard-uses/%ju} "
729 "{N:/use%s of a wildcard route}\n");
732 if (rttrash || sflag <= 1)
733 xo_emit("\t{:unused-but-not-freed/%u} "
734 "{N:/route%s not in table but not freed}\n",
735 rttrash, plural(rttrash));