]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - usr.bin/netstat/main.c
Merge OpenSSL 1.1.1g.
[FreeBSD/FreeBSD.git] / usr.bin / netstat / main.c
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 1983, 1988, 1993
5  *      Regents of the University of California.  All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. Neither the name of the University nor the names of its contributors
16  *    may be used to endorse or promote products derived from this software
17  *    without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  */
31
32 #ifndef lint
33 static char const copyright[] =
34 "@(#) Copyright (c) 1983, 1988, 1993\n\
35         Regents of the University of California.  All rights reserved.\n";
36 #endif /* not lint */
37
38 #if 0
39 #ifndef lint
40 static char sccsid[] = "@(#)main.c      8.4 (Berkeley) 3/1/94";
41 #endif /* not lint */
42 #endif
43
44 #include <sys/cdefs.h>
45 __FBSDID("$FreeBSD$");
46
47 #include <sys/param.h>
48 #include <sys/file.h>
49 #include <sys/protosw.h>
50 #include <sys/socket.h>
51 #include <sys/socketvar.h>
52 #include <sys/sysctl.h>
53
54 #include <netinet/in.h>
55
56 #ifdef NETGRAPH
57 #include <netgraph/ng_socket.h>
58 #endif
59
60 #include <ctype.h>
61 #include <err.h>
62 #include <errno.h>
63 #include <kvm.h>
64 #include <limits.h>
65 #include <netdb.h>
66 #include <nlist.h>
67 #include <paths.h>
68 #include <stdint.h>
69 #include <stdio.h>
70 #include <stdlib.h>
71 #include <stdbool.h>
72 #include <string.h>
73 #include <unistd.h>
74 #include "netstat.h"
75 #include "nl_defs.h"
76 #include <libxo/xo.h>
77
78 static struct protox {
79         int     pr_index;               /* index into nlist of cb head */
80         int     pr_sindex;              /* index into nlist of stat block */
81         u_char  pr_wanted;              /* 1 if wanted, 0 otherwise */
82         void    (*pr_cblocks)(u_long, const char *, int, int);
83                                         /* control blocks printing routine */
84         void    (*pr_stats)(u_long, const char *, int, int);
85                                         /* statistics printing routine */
86         void    (*pr_istats)(char *);   /* per/if statistics printing routine */
87         const char      *pr_name;               /* well-known name */
88         int     pr_usesysctl;           /* non-zero if we use sysctl, not kvm */
89         int     pr_protocol;
90 } protox[] = {
91         { N_TCBINFO,    N_TCPSTAT,      1,      protopr,
92           tcp_stats,    NULL,           "tcp",  1,      IPPROTO_TCP },
93         { N_UDBINFO,    N_UDPSTAT,      1,      protopr,
94           udp_stats,    NULL,           "udp",  1,      IPPROTO_UDP },
95 #ifdef SCTP
96         { -1,           N_SCTPSTAT,     1,      sctp_protopr,
97           sctp_stats,   NULL,           "sctp", 1,      IPPROTO_SCTP },
98 #endif
99 #ifdef SDP
100         { -1,           -1,             1,      protopr,
101          NULL,          NULL,           "sdp",  1,      IPPROTO_TCP },
102 #endif
103         { N_DIVCBINFO,  -1,             1,      protopr,
104           NULL,         NULL,           "divert", 1,    IPPROTO_DIVERT },
105         { N_RIPCBINFO,  N_IPSTAT,       1,      protopr,
106           ip_stats,     NULL,           "ip",   1,      IPPROTO_RAW },
107         { N_RIPCBINFO,  N_ICMPSTAT,     1,      protopr,
108           icmp_stats,   NULL,           "icmp", 1,      IPPROTO_ICMP },
109         { N_RIPCBINFO,  N_IGMPSTAT,     1,      protopr,
110           igmp_stats,   NULL,           "igmp", 1,      IPPROTO_IGMP },
111 #ifdef IPSEC
112         { -1,           N_IPSEC4STAT,   1,      NULL,   /* keep as compat */
113           ipsec_stats,  NULL,           "ipsec", 1,     0},
114         { -1,           N_AHSTAT,       1,      NULL,
115           ah_stats,     NULL,           "ah",   1,      0},
116         { -1,           N_ESPSTAT,      1,      NULL,
117           esp_stats,    NULL,           "esp",  1,      0},
118         { -1,           N_IPCOMPSTAT,   1,      NULL,
119           ipcomp_stats, NULL,           "ipcomp", 1,    0},
120 #endif
121         { N_RIPCBINFO,  N_PIMSTAT,      1,      protopr,
122           pim_stats,    NULL,           "pim",  1,      IPPROTO_PIM },
123         { -1,           N_CARPSTATS,    1,      NULL,
124           carp_stats,   NULL,           "carp", 1,      0 },
125 #ifdef PF
126         { -1,           N_PFSYNCSTATS,  1,      NULL,
127           pfsync_stats, NULL,           "pfsync", 1,    0 },
128 #endif
129         { -1,           N_ARPSTAT,      1,      NULL,
130           arp_stats,    NULL,           "arp", 1,       0 },
131         { -1,           -1,             0,      NULL,
132           NULL,         NULL,           NULL,   0,      0 }
133 };
134
135 #ifdef INET6
136 static struct protox ip6protox[] = {
137         { N_TCBINFO,    N_TCPSTAT,      1,      protopr,
138           tcp_stats,    NULL,           "tcp",  1,      IPPROTO_TCP },
139         { N_UDBINFO,    N_UDPSTAT,      1,      protopr,
140           udp_stats,    NULL,           "udp",  1,      IPPROTO_UDP },
141         { N_RIPCBINFO,  N_IP6STAT,      1,      protopr,
142           ip6_stats,    ip6_ifstats,    "ip6",  1,      IPPROTO_RAW },
143         { N_RIPCBINFO,  N_ICMP6STAT,    1,      protopr,
144           icmp6_stats,  icmp6_ifstats,  "icmp6", 1,     IPPROTO_ICMPV6 },
145 #ifdef SDP
146         { -1,           -1,             1,      protopr,
147          NULL,          NULL,           "sdp",  1,      IPPROTO_TCP },
148 #endif
149 #ifdef IPSEC
150         { -1,           N_IPSEC6STAT,   1,      NULL,
151           ipsec_stats,  NULL,           "ipsec6", 1,    0 },
152 #endif
153 #ifdef notyet
154         { -1,           N_PIM6STAT,     1,      NULL,
155           pim6_stats,   NULL,           "pim6", 1,      0 },
156 #endif
157         { -1,           N_RIP6STAT,     1,      NULL,
158           rip6_stats,   NULL,           "rip6", 1,      0 },
159         { -1,           -1,             0,      NULL,
160           NULL,         NULL,           NULL,   0,      0 }
161 };
162 #endif /*INET6*/
163
164 #ifdef IPSEC
165 static struct protox pfkeyprotox[] = {
166         { -1,           N_PFKEYSTAT,    1,      NULL,
167           pfkey_stats,  NULL,           "pfkey", 0,     0 },
168         { -1,           -1,             0,      NULL,
169           NULL,         NULL,           NULL,   0,      0 }
170 };
171 #endif
172
173 #ifdef NETGRAPH
174 static struct protox netgraphprotox[] = {
175         { N_NGSOCKLIST, -1,             1,      netgraphprotopr,
176           NULL,         NULL,           "ctrl", 0,      0 },
177         { N_NGSOCKLIST, -1,             1,      netgraphprotopr,
178           NULL,         NULL,           "data", 0,      0 },
179         { -1,           -1,             0,      NULL,
180           NULL,         NULL,           NULL,   0,      0 }
181 };
182 #endif
183
184 static struct protox *protoprotox[] = {
185                                          protox,
186 #ifdef INET6
187                                          ip6protox,
188 #endif
189 #ifdef IPSEC
190                                          pfkeyprotox,
191 #endif
192                                          NULL };
193
194 static void printproto(struct protox *, const char *, bool *);
195 static void usage(void);
196 static struct protox *name2protox(const char *);
197 static struct protox *knownname(const char *);
198
199 static int kresolve_list(struct nlist *_nl);
200
201 static kvm_t *kvmd;
202 static char *nlistf = NULL, *memf = NULL;
203
204 int     Aflag;          /* show addresses of protocol control block */
205 int     aflag;          /* show all sockets (including servers) */
206 static int      Bflag;          /* show information about bpf consumers */
207 int     bflag;          /* show i/f total bytes in/out */
208 int     dflag;          /* show i/f dropped packets */
209 int     gflag;          /* show group (multicast) routing or stats */
210 int     hflag;          /* show counters in human readable format */
211 int     iflag;          /* show interfaces */
212 int     Lflag;          /* show size of listen queues */
213 int     mflag;          /* show memory stats */
214 int     noutputs = 0;   /* how much outputs before we exit */
215 int     numeric_addr;   /* show addresses numerically */
216 int     numeric_port;   /* show ports numerically */
217 int     oflag;          /* show nexthop objects*/
218 int     Pflag;          /* show TCP log ID */
219 static int pflag;       /* show given protocol */
220 static int      Qflag;          /* show netisr information */
221 int     rflag;          /* show routing tables (or routing stats) */
222 int     Rflag;          /* show flow / RSS statistics */
223 int     sflag;          /* show protocol statistics */
224 int     Wflag;          /* wide display */
225 int     Tflag;          /* TCP Information */
226 int     xflag;          /* extra information, includes all socket buffer info */
227 int     zflag;          /* zero stats */
228
229 int     interval;       /* repeat interval for i/f stats */
230
231 char    *interface;     /* desired i/f for stats, or NULL for all i/fs */
232 int     unit;           /* unit number for above */
233
234 static int      af;             /* address family */
235 int     live;           /* true if we are examining a live system */
236
237 int
238 main(int argc, char *argv[])
239 {
240         struct protox *tp = NULL;  /* for printing cblocks & stats */
241         int ch;
242         int fib = -1;
243         char *endptr;
244         bool first = true;
245
246         af = AF_UNSPEC;
247
248         argc = xo_parse_args(argc, argv);
249         if (argc < 0)
250                 exit(EXIT_FAILURE);
251
252         while ((ch = getopt(argc, argv, "46AaBbdF:f:ghI:iLlM:mN:noPp:Qq:RrSTsuWw:xz"))
253             != -1)
254                 switch(ch) {
255                 case '4':
256 #ifdef INET
257                         af = AF_INET;
258 #else
259                         errx(1, "IPv4 support is not compiled in");
260 #endif
261                         break;
262                 case '6':
263 #ifdef INET6
264                         af = AF_INET6;
265 #else
266                         errx(1, "IPv6 support is not compiled in");
267 #endif
268                         break;
269                 case 'A':
270                         Aflag = 1;
271                         break;
272                 case 'a':
273                         aflag = 1;
274                         break;
275                 case 'B':
276                         Bflag = 1;
277                         break;
278                 case 'b':
279                         bflag = 1;
280                         break;
281                 case 'd':
282                         dflag = 1;
283                         break;
284                 case 'F':
285                         fib = strtol(optarg, &endptr, 0);
286                         if (*endptr != '\0' ||
287                             (fib == 0 && (errno == EINVAL || errno == ERANGE)))
288                                 xo_errx(1, "%s: invalid fib", optarg);
289                         break;
290                 case 'f':
291                         if (strcmp(optarg, "inet") == 0)
292                                 af = AF_INET;
293 #ifdef INET6
294                         else if (strcmp(optarg, "inet6") == 0)
295                                 af = AF_INET6;
296 #endif
297 #ifdef IPSEC
298                         else if (strcmp(optarg, "pfkey") == 0)
299                                 af = PF_KEY;
300 #endif
301                         else if (strcmp(optarg, "unix") == 0 ||
302                                  strcmp(optarg, "local") == 0)
303                                 af = AF_UNIX;
304 #ifdef NETGRAPH
305                         else if (strcmp(optarg, "ng") == 0
306                             || strcmp(optarg, "netgraph") == 0)
307                                 af = AF_NETGRAPH;
308 #endif
309                         else if (strcmp(optarg, "link") == 0)
310                                 af = AF_LINK;
311                         else {
312                                 xo_errx(1, "%s: unknown address family",
313                                     optarg);
314                         }
315                         break;
316                 case 'g':
317                         gflag = 1;
318                         break;
319                 case 'h':
320                         hflag = 1;
321                         break;
322                 case 'I': {
323                         char *cp;
324
325                         iflag = 1;
326                         for (cp = interface = optarg; isalpha(*cp); cp++)
327                                 continue;
328                         unit = atoi(cp);
329                         break;
330                 }
331                 case 'i':
332                         iflag = 1;
333                         break;
334                 case 'L':
335                         Lflag = 1;
336                         break;
337                 case 'M':
338                         memf = optarg;
339                         break;
340                 case 'm':
341                         mflag = 1;
342                         break;
343                 case 'N':
344                         nlistf = optarg;
345                         break;
346                 case 'n':
347                         numeric_addr = numeric_port = 1;
348                         break;
349                 case 'o':
350                         oflag = 1;
351                         break;
352                 case 'P':
353                         Pflag = 1;
354                         break;
355                 case 'p':
356                         if ((tp = name2protox(optarg)) == NULL) {
357                                 xo_errx(1, "%s: unknown or uninstrumented "
358                                     "protocol", optarg);
359                         }
360                         pflag = 1;
361                         break;
362                 case 'Q':
363                         Qflag = 1;
364                         break;
365                 case 'q':
366                         noutputs = atoi(optarg);
367                         if (noutputs != 0)
368                                 noutputs++;
369                         break;
370                 case 'r':
371                         rflag = 1;
372                         break;
373                 case 'R':
374                         Rflag = 1;
375                         break;
376                 case 's':
377                         ++sflag;
378                         break;
379                 case 'S':
380                         numeric_addr = 1;
381                         break;
382                 case 'u':
383                         af = AF_UNIX;
384                         break;
385                 case 'W':
386                 case 'l':
387                         Wflag = 1;
388                         break;
389                 case 'w':
390                         interval = atoi(optarg);
391                         iflag = 1;
392                         break;
393                 case 'T':
394                         Tflag = 1;
395                         break;
396                 case 'x':
397                         xflag = 1;
398                         break;
399                 case 'z':
400                         zflag = 1;
401                         break;
402                 case '?':
403                 default:
404                         usage();
405                 }
406         argv += optind;
407         argc -= optind;
408
409 #define BACKWARD_COMPATIBILITY
410 #ifdef  BACKWARD_COMPATIBILITY
411         if (*argv) {
412                 if (isdigit(**argv)) {
413                         interval = atoi(*argv);
414                         if (interval <= 0)
415                                 usage();
416                         ++argv;
417                         iflag = 1;
418                 }
419                 if (*argv) {
420                         nlistf = *argv;
421                         if (*++argv)
422                                 memf = *argv;
423                 }
424         }
425 #endif
426
427         /*
428          * Discard setgid privileges if not the running kernel so that bad
429          * guys can't print interesting stuff from kernel memory.
430          */
431         live = (nlistf == NULL && memf == NULL);
432         if (!live) {
433                 if (setgid(getgid()) != 0)
434                         xo_err(-1, "setgid");
435                 /* Load all necessary kvm symbols */
436                 kresolve_list(nl);
437         }
438
439         if (xflag && Tflag)
440                 xo_errx(1, "-x and -T are incompatible, pick one.");
441
442         if (Bflag) {
443                 if (!live)
444                         usage();
445                 bpf_stats(interface);
446                 xo_finish();
447                 exit(0);
448         }
449         if (mflag) {
450                 if (!live) {
451                         if (kread(0, NULL, 0) == 0)
452                                 mbpr(kvmd, nl[N_SFSTAT].n_value);
453                 } else
454                         mbpr(NULL, 0);
455                 xo_finish();
456                 exit(0);
457         }
458         if (Qflag) {
459                 if (!live) {
460                         if (kread(0, NULL, 0) == 0)
461                                 netisr_stats();
462                 } else
463                         netisr_stats();
464                 xo_finish();
465                 exit(0);
466         }
467 #if 0
468         /*
469          * Keep file descriptors open to avoid overhead
470          * of open/close on each call to get* routines.
471          */
472         sethostent(1);
473         setnetent(1);
474 #else
475         /*
476          * This does not make sense any more with DNS being default over
477          * the files.  Doing a setXXXXent(1) causes a tcp connection to be
478          * used for the queries, which is slower.
479          */
480 #endif
481         if (iflag && !sflag) {
482                 xo_open_container("statistics");
483                 intpr(NULL, af);
484                 xo_close_container("statistics");
485                 xo_finish();
486                 exit(0);
487         }
488         if (rflag) {
489                 xo_open_container("statistics");
490                 if (sflag) {
491                         if (live) {
492                                 kresolve_list(nl);
493                         }
494                         rt_stats();
495                 } else
496                         routepr(fib, af);
497                 xo_close_container("statistics");
498                 xo_finish();
499                 exit(0);
500         }
501         if (oflag) {
502                 xo_open_container("statistics");
503                 nhops_print(fib, af);
504                 xo_close_container("statistics");
505                 xo_finish();
506                 exit(0);
507         }
508
509
510         if (gflag) {
511                 xo_open_container("statistics");
512                 if (sflag) {
513                         if (af == AF_INET || af == AF_UNSPEC)
514                                 mrt_stats();
515 #ifdef INET6
516                         if (af == AF_INET6 || af == AF_UNSPEC)
517                                 mrt6_stats();
518 #endif
519                 } else {
520                         if (af == AF_INET || af == AF_UNSPEC)
521                                 mroutepr();
522 #ifdef INET6
523                         if (af == AF_INET6 || af == AF_UNSPEC)
524                                 mroute6pr();
525 #endif
526                 }
527                 xo_close_container("statistics");
528                 xo_finish();
529                 exit(0);
530         }
531
532         if (tp) {
533                 xo_open_container("statistics");
534                 printproto(tp, tp->pr_name, &first);
535                 if (!first)
536                         xo_close_list("socket");
537                 xo_close_container("statistics");
538                 xo_finish();
539                 exit(0);
540         }
541
542         xo_open_container("statistics");
543         if (af == AF_INET || af == AF_UNSPEC)
544                 for (tp = protox; tp->pr_name; tp++)
545                         printproto(tp, tp->pr_name, &first);
546 #ifdef INET6
547         if (af == AF_INET6 || af == AF_UNSPEC)
548                 for (tp = ip6protox; tp->pr_name; tp++)
549                         printproto(tp, tp->pr_name, &first);
550 #endif /*INET6*/
551 #ifdef IPSEC
552         if (af == PF_KEY || af == AF_UNSPEC)
553                 for (tp = pfkeyprotox; tp->pr_name; tp++)
554                         printproto(tp, tp->pr_name, &first);
555 #endif /*IPSEC*/
556 #ifdef NETGRAPH
557         if (af == AF_NETGRAPH || af == AF_UNSPEC)
558                 for (tp = netgraphprotox; tp->pr_name; tp++)
559                         printproto(tp, tp->pr_name, &first);
560 #endif /* NETGRAPH */
561         if ((af == AF_UNIX || af == AF_UNSPEC) && !sflag)
562                 unixpr(nl[N_UNP_COUNT].n_value, nl[N_UNP_GENCNT].n_value,
563                     nl[N_UNP_DHEAD].n_value, nl[N_UNP_SHEAD].n_value,
564                     nl[N_UNP_SPHEAD].n_value, &first);
565
566         if (!first)
567                 xo_close_list("socket");
568         xo_close_container("statistics");
569         xo_finish();
570         exit(0);
571 }
572
573 static int
574 fetch_stats_internal(const char *sysctlname, u_long off, void *stats,
575     size_t len, kreadfn_t kreadfn, int zero)
576 {
577         int error;
578
579         if (live) {
580                 memset(stats, 0, len);
581                 if (zero)
582                         error = sysctlbyname(sysctlname, NULL, NULL, stats,
583                             len);
584                 else
585                         error = sysctlbyname(sysctlname, stats, &len, NULL, 0);
586                 if (error == -1 && errno != ENOENT)
587                         xo_warn("sysctl %s", sysctlname);
588         } else {
589                 if (off == 0)
590                         return (1);
591                 error = kreadfn(off, stats, len);
592         }
593         return (error);
594 }
595
596 int
597 fetch_stats(const char *sysctlname, u_long off, void *stats,
598     size_t len, kreadfn_t kreadfn)
599 {
600
601         return (fetch_stats_internal(sysctlname, off, stats, len, kreadfn,
602     zflag));
603 }
604
605 int
606 fetch_stats_ro(const char *sysctlname, u_long off, void *stats,
607     size_t len, kreadfn_t kreadfn)
608 {
609
610         return (fetch_stats_internal(sysctlname, off, stats, len, kreadfn, 0));
611 }
612
613 /*
614  * Print out protocol statistics or control blocks (per sflag).
615  * If the interface was not specifically requested, and the symbol
616  * is not in the namelist, ignore this one.
617  */
618 static void
619 printproto(struct protox *tp, const char *name, bool *first)
620 {
621         void (*pr)(u_long, const char *, int, int);
622         u_long off;
623         bool doingdblocks = false;
624
625         if (sflag) {
626                 if (iflag) {
627                         if (tp->pr_istats)
628                                 intpr(tp->pr_istats, af);
629                         else if (pflag)
630                                 xo_message("%s: no per-interface stats routine",
631                                     tp->pr_name);
632                         return;
633                 } else {
634                         pr = tp->pr_stats;
635                         if (!pr) {
636                                 if (pflag)
637                                         xo_message("%s: no stats routine",
638                                             tp->pr_name);
639                                 return;
640                         }
641                         if (tp->pr_usesysctl && live)
642                                 off = 0;
643                         else if (tp->pr_sindex < 0) {
644                                 if (pflag)
645                                         xo_message("%s: stats routine doesn't "
646                                             "work on cores", tp->pr_name);
647                                 return;
648                         } else
649                                 off = nl[tp->pr_sindex].n_value;
650                 }
651         } else {
652                 doingdblocks = true;
653                 pr = tp->pr_cblocks;
654                 if (!pr) {
655                         if (pflag)
656                                 xo_message("%s: no PCB routine", tp->pr_name);
657                         return;
658                 }
659                 if (tp->pr_usesysctl && live)
660                         off = 0;
661                 else if (tp->pr_index < 0) {
662                         if (pflag)
663                                 xo_message("%s: PCB routine doesn't work on "
664                                     "cores", tp->pr_name);
665                         return;
666                 } else
667                         off = nl[tp->pr_index].n_value;
668         }
669         if (pr != NULL && (off || (live && tp->pr_usesysctl) ||
670             af != AF_UNSPEC)) {
671                 if (doingdblocks && *first) {
672                         xo_open_list("socket");
673                         *first = false;
674                 }
675
676                 (*pr)(off, name, af, tp->pr_protocol);
677         }
678 }
679
680 static int
681 kvmd_init(void)
682 {
683         char errbuf[_POSIX2_LINE_MAX];
684
685         if (kvmd != NULL)
686                 return (0);
687
688         kvmd = kvm_openfiles(nlistf, memf, NULL, O_RDONLY, errbuf);
689         if (setgid(getgid()) != 0)
690                 xo_err(-1, "setgid");
691
692         if (kvmd == NULL) {
693                 xo_warnx("kvm not available: %s", errbuf);
694                 return (-1);
695         }
696
697         return (0);
698 }
699
700 /*
701  * Resolve symbol list, return 0 on success.
702  */
703 static int
704 kresolve_list(struct nlist *_nl)
705 {
706
707         if ((kvmd == NULL) && (kvmd_init() != 0))
708                 return (-1);
709
710         if (_nl[0].n_type != 0)
711                 return (0);
712
713         if (kvm_nlist(kvmd, _nl) < 0) {
714                 if (nlistf)
715                         xo_errx(1, "%s: kvm_nlist: %s", nlistf,
716                             kvm_geterr(kvmd));
717                 else
718                         xo_errx(1, "kvm_nlist: %s", kvm_geterr(kvmd));
719         }
720
721         return (0);
722 }
723
724 /*
725  * Wrapper of kvm_dpcpu_setcpu().
726  */
727 void
728 kset_dpcpu(u_int cpuid)
729 {
730
731         if ((kvmd == NULL) && (kvmd_init() != 0))
732                 xo_errx(-1, "%s: kvm is not available", __func__);
733
734         if (kvm_dpcpu_setcpu(kvmd, cpuid) < 0)
735                 xo_errx(-1, "%s: kvm_dpcpu_setcpu(%u): %s", __func__,
736                     cpuid, kvm_geterr(kvmd)); 
737         return;
738 }
739
740 /*
741  * Read kernel memory, return 0 on success.
742  */
743 int
744 kread(u_long addr, void *buf, size_t size)
745 {
746
747         if (kvmd_init() < 0)
748                 return (-1);
749
750         if (!buf)
751                 return (0);
752         if (kvm_read(kvmd, addr, buf, size) != (ssize_t)size) {
753                 xo_warnx("%s", kvm_geterr(kvmd));
754                 return (-1);
755         }
756         return (0);
757 }
758
759 /*
760  * Read single counter(9).
761  */
762 uint64_t
763 kread_counter(u_long addr)
764 {
765
766         if (kvmd_init() < 0)
767                 return (-1);
768
769         return (kvm_counter_u64_fetch(kvmd, addr));
770 }
771
772 /*
773  * Read an array of N counters in kernel memory into array of N uint64_t's.
774  */
775 int
776 kread_counters(u_long addr, void *buf, size_t size)
777 {
778         uint64_t *c;
779         u_long *counters;
780         size_t i, n;
781
782         if (kvmd_init() < 0)
783                 return (-1);
784
785         if (size % sizeof(uint64_t) != 0) {
786                 xo_warnx("kread_counters: invalid counter set size");
787                 return (-1);
788         }
789
790         n = size / sizeof(uint64_t);
791         if ((counters = malloc(n * sizeof(u_long))) == NULL)
792                 xo_err(-1, "malloc");
793         if (kread(addr, counters, n * sizeof(u_long)) < 0) {
794                 free(counters);
795                 return (-1);
796         }
797
798         c = buf;
799         for (i = 0; i < n; i++)
800                 c[i] = kvm_counter_u64_fetch(kvmd, counters[i]);
801
802         free(counters);
803         return (0);
804 }
805
806 const char *
807 plural(uintmax_t n)
808 {
809         return (n != 1 ? "s" : "");
810 }
811
812 const char *
813 plurales(uintmax_t n)
814 {
815         return (n != 1 ? "es" : "");
816 }
817
818 const char *
819 pluralies(uintmax_t n)
820 {
821         return (n != 1 ? "ies" : "y");
822 }
823
824 /*
825  * Find the protox for the given "well-known" name.
826  */
827 static struct protox *
828 knownname(const char *name)
829 {
830         struct protox **tpp, *tp;
831
832         for (tpp = protoprotox; *tpp; tpp++)
833                 for (tp = *tpp; tp->pr_name; tp++)
834                         if (strcmp(tp->pr_name, name) == 0)
835                                 return (tp);
836         return (NULL);
837 }
838
839 /*
840  * Find the protox corresponding to name.
841  */
842 static struct protox *
843 name2protox(const char *name)
844 {
845         struct protox *tp;
846         char **alias;                   /* alias from p->aliases */
847         struct protoent *p;
848
849         /*
850          * Try to find the name in the list of "well-known" names. If that
851          * fails, check if name is an alias for an Internet protocol.
852          */
853         if ((tp = knownname(name)) != NULL)
854                 return (tp);
855
856         setprotoent(1);                 /* make protocol lookup cheaper */
857         while ((p = getprotoent()) != NULL) {
858                 /* assert: name not same as p->name */
859                 for (alias = p->p_aliases; *alias; alias++)
860                         if (strcmp(name, *alias) == 0) {
861                                 endprotoent();
862                                 return (knownname(p->p_name));
863                         }
864         }
865         endprotoent();
866         return (NULL);
867 }
868
869 static void
870 usage(void)
871 {
872         (void)xo_error("%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n",
873 "usage: netstat [-46AaLnRSTWx] [-f protocol_family | -p protocol]\n"
874 "               [-M core] [-N system]",
875 "       netstat -i | -I interface [-46abdhnW] [-f address_family]\n"
876 "               [-M core] [-N system]",
877 "       netstat -w wait [-I interface] [-46d] [-M core] [-N system]\n"
878 "               [-q howmany]",
879 "       netstat -s [-46sz] [-f protocol_family | -p protocol]\n"
880 "               [-M core] [-N system]",
881 "       netstat -i | -I interface -s [-46s]\n"
882 "               [-f protocol_family | -p protocol] [-M core] [-N system]",
883 "       netstat -m [-M core] [-N system]",
884 "       netstat -B [-z] [-I interface]",
885 "       netstat -r [-46AnW] [-F fibnum] [-f address_family]\n"
886 "               [-M core] [-N system]",
887 "       netstat -rs [-s] [-M core] [-N system]",
888 "       netstat -g [-46W] [-f address_family] [-M core] [-N system]",
889 "       netstat -gs [-46s] [-f address_family] [-M core] [-N system]",
890 "       netstat -Q");
891         xo_finish();
892         exit(1);
893 }