5bca67d0088c552ff9d0ec29786a106fd5a9a899
[dragonfly.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  * 3. 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  * @(#)route.c  8.6 (Berkeley) 4/28/95
30  * $FreeBSD: src/usr.bin/netstat/route.c,v 1.41.2.14 2002/07/17 02:22:22 kbyanc Exp $
31  */
32
33 #include <sys/kinfo.h>
34 #include <sys/param.h>
35 #include <sys/socket.h>
36 #include <sys/time.h>
37
38 #include <net/ethernet.h>
39 #include <net/if.h>
40 #include <net/if_var.h>
41 #include <net/if_dl.h>
42 #include <net/if_types.h>
43 #include <net/route.h>
44
45 #include <netinet/in.h>
46 #include <netgraph/socket/ng_socket.h>
47
48 #include <netproto/mpls/mpls.h>
49
50 #include <sys/sysctl.h>
51
52 #include <arpa/inet.h>
53 #include <libutil.h>
54 #include <netdb.h>
55 #include <stdio.h>
56 #include <stdlib.h>
57 #include <string.h>
58 #include <unistd.h>
59 #include <err.h>
60 #include <time.h>
61 #include <kinfo.h>
62 #include "netstat.h"
63
64 #define kget(p, d) (kread((u_long)(p), (char *)&(d), sizeof (d)))
65
66
67 /* alignment constraint for routing socket */
68 #define ROUNDUP(a) \
69        ((a) > 0 ? (1 + (((a) - 1) | (sizeof(long) - 1))) : sizeof(long))
70 #define ADVANCE(x, n) (x += ROUNDUP((n)->sa_len))
71
72 /*
73  * Definitions for showing gateway flags.
74  */
75 struct bits {
76         u_long  b_mask;
77         char    b_val;
78 } bits[] = {
79         { RTF_UP,       'U' },
80         { RTF_GATEWAY,  'G' },
81         { RTF_HOST,     'H' },
82         { RTF_REJECT,   'R' },
83         { RTF_DYNAMIC,  'D' },
84         { RTF_MODIFIED, 'M' },
85         { RTF_DONE,     'd' }, /* Completed -- for routing messages only */
86         { RTF_CLONING,  'C' },
87         { RTF_XRESOLVE, 'X' },
88         { RTF_LLINFO,   'L' },
89         { RTF_STATIC,   'S' },
90         { RTF_PROTO1,   '1' },
91         { RTF_PROTO2,   '2' },
92         { RTF_WASCLONED,'W' },
93         { RTF_PRCLONING,'c' },
94         { RTF_PROTO3,   '3' },
95         { RTF_BLACKHOLE,'B' },
96         { RTF_BROADCAST,'b' },
97         { RTF_MPLSOPS,  'm' },
98         { 0, 0 }
99 };
100
101 typedef union {
102         long    dummy;          /* Helps align structure. */
103         struct  sockaddr u_sa;
104         u_short u_data[128];
105 } sa_u;
106
107 static sa_u pt_u;
108
109 int     do_rtent = 0;
110 struct  rtentry rtentry;
111 struct  radix_node rnode;
112 struct  radix_mask rmask;
113 struct  radix_node_head *rt_tables[AF_MAX+1];
114
115 int     NewTree = 0;
116
117 static struct sockaddr *kgetsa (struct sockaddr *);
118 static void size_cols (int ef, struct radix_node *rn);
119 static void size_cols_tree (struct radix_node *rn);
120 static void size_cols_rtentry (struct rtentry *rt);
121 static void p_tree (struct radix_node *);
122 static void p_rtnode (void);
123 static void ntreestuff (void);
124 static void np_rtentry (struct rt_msghdr *);
125 static void p_sockaddr (struct sockaddr *, struct sockaddr *, int, int);
126 static const char *fmt_sockaddr (struct sockaddr *sa, struct sockaddr *mask,
127                                  int flags);
128 static void p_flags (int, const char *);
129 static const char *fmt_flags(int f);
130 static void p_rtentry (struct rtentry *);
131 static u_long forgemask (u_long);
132 static void domask (char *, u_long, u_long);
133 static const char *labelops(struct rtentry *);
134
135 /*
136  * Print routing tables.
137  */
138 void
139 routepr(u_long rtree)
140 {
141         struct radix_node_head *rnh, head;
142         int i;
143
144         printf("Routing tables\n");
145
146         if (Aflag == 0 && NewTree) {
147                 ntreestuff();
148         } else {
149                 if (rtree == 0) {
150                         printf("rt_tables: symbol not in namelist\n");
151                         return;
152                 }
153                 if (cpuflag >= 0) {
154                         /*
155                          * Severe hack.
156                          */
157                         rtree += cpuflag * (AF_MAX + 1) * sizeof(void *);
158                 }
159                 if (kget(rtree, rt_tables) != 0)
160                         return;
161                 for (i = 0; i <= AF_MAX; i++) {
162                         if ((rnh = rt_tables[i]) == NULL)
163                                 continue;
164                         if (kget(rnh, head) != 0)
165                                 continue;
166                         if (i == AF_UNSPEC) {
167                                 if (Aflag && af == 0) {
168                                         printf("Netmasks:\n");
169                                         p_tree(head.rnh_treetop);
170                                 }
171                         } else if (af == AF_UNSPEC || af == i) {
172                                 size_cols(i, head.rnh_treetop);
173                                 pr_family(i);
174                                 do_rtent = 1;
175                                 pr_rthdr(i);
176                                 p_tree(head.rnh_treetop);
177                         }
178                 }
179         }
180 }
181
182 /*
183  * Print address family header before a section of the routing table.
184  */
185 void
186 pr_family(int af1)
187 {
188         const char *afname;
189
190         switch (af1) {
191         case AF_INET:
192                 afname = "Internet";
193                 break;
194 #ifdef INET6
195         case AF_INET6:
196                 afname = "Internet6";
197                 break;
198 #endif /*INET6*/
199         case AF_ISO:
200                 afname = "ISO";
201                 break;
202         case AF_CCITT:
203                 afname = "X.25";
204                 break;
205         case AF_NETGRAPH:
206                 afname = "Netgraph";
207                 break;
208         case AF_MPLS:
209                 afname = "MPLS";
210                 break;
211         default:
212                 afname = NULL;
213                 break;
214         }
215         if (afname)
216                 printf("\n%s:\n", afname);
217         else
218                 printf("\nProtocol Family %d:\n", af1);
219 }
220
221 /* column widths; each followed by one space */
222 #ifndef INET6
223 #define WID_DST_DEFAULT(af)     18      /* width of destination column */
224 #define WID_GW_DEFAULT(af)      18      /* width of gateway column */
225 #define WID_IF_DEFAULT(af)      (Wflag ? 8 : 6) /* width of netif column */
226 #else
227 #define WID_DST_DEFAULT(af) \
228         ((af) == AF_INET6 ? (numeric_addr ? 33: 18) : 18)
229 #define WID_GW_DEFAULT(af) \
230         ((af) == AF_INET6 ? (numeric_addr ? 29 : 18) : 18)
231 #define WID_IF_DEFAULT(af)      ((af) == AF_INET6 ? 8 : (Wflag ? 8 :6))
232 #endif /*INET6*/
233
234 static int wid_dst;
235 static int wid_gw;
236 static int wid_flags;
237 static int wid_refs;
238 static int wid_use;
239 static int wid_mtu;
240 static int wid_if;
241 static int wid_expire;
242 static int wid_mplslops;
243 static int wid_msl;
244 static int wid_iwmax;
245 static int wid_iw;
246
247 static void
248 size_cols(int ef, struct radix_node *rn)
249 {
250         wid_dst = WID_DST_DEFAULT(ef);
251         wid_gw = WID_GW_DEFAULT(ef);
252         wid_flags = 6;
253         wid_refs = 6;
254         wid_use = 8;
255         wid_mtu = 6;
256         wid_if = WID_IF_DEFAULT(ef);
257         wid_expire = 6;
258         wid_mplslops = 7;
259         wid_msl = 7;
260         wid_iwmax = 5;
261         wid_iw = 2;
262
263         if (Wflag)
264                 size_cols_tree(rn);
265 }
266
267 static void
268 size_cols_tree(struct radix_node *rn)
269 {
270 again:
271         if (kget(rn, rnode) != 0)
272                 return;
273         if (!(rnode.rn_flags & RNF_ACTIVE))
274                 return;
275         if (rnode.rn_bit < 0) {
276                 if ((rnode.rn_flags & RNF_ROOT) == 0) {
277                         if (kget(rn, rtentry) != 0)
278                                 return;
279                         size_cols_rtentry(&rtentry);
280                 }
281                 if ((rn = rnode.rn_dupedkey))
282                         goto again;
283         } else {
284                 rn = rnode.rn_right;
285                 size_cols_tree(rnode.rn_left);
286                 size_cols_tree(rn);
287         }
288 }
289
290 static void
291 size_cols_rtentry(struct rtentry *rt)
292 {
293         static struct ifnet ifnet, *lastif;
294         struct rtentry parent;
295         static char buffer[100];
296         const char *bp;
297         struct sockaddr *sa;
298         sa_u addr, mask;
299         int len;
300
301         /*
302          * Don't print protocol-cloned routes unless -a.
303          */
304         if (rt->rt_flags & RTF_WASCLONED && !aflag) {
305                 if (kget(rt->rt_parent, parent) != 0)
306                         return;
307                 if (parent.rt_flags & RTF_PRCLONING)
308                         return;
309         }
310
311         bzero(&addr, sizeof(addr));
312         if ((sa = kgetsa(rt_key(rt))))
313                 bcopy(sa, &addr, sa->sa_len);
314         bzero(&mask, sizeof(mask));
315         if (rt_mask(rt) && (sa = kgetsa(rt_mask(rt))))
316                 bcopy(sa, &mask, sa->sa_len);
317         bp = fmt_sockaddr(&addr.u_sa, &mask.u_sa, rt->rt_flags);
318         len = strlen(bp);
319         wid_dst = MAX(len, wid_dst);
320
321         bp = fmt_sockaddr(kgetsa(rt->rt_gateway), NULL, RTF_HOST);
322         len = strlen(bp);
323         wid_gw = MAX(len, wid_gw);
324
325         bp = fmt_flags(rt->rt_flags);
326         len = strlen(bp);
327         wid_flags = MAX(len, wid_flags);
328
329         if (addr.u_sa.sa_family == AF_INET || Wflag) {
330                 len = snprintf(buffer, sizeof(buffer), "%ld", rt->rt_refcnt);
331                 wid_refs = MAX(len, wid_refs);
332                 len = snprintf(buffer, sizeof(buffer), "%lu", rt->rt_use);
333                 wid_use = MAX(len, wid_use);
334                 if (Wflag && rt->rt_rmx.rmx_mtu != 0) {
335                         len = snprintf(buffer, sizeof(buffer),
336                                        "%lu", rt->rt_rmx.rmx_mtu);
337                         wid_mtu = MAX(len, wid_mtu);
338                 }
339         }
340         if (rt->rt_ifp) {
341                 if (rt->rt_ifp != lastif) {
342                         if (kget(rt->rt_ifp, ifnet) == 0) 
343                                 len = strlen(ifnet.if_xname);
344                         else
345                                 len = strlen("---");
346                         lastif = rt->rt_ifp;
347                         wid_if = MAX(len, wid_if);
348                 }
349                 if (rt->rt_rmx.rmx_expire) {
350                         struct timespec sp;
351                         int expire_time;
352
353                         clock_gettime(CLOCK_MONOTONIC, &sp);
354
355                         expire_time = (int)(rt->rt_rmx.rmx_expire - sp.tv_sec);
356
357                         if (expire_time > 0) {
358                                 snprintf(buffer, sizeof(buffer), "%d",
359                                          (int)expire_time);
360                                 wid_expire = MAX(len, wid_expire);
361                         }
362                 }
363         }
364         if (Wflag) {
365                 if (rt->rt_shim[0] != NULL) {
366                         len = strlen(labelops(rt));
367                         wid_mplslops = MAX(len, wid_mplslops);
368                 }
369
370                 if (rt->rt_rmx.rmx_msl) {
371                         len = snprintf(buffer, sizeof(buffer),
372                                        "%lu", rt->rt_rmx.rmx_msl);
373                         wid_msl = MAX(len, wid_msl);
374                 }
375                 if (rt->rt_rmx.rmx_iwmaxsegs) {
376                         len = snprintf(buffer, sizeof(buffer),
377                                        "%lu", rt->rt_rmx.rmx_iwmaxsegs);
378                         wid_iwmax = MAX(len, wid_iwmax);
379                 }
380                 if (rt->rt_rmx.rmx_iwcapsegs) {
381                         len = snprintf(buffer, sizeof(buffer),
382                                        "%lu", rt->rt_rmx.rmx_iwcapsegs);
383                         wid_iw = MAX(len, wid_iw);
384                 }
385         }
386 }
387
388
389 /*
390  * Print header for routing table columns.
391  */
392 void
393 pr_rthdr(int af1)
394 {
395
396         if (Aflag)
397                 printf("%-8.8s ","Address");
398         if (af1 == AF_INET || Wflag) {
399                 if (Wflag) {
400                         printf("%-*.*s %-*.*s %-*.*s %*.*s %*.*s %*.*s %*.*s "
401                                "%*s %-*s%*s %*s %*s\n",
402                                 wid_dst,        wid_dst,        "Destination",
403                                 wid_gw,         wid_gw,         "Gateway",
404                                 wid_flags,      wid_flags,      "Flags",
405                                 wid_refs,       wid_refs,       "Refs",
406                                 wid_use,        wid_use,        "Use",
407                                 wid_mtu,        wid_mtu,        "Mtu",
408                                 wid_if,         wid_if,         "Netif",
409                                 wid_expire,                     "Expire",
410                                 wid_mplslops,                   "Labelops",
411                                 wid_msl,                        "Msl",
412                                 wid_iwmax,                      "IWmax",
413                                 wid_iw,                         "IW");
414                 } else {
415                         printf("%-*.*s %-*.*s %-*.*s %*.*s %*.*s %*.*s %*s\n",
416                                 wid_dst,        wid_dst,        "Destination",
417                                 wid_gw,         wid_gw,         "Gateway",
418                                 wid_flags,      wid_flags,      "Flags",
419                                 wid_refs,       wid_refs,       "Refs",
420                                 wid_use,        wid_use,        "Use",
421                                 wid_if,         wid_if,         "Netif",
422                                 wid_expire,                     "Expire");
423                 }
424         } else {
425                 printf("%-*.*s %-*.*s %-*.*s  %*.*s %*s\n",
426                         wid_dst,        wid_dst,        "Destination",
427                         wid_gw,         wid_gw,         "Gateway",
428                         wid_flags,      wid_flags,      "Flags",
429                         wid_if,         wid_if,         "Netif",
430                         wid_expire,                     "Expire");
431         }
432 }
433
434 static struct sockaddr *
435 kgetsa(struct sockaddr *dst)
436 {
437
438         if (kget(dst, pt_u.u_sa) != 0)
439                 return (NULL);
440         if (pt_u.u_sa.sa_len > sizeof (pt_u.u_sa))
441                 kread((u_long)dst, (char *)pt_u.u_data, pt_u.u_sa.sa_len);
442         return (&pt_u.u_sa);
443 }
444
445 static void
446 p_tree(struct radix_node *rn)
447 {
448
449 again:
450         if (kget(rn, rnode) != 0)
451                 return;
452         if (!(rnode.rn_flags & RNF_ACTIVE))
453                 return;
454         if (rnode.rn_bit < 0) {
455                 if (Aflag)
456                         printf("%-8.8lx ", (u_long)rn);
457                 if (rnode.rn_flags & RNF_ROOT) {
458                         if (Aflag)
459                                 printf("(root node)%s",
460                                     rnode.rn_dupedkey ? " =>\n" : "\n");
461                 } else if (do_rtent) {
462                         if (kget(rn, rtentry) == 0) {
463                                 p_rtentry(&rtentry);
464                                 if (Aflag)
465                                         p_rtnode();
466                         }
467                 } else {
468                         p_sockaddr(kgetsa((struct sockaddr *)rnode.rn_key),
469                                    NULL, 0, 44);
470                         putchar('\n');
471                 }
472                 if ((rn = rnode.rn_dupedkey))
473                         goto again;
474         } else {
475                 if (Aflag && do_rtent) {
476                         printf("%-8.8lx ", (u_long)rn);
477                         p_rtnode();
478                 }
479                 rn = rnode.rn_right;
480                 p_tree(rnode.rn_left);
481                 p_tree(rn);
482         }
483 }
484
485 char    nbuf[20];
486
487 static void
488 p_rtnode(void)
489 {
490         struct radix_mask *rm = rnode.rn_mklist;
491
492         if (rnode.rn_bit < 0) {
493                 if (rnode.rn_mask) {
494                         printf("\t  mask ");
495                         p_sockaddr(kgetsa((struct sockaddr *)rnode.rn_mask),
496                                    NULL, 0, -1);
497                 } else if (rm == NULL)
498                         return;
499         } else {
500                 sprintf(nbuf, "(%d)", rnode.rn_bit);
501                 printf("%6.6s %8.8lx : %8.8lx", nbuf, (u_long)rnode.rn_left, (u_long)rnode.rn_right);
502         }
503         while (rm) {
504                 if (kget(rm, rmask) != 0)
505                         break;
506                 sprintf(nbuf, " %d refs, ", rmask.rm_refs);
507                 printf(" mk = %8.8lx {(%d),%s",
508                         (u_long)rm, -1 - rmask.rm_bit, rmask.rm_refs ? nbuf : " ");
509                 if (rmask.rm_flags & RNF_NORMAL) {
510                         struct radix_node rnode_aux;
511                         printf(" <normal>, ");
512                         if (kget(rmask.rm_leaf, rnode_aux) == 0)
513                                 p_sockaddr(kgetsa((struct sockaddr *)rnode_aux.rn_mask),
514                                     NULL, 0, -1);
515                         else
516                                 p_sockaddr(NULL, NULL, 0, -1);
517                 } else
518                     p_sockaddr(kgetsa((struct sockaddr *)rmask.rm_mask),
519                                 NULL, 0, -1);
520                 putchar('}');
521                 if ((rm = rmask.rm_next))
522                         printf(" ->");
523         }
524         putchar('\n');
525 }
526
527 static void
528 ntreestuff(void)
529 {
530         size_t needed;
531         int mib[7];
532         int miblen;
533         char *buf, *next, *lim;
534         struct rt_msghdr *rtm;
535
536         mib[0] = CTL_NET;
537         mib[1] = PF_ROUTE;
538         mib[2] = 0;
539         mib[3] = 0;
540         mib[4] = NET_RT_DUMP;
541         mib[5] = 0;
542         if (cpuflag >= 0) {
543                 mib[6] = cpuflag;
544                 miblen = 7;
545         } else {
546                 miblen = 6;
547         }
548         if (sysctl(mib, miblen, NULL, &needed, NULL, 0) < 0) {
549                 err(1, "sysctl: net.route.0.0.dump estimate");
550         }
551
552         if ((buf = malloc(needed)) == NULL) {
553                 err(2, "malloc(%lu)", (unsigned long)needed);
554         }
555         if (sysctl(mib, miblen, buf, &needed, NULL, 0) < 0) {
556                 err(1, "sysctl: net.route.0.0.dump");
557         }
558         lim  = buf + needed;
559         for (next = buf; next < lim; next += rtm->rtm_msglen) {
560                 rtm = (struct rt_msghdr *)next;
561                 np_rtentry(rtm);
562         }
563 }
564
565 static void
566 np_rtentry(struct rt_msghdr *rtm)
567 {
568         struct sockaddr *sa = (struct sockaddr *)(rtm + 1);
569 #ifdef notdef
570         static int masks_done, banner_printed;
571 #endif
572         static int old_af;
573         int af1 = 0, interesting = RTF_UP | RTF_GATEWAY | RTF_HOST;
574
575 #ifdef notdef
576         /* for the moment, netmasks are skipped over */
577         if (!banner_printed) {
578                 printf("Netmasks:\n");
579                 banner_printed = 1;
580         }
581         if (masks_done == 0) {
582                 if (rtm->rtm_addrs != RTA_DST ) {
583                         masks_done = 1;
584                         af1 = sa->sa_family;
585                 }
586         } else
587 #endif
588                 af1 = sa->sa_family;
589         if (af1 != old_af) {
590                 pr_family(af1);
591                 old_af = af1;
592         }
593         if (rtm->rtm_addrs == RTA_DST)
594                 p_sockaddr(sa, NULL, 0, 36);
595         else {
596                 p_sockaddr(sa, NULL, rtm->rtm_flags, 16);
597                 sa = (struct sockaddr *)(ROUNDUP(sa->sa_len) + (char *)sa);
598                 p_sockaddr(sa, NULL, 0, 18);
599         }
600         p_flags(rtm->rtm_flags & interesting, "%-6.6s ");
601         putchar('\n');
602 }
603
604 static void
605 p_sockaddr(struct sockaddr *sa, struct sockaddr *mask, int flags, int width)
606 {
607         const char *cp;
608
609         cp = fmt_sockaddr(sa, mask, flags);
610
611         if (width < 0 )
612                 printf("%s ", cp);
613         else {
614                 if (numeric_addr)
615                         printf("%-*s ", width, cp);
616                 else
617                         printf("%-*.*s ", width, width, cp);
618         }
619 }
620
621 static const char *
622 fmt_sockaddr(struct sockaddr *sa, struct sockaddr *mask, int flags)
623 {
624         static char workbuf[128];
625         const char *cp = workbuf;
626
627         if (sa == NULL)
628                 return ("null");
629
630         switch(sa->sa_family) {
631         case AF_INET:
632             {
633                 struct sockaddr_in *sin = (struct sockaddr_in *)sa;
634
635                 if ((sin->sin_addr.s_addr == INADDR_ANY) &&
636                         mask &&
637                         ntohl(((struct sockaddr_in *)mask)->sin_addr.s_addr)
638                                 ==0L)
639                                 cp = "default" ;
640                 else if (flags & RTF_HOST)
641                         cp = routename(sin->sin_addr.s_addr);
642                 else if (mask)
643                         cp = netname(sin->sin_addr.s_addr,
644                                      ntohl(((struct sockaddr_in *)mask)
645                                            ->sin_addr.s_addr));
646                 else
647                         cp = netname(sin->sin_addr.s_addr, 0L);
648                 break;
649             }
650
651 #ifdef INET6
652         case AF_INET6:
653             {
654                 struct sockaddr_in6 *sa6 = (struct sockaddr_in6 *)sa;
655                 struct in6_addr *in6 = &sa6->sin6_addr;
656
657                 /*
658                  * XXX: This is a special workaround for KAME kernels.
659                  * sin6_scope_id field of SA should be set in the future.
660                  */
661                 if (IN6_IS_ADDR_LINKLOCAL(in6) ||
662                     IN6_IS_ADDR_MC_LINKLOCAL(in6)) {
663                     /* XXX: override is ok? */
664                     sa6->sin6_scope_id = (u_int32_t)ntohs(*(u_short *)&in6->s6_addr[2]);
665                     *(u_short *)&in6->s6_addr[2] = 0;
666                 }
667
668                 if (flags & RTF_HOST)
669                     cp = routename6(sa6);
670                 else if (mask)
671                     cp = netname6(sa6,
672                                   &((struct sockaddr_in6 *)mask)->sin6_addr);
673                 else {
674                     cp = netname6(sa6, NULL);
675                 }
676                 break;
677             }
678 #endif /*INET6*/
679
680         case AF_NETGRAPH:
681             {
682                 printf("%s", ((struct sockaddr_ng *)sa)->sg_data);
683                 break;
684             }
685         case AF_LINK:
686             {
687                 struct sockaddr_dl *sdl = (struct sockaddr_dl *)sa;
688
689                 if (sdl->sdl_nlen == 0 && sdl->sdl_alen == 0 &&
690                     sdl->sdl_slen == 0)
691                         (void) sprintf(workbuf, "link#%d", sdl->sdl_index);
692                 else
693                         switch (sdl->sdl_type) {
694
695                         case IFT_ETHER:
696                         case IFT_L2VLAN:
697                         case IFT_CARP:
698                                 if (sdl->sdl_alen == ETHER_ADDR_LEN) {
699                                         cp = ether_ntoa((struct ether_addr *)
700                                             (sdl->sdl_data + sdl->sdl_nlen));
701                                         break;
702                                 }
703                                 /* FALLTHROUGH */
704                         default:
705                                 cp = link_ntoa(sdl);
706                                 break;
707                         }
708                 break;
709             }
710
711         case AF_MPLS:
712             {
713                 struct sockaddr_mpls *smpls = (struct sockaddr_mpls *)sa;
714
715                 (void) sprintf(workbuf, "%d", ntohl(smpls->smpls_label));
716                 break;
717             }
718                 
719         default:
720             {
721                 u_char *s = (u_char *)sa->sa_data, *slim;
722                 char *cq, *cqlim;
723
724                 cq = workbuf;
725                 slim =  sa->sa_len + (u_char *) sa;
726                 cqlim = cq + sizeof(workbuf) - 6;
727                 cq += sprintf(cq, "(%d)", sa->sa_family);
728                 while (s < slim && cq < cqlim) {
729                         cq += sprintf(cq, " %02x", *s++);
730                         if (s < slim)
731                             cq += sprintf(cq, "%02x", *s++);
732                 }
733                 cp = workbuf;
734             }
735         }
736
737         return (cp);
738 }
739
740 static void
741 p_flags(int f, const char *format)
742 {
743         printf(format, fmt_flags(f));
744 }
745
746 static const char *
747 fmt_flags(int f)
748 {
749         static char name[33];
750         char *flags;
751         struct bits *p = bits;
752
753         for (flags = name; p->b_mask; p++)
754                 if (p->b_mask & f)
755                         *flags++ = p->b_val;
756         *flags = '\0';
757         return (name);
758 }
759
760 static void
761 p_rtentry(struct rtentry *rt)
762 {
763         static struct ifnet ifnet, *lastif;
764         struct rtentry parent;
765         static char buffer[128];
766         static char prettyname[128];
767         struct sockaddr *sa;
768         sa_u addr, mask;
769
770         /*
771          * Don't print protocol-cloned routes unless -a.
772          */
773         if (rt->rt_flags & RTF_WASCLONED && !aflag) {
774                 if (kget(rt->rt_parent, parent) != 0)
775                         return;
776                 if (parent.rt_flags & RTF_PRCLONING)
777                         return;
778         }
779
780         bzero(&addr, sizeof(addr));
781         if ((sa = kgetsa(rt_key(rt))))
782                 bcopy(sa, &addr, sa->sa_len);
783         bzero(&mask, sizeof(mask));
784         if (rt_mask(rt) && (sa = kgetsa(rt_mask(rt))))
785                 bcopy(sa, &mask, sa->sa_len);
786         p_sockaddr(&addr.u_sa, &mask.u_sa, rt->rt_flags, wid_dst);
787         p_sockaddr(kgetsa(rt->rt_gateway), NULL, RTF_HOST, wid_gw);
788         snprintf(buffer, sizeof(buffer), "%%-%d.%ds ", wid_flags, wid_flags);
789         p_flags(rt->rt_flags, buffer);
790         if (addr.u_sa.sa_family == AF_INET || Wflag) {
791                 printf("%*ld %*lu ", wid_refs, rt->rt_refcnt,
792                                      wid_use, rt->rt_use);
793                 if (Wflag) {
794                         if (rt->rt_rmx.rmx_mtu != 0)
795                                 printf("%*lu ", wid_mtu, rt->rt_rmx.rmx_mtu);
796                         else
797                                 printf("%*s ", wid_mtu, "");
798                 }
799         }
800         if (rt->rt_ifp) {
801                 if (rt->rt_ifp != lastif) {
802                         if (kget(rt->rt_ifp, ifnet) == 0)
803                                 strlcpy(prettyname, ifnet.if_xname,
804                                     sizeof(prettyname));
805                         else
806                                 strlcpy(prettyname, "---", sizeof(prettyname));
807                         lastif = rt->rt_ifp;
808                 }
809                 printf("%*.*s", wid_if, wid_if, prettyname);
810                 if (rt->rt_rmx.rmx_expire) {
811                         struct timespec sp;
812                         int expire_time;
813
814                         clock_gettime(CLOCK_MONOTONIC, &sp);
815
816                         expire_time = (int)(rt->rt_rmx.rmx_expire - sp.tv_sec);
817                         if (expire_time > 0)
818                                 printf(" %*d", wid_expire, (int)expire_time);
819                         else
820                                 printf("%*s ", wid_expire, "");
821                 } else {
822                         printf("%*s ", wid_expire, "");
823                 }
824                 if (rt->rt_nodes[0].rn_dupedkey)
825                         printf(" =>");
826         }
827         if (Wflag) {
828                 if (rt->rt_shim[0] != NULL)
829                         printf(" %-*s", wid_mplslops, labelops(rt));
830                 else
831                         printf(" %-*s", wid_mplslops, "");
832                 if (rt->rt_rmx.rmx_msl != 0)
833                         printf(" %*lu", wid_msl, rt->rt_rmx.rmx_msl);
834                 else
835                         printf("%*s ", wid_msl, "");
836                 if (rt->rt_rmx.rmx_iwmaxsegs != 0)
837                         printf(" %*lu", wid_iwmax, rt->rt_rmx.rmx_iwmaxsegs);
838                 else
839                         printf("%*s ", wid_iwmax, "");
840                 if (rt->rt_rmx.rmx_iwcapsegs != 0)
841                         printf(" %*lu", wid_iw, rt->rt_rmx.rmx_iwcapsegs);
842                 else
843                         printf("%*s ", wid_iw, "");
844         }
845         putchar('\n');
846 }
847
848 char *
849 routename(u_long in)
850 {
851         char *cp;
852         static char line[MAXHOSTNAMELEN];
853         struct hostent *hp;
854
855         cp = NULL;
856         if (!numeric_addr) {
857                 hp = gethostbyaddr(&in, sizeof (struct in_addr), AF_INET);
858                 if (hp) {
859                         cp = hp->h_name;
860                         trimdomain(cp, strlen(cp));
861                 }
862         }
863         if (cp) {
864                 strncpy(line, cp, sizeof(line) - 1);
865                 line[sizeof(line) - 1] = '\0';
866         } else {
867 #define C(x)    ((x) & 0xff)
868                 in = ntohl(in);
869                 sprintf(line, "%lu.%lu.%lu.%lu",
870                     C(in >> 24), C(in >> 16), C(in >> 8), C(in));
871         }
872         return (line);
873 }
874
875 static u_long
876 forgemask(u_long a)
877 {
878         u_long m;
879
880         if (IN_CLASSA(a))
881                 m = IN_CLASSA_NET;
882         else if (IN_CLASSB(a))
883                 m = IN_CLASSB_NET;
884         else
885                 m = IN_CLASSC_NET;
886         return (m);
887 }
888
889 static void
890 domask(char *dst, u_long addr, u_long mask)
891 {
892         int b, i;
893
894         if (!mask || (forgemask(addr) == mask)) {
895                 *dst = '\0';
896                 return;
897         }
898         i = 0;
899         for (b = 0; b < 32; b++)
900                 if (mask & (1 << b)) {
901                         int bb;
902
903                         i = b;
904                         for (bb = b+1; bb < 32; bb++)
905                                 if (!(mask & (1 << bb))) {
906                                         i = -1; /* noncontig */
907                                         break;
908                                 }
909                         break;
910                 }
911         if (i == -1)
912                 sprintf(dst, "&0x%lx", mask);
913         else
914                 sprintf(dst, "/%d", 32-i);
915 }
916
917 /*
918  * Return the name of the network whose address is given.
919  * The address is assumed to be that of a net or subnet, not a host.
920  */
921 char *
922 netname(u_long in, u_long mask)
923 {
924         char *cp = NULL;
925         static char line[MAXHOSTNAMELEN];
926         struct netent *np = NULL;
927         u_long dmask;
928         u_long i;
929
930 #define NSHIFT(m) (                                                     \
931         (m) == IN_CLASSA_NET ? IN_CLASSA_NSHIFT :                       \
932         (m) == IN_CLASSB_NET ? IN_CLASSB_NSHIFT :                       \
933         (m) == IN_CLASSC_NET ? IN_CLASSC_NSHIFT :                       \
934         0)
935
936         i = ntohl(in);
937         dmask = forgemask(i);
938         if (!numeric_addr && i) {
939                 np = getnetbyaddr(i >> NSHIFT(mask), AF_INET);
940                 if (np == NULL && mask == 0)
941                         np = getnetbyaddr(i >> NSHIFT(dmask), AF_INET);
942                 if (np != NULL) {
943                         cp = np->n_name;
944                         trimdomain(cp, strlen(cp));
945                 }
946         }
947 #undef NSHIFT
948         if (cp != NULL) {
949                 strncpy(line, cp, sizeof(line) - 1);
950                 line[sizeof(line) - 1] = '\0';
951         } else {
952                 if (mask <= IN_CLASSA_NET &&
953                         (i & IN_CLASSA_HOST) == 0) {
954                                 sprintf(line, "%lu", C(i >> 24));
955                 } else if (mask <= IN_CLASSB_NET &&
956                         (i & IN_CLASSB_HOST) == 0) {
957                                 sprintf(line, "%lu.%lu",
958                                         C(i >> 24), C(i >> 16));
959                 } else if (mask <= IN_CLASSC_NET &&
960                         (i & IN_CLASSC_HOST) == 0) {
961                                 sprintf(line, "%lu.%lu.%lu",
962                                         C(i >> 24), C(i >> 16), C(i >> 8));
963                 } else {
964                         sprintf(line, "%lu.%lu.%lu.%lu",
965                                 C(i >> 24), C(i >> 16), C(i >> 8), C(i));
966                 }
967         }
968         domask(line + strlen(line), i, mask);
969         return (line);
970 }
971
972 #ifdef INET6
973 const char *
974 netname6(struct sockaddr_in6 *sa6, struct in6_addr *mask)
975 {
976         static char line[MAXHOSTNAMELEN];
977         u_char *p = (u_char *)mask;
978         u_char *lim;
979         int masklen, illegal = 0, flag = NI_WITHSCOPEID;
980
981         if (mask) {
982                 for (masklen = 0, lim = p + 16; p < lim; p++) {
983                         switch (*p) {
984                          case 0xff:
985                                  masklen += 8;
986                                  break;
987                          case 0xfe:
988                                  masklen += 7;
989                                  break;
990                          case 0xfc:
991                                  masklen += 6;
992                                  break;
993                          case 0xf8:
994                                  masklen += 5;
995                                  break;
996                          case 0xf0:
997                                  masklen += 4;
998                                  break;
999                          case 0xe0:
1000                                  masklen += 3;
1001                                  break;
1002                          case 0xc0:
1003                                  masklen += 2;
1004                                  break;
1005                          case 0x80:
1006                                  masklen += 1;
1007                                  break;
1008                          case 0x00:
1009                                  break;
1010                          default:
1011                                  illegal ++;
1012                                  break;
1013                         }
1014                 }
1015                 if (illegal)
1016                         fprintf(stderr, "illegal prefixlen\n");
1017         }
1018         else
1019                 masklen = 128;
1020
1021         if (masklen == 0 && IN6_IS_ADDR_UNSPECIFIED(&sa6->sin6_addr))
1022                 return("default");
1023
1024         if (numeric_addr)
1025                 flag |= NI_NUMERICHOST;
1026         getnameinfo((struct sockaddr *)sa6, sa6->sin6_len, line, sizeof(line),
1027                     NULL, 0, flag);
1028
1029         if (numeric_addr)
1030                 sprintf(&line[strlen(line)], "/%d", masklen);
1031
1032         return line;
1033 }
1034
1035 char *
1036 routename6(struct sockaddr_in6 *sa6)
1037 {
1038         static char line[MAXHOSTNAMELEN];
1039         int flag = NI_WITHSCOPEID;
1040         /* use local variable for safety */
1041         struct sockaddr_in6 sa6_local;
1042
1043         sa6_local.sin6_family = AF_INET6;
1044         sa6_local.sin6_len = sizeof(sa6_local);
1045         sa6_local.sin6_addr = sa6->sin6_addr;
1046         sa6_local.sin6_scope_id = sa6->sin6_scope_id;
1047
1048         if (numeric_addr)
1049                 flag |= NI_NUMERICHOST;
1050
1051         getnameinfo((struct sockaddr *)&sa6_local, sa6_local.sin6_len,
1052                     line, sizeof(line), NULL, 0, flag);
1053
1054         return line;
1055 }
1056 #endif /*INET6*/
1057
1058 /*
1059  * Print routing statistics
1060  */
1061 void
1062 rt_stats(void)
1063 {
1064         struct rtstatistics rts;
1065         int error = 0;
1066
1067         error = kinfo_get_net_rtstatistics(&rts);
1068         if (error) {
1069                 printf("routing: could not retrieve statistics\n");
1070                 return;
1071         }
1072         printf("routing:\n");
1073
1074 #define p(f, m) if (rts.f || sflag <= 1) \
1075         printf(m, rts.f, plural(rts.f))
1076
1077         p(rts_badredirect, "\t%lu bad routing redirect%s\n");
1078         p(rts_dynamic, "\t%lu dynamically created route%s\n");
1079         p(rts_newgateway, "\t%lu new gateway%s due to redirects\n");
1080         p(rts_unreach, "\t%lu destination%s found unreachable\n");
1081         p(rts_wildcard, "\t%lu use%s of a wildcard route\n");
1082 #undef p
1083 }
1084
1085 static const char *
1086 labelops(struct rtentry *rt)
1087 {
1088         const char *lops[] = { "push", "pop", "swap", "pop all" };
1089         static char buffer[100];
1090         char *cp = buffer;
1091         struct sockaddr_mpls *smpls;
1092         int i;
1093
1094         for (i=0; i<MPLS_MAXLOPS; ++i) {
1095
1096                 if (rt->rt_shim[i] == NULL)
1097                         break;
1098                 if (i>0) {
1099                         cp += snprintf(cp,
1100                                        sizeof(buffer) - (cp - buffer),
1101                                        ", ");
1102                 }
1103                 smpls = (struct sockaddr_mpls *)kgetsa(rt->rt_shim[i]);
1104                 if (smpls->smpls_op != MPLSLOP_POP &&
1105                     smpls->smpls_op != MPLSLOP_POPALL){
1106                         cp += snprintf(cp,
1107                                        sizeof(buffer) - (cp - buffer),
1108                                        "%s %d",
1109                                        lops[smpls->smpls_op - 1],
1110                                        ntohl(smpls->smpls_label));
1111                 } else {
1112                         cp += snprintf(cp,
1113                                        sizeof(buffer) - (cp - buffer),
1114                                        "%s",
1115                                        lops[smpls->smpls_op - 1]);
1116                 }
1117         }
1118
1119         return (buffer);
1120 }