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