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