]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - usr.bin/netstat/route.c
Merge branch 'releng/11.2' into releng-CDN/11.2
[FreeBSD/FreeBSD.git] / usr.bin / netstat / route.c
1 /*-
2  * Copyright (c) 1983, 1988, 1993
3  *      The Regents of the University of California.  All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
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.
16  *
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
27  * SUCH DAMAGE.
28  */
29
30 #if 0
31 #ifndef lint
32 static char sccsid[] = "From: @(#)route.c       8.6 (Berkeley) 4/28/95";
33 #endif /* not lint */
34 #endif
35
36 #include <sys/cdefs.h>
37 __FBSDID("$FreeBSD$");
38
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>
44 #include <sys/time.h>
45
46 #include <net/ethernet.h>
47 #include <net/if.h>
48 #include <net/if_dl.h>
49 #include <net/if_types.h>
50 #include <net/route.h>
51
52 #include <netinet/in.h>
53 #include <netgraph/ng_socket.h>
54
55 #include <arpa/inet.h>
56 #include <ifaddrs.h>
57 #include <libutil.h>
58 #include <netdb.h>
59 #include <stdbool.h>
60 #include <stdint.h>
61 #include <stdio.h>
62 #include <stdlib.h>
63 #include <stdbool.h>
64 #include <string.h>
65 #include <sysexits.h>
66 #include <unistd.h>
67 #include <err.h>
68 #include <libxo/xo.h>
69 #include "netstat.h"
70 #include "nl_defs.h"
71
72 /*
73  * Definitions for showing gateway flags.
74  */
75 static struct bits {
76         u_long  b_mask;
77         char    b_val;
78         const char *b_name;
79 } bits[] = {
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" },
94 #ifdef RTF_LLINFO
95         { RTF_LLINFO,   'L', "llinfo" },
96 #endif
97         { 0 , 0, NULL }
98 };
99
100 struct ifmap_entry {
101         char ifname[IFNAMSIZ];
102 };
103 static struct ifmap_entry *ifmap;
104 static int ifmap_size;
105 static struct timespec uptime;
106
107 static const char *netname4(in_addr_t, in_addr_t);
108 static const char *netname6(struct sockaddr_in6 *, struct sockaddr_in6 *);
109 static void p_rtable_sysctl(int, int);
110 static void p_rtentry_sysctl(const char *name, struct rt_msghdr *);
111 static int p_sockaddr(const char *name, struct sockaddr *, struct sockaddr *,
112     int, int);
113 static const char *fmt_sockaddr(struct sockaddr *sa, struct sockaddr *mask,
114     int flags);
115 static void p_flags(int, const char *);
116 static const char *fmt_flags(int f);
117 static void domask(char *, size_t, u_long);
118
119
120 /*
121  * Print routing tables.
122  */
123 void
124 routepr(int fibnum, int af)
125 {
126         size_t intsize;
127         int numfibs;
128
129         if (live == 0)
130                 return;
131
132         intsize = sizeof(int);
133         if (fibnum == -1 &&
134             sysctlbyname("net.my_fibnum", &fibnum, &intsize, NULL, 0) == -1)
135                 fibnum = 0;
136         if (sysctlbyname("net.fibs", &numfibs, &intsize, NULL, 0) == -1)
137                 numfibs = 1;
138         if (fibnum < 0 || fibnum > numfibs - 1)
139                 errx(EX_USAGE, "%d: invalid fib", fibnum);
140         /*
141          * Since kernel & userland use different timebase
142          * (time_uptime vs time_second) and we are reading kernel memory
143          * directly we should do rt_expire --> expire_time conversion.
144          */
145         if (clock_gettime(CLOCK_UPTIME, &uptime) < 0)
146                 err(EX_OSERR, "clock_gettime() failed");
147
148         xo_open_container("route-information");
149         xo_emit("{T:Routing tables}");
150         if (fibnum)
151                 xo_emit(" ({L:fib}: {:fib/%d})", fibnum);
152         xo_emit("\n");
153         p_rtable_sysctl(fibnum, af);
154         xo_close_container("route-information");
155 }
156
157
158 /*
159  * Print address family header before a section of the routing table.
160  */
161 void
162 pr_family(int af1)
163 {
164         const char *afname;
165
166         switch (af1) {
167         case AF_INET:
168                 afname = "Internet";
169                 break;
170 #ifdef INET6
171         case AF_INET6:
172                 afname = "Internet6";
173                 break;
174 #endif /*INET6*/
175         case AF_ISO:
176                 afname = "ISO";
177                 break;
178         case AF_CCITT:
179                 afname = "X.25";
180                 break;
181         case AF_NETGRAPH:
182                 afname = "Netgraph";
183                 break;
184         default:
185                 afname = NULL;
186                 break;
187         }
188         if (afname)
189                 xo_emit("\n{k:address-family/%s}:\n", afname);
190         else
191                 xo_emit("\n{L:Protocol Family} {k:address-family/%d}:\n", af1);
192 }
193
194 /* column widths; each followed by one space */
195 #ifndef INET6
196 #define WID_DST_DEFAULT(af)     18      /* width of destination column */
197 #define WID_GW_DEFAULT(af)      18      /* width of gateway column */
198 #define WID_IF_DEFAULT(af)      (Wflag ? 10 : 8) /* width of netif column */
199 #else
200 #define WID_DST_DEFAULT(af) \
201         ((af) == AF_INET6 ? (numeric_addr ? 33: 18) : 18)
202 #define WID_GW_DEFAULT(af) \
203         ((af) == AF_INET6 ? (numeric_addr ? 29 : 18) : 18)
204 #define WID_IF_DEFAULT(af)      ((af) == AF_INET6 ? 8 : (Wflag ? 10 : 8))
205 #endif /*INET6*/
206
207 static int wid_dst;
208 static int wid_gw;
209 static int wid_flags;
210 static int wid_pksent;
211 static int wid_mtu;
212 static int wid_if;
213 static int wid_expire;
214
215 /*
216  * Print header for routing table columns.
217  */
218 static void
219 pr_rthdr(int af1 __unused)
220 {
221
222         if (Wflag) {
223                 xo_emit("{T:/%-*.*s} {T:/%-*.*s} {T:/%-*.*s} {T:/%*.*s} "
224                     "{T:/%*.*s} {T:/%*.*s} {T:/%*s}\n",
225                         wid_dst,        wid_dst,        "Destination",
226                         wid_gw,         wid_gw,         "Gateway",
227                         wid_flags,      wid_flags,      "Flags",
228                         wid_pksent,     wid_pksent,     "Use",
229                         wid_mtu,        wid_mtu,        "Mtu",
230                         wid_if,         wid_if,         "Netif",
231                         wid_expire,                     "Expire");
232         } else {
233                 xo_emit("{T:/%-*.*s} {T:/%-*.*s} {T:/%-*.*s} {T:/%*.*s} "
234                     "{T:/%*s}\n",
235                         wid_dst,        wid_dst,        "Destination",
236                         wid_gw,         wid_gw,         "Gateway",
237                         wid_flags,      wid_flags,      "Flags",
238                         wid_if,         wid_if,         "Netif",
239                         wid_expire,                     "Expire");
240         }
241 }
242
243 static void
244 p_rtable_sysctl(int fibnum, int af)
245 {
246         size_t needed;
247         int mib[7];
248         char *buf, *next, *lim;
249         struct rt_msghdr *rtm;
250         struct sockaddr *sa;
251         int fam = AF_UNSPEC, ifindex = 0, size;
252         int need_table_close = false;
253
254         struct ifaddrs *ifap, *ifa;
255         struct sockaddr_dl *sdl;
256
257         /*
258          * Retrieve interface list at first
259          * since we need #ifindex -> if_xname match
260          */
261         if (getifaddrs(&ifap) != 0)
262                 err(EX_OSERR, "getifaddrs");
263
264         for (ifa = ifap; ifa; ifa = ifa->ifa_next) {
265                 
266                 if (ifa->ifa_addr->sa_family != AF_LINK)
267                         continue;
268
269                 sdl = (struct sockaddr_dl *)ifa->ifa_addr;
270                 ifindex = sdl->sdl_index;
271
272                 if (ifindex >= ifmap_size) {
273                         size = roundup(ifindex + 1, 32) *
274                             sizeof(struct ifmap_entry);
275                         if ((ifmap = realloc(ifmap, size)) == NULL)
276                                 errx(2, "realloc(%d) failed", size);
277                         memset(&ifmap[ifmap_size], 0,
278                             size - ifmap_size *
279                             sizeof(struct ifmap_entry));
280
281                         ifmap_size = roundup(ifindex + 1, 32);
282                 }
283
284                 if (*ifmap[ifindex].ifname != '\0')
285                         continue;
286
287                 strlcpy(ifmap[ifindex].ifname, ifa->ifa_name, IFNAMSIZ);
288         }
289
290         freeifaddrs(ifap);
291
292         mib[0] = CTL_NET;
293         mib[1] = PF_ROUTE;
294         mib[2] = 0;
295         mib[3] = af;
296         mib[4] = NET_RT_DUMP;
297         mib[5] = 0;
298         mib[6] = fibnum;
299         if (sysctl(mib, nitems(mib), NULL, &needed, NULL, 0) < 0)
300                 err(EX_OSERR, "sysctl: net.route.0.%d.dump.%d estimate", af,
301                     fibnum);
302         if ((buf = malloc(needed)) == NULL)
303                 errx(2, "malloc(%lu)", (unsigned long)needed);
304         if (sysctl(mib, nitems(mib), buf, &needed, NULL, 0) < 0)
305                 err(1, "sysctl: net.route.0.%d.dump.%d", af, fibnum);
306         lim  = buf + needed;
307         xo_open_container("route-table");
308         xo_open_list("rt-family");
309         for (next = buf; next < lim; next += rtm->rtm_msglen) {
310                 rtm = (struct rt_msghdr *)next;
311                 if (rtm->rtm_version != RTM_VERSION)
312                         continue;
313                 /*
314                  * Peek inside header to determine AF
315                  */
316                 sa = (struct sockaddr *)(rtm + 1);
317                 /* Only print family first time. */
318                 if (fam != sa->sa_family) {
319                         if (need_table_close) {
320                                 xo_close_list("rt-entry");
321                                 xo_close_instance("rt-family");
322                         }
323                         need_table_close = true;
324
325                         fam = sa->sa_family;
326                         wid_dst = WID_DST_DEFAULT(fam);
327                         wid_gw = WID_GW_DEFAULT(fam);
328                         wid_flags = 6;
329                         wid_pksent = 8;
330                         wid_mtu = 6;
331                         wid_if = WID_IF_DEFAULT(fam);
332                         wid_expire = 6;
333                         xo_open_instance("rt-family");
334                         pr_family(fam);
335                         xo_open_list("rt-entry");
336
337                         pr_rthdr(fam);
338                 }
339                 p_rtentry_sysctl("rt-entry", rtm);
340         }
341         if (need_table_close) {
342                 xo_close_list("rt-entry");
343                 xo_close_instance("rt-family");
344         }
345         xo_close_list("rt-family");
346         xo_close_container("route-table");
347         free(buf);
348 }
349
350 static void
351 p_rtentry_sysctl(const char *name, struct rt_msghdr *rtm)
352 {
353         struct sockaddr *sa, *addr[RTAX_MAX];
354         char buffer[128];
355         char prettyname[128];
356         int i, protrusion;
357
358         xo_open_instance(name);
359         sa = (struct sockaddr *)(rtm + 1);
360         for (i = 0; i < RTAX_MAX; i++) {
361                 if (rtm->rtm_addrs & (1 << i))
362                         addr[i] = sa;
363                 sa = (struct sockaddr *)((char *)sa + SA_SIZE(sa));
364         }
365
366         protrusion = p_sockaddr("destination", addr[RTAX_DST],
367             addr[RTAX_NETMASK],
368             rtm->rtm_flags, wid_dst);
369         protrusion = p_sockaddr("gateway", addr[RTAX_GATEWAY], NULL, RTF_HOST,
370             wid_gw - protrusion);
371         snprintf(buffer, sizeof(buffer), "{[:-%d}{:flags/%%s}{]:} ",
372             wid_flags - protrusion);
373         p_flags(rtm->rtm_flags, buffer);
374         if (Wflag) {
375                 xo_emit("{t:use/%*lu} ", wid_pksent, rtm->rtm_rmx.rmx_pksent);
376
377                 if (rtm->rtm_rmx.rmx_mtu != 0)
378                         xo_emit("{t:mtu/%*lu} ", wid_mtu, rtm->rtm_rmx.rmx_mtu);
379                 else
380                         xo_emit("{P:/%*s} ", wid_mtu, "");
381         }
382
383         memset(prettyname, 0, sizeof(prettyname));
384         if (rtm->rtm_index < ifmap_size) {
385                 strlcpy(prettyname, ifmap[rtm->rtm_index].ifname,
386                     sizeof(prettyname));
387                 if (*prettyname == '\0')
388                         strlcpy(prettyname, "---", sizeof(prettyname));
389         }
390
391         if (Wflag)
392                 xo_emit("{t:interface-name/%*s}", wid_if, prettyname);
393         else
394                 xo_emit("{t:interface-name/%*.*s}", wid_if, wid_if,
395                     prettyname);
396         if (rtm->rtm_rmx.rmx_expire) {
397                 time_t expire_time;
398
399                 if ((expire_time = rtm->rtm_rmx.rmx_expire - uptime.tv_sec) > 0)
400                         xo_emit(" {:expire-time/%*d}", wid_expire,
401                             (int)expire_time);
402         }
403
404         xo_emit("\n");
405         xo_close_instance(name);
406 }
407
408 static int
409 p_sockaddr(const char *name, struct sockaddr *sa, struct sockaddr *mask,
410     int flags, int width)
411 {
412         const char *cp;
413         char buf[128];
414         int protrusion;
415
416         cp = fmt_sockaddr(sa, mask, flags);
417
418         if (width < 0) {
419                 snprintf(buf, sizeof(buf), "{:%s/%%s} ", name);
420                 xo_emit(buf, cp);
421                 protrusion = 0;
422         } else {
423                 if (Wflag != 0 || numeric_addr) {
424                         snprintf(buf, sizeof(buf), "{[:%d}{:%s/%%s}{]:} ",
425                             -width, name);
426                         xo_emit(buf, cp);
427                         protrusion = strlen(cp) - width;
428                         if (protrusion < 0)
429                                 protrusion = 0;
430                 } else {
431                         snprintf(buf, sizeof(buf), "{[:%d}{:%s/%%-.*s}{]:} ",
432                             -width, name);
433                         xo_emit(buf, width, cp);
434                         protrusion = 0;
435                 }
436         }
437         return (protrusion);
438 }
439
440 static const char *
441 fmt_sockaddr(struct sockaddr *sa, struct sockaddr *mask, int flags)
442 {
443         static char buf[128];
444         const char *cp;
445
446         if (sa == NULL)
447                 return ("null");
448
449         switch(sa->sa_family) {
450 #ifdef INET6
451         case AF_INET6:
452                 /*
453                  * The sa6->sin6_scope_id must be filled here because
454                  * this sockaddr is extracted from kmem(4) directly
455                  * and has KAME-specific embedded scope id in
456                  * sa6->sin6_addr.s6_addr[2].
457                  */
458                 in6_fillscopeid(satosin6(sa));
459                 /* FALLTHROUGH */
460 #endif /*INET6*/
461         case AF_INET:
462                 if (flags & RTF_HOST)
463                         cp = routename(sa, numeric_addr);
464                 else if (mask)
465                         cp = netname(sa, mask);
466                 else
467                         cp = netname(sa, NULL);
468                 break;
469         case AF_NETGRAPH:
470             {
471                 strlcpy(buf, ((struct sockaddr_ng *)sa)->sg_data,
472                     sizeof(buf));
473                 cp = buf;
474                 break;
475             }
476         case AF_LINK:
477             {
478 #if 0
479                 struct sockaddr_dl *sdl = (struct sockaddr_dl *)sa;
480
481                 /* Interface route. */
482                 if (sdl->sdl_nlen)
483                         cp = sdl->sdl_data;
484                 else
485 #endif
486                         cp = routename(sa, 1);
487                 break;
488             }
489         default:
490             {
491                 u_char *s = (u_char *)sa->sa_data, *slim;
492                 char *cq, *cqlim;
493
494                 cq = buf;
495                 slim =  sa->sa_len + (u_char *) sa;
496                 cqlim = cq + sizeof(buf) - sizeof(" ffff");
497                 snprintf(cq, sizeof(buf), "(%d)", sa->sa_family);
498                 cq += strlen(cq);
499                 while (s < slim && cq < cqlim) {
500                         snprintf(cq, sizeof(" ff"), " %02x", *s++);
501                         cq += strlen(cq);
502                         if (s < slim) {
503                             snprintf(cq, sizeof("ff"), "%02x", *s++);
504                             cq += strlen(cq);
505                         }
506                 }
507                 cp = buf;
508             }
509         }
510
511         return (cp);
512 }
513
514 static void
515 p_flags(int f, const char *format)
516 {
517         struct bits *p;
518
519         xo_emit(format, fmt_flags(f));
520
521         xo_open_list("flags_pretty");
522         for (p = bits; p->b_mask; p++)
523                 if (p->b_mask & f)
524                         xo_emit("{le:flags_pretty/%s}", p->b_name);
525         xo_close_list("flags_pretty");
526 }
527
528 static const char *
529 fmt_flags(int f)
530 {
531         static char name[33];
532         char *flags;
533         struct bits *p = bits;
534
535         for (flags = name; p->b_mask; p++)
536                 if (p->b_mask & f)
537                         *flags++ = p->b_val;
538         *flags = '\0';
539         return (name);
540 }
541
542 char *
543 routename(struct sockaddr *sa, int flags)
544 {
545         static char line[NI_MAXHOST];
546         int error, f;
547
548         f = (flags) ? NI_NUMERICHOST : 0;
549         error = getnameinfo(sa, sa->sa_len, line, sizeof(line),
550             NULL, 0, f);
551         if (error) {
552                 const void *src;
553                 switch (sa->sa_family) {
554 #ifdef INET
555                 case AF_INET:
556                         src = &satosin(sa)->sin_addr;
557                         break;
558 #endif /* INET */
559 #ifdef INET6
560                 case AF_INET6:
561                         src = &satosin6(sa)->sin6_addr;
562                         break;
563 #endif /* INET6 */
564                 default:
565                         return(line);
566                 }
567                 inet_ntop(sa->sa_family, src, line, sizeof(line) - 1);
568                 return (line);
569         }
570         trimdomain(line, strlen(line));
571
572         return (line);
573 }
574
575 #define NSHIFT(m) (                                                     \
576         (m) == IN_CLASSA_NET ? IN_CLASSA_NSHIFT :                       \
577         (m) == IN_CLASSB_NET ? IN_CLASSB_NSHIFT :                       \
578         (m) == IN_CLASSC_NET ? IN_CLASSC_NSHIFT :                       \
579         0)
580
581 static void
582 domask(char *dst, size_t buflen, u_long mask)
583 {
584         int b, i;
585
586         if (mask == 0) {
587                 *dst = '\0';
588                 return;
589         }
590         i = 0;
591         for (b = 0; b < 32; b++)
592                 if (mask & (1 << b)) {
593                         int bb;
594
595                         i = b;
596                         for (bb = b+1; bb < 32; bb++)
597                                 if (!(mask & (1 << bb))) {
598                                         i = -1; /* noncontig */
599                                         break;
600                                 }
601                         break;
602                 }
603         if (i == -1)
604                 snprintf(dst, buflen, "&0x%lx", mask);
605         else
606                 snprintf(dst, buflen, "/%d", 32-i);
607 }
608
609 /*
610  * Return the name of the network whose address is given.
611  */
612 const char *
613 netname(struct sockaddr *sa, struct sockaddr *mask)
614 {
615         switch (sa->sa_family) {
616         case AF_INET:
617                 if (mask != NULL)
618                         return (netname4(satosin(sa)->sin_addr.s_addr,
619                             satosin(mask)->sin_addr.s_addr));
620                 else
621                         return (netname4(satosin(sa)->sin_addr.s_addr,
622                             INADDR_ANY));
623                 break;
624 #ifdef INET6
625         case AF_INET6:
626                 return (netname6(satosin6(sa), satosin6(mask)));
627 #endif /* INET6 */
628         default:
629                 return (NULL);
630         }
631 }
632
633 static const char *
634 netname4(in_addr_t in, in_addr_t mask)
635 {
636         char *cp = 0;
637         static char line[MAXHOSTNAMELEN + sizeof("&0xffffffff")];
638         char nline[INET_ADDRSTRLEN];
639         struct netent *np = 0;
640         in_addr_t i;
641
642         if (in == INADDR_ANY && mask == 0) {
643                 strlcpy(line, "default", sizeof(line));
644                 return (line);
645         }
646
647         /* It is ok to supply host address. */
648         in &= mask;
649
650         i = ntohl(in);
651         if (!numeric_addr && i) {
652                 np = getnetbyaddr(i >> NSHIFT(ntohl(mask)), AF_INET);
653                 if (np != NULL) {
654                         cp = np->n_name;
655                         trimdomain(cp, strlen(cp));
656                 }
657         }
658         if (cp != NULL)
659                 strlcpy(line, cp, sizeof(line));
660         else {
661                 inet_ntop(AF_INET, &in, nline, sizeof(nline));
662                 strlcpy(line, nline, sizeof(line));
663                 domask(line + strlen(line), sizeof(line) - strlen(line), ntohl(mask));
664         }
665
666         return (line);
667 }
668
669 #undef NSHIFT
670
671 #ifdef INET6
672 void
673 in6_fillscopeid(struct sockaddr_in6 *sa6)
674 {
675 #if defined(__KAME__)
676         /*
677          * XXX: This is a special workaround for KAME kernels.
678          * sin6_scope_id field of SA should be set in the future.
679          */
680         if (IN6_IS_ADDR_LINKLOCAL(&sa6->sin6_addr) ||
681             IN6_IS_ADDR_MC_NODELOCAL(&sa6->sin6_addr) ||
682             IN6_IS_ADDR_MC_LINKLOCAL(&sa6->sin6_addr)) {
683                 if (sa6->sin6_scope_id == 0)
684                         sa6->sin6_scope_id =
685                             ntohs(*(u_int16_t *)&sa6->sin6_addr.s6_addr[2]);
686                 sa6->sin6_addr.s6_addr[2] = sa6->sin6_addr.s6_addr[3] = 0;
687         }
688 #endif
689 }
690
691 /* Mask to length table.  To check an invalid value, (length + 1) is used. */
692 static const u_char masktolen[256] = {
693         [0xff] = 8 + 1,
694         [0xfe] = 7 + 1,
695         [0xfc] = 6 + 1,
696         [0xf8] = 5 + 1,
697         [0xf0] = 4 + 1,
698         [0xe0] = 3 + 1,
699         [0xc0] = 2 + 1,
700         [0x80] = 1 + 1,
701         [0x00] = 0 + 1,
702 };
703
704 static const char *
705 netname6(struct sockaddr_in6 *sa6, struct sockaddr_in6 *mask)
706 {
707         static char line[NI_MAXHOST + sizeof("/xxx") - 1];
708         struct sockaddr_in6 addr;
709         char nline[NI_MAXHOST];
710         char maskbuf[sizeof("/xxx")];
711         u_char *p, *lim;
712         u_char masklen;
713         int i;
714         bool illegal = false;
715
716         if (mask) {
717                 p = (u_char *)&mask->sin6_addr;
718                 for (masklen = 0, lim = p + 16; p < lim; p++) {
719                         if (masktolen[*p] > 0) {
720                                 /* -1 is required. */
721                                 masklen += (masktolen[*p] - 1);
722                         } else
723                                 illegal = true;
724                 }
725                 if (illegal)
726                         xo_error("illegal prefixlen\n");
727
728                 memcpy(&addr, sa6, sizeof(addr));
729                 for (i = 0; i < 16; ++i)
730                         addr.sin6_addr.s6_addr[i] &=
731                             mask->sin6_addr.s6_addr[i];
732                 sa6 = &addr;
733         }
734         else
735                 masklen = 128;
736
737         if (masklen == 0 && IN6_IS_ADDR_UNSPECIFIED(&sa6->sin6_addr))
738                 return("default");
739
740         getnameinfo((struct sockaddr *)sa6, sa6->sin6_len, nline, sizeof(nline),
741             NULL, 0, NI_NUMERICHOST);
742         if (numeric_addr)
743                 strlcpy(line, nline, sizeof(line));
744         else
745                 getnameinfo((struct sockaddr *)sa6, sa6->sin6_len, line,
746                     sizeof(line), NULL, 0, 0);
747         if (numeric_addr || strcmp(line, nline) == 0) {
748                 snprintf(maskbuf, sizeof(maskbuf), "/%d", masklen);
749                 strlcat(line, maskbuf, sizeof(line));
750         }
751
752         return (line);
753 }
754 #endif /*INET6*/
755
756 /*
757  * Print routing statistics
758  */
759 void
760 rt_stats(void)
761 {
762         struct rtstat rtstat;
763         u_long rtsaddr, rttaddr;
764         int rttrash;
765
766         if ((rtsaddr = nl[N_RTSTAT].n_value) == 0) {
767                 xo_emit("{W:rtstat: symbol not in namelist}\n");
768                 return;
769         }
770         if ((rttaddr = nl[N_RTTRASH].n_value) == 0) {
771                 xo_emit("{W:rttrash: symbol not in namelist}\n");
772                 return;
773         }
774         kread(rtsaddr, (char *)&rtstat, sizeof (rtstat));
775         kread(rttaddr, (char *)&rttrash, sizeof (rttrash));
776         xo_emit("{T:routing}:\n");
777
778 #define p(f, m) if (rtstat.f || sflag <= 1) \
779         xo_emit(m, rtstat.f, plural(rtstat.f))
780
781         p(rts_badredirect, "\t{:bad-redirects/%hu} "
782             "{N:/bad routing redirect%s}\n");
783         p(rts_dynamic, "\t{:dynamically-created/%hu} "
784             "{N:/dynamically created route%s}\n");
785         p(rts_newgateway, "\t{:new-gateways/%hu} "
786             "{N:/new gateway%s due to redirects}\n");
787         p(rts_unreach, "\t{:unreachable-destination/%hu} "
788             "{N:/destination%s found unreachable}\n");
789         p(rts_wildcard, "\t{:wildcard-uses/%hu} "
790             "{N:/use%s of a wildcard route}\n");
791 #undef p
792
793         if (rttrash || sflag <= 1)
794                 xo_emit("\t{:unused-but-not-freed/%u} "
795                     "{N:/route%s not in table but not freed}\n",
796                     rttrash, plural(rttrash));
797 }