xref: /freebsd/usr.bin/netstat/main.c (revision fedeb08b)
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	Cflag;		/* show congestion control */
209 int	dflag;		/* show i/f dropped packets */
210 int	gflag;		/* show group (multicast) routing or stats */
211 int	hflag;		/* show counters in human readable format */
212 int	iflag;		/* show interfaces */
213 int	Lflag;		/* show size of listen queues */
214 int	mflag;		/* show memory stats */
215 int	noutputs = 0;	/* how much outputs before we exit */
216 int	numeric_addr;	/* show addresses numerically */
217 int	numeric_port;	/* show ports numerically */
218 int	Oflag;		/* show nhgrp objects*/
219 int	oflag;		/* show nexthop objects*/
220 int	Pflag;		/* show TCP log ID */
221 static int pflag;	/* show given protocol */
222 static int	Qflag;		/* show netisr information */
223 int	rflag;		/* show routing tables (or routing stats) */
224 int	Rflag;		/* show flow / RSS statistics */
225 int	sflag;		/* show protocol statistics */
226 int	Wflag;		/* wide display */
227 int	Tflag;		/* TCP Information */
228 int	xflag;		/* extra information, includes all socket buffer info */
229 int	zflag;		/* zero stats */
230 
231 int	interval;	/* repeat interval for i/f stats */
232 
233 char	*interface;	/* desired i/f for stats, or NULL for all i/fs */
234 int	unit;		/* unit number for above */
235 
236 static int	af;		/* address family */
237 int	live;		/* true if we are examining a live system */
238 
239 int
240 main(int argc, char *argv[])
241 {
242 	struct protox *tp = NULL;  /* for printing cblocks & stats */
243 	int ch;
244 	int fib = -1;
245 	char *endptr;
246 	bool first = true;
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, "46AaBbCdF:f:ghI:iLlM:mN:nOoPp:Qq:RrSTsuWw:xz"))
255 	    != -1)
256 		switch(ch) {
257 		case '4':
258 #ifdef INET
259 			af = AF_INET;
260 #else
261 			errx(1, "IPv4 support is not compiled in");
262 #endif
263 			break;
264 		case '6':
265 #ifdef INET6
266 			af = AF_INET6;
267 #else
268 			errx(1, "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 'd':
287 			dflag = 1;
288 			break;
289 		case 'F':
290 			fib = strtol(optarg, &endptr, 0);
291 			if (*endptr != '\0' ||
292 			    (fib == 0 && (errno == EINVAL || errno == ERANGE)))
293 				xo_errx(1, "%s: invalid fib", optarg);
294 			break;
295 		case 'f':
296 			if (strcmp(optarg, "inet") == 0)
297 				af = AF_INET;
298 #ifdef INET6
299 			else if (strcmp(optarg, "inet6") == 0)
300 				af = AF_INET6;
301 #endif
302 #ifdef IPSEC
303 			else if (strcmp(optarg, "pfkey") == 0)
304 				af = PF_KEY;
305 #endif
306 			else if (strcmp(optarg, "unix") == 0 ||
307 				 strcmp(optarg, "local") == 0)
308 				af = AF_UNIX;
309 #ifdef NETGRAPH
310 			else if (strcmp(optarg, "ng") == 0
311 			    || strcmp(optarg, "netgraph") == 0)
312 				af = AF_NETGRAPH;
313 #endif
314 			else if (strcmp(optarg, "link") == 0)
315 				af = AF_LINK;
316 			else {
317 				xo_errx(1, "%s: unknown address family",
318 				    optarg);
319 			}
320 			break;
321 		case 'g':
322 			gflag = 1;
323 			break;
324 		case 'h':
325 			hflag = 1;
326 			break;
327 		case 'I': {
328 			char *cp;
329 
330 			iflag = 1;
331 			for (cp = interface = optarg; isalpha(*cp); cp++)
332 				continue;
333 			unit = atoi(cp);
334 			break;
335 		}
336 		case 'i':
337 			iflag = 1;
338 			break;
339 		case 'L':
340 			Lflag = 1;
341 			break;
342 		case 'M':
343 			memf = optarg;
344 			break;
345 		case 'm':
346 			mflag = 1;
347 			break;
348 		case 'N':
349 			nlistf = optarg;
350 			break;
351 		case 'n':
352 			numeric_addr = numeric_port = 1;
353 			break;
354 		case 'o':
355 			oflag = 1;
356 			break;
357 		case 'O':
358 			Oflag = 1;
359 			break;
360 		case 'P':
361 			Pflag = 1;
362 			break;
363 		case 'p':
364 			if ((tp = name2protox(optarg)) == NULL) {
365 				xo_errx(1, "%s: unknown or uninstrumented "
366 				    "protocol", optarg);
367 			}
368 			pflag = 1;
369 			break;
370 		case 'Q':
371 			Qflag = 1;
372 			break;
373 		case 'q':
374 			noutputs = atoi(optarg);
375 			if (noutputs != 0)
376 				noutputs++;
377 			break;
378 		case 'r':
379 			rflag = 1;
380 			break;
381 		case 'R':
382 			Rflag = 1;
383 			break;
384 		case 's':
385 			++sflag;
386 			break;
387 		case 'S':
388 			numeric_addr = 1;
389 			break;
390 		case 'u':
391 			af = AF_UNIX;
392 			break;
393 		case 'W':
394 		case 'l':
395 			Wflag = 1;
396 			break;
397 		case 'w':
398 			interval = atoi(optarg);
399 			iflag = 1;
400 			break;
401 		case 'T':
402 			Tflag = 1;
403 			break;
404 		case 'x':
405 			xflag = 1;
406 			break;
407 		case 'z':
408 			zflag = 1;
409 			break;
410 		case '?':
411 		default:
412 			usage();
413 		}
414 	argv += optind;
415 	argc -= optind;
416 
417 #define	BACKWARD_COMPATIBILITY
418 #ifdef	BACKWARD_COMPATIBILITY
419 	if (*argv) {
420 		if (isdigit(**argv)) {
421 			interval = atoi(*argv);
422 			if (interval <= 0)
423 				usage();
424 			++argv;
425 			iflag = 1;
426 		}
427 		if (*argv) {
428 			nlistf = *argv;
429 			if (*++argv)
430 				memf = *argv;
431 		}
432 	}
433 #endif
434 
435 	/*
436 	 * Discard setgid privileges if not the running kernel so that bad
437 	 * guys can't print interesting stuff from kernel memory.
438 	 */
439 	live = (nlistf == NULL && memf == NULL);
440 	if (!live) {
441 		if (setgid(getgid()) != 0)
442 			xo_err(-1, "setgid");
443 		/* Load all necessary kvm symbols */
444 		kresolve_list(nl);
445 	}
446 
447 	if (xflag && Tflag)
448 		xo_errx(1, "-x and -T are incompatible, pick one.");
449 
450 	if (Bflag) {
451 		if (!live)
452 			usage();
453 		bpf_stats(interface);
454 		xo_finish();
455 		exit(0);
456 	}
457 	if (mflag) {
458 		if (!live) {
459 			if (kread(0, NULL, 0) == 0)
460 				mbpr(kvmd, nl[N_SFSTAT].n_value);
461 		} else
462 			mbpr(NULL, 0);
463 		xo_finish();
464 		exit(0);
465 	}
466 	if (Qflag) {
467 		if (!live) {
468 			if (kread(0, NULL, 0) == 0)
469 				netisr_stats();
470 		} else
471 			netisr_stats();
472 		xo_finish();
473 		exit(0);
474 	}
475 #if 0
476 	/*
477 	 * Keep file descriptors open to avoid overhead
478 	 * of open/close on each call to get* routines.
479 	 */
480 	sethostent(1);
481 	setnetent(1);
482 #else
483 	/*
484 	 * This does not make sense any more with DNS being default over
485 	 * the files.  Doing a setXXXXent(1) causes a tcp connection to be
486 	 * used for the queries, which is slower.
487 	 */
488 #endif
489 	if (iflag && !sflag) {
490 		xo_open_container("statistics");
491 		intpr(NULL, af);
492 		xo_close_container("statistics");
493 		xo_finish();
494 		exit(0);
495 	}
496 	if (rflag) {
497 		xo_open_container("statistics");
498 		if (sflag) {
499 			if (live) {
500 				kresolve_list(nl);
501 			}
502 			rt_stats();
503 		} else
504 			routepr(fib, af);
505 		xo_close_container("statistics");
506 		xo_finish();
507 		exit(0);
508 	}
509 	if (oflag) {
510 		xo_open_container("statistics");
511 		nhops_print(fib, af);
512 		xo_close_container("statistics");
513 		xo_finish();
514 		exit(0);
515 	}
516 	if (Oflag) {
517 		xo_open_container("statistics");
518 		nhgrp_print(fib, af);
519 		xo_close_container("statistics");
520 		xo_finish();
521 		exit(0);
522 	}
523 
524 
525 
526 	if (gflag) {
527 		xo_open_container("statistics");
528 		if (sflag) {
529 			if (af == AF_INET || af == AF_UNSPEC)
530 				mrt_stats();
531 #ifdef INET6
532 			if (af == AF_INET6 || af == AF_UNSPEC)
533 				mrt6_stats();
534 #endif
535 		} else {
536 			if (af == AF_INET || af == AF_UNSPEC)
537 				mroutepr();
538 #ifdef INET6
539 			if (af == AF_INET6 || af == AF_UNSPEC)
540 				mroute6pr();
541 #endif
542 		}
543 		xo_close_container("statistics");
544 		xo_finish();
545 		exit(0);
546 	}
547 
548 	if (tp) {
549 		xo_open_container("statistics");
550 		printproto(tp, tp->pr_name, &first);
551 		if (!first)
552 			xo_close_list("socket");
553 		xo_close_container("statistics");
554 		xo_finish();
555 		exit(0);
556 	}
557 
558 	xo_open_container("statistics");
559 	if (af == AF_INET || af == AF_UNSPEC)
560 		for (tp = protox; tp->pr_name; tp++)
561 			printproto(tp, tp->pr_name, &first);
562 #ifdef INET6
563 	if (af == AF_INET6 || af == AF_UNSPEC)
564 		for (tp = ip6protox; tp->pr_name; tp++)
565 			printproto(tp, tp->pr_name, &first);
566 #endif /*INET6*/
567 #ifdef IPSEC
568 	if (af == PF_KEY || af == AF_UNSPEC)
569 		for (tp = pfkeyprotox; tp->pr_name; tp++)
570 			printproto(tp, tp->pr_name, &first);
571 #endif /*IPSEC*/
572 #ifdef NETGRAPH
573 	if (af == AF_NETGRAPH || af == AF_UNSPEC)
574 		for (tp = netgraphprotox; tp->pr_name; tp++)
575 			printproto(tp, tp->pr_name, &first);
576 #endif /* NETGRAPH */
577 	if ((af == AF_UNIX || af == AF_UNSPEC) && !sflag)
578 		unixpr(nl[N_UNP_COUNT].n_value, nl[N_UNP_GENCNT].n_value,
579 		    nl[N_UNP_DHEAD].n_value, nl[N_UNP_SHEAD].n_value,
580 		    nl[N_UNP_SPHEAD].n_value, &first);
581 
582 	if (!first)
583 		xo_close_list("socket");
584 	xo_close_container("statistics");
585 	xo_finish();
586 	exit(0);
587 }
588 
589 static int
590 fetch_stats_internal(const char *sysctlname, u_long off, void *stats,
591     size_t len, kreadfn_t kreadfn, int zero)
592 {
593 	int error;
594 
595 	if (live) {
596 		memset(stats, 0, len);
597 		if (zero)
598 			error = sysctlbyname(sysctlname, NULL, NULL, stats,
599 			    len);
600 		else
601 			error = sysctlbyname(sysctlname, stats, &len, NULL, 0);
602 		if (error == -1 && errno != ENOENT)
603 			xo_warn("sysctl %s", sysctlname);
604 	} else {
605 		if (off == 0)
606 			return (1);
607 		error = kreadfn(off, stats, len);
608 	}
609 	return (error);
610 }
611 
612 int
613 fetch_stats(const char *sysctlname, u_long off, void *stats,
614     size_t len, kreadfn_t kreadfn)
615 {
616 
617 	return (fetch_stats_internal(sysctlname, off, stats, len, kreadfn,
618     zflag));
619 }
620 
621 int
622 fetch_stats_ro(const char *sysctlname, u_long off, void *stats,
623     size_t len, kreadfn_t kreadfn)
624 {
625 
626 	return (fetch_stats_internal(sysctlname, off, stats, len, kreadfn, 0));
627 }
628 
629 /*
630  * Print out protocol statistics or control blocks (per sflag).
631  * If the interface was not specifically requested, and the symbol
632  * is not in the namelist, ignore this one.
633  */
634 static void
635 printproto(struct protox *tp, const char *name, bool *first)
636 {
637 	void (*pr)(u_long, const char *, int, int);
638 	u_long off;
639 	bool doingdblocks = false;
640 
641 	if (sflag) {
642 		if (iflag) {
643 			if (tp->pr_istats)
644 				intpr(tp->pr_istats, af);
645 			else if (pflag)
646 				xo_message("%s: no per-interface stats routine",
647 				    tp->pr_name);
648 			return;
649 		} else {
650 			pr = tp->pr_stats;
651 			if (!pr) {
652 				if (pflag)
653 					xo_message("%s: no stats routine",
654 					    tp->pr_name);
655 				return;
656 			}
657 			if (tp->pr_usesysctl && live)
658 				off = 0;
659 			else if (tp->pr_sindex < 0) {
660 				if (pflag)
661 					xo_message("%s: stats routine doesn't "
662 					    "work on cores", tp->pr_name);
663 				return;
664 			} else
665 				off = nl[tp->pr_sindex].n_value;
666 		}
667 	} else {
668 		doingdblocks = true;
669 		pr = tp->pr_cblocks;
670 		if (!pr) {
671 			if (pflag)
672 				xo_message("%s: no PCB routine", tp->pr_name);
673 			return;
674 		}
675 		if (tp->pr_usesysctl && live)
676 			off = 0;
677 		else if (tp->pr_index < 0) {
678 			if (pflag)
679 				xo_message("%s: PCB routine doesn't work on "
680 				    "cores", tp->pr_name);
681 			return;
682 		} else
683 			off = nl[tp->pr_index].n_value;
684 	}
685 	if (pr != NULL && (off || (live && tp->pr_usesysctl) ||
686 	    af != AF_UNSPEC)) {
687 		if (doingdblocks && *first) {
688 			xo_open_list("socket");
689 			*first = false;
690 		}
691 
692 		(*pr)(off, name, af, tp->pr_protocol);
693 	}
694 }
695 
696 static int
697 kvmd_init(void)
698 {
699 	char errbuf[_POSIX2_LINE_MAX];
700 
701 	if (kvmd != NULL)
702 		return (0);
703 
704 	kvmd = kvm_openfiles(nlistf, memf, NULL, O_RDONLY, errbuf);
705 	if (setgid(getgid()) != 0)
706 		xo_err(-1, "setgid");
707 
708 	if (kvmd == NULL) {
709 		xo_warnx("kvm not available: %s", errbuf);
710 		return (-1);
711 	}
712 
713 	return (0);
714 }
715 
716 /*
717  * Resolve symbol list, return 0 on success.
718  */
719 static int
720 kresolve_list(struct nlist *_nl)
721 {
722 
723 	if ((kvmd == NULL) && (kvmd_init() != 0))
724 		return (-1);
725 
726 	if (_nl[0].n_type != 0)
727 		return (0);
728 
729 	if (kvm_nlist(kvmd, _nl) < 0) {
730 		if (nlistf)
731 			xo_errx(1, "%s: kvm_nlist: %s", nlistf,
732 			    kvm_geterr(kvmd));
733 		else
734 			xo_errx(1, "kvm_nlist: %s", kvm_geterr(kvmd));
735 	}
736 
737 	return (0);
738 }
739 
740 /*
741  * Wrapper of kvm_dpcpu_setcpu().
742  */
743 void
744 kset_dpcpu(u_int cpuid)
745 {
746 
747 	if ((kvmd == NULL) && (kvmd_init() != 0))
748 		xo_errx(-1, "%s: kvm is not available", __func__);
749 
750 	if (kvm_dpcpu_setcpu(kvmd, cpuid) < 0)
751 		xo_errx(-1, "%s: kvm_dpcpu_setcpu(%u): %s", __func__,
752 		    cpuid, kvm_geterr(kvmd));
753 	return;
754 }
755 
756 /*
757  * Read kernel memory, return 0 on success.
758  */
759 int
760 kread(u_long addr, void *buf, size_t size)
761 {
762 
763 	if (kvmd_init() < 0)
764 		return (-1);
765 
766 	if (!buf)
767 		return (0);
768 	if (kvm_read(kvmd, addr, buf, size) != (ssize_t)size) {
769 		xo_warnx("%s", kvm_geterr(kvmd));
770 		return (-1);
771 	}
772 	return (0);
773 }
774 
775 /*
776  * Read single counter(9).
777  */
778 uint64_t
779 kread_counter(u_long addr)
780 {
781 
782 	if (kvmd_init() < 0)
783 		return (-1);
784 
785 	return (kvm_counter_u64_fetch(kvmd, addr));
786 }
787 
788 /*
789  * Read an array of N counters in kernel memory into array of N uint64_t's.
790  */
791 int
792 kread_counters(u_long addr, void *buf, size_t size)
793 {
794 	uint64_t *c;
795 	u_long *counters;
796 	size_t i, n;
797 
798 	if (kvmd_init() < 0)
799 		return (-1);
800 
801 	if (size % sizeof(uint64_t) != 0) {
802 		xo_warnx("kread_counters: invalid counter set size");
803 		return (-1);
804 	}
805 
806 	n = size / sizeof(uint64_t);
807 	if ((counters = malloc(n * sizeof(u_long))) == NULL)
808 		xo_err(-1, "malloc");
809 	if (kread(addr, counters, n * sizeof(u_long)) < 0) {
810 		free(counters);
811 		return (-1);
812 	}
813 
814 	c = buf;
815 	for (i = 0; i < n; i++)
816 		c[i] = kvm_counter_u64_fetch(kvmd, counters[i]);
817 
818 	free(counters);
819 	return (0);
820 }
821 
822 const char *
823 plural(uintmax_t n)
824 {
825 	return (n != 1 ? "s" : "");
826 }
827 
828 const char *
829 plurales(uintmax_t n)
830 {
831 	return (n != 1 ? "es" : "");
832 }
833 
834 const char *
835 pluralies(uintmax_t n)
836 {
837 	return (n != 1 ? "ies" : "y");
838 }
839 
840 /*
841  * Find the protox for the given "well-known" name.
842  */
843 static struct protox *
844 knownname(const char *name)
845 {
846 	struct protox **tpp, *tp;
847 
848 	for (tpp = protoprotox; *tpp; tpp++)
849 		for (tp = *tpp; tp->pr_name; tp++)
850 			if (strcmp(tp->pr_name, name) == 0)
851 				return (tp);
852 	return (NULL);
853 }
854 
855 /*
856  * Find the protox corresponding to name.
857  */
858 static struct protox *
859 name2protox(const char *name)
860 {
861 	struct protox *tp;
862 	char **alias;			/* alias from p->aliases */
863 	struct protoent *p;
864 
865 	/*
866 	 * Try to find the name in the list of "well-known" names. If that
867 	 * fails, check if name is an alias for an Internet protocol.
868 	 */
869 	if ((tp = knownname(name)) != NULL)
870 		return (tp);
871 
872 	setprotoent(1);			/* make protocol lookup cheaper */
873 	while ((p = getprotoent()) != NULL) {
874 		/* assert: name not same as p->name */
875 		for (alias = p->p_aliases; *alias; alias++)
876 			if (strcmp(name, *alias) == 0) {
877 				endprotoent();
878 				return (knownname(p->p_name));
879 			}
880 	}
881 	endprotoent();
882 	return (NULL);
883 }
884 
885 static void
886 usage(void)
887 {
888 	(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",
889 "usage: netstat [-46AaLnRSTWx] [-f protocol_family | -p protocol]\n"
890 "               [-M core] [-N system]",
891 "       netstat -i | -I interface [-46abdhnW] [-f address_family]\n"
892 "               [-M core] [-N system]",
893 "       netstat -w wait [-I interface] [-46d] [-M core] [-N system]\n"
894 "               [-q howmany]",
895 "       netstat -s [-46sz] [-f protocol_family | -p protocol]\n"
896 "               [-M core] [-N system]",
897 "       netstat -i | -I interface -s [-46s]\n"
898 "               [-f protocol_family | -p protocol] [-M core] [-N system]",
899 "       netstat -m [-M core] [-N system]",
900 "       netstat -B [-z] [-I interface]",
901 "       netstat -r [-46AnW] [-F fibnum] [-f address_family]\n"
902 "               [-M core] [-N system]",
903 "       netstat -rs [-s] [-M core] [-N system]",
904 "       netstat -g [-46W] [-f address_family] [-M core] [-N system]",
905 "       netstat -gs [-46s] [-f address_family] [-M core] [-N system]",
906 "       netstat -Q");
907 	xo_finish();
908 	exit(1);
909 }
910