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