xref: /freebsd/usr.bin/netstat/main.c (revision 49f31b5e0ca7a335b35dbaec92769e4c7237a85e)
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 bool	Aflag;		/* show addresses of protocol control block */
198 bool	aflag;		/* show all sockets (including servers) */
199 static bool	Bflag;		/* show information about bpf consumers */
200 bool	bflag;		/* show i/f total bytes in/out */
201 bool	cflag;		/* show TCP congestion control stack */
202 bool	Cflag;		/* show congestion control algo and vars */
203 bool	dflag;		/* show i/f dropped packets */
204 bool	gflag;		/* show group (multicast) routing or stats */
205 bool	hflag;		/* show counters in human readable format */
206 bool	iflag;		/* show interfaces */
207 bool	Lflag;		/* show size of listen queues */
208 bool	mflag;		/* show memory stats */
209 int	noutputs = 0;	/* how much outputs before we exit */
210 u_int	numeric_addr = 0; /* show addresses numerically */
211 bool	numeric_port;	/* show ports numerically */
212 bool	Oflag;		/* show nhgrp objects*/
213 bool	oflag;		/* show nexthop objects*/
214 bool	Pflag;		/* show TCP log ID */
215 static bool pflag;	/* show given protocol */
216 static bool Qflag;	/* show netisr information */
217 bool	rflag;		/* show routing tables (or routing stats) */
218 bool	Rflag;		/* show flow / RSS statistics */
219 int	sflag;		/* show protocol statistics */
220 bool	Wflag;		/* wide display */
221 bool	Tflag;		/* TCP Information */
222 bool	xflag;		/* extra information, includes all socket buffer info */
223 bool	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
main(int argc,char * argv[])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 = true;
273 			break;
274 		case 'a':
275 			aflag = true;
276 			break;
277 		case 'B':
278 			Bflag = true;
279 			break;
280 		case 'b':
281 			bflag = true;
282 			break;
283 		case 'c':
284 			cflag = true;
285 			break;
286 		case 'C':
287 			Cflag = true;
288 			break;
289 		case 'd':
290 			dflag = true;
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 = true;
326 			break;
327 		case 'h':
328 			hflag = true;
329 			break;
330 		case 'I': {
331 			char *cp;
332 
333 			iflag = true;
334 			for (cp = interface = optarg; isalpha(*cp); cp++)
335 				continue;
336 			unit = atoi(cp);
337 			break;
338 		}
339 		case 'i':
340 			iflag = true;
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 = true;
353 			break;
354 		case 'M':
355 			memf = optarg;
356 			break;
357 		case 'm':
358 			mflag = true;
359 			break;
360 		case 'N':
361 			nlistf = optarg;
362 			break;
363 		case 'n':
364 			numeric_addr++;
365 			numeric_port = true;
366 			break;
367 		case 'o':
368 			oflag = true;
369 			break;
370 		case 'O':
371 			Oflag = true;
372 			break;
373 		case 'P':
374 			Pflag = true;
375 			break;
376 		case 'p':
377 			if ((tp = name2protox(optarg)) == NULL) {
378 				xo_errx(EX_DATAERR, "%s: unknown or uninstrumented "
379 				    "protocol", optarg);
380 			}
381 			pflag = true;
382 			break;
383 		case 'Q':
384 			Qflag = true;
385 			break;
386 		case 'q':
387 			noutputs = atoi(optarg);
388 			if (noutputs != 0)
389 				noutputs++;
390 			break;
391 		case 'r':
392 			rflag = true;
393 			break;
394 		case 'R':
395 			Rflag = true;
396 			break;
397 		case 's':
398 			++sflag;
399 			break;
400 		case 'S':
401 			numeric_addr = 1;
402 			break;
403 		case 'u':
404 			af = AF_UNIX;
405 			break;
406 		case 'W':
407 		case 'l':
408 			Wflag = true;
409 			break;
410 		case 'w':
411 			interval = atoi(optarg);
412 			iflag = true;
413 			break;
414 		case 'T':
415 			Tflag = true;
416 			break;
417 		case 'x':
418 			xflag = true;
419 			break;
420 		case 'z':
421 			zflag = true;
422 			break;
423 		case '?':
424 		default:
425 			usage();
426 		}
427 	argv += optind;
428 	argc -= optind;
429 
430 #define	BACKWARD_COMPATIBILITY
431 #ifdef	BACKWARD_COMPATIBILITY
432 	if (*argv) {
433 		if (isdigit(**argv)) {
434 			interval = atoi(*argv);
435 			if (interval <= 0)
436 				usage();
437 			++argv;
438 			iflag = true;
439 		}
440 		if (*argv) {
441 			nlistf = *argv;
442 			if (*++argv)
443 				memf = *argv;
444 		}
445 	}
446 #endif
447 
448 #ifdef JAIL
449 	if (jail_name != NULL) {
450 		jid = jail_getid(jail_name);
451 		if (jid == -1)
452 			xo_errx(EX_UNAVAILABLE, "Jail not found");
453 		if (jail_attach(jid) != 0)
454 			xo_errx(EX_UNAVAILABLE, "Cannot attach to jail");
455 	}
456 #endif
457 
458 	live = (nlistf == NULL && memf == NULL);
459 	/* Load all necessary kvm symbols */
460 	if (!live)
461 		kresolve_list(nl);
462 
463 	if (xflag && Tflag)
464 		xo_errx(EX_USAGE, "-x and -T are incompatible, pick one.");
465 
466 	if (Bflag) {
467 		if (!live)
468 			usage();
469 		bpf_stats(interface);
470 		if (xo_finish() < 0)
471 			xo_err(EX_IOERR, "stdout");
472 		exit(EX_OK);
473 	}
474 	if (mflag) {
475 		if (!live) {
476 			if (kread(0, NULL, 0) == 0)
477 				mbpr(kvmd, nl[N_SFSTAT].n_value);
478 		} else
479 			mbpr(NULL, 0);
480 		if (xo_finish() < 0)
481 			xo_err(EX_IOERR, "stdout");
482 		exit(EX_OK);
483 	}
484 	if (Qflag) {
485 		if (!live) {
486 			if (kread(0, NULL, 0) == 0)
487 				netisr_stats();
488 		} else
489 			netisr_stats();
490 		if (xo_finish() < 0)
491 			xo_err(EX_IOERR, "stdout");
492 		exit(EX_OK);
493 	}
494 #if 0
495 	/*
496 	 * Keep file descriptors open to avoid overhead
497 	 * of open/close on each call to get* routines.
498 	 */
499 	sethostent(1);
500 	setnetent(1);
501 #else
502 	/*
503 	 * This does not make sense any more with DNS being default over
504 	 * the files.  Doing a setXXXXent(1) causes a tcp connection to be
505 	 * used for the queries, which is slower.
506 	 */
507 #endif
508 	if (iflag && !sflag) {
509 		xo_open_container("statistics");
510 		xo_set_version(NETSTAT_XO_VERSION);
511 		intpr(NULL, af);
512 		xo_close_container("statistics");
513 		if (xo_finish() < 0)
514 			xo_err(EX_IOERR, "stdout");
515 		exit(EX_OK);
516 	}
517 	if (rflag) {
518 		xo_open_container("statistics");
519 		xo_set_version(NETSTAT_XO_VERSION);
520 		if (sflag)
521 			rt_stats();
522 		else
523 			routepr(fib, af);
524 		xo_close_container("statistics");
525 		if (xo_finish() < 0)
526 			xo_err(EX_IOERR, "stdout");
527 		exit(EX_OK);
528 	}
529 	if (oflag) {
530 		xo_open_container("statistics");
531 		xo_set_version(NETSTAT_XO_VERSION);
532 		nhops_print(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 		nhgrp_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 
548 
549 
550 	if (gflag) {
551 		xo_open_container("statistics");
552 		xo_set_version(NETSTAT_XO_VERSION);
553 		if (sflag) {
554 			if (af == AF_INET || af == AF_UNSPEC)
555 				mrt_stats();
556 #ifdef INET6
557 			if (af == AF_INET6 || af == AF_UNSPEC)
558 				mrt6_stats();
559 #endif
560 		} else {
561 			if (af == AF_INET || af == AF_UNSPEC)
562 				mroutepr();
563 #ifdef INET6
564 			if (af == AF_INET6 || af == AF_UNSPEC)
565 				mroute6pr();
566 #endif
567 		}
568 		xo_close_container("statistics");
569 		if (xo_finish() < 0)
570 			xo_err(EX_IOERR, "stdout");
571 		exit(EX_OK);
572 	}
573 
574 	if (tp) {
575 		xo_open_container("statistics");
576 		xo_set_version(NETSTAT_XO_VERSION);
577 		printproto(tp, tp->pr_name, &first);
578 		if (!first)
579 			xo_close_list("socket");
580 		xo_close_container("statistics");
581 		if (xo_finish() < 0)
582 			xo_err(EX_IOERR, "stdout");
583 		exit(EX_OK);
584 	}
585 
586 	xo_open_container("statistics");
587 	xo_set_version(NETSTAT_XO_VERSION);
588 	if (af == AF_INET || af == AF_UNSPEC)
589 		for (tp = protox; tp->pr_name; tp++)
590 			printproto(tp, tp->pr_name, &first);
591 #ifdef INET6
592 	if (af == AF_INET6 || af == AF_UNSPEC)
593 		for (tp = ip6protox; tp->pr_name; tp++)
594 			printproto(tp, tp->pr_name, &first);
595 #endif /*INET6*/
596 #ifdef IPSEC
597 	if (af == PF_KEY || af == AF_UNSPEC)
598 		for (tp = pfkeyprotox; tp->pr_name; tp++)
599 			printproto(tp, tp->pr_name, &first);
600 #endif /*IPSEC*/
601 #ifdef NETGRAPH
602 	if (af == AF_NETGRAPH || af == AF_UNSPEC)
603 		for (tp = netgraphprotox; tp->pr_name; tp++)
604 			printproto(tp, tp->pr_name, &first);
605 #endif /* NETGRAPH */
606 	if ((af == AF_UNIX || af == AF_UNSPEC) && !sflag)
607 		unixpr(nl[N_UNP_COUNT].n_value, nl[N_UNP_GENCNT].n_value,
608 		    nl[N_UNP_DHEAD].n_value, nl[N_UNP_SHEAD].n_value,
609 		    nl[N_UNP_SPHEAD].n_value, &first);
610 
611 	if (!first)
612 		xo_close_list("socket");
613 	xo_close_container("statistics");
614 	if (xo_finish() < 0)
615 		xo_err(EX_IOERR, "stdout");
616 	exit(EX_OK);
617 }
618 
619 static int
fetch_stats_internal(const char * sysctlname,u_long off,void * stats,size_t len,kreadfn_t kreadfn,int zero)620 fetch_stats_internal(const char *sysctlname, u_long off, void *stats,
621     size_t len, kreadfn_t kreadfn, int zero)
622 {
623 	int error;
624 
625 	if (live) {
626 		memset(stats, 0, len);
627 		if (zero)
628 			error = sysctlbyname(sysctlname, NULL, NULL, stats,
629 			    len);
630 		else
631 			error = sysctlbyname(sysctlname, stats, &len, NULL, 0);
632 		if (error == -1 && errno != ENOENT)
633 			xo_warn("sysctl %s", sysctlname);
634 	} else {
635 		if (off == 0)
636 			return (1);
637 		error = kreadfn(off, stats, len);
638 	}
639 	return (error);
640 }
641 
642 int
fetch_stats(const char * sysctlname,u_long off,void * stats,size_t len,kreadfn_t kreadfn)643 fetch_stats(const char *sysctlname, u_long off, void *stats,
644     size_t len, kreadfn_t kreadfn)
645 {
646 
647 	return (fetch_stats_internal(sysctlname, off, stats, len, kreadfn,
648     zflag));
649 }
650 
651 int
fetch_stats_ro(const char * sysctlname,u_long off,void * stats,size_t len,kreadfn_t kreadfn)652 fetch_stats_ro(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, 0));
657 }
658 
659 /*
660  * Print out protocol statistics or control blocks (per sflag).
661  * If the interface was not specifically requested, and the symbol
662  * is not in the namelist, ignore this one.
663  */
664 static void
printproto(struct protox * tp,const char * name,bool * first)665 printproto(struct protox *tp, const char *name, bool *first)
666 {
667 	void (*pr)(u_long, const char *, int, int);
668 	u_long off;
669 	bool doingdblocks = false;
670 
671 	if (sflag) {
672 		if (iflag) {
673 			if (tp->pr_istats)
674 				intpr(tp->pr_istats, af);
675 			else if (pflag)
676 				xo_message("%s: no per-interface stats routine",
677 				    tp->pr_name);
678 			return;
679 		} else {
680 			pr = tp->pr_stats;
681 			if (!pr) {
682 				if (pflag)
683 					xo_message("%s: no stats routine",
684 					    tp->pr_name);
685 				return;
686 			}
687 			if (tp->pr_usesysctl && live)
688 				off = 0;
689 			else if (tp->pr_sindex < 0) {
690 				if (pflag)
691 					xo_message("%s: stats routine doesn't "
692 					    "work on cores", tp->pr_name);
693 				return;
694 			} else
695 				off = nl[tp->pr_sindex].n_value;
696 		}
697 	} else {
698 		doingdblocks = true;
699 		pr = tp->pr_cblocks;
700 		if (!pr) {
701 			if (pflag)
702 				xo_message("%s: no PCB routine", tp->pr_name);
703 			return;
704 		}
705 		if (tp->pr_usesysctl && live)
706 			off = 0;
707 		else if (tp->pr_index < 0) {
708 			if (pflag)
709 				xo_message("%s: PCB routine doesn't work on "
710 				    "cores", tp->pr_name);
711 			return;
712 		} else
713 			off = nl[tp->pr_index].n_value;
714 	}
715 	if (pr != NULL && (off || (live && tp->pr_usesysctl) ||
716 	    af != AF_UNSPEC)) {
717 		if (doingdblocks && *first) {
718 			xo_open_list("socket");
719 			*first = false;
720 		}
721 
722 		(*pr)(off, name, af, tp->pr_protocol);
723 	}
724 }
725 
726 static int
kvmd_init(void)727 kvmd_init(void)
728 {
729 	char errbuf[_POSIX2_LINE_MAX];
730 
731 	if (kvmd != NULL)
732 		return (0);
733 
734 	kvmd = kvm_openfiles(nlistf, memf, NULL, O_RDONLY, errbuf);
735 	if (kvmd == NULL) {
736 		xo_warnx("kvm not available: %s", errbuf);
737 		return (-1);
738 	}
739 
740 	return (0);
741 }
742 
743 /*
744  * Resolve symbol list, return 0 on success.
745  */
746 static int
kresolve_list(struct nlist * _nl)747 kresolve_list(struct nlist *_nl)
748 {
749 
750 	if ((kvmd == NULL) && (kvmd_init() != 0))
751 		return (-1);
752 
753 	if (_nl[0].n_type != 0)
754 		return (0);
755 
756 	if (kvm_nlist(kvmd, _nl) < 0) {
757 		if (nlistf)
758 			xo_errx(EX_UNAVAILABLE, "%s: kvm_nlist: %s", nlistf,
759 			    kvm_geterr(kvmd));
760 		else
761 			xo_errx(EX_UNAVAILABLE, "kvm_nlist: %s", kvm_geterr(kvmd));
762 	}
763 
764 	return (0);
765 }
766 
767 /*
768  * Wrapper of kvm_dpcpu_setcpu().
769  */
770 void
kset_dpcpu(u_int cpuid)771 kset_dpcpu(u_int cpuid)
772 {
773 
774 	if ((kvmd == NULL) && (kvmd_init() != 0))
775 		xo_errx(EX_UNAVAILABLE, "%s: kvm is not available", __func__);
776 
777 	if (kvm_dpcpu_setcpu(kvmd, cpuid) < 0)
778 		xo_errx(EX_UNAVAILABLE, "%s: kvm_dpcpu_setcpu(%u): %s", __func__,
779 		    cpuid, kvm_geterr(kvmd));
780 	return;
781 }
782 
783 /*
784  * Read kernel memory, return 0 on success.
785  */
786 int
kread(u_long addr,void * buf,size_t size)787 kread(u_long addr, void *buf, size_t size)
788 {
789 
790 	if (kvmd_init() < 0)
791 		return (-1);
792 
793 	if (!buf)
794 		return (0);
795 	if (kvm_read(kvmd, addr, buf, size) != (ssize_t)size) {
796 		xo_warnx("%s", kvm_geterr(kvmd));
797 		return (-1);
798 	}
799 	return (0);
800 }
801 
802 /*
803  * Read single counter(9).
804  */
805 uint64_t
kread_counter(u_long addr)806 kread_counter(u_long addr)
807 {
808 
809 	if (kvmd_init() < 0)
810 		return (-1);
811 
812 	return (kvm_counter_u64_fetch(kvmd, addr));
813 }
814 
815 /*
816  * Read an array of N counters in kernel memory into array of N uint64_t's.
817  */
818 int
kread_counters(u_long addr,void * buf,size_t size)819 kread_counters(u_long addr, void *buf, size_t size)
820 {
821 	uint64_t *c;
822 	u_long *counters;
823 	size_t i, n;
824 
825 	if (kvmd_init() < 0)
826 		return (-1);
827 
828 	if (size % sizeof(uint64_t) != 0) {
829 		xo_warnx("kread_counters: invalid counter set size");
830 		return (-1);
831 	}
832 
833 	n = size / sizeof(uint64_t);
834 	if ((counters = malloc(n * sizeof(u_long))) == NULL)
835 		xo_err(EX_OSERR, "malloc");
836 	if (kread(addr, counters, n * sizeof(u_long)) < 0) {
837 		free(counters);
838 		return (-1);
839 	}
840 
841 	c = buf;
842 	for (i = 0; i < n; i++)
843 		c[i] = kvm_counter_u64_fetch(kvmd, counters[i]);
844 
845 	free(counters);
846 	return (0);
847 }
848 
849 const char *
plural(uintmax_t n)850 plural(uintmax_t n)
851 {
852 	return (n != 1 ? "s" : "");
853 }
854 
855 const char *
plurales(uintmax_t n)856 plurales(uintmax_t n)
857 {
858 	return (n != 1 ? "es" : "");
859 }
860 
861 const char *
pluralies(uintmax_t n)862 pluralies(uintmax_t n)
863 {
864 	return (n != 1 ? "ies" : "y");
865 }
866 
867 /*
868  * Find the protox for the given "well-known" name.
869  */
870 static struct protox *
knownname(const char * name)871 knownname(const char *name)
872 {
873 	struct protox **tpp, *tp;
874 
875 	for (tpp = protoprotox; *tpp; tpp++)
876 		for (tp = *tpp; tp->pr_name; tp++)
877 			if (strcmp(tp->pr_name, name) == 0)
878 				return (tp);
879 	return (NULL);
880 }
881 
882 /*
883  * Find the protox corresponding to name.
884  */
885 static struct protox *
name2protox(const char * name)886 name2protox(const char *name)
887 {
888 	struct protox *tp;
889 	char **alias;			/* alias from p->aliases */
890 	struct protoent *p;
891 
892 	/*
893 	 * Try to find the name in the list of "well-known" names. If that
894 	 * fails, check if name is an alias for an Internet protocol.
895 	 */
896 	if ((tp = knownname(name)) != NULL)
897 		return (tp);
898 
899 	setprotoent(1);			/* make protocol lookup cheaper */
900 	while ((p = getprotoent()) != NULL) {
901 		/* assert: name not same as p->name */
902 		for (alias = p->p_aliases; *alias; alias++)
903 			if (strcmp(name, *alias) == 0) {
904 				endprotoent();
905 				return (knownname(p->p_name));
906 			}
907 	}
908 	endprotoent();
909 	return (NULL);
910 }
911 
912 static void
usage(void)913 usage(void)
914 {
915 	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",
916 "usage: netstat [-j jail] [-46AaCcLnRSTWx] [-f protocol_family | -p protocol]\n"
917 "               [-M core] [-N system]",
918 "       netstat [-j jail] -i | -I interface [-46abdhnW] [-f address_family]\n"
919 "               [-M core] [-N system]",
920 "       netstat [-j jail] -w wait [-I interface] [-46d] [-M core] [-N system]\n"
921 "               [-q howmany]",
922 "       netstat [-j jail] -s [-46sz] [-f protocol_family | -p protocol]\n"
923 "               [-M core] [-N system]",
924 "       netstat [-j jail] -i | -I interface -s [-46s]\n"
925 "               [-f protocol_family | -p protocol] [-M core] [-N system]",
926 "       netstat [-j jail] -m [-M core] [-N system]",
927 "       netstat [-j jail] -B [-z] [-I interface]",
928 "       netstat [-j jail] -r [-46AnW] [-F fibnum] [-f address_family]\n"
929 "               [-M core] [-N system]",
930 "       netstat [-j jail] -rs [-s] [-M core] [-N system]",
931 "       netstat [-j jail] -g [-46W] [-f address_family] [-M core] [-N system]",
932 "       netstat [-j jail] -gs [-46s] [-f address_family] [-M core] [-N system]",
933 "       netstat [-j jail] -Q");
934 	exit(EX_USAGE);
935 }
936