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);
108 static const char *netname6(struct sockaddr_in6 *, struct sockaddr_in6 *);
110 static void p_rtable_sysctl(int, int);
111 static void p_rtentry_sysctl(const char *name, struct rt_msghdr *);
112 static int p_sockaddr(const char *name, struct sockaddr *, struct sockaddr *,
114 static const char *fmt_sockaddr(struct sockaddr *sa, struct sockaddr *mask,
116 static void p_flags(int, const char *);
117 static const char *fmt_flags(int f);
118 static void domask(char *, in_addr_t, u_long);
122 * Print routing tables.
125 routepr(int fibnum, int af)
133 intsize = sizeof(int);
135 sysctlbyname("net.my_fibnum", &fibnum, &intsize, NULL, 0) == -1)
137 if (sysctlbyname("net.fibs", &numfibs, &intsize, NULL, 0) == -1)
139 if (fibnum < 0 || fibnum > numfibs - 1)
140 errx(EX_USAGE, "%d: invalid fib", fibnum);
142 * Since kernel & userland use different timebase
143 * (time_uptime vs time_second) and we are reading kernel memory
144 * directly we should do rt_expire --> expire_time conversion.
146 if (clock_gettime(CLOCK_UPTIME, &uptime) < 0)
147 err(EX_OSERR, "clock_gettime() failed");
149 xo_open_container("route-information");
150 xo_emit("{T:Routing tables}");
152 xo_emit(" ({L:fib}: {:fib/%d})", fibnum);
154 p_rtable_sysctl(fibnum, af);
155 xo_close_container("route-information");
160 * Print address family header before a section of the routing table.
173 afname = "Internet6";
190 xo_emit("\n{k:address-family/%s}:\n", afname);
192 xo_emit("\n{L:Protocol Family} {k:address-family/%d}:\n", af1);
195 /* column widths; each followed by one space */
197 #define WID_DST_DEFAULT(af) 18 /* width of destination column */
198 #define WID_GW_DEFAULT(af) 18 /* width of gateway column */
199 #define WID_IF_DEFAULT(af) (Wflag ? 10 : 8) /* width of netif column */
201 #define WID_DST_DEFAULT(af) \
202 ((af) == AF_INET6 ? (numeric_addr ? 33: 18) : 18)
203 #define WID_GW_DEFAULT(af) \
204 ((af) == AF_INET6 ? (numeric_addr ? 29 : 18) : 18)
205 #define WID_IF_DEFAULT(af) ((af) == AF_INET6 ? 8 : (Wflag ? 10 : 8))
210 static int wid_flags;
211 static int wid_pksent;
214 static int wid_expire;
217 * Print header for routing table columns.
220 pr_rthdr(int af1 __unused)
224 xo_emit("{T:/%-*.*s} {T:/%-*.*s} {T:/%-*.*s} {T:/%*.*s} "
225 "{T:/%*.*s} {T:/%*.*s} {T:/%*s}\n",
226 wid_dst, wid_dst, "Destination",
227 wid_gw, wid_gw, "Gateway",
228 wid_flags, wid_flags, "Flags",
229 wid_pksent, wid_pksent, "Use",
230 wid_mtu, wid_mtu, "Mtu",
231 wid_if, wid_if, "Netif",
232 wid_expire, "Expire");
234 xo_emit("{T:/%-*.*s} {T:/%-*.*s} {T:/%-*.*s} {T:/%*.*s} "
236 wid_dst, wid_dst, "Destination",
237 wid_gw, wid_gw, "Gateway",
238 wid_flags, wid_flags, "Flags",
239 wid_if, wid_if, "Netif",
240 wid_expire, "Expire");
245 p_rtable_sysctl(int fibnum, int af)
249 char *buf, *next, *lim;
250 struct rt_msghdr *rtm;
252 int fam = AF_UNSPEC, ifindex = 0, size;
253 int need_table_close = false;
255 struct ifaddrs *ifap, *ifa;
256 struct sockaddr_dl *sdl;
259 * Retrieve interface list at first
260 * since we need #ifindex -> if_xname match
262 if (getifaddrs(&ifap) != 0)
263 err(EX_OSERR, "getifaddrs");
265 for (ifa = ifap; ifa; ifa = ifa->ifa_next) {
267 if (ifa->ifa_addr->sa_family != AF_LINK)
270 sdl = (struct sockaddr_dl *)ifa->ifa_addr;
271 ifindex = sdl->sdl_index;
273 if (ifindex >= ifmap_size) {
274 size = roundup(ifindex + 1, 32) *
275 sizeof(struct ifmap_entry);
276 if ((ifmap = realloc(ifmap, size)) == NULL)
277 errx(2, "realloc(%d) failed", size);
278 memset(&ifmap[ifmap_size], 0,
280 sizeof(struct ifmap_entry));
282 ifmap_size = roundup(ifindex + 1, 32);
285 if (*ifmap[ifindex].ifname != '\0')
288 strlcpy(ifmap[ifindex].ifname, ifa->ifa_name, IFNAMSIZ);
297 mib[4] = NET_RT_DUMP;
300 if (sysctl(mib, nitems(mib), NULL, &needed, NULL, 0) < 0)
301 err(EX_OSERR, "sysctl: net.route.0.%d.dump.%d estimate", af,
303 if ((buf = malloc(needed)) == NULL)
304 errx(2, "malloc(%lu)", (unsigned long)needed);
305 if (sysctl(mib, nitems(mib), buf, &needed, NULL, 0) < 0)
306 err(1, "sysctl: net.route.0.%d.dump.%d", af, fibnum);
308 xo_open_container("route-table");
309 xo_open_list("rt-family");
310 for (next = buf; next < lim; next += rtm->rtm_msglen) {
311 rtm = (struct rt_msghdr *)next;
312 if (rtm->rtm_version != RTM_VERSION)
315 * Peek inside header to determine AF
317 sa = (struct sockaddr *)(rtm + 1);
318 /* Only print family first time. */
319 if (fam != sa->sa_family) {
320 if (need_table_close) {
321 xo_close_list("rt-entry");
322 xo_close_instance("rt-family");
324 need_table_close = true;
327 wid_dst = WID_DST_DEFAULT(fam);
328 wid_gw = WID_GW_DEFAULT(fam);
332 wid_if = WID_IF_DEFAULT(fam);
334 xo_open_instance("rt-family");
336 xo_open_list("rt-entry");
340 p_rtentry_sysctl("rt-entry", rtm);
342 if (need_table_close) {
343 xo_close_list("rt-entry");
344 xo_close_instance("rt-family");
346 xo_close_list("rt-family");
347 xo_close_container("route-table");
352 p_rtentry_sysctl(const char *name, struct rt_msghdr *rtm)
354 struct sockaddr *sa, *addr[RTAX_MAX];
356 char prettyname[128];
359 xo_open_instance(name);
360 sa = (struct sockaddr *)(rtm + 1);
361 for (i = 0; i < RTAX_MAX; i++) {
362 if (rtm->rtm_addrs & (1 << i))
364 sa = (struct sockaddr *)((char *)sa + SA_SIZE(sa));
367 protrusion = p_sockaddr("destination", addr[RTAX_DST],
369 rtm->rtm_flags, wid_dst);
370 protrusion = p_sockaddr("gateway", addr[RTAX_GATEWAY], NULL, RTF_HOST,
371 wid_gw - protrusion);
372 snprintf(buffer, sizeof(buffer), "{[:-%d}{:flags/%%s}{]:} ",
373 wid_flags - protrusion);
374 p_flags(rtm->rtm_flags, buffer);
376 xo_emit("{t:use/%*lu} ", wid_pksent, rtm->rtm_rmx.rmx_pksent);
378 if (rtm->rtm_rmx.rmx_mtu != 0)
379 xo_emit("{t:mtu/%*lu} ", wid_mtu, rtm->rtm_rmx.rmx_mtu);
381 xo_emit("{P:/%*s} ", wid_mtu, "");
384 memset(prettyname, 0, sizeof(prettyname));
385 if (rtm->rtm_index < ifmap_size) {
386 strlcpy(prettyname, ifmap[rtm->rtm_index].ifname,
388 if (*prettyname == '\0')
389 strlcpy(prettyname, "---", sizeof(prettyname));
393 xo_emit("{t:interface-name/%*s}", wid_if, prettyname);
395 xo_emit("{t:interface-name/%*.*s}", wid_if, wid_if,
397 if (rtm->rtm_rmx.rmx_expire) {
400 if ((expire_time = rtm->rtm_rmx.rmx_expire - uptime.tv_sec) > 0)
401 xo_emit(" {:expire-time/%*d}", wid_expire,
406 xo_close_instance(name);
410 p_sockaddr(const char *name, struct sockaddr *sa, struct sockaddr *mask,
411 int flags, int width)
417 cp = fmt_sockaddr(sa, mask, flags);
420 snprintf(buf, sizeof(buf), "{:%s/%%s} ", name);
424 if (Wflag != 0 || numeric_addr) {
425 snprintf(buf, sizeof(buf), "{[:%d}{:%s/%%s}{]:} ",
428 protrusion = strlen(cp) - width;
432 snprintf(buf, sizeof(buf), "{[:%d}{:%s/%%-.*s}{]:} ",
434 xo_emit(buf, width, cp);
442 fmt_sockaddr(struct sockaddr *sa, struct sockaddr *mask, int flags)
444 static char buf[128];
450 switch(sa->sa_family) {
454 * The sa6->sin6_scope_id must be filled here because
455 * this sockaddr is extracted from kmem(4) directly
456 * and has KAME-specific embedded scope id in
457 * sa6->sin6_addr.s6_addr[2].
459 in6_fillscopeid(satosin6(sa));
463 if (flags & RTF_HOST)
464 cp = routename(sa, numeric_addr);
466 cp = netname(sa, mask);
468 cp = netname(sa, NULL);
472 strlcpy(buf, ((struct sockaddr_ng *)sa)->sg_data,
480 struct sockaddr_dl *sdl = (struct sockaddr_dl *)sa;
482 /* Interface route. */
487 cp = routename(sa, 1);
492 u_char *s = (u_char *)sa->sa_data, *slim;
496 slim = sa->sa_len + (u_char *) sa;
497 cqlim = cq + sizeof(buf) - 6;
498 cq += sprintf(cq, "(%d)", sa->sa_family);
499 while (s < slim && cq < cqlim) {
500 cq += sprintf(cq, " %02x", *s++);
502 cq += sprintf(cq, "%02x", *s++);
512 p_flags(int f, const char *format)
516 xo_emit(format, fmt_flags(f));
518 xo_open_list("flags_pretty");
519 for (p = bits; p->b_mask; p++)
521 xo_emit("{le:flags_pretty/%s}", p->b_name);
522 xo_close_list("flags_pretty");
528 static char name[33];
530 struct bits *p = bits;
532 for (flags = name; p->b_mask; p++)
540 routename(struct sockaddr *sa, int flags)
542 static char line[NI_MAXHOST];
545 f = (flags) ? NI_NUMERICHOST : 0;
546 error = getnameinfo(sa, sa->sa_len, line, sizeof(line),
550 switch (sa->sa_family) {
553 src = &satosin(sa)->sin_addr;
558 src = &satosin6(sa)->sin6_addr;
564 inet_ntop(sa->sa_family, src, line, sizeof(line) - 1);
567 trimdomain(line, strlen(line));
572 #define NSHIFT(m) ( \
573 (m) == IN_CLASSA_NET ? IN_CLASSA_NSHIFT : \
574 (m) == IN_CLASSB_NET ? IN_CLASSB_NSHIFT : \
575 (m) == IN_CLASSC_NET ? IN_CLASSC_NSHIFT : \
579 domask(char *dst, in_addr_t addr __unused, u_long mask)
588 for (b = 0; b < 32; b++)
589 if (mask & (1 << b)) {
593 for (bb = b+1; bb < 32; bb++)
594 if (!(mask & (1 << bb))) {
595 i = -1; /* noncontig */
601 sprintf(dst, "&0x%lx", mask);
603 sprintf(dst, "/%d", 32-i);
607 * Return the name of the network whose address is given.
610 netname(struct sockaddr *sa, struct sockaddr *mask)
612 switch (sa->sa_family) {
615 return (netname4(satosin(sa)->sin_addr.s_addr,
616 satosin(mask)->sin_addr.s_addr));
618 return (netname4(satosin(sa)->sin_addr.s_addr,
623 return (netname6(satosin6(sa), satosin6(mask)));
631 netname4(in_addr_t in, in_addr_t mask)
634 static char line[MAXHOSTNAMELEN + sizeof("/xx")];
635 char nline[INET_ADDRSTRLEN];
636 struct netent *np = 0;
639 if (in == INADDR_ANY && mask == 0) {
640 strlcpy(line, "default", sizeof(line));
644 /* It is ok to supply host address. */
648 if (!numeric_addr && i) {
649 np = getnetbyaddr(i >> NSHIFT(ntohl(mask)), AF_INET);
652 trimdomain(cp, strlen(cp));
656 strlcpy(line, cp, sizeof(line));
658 inet_ntop(AF_INET, &in, nline, sizeof(nline));
659 strlcpy(line, nline, sizeof(line));
660 domask(line + strlen(line), i, ntohl(mask));
670 in6_fillscopeid(struct sockaddr_in6 *sa6)
672 #if defined(__KAME__)
674 * XXX: This is a special workaround for KAME kernels.
675 * sin6_scope_id field of SA should be set in the future.
677 if (IN6_IS_ADDR_LINKLOCAL(&sa6->sin6_addr) ||
678 IN6_IS_ADDR_MC_NODELOCAL(&sa6->sin6_addr) ||
679 IN6_IS_ADDR_MC_LINKLOCAL(&sa6->sin6_addr)) {
680 if (sa6->sin6_scope_id == 0)
682 ntohs(*(u_int16_t *)&sa6->sin6_addr.s6_addr[2]);
683 sa6->sin6_addr.s6_addr[2] = sa6->sin6_addr.s6_addr[3] = 0;
688 /* Mask to length table. To check an invalid value, (length + 1) is used. */
689 static int masktolen[256] = {
702 netname6(struct sockaddr_in6 *sa6, struct sockaddr_in6 *mask)
704 static char line[NI_MAXHOST + sizeof("/xxx") - 1];
705 struct sockaddr_in6 addr;
706 char nline[NI_MAXHOST];
708 int masklen, illegal = 0, i;
711 p = (u_char *)&mask->sin6_addr;
712 for (masklen = 0, lim = p + 16; p < lim; p++) {
713 if (masktolen[*p] > 0)
714 /* -1 is required. */
715 masklen += masktolen[*p] - 1;
720 xo_error("illegal prefixlen\n");
722 memcpy(&addr, sa6, sizeof(addr));
723 for (i = 0; i < 16; ++i)
724 addr.sin6_addr.s6_addr[i] &=
725 mask->sin6_addr.s6_addr[i];
731 if (masklen == 0 && IN6_IS_ADDR_UNSPECIFIED(&sa6->sin6_addr))
734 getnameinfo((struct sockaddr *)sa6, sa6->sin6_len, nline, sizeof(nline),
735 NULL, 0, NI_NUMERICHOST);
737 strlcpy(line, nline, sizeof(line));
739 getnameinfo((struct sockaddr *)sa6, sa6->sin6_len, line,
740 sizeof(line), NULL, 0, 0);
741 if (numeric_addr || strcmp(line, nline) == 0)
742 sprintf(&line[strlen(line)], "/%d", masklen);
749 * Print routing statistics
754 struct rtstat rtstat;
755 u_long rtsaddr, rttaddr;
758 if ((rtsaddr = nl[N_RTSTAT].n_value) == 0) {
759 xo_emit("{W:rtstat: symbol not in namelist}\n");
762 if ((rttaddr = nl[N_RTTRASH].n_value) == 0) {
763 xo_emit("{W:rttrash: symbol not in namelist}\n");
766 kread(rtsaddr, (char *)&rtstat, sizeof (rtstat));
767 kread(rttaddr, (char *)&rttrash, sizeof (rttrash));
768 xo_emit("{T:routing}:\n");
770 #define p(f, m) if (rtstat.f || sflag <= 1) \
771 xo_emit(m, rtstat.f, plural(rtstat.f))
773 p(rts_badredirect, "\t{:bad-redirects/%hu} "
774 "{N:/bad routing redirect%s}\n");
775 p(rts_dynamic, "\t{:dynamically-created/%hu} "
776 "{N:/dynamically created route%s}\n");
777 p(rts_newgateway, "\t{:new-gateways/%hu} "
778 "{N:/new gateway%s due to redirects}\n");
779 p(rts_unreach, "\t{:unreachable-destination/%hu} "
780 "{N:/destination%s found unreachable}\n");
781 p(rts_wildcard, "\t{:wildcard-uses/%hu} "
782 "{N:/use%s of a wildcard route}\n");
785 if (rttrash || sflag <= 1)
786 xo_emit("\t{:unused-but-not-freed/%u} "
787 "{N:/route%s not in table but not freed}\n",
788 rttrash, plural(rttrash));