xref: /freebsd/usr.bin/netstat/inet.c (revision b88cc53d4ddda4486683ee2121f131b10ed21c30)
1 /*-
2  * Copyright (c) 1983, 1988, 1993, 1995
3  *	The 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  * 3. 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 #if 0
31 #ifndef lint
32 static char sccsid[] = "@(#)inet.c	8.5 (Berkeley) 5/24/95";
33 #endif /* not lint */
34 #endif
35 
36 #include <sys/cdefs.h>
37 __FBSDID("$FreeBSD$");
38 
39 #include <sys/param.h>
40 #include <sys/queue.h>
41 #include <sys/domain.h>
42 #include <sys/protosw.h>
43 #include <sys/socket.h>
44 #define	_WANT_SOCKET
45 #include <sys/socketvar.h>
46 #include <sys/sysctl.h>
47 
48 #include <net/route.h>
49 #include <net/if_arp.h>
50 #include <netinet/in.h>
51 #include <netinet/in_systm.h>
52 #include <netinet/ip.h>
53 #include <netinet/ip_carp.h>
54 #ifdef INET6
55 #include <netinet/ip6.h>
56 #endif /* INET6 */
57 #include <netinet/in_pcb.h>
58 #include <netinet/ip_icmp.h>
59 #include <netinet/icmp_var.h>
60 #include <netinet/igmp_var.h>
61 #include <netinet/ip_var.h>
62 #include <netinet/pim_var.h>
63 #include <netinet/tcp.h>
64 #include <netinet/tcpip.h>
65 #include <netinet/tcp_seq.h>
66 #define	TCPSTATES
67 #include <netinet/tcp_fsm.h>
68 #include <netinet/tcp_timer.h>
69 #include <netinet/tcp_var.h>
70 #include <netinet/udp.h>
71 #include <netinet/udp_var.h>
72 
73 #include <arpa/inet.h>
74 #include <err.h>
75 #include <errno.h>
76 #include <libutil.h>
77 #include <netdb.h>
78 #include <stdint.h>
79 #include <stdio.h>
80 #include <stdlib.h>
81 #include <stdbool.h>
82 #include <string.h>
83 #include <unistd.h>
84 #include <libxo/xo.h>
85 #include "netstat.h"
86 #include "nl_defs.h"
87 
88 #ifdef INET
89 static void inetprint(const char *, struct in_addr *, int, const char *, int,
90     const int);
91 #endif
92 #ifdef INET6
93 static int udp_done, tcp_done, sdp_done;
94 #endif /* INET6 */
95 
96 static int
97 pcblist_sysctl(int proto, const char *name, char **bufp)
98 {
99 	const char *mibvar;
100 	char *buf;
101 	size_t len;
102 
103 	switch (proto) {
104 	case IPPROTO_TCP:
105 		mibvar = "net.inet.tcp.pcblist";
106 		break;
107 	case IPPROTO_UDP:
108 		mibvar = "net.inet.udp.pcblist";
109 		break;
110 	case IPPROTO_DIVERT:
111 		mibvar = "net.inet.divert.pcblist";
112 		break;
113 	default:
114 		mibvar = "net.inet.raw.pcblist";
115 		break;
116 	}
117 	if (strncmp(name, "sdp", 3) == 0)
118 		mibvar = "net.inet.sdp.pcblist";
119 	len = 0;
120 	if (sysctlbyname(mibvar, 0, &len, 0, 0) < 0) {
121 		if (errno != ENOENT)
122 			xo_warn("sysctl: %s", mibvar);
123 		return (0);
124 	}
125 	if ((buf = malloc(len)) == NULL) {
126 		xo_warnx("malloc %lu bytes", (u_long)len);
127 		return (0);
128 	}
129 	if (sysctlbyname(mibvar, buf, &len, 0, 0) < 0) {
130 		xo_warn("sysctl: %s", mibvar);
131 		free(buf);
132 		return (0);
133 	}
134 	*bufp = buf;
135 	return (1);
136 }
137 
138 /*
139  * Copied directly from uipc_socket2.c.  We leave out some fields that are in
140  * nested structures that aren't used to avoid extra work.
141  */
142 static void
143 sbtoxsockbuf(struct sockbuf *sb, struct xsockbuf *xsb)
144 {
145 	xsb->sb_cc = sb->sb_ccc;
146 	xsb->sb_hiwat = sb->sb_hiwat;
147 	xsb->sb_mbcnt = sb->sb_mbcnt;
148 	xsb->sb_mcnt = sb->sb_mcnt;
149 	xsb->sb_ccnt = sb->sb_ccnt;
150 	xsb->sb_mbmax = sb->sb_mbmax;
151 	xsb->sb_lowat = sb->sb_lowat;
152 	xsb->sb_flags = sb->sb_flags;
153 	xsb->sb_timeo = sb->sb_timeo;
154 }
155 
156 int
157 sotoxsocket(struct socket *so, struct xsocket *xso)
158 {
159 	struct protosw proto;
160 	struct domain domain;
161 
162 	bzero(xso, sizeof *xso);
163 	xso->xso_len = sizeof *xso;
164 	xso->xso_so = (uintptr_t)so;
165 	xso->so_type = so->so_type;
166 	xso->so_options = so->so_options;
167 	xso->so_linger = so->so_linger;
168 	xso->so_state = so->so_state;
169 	xso->so_pcb = (uintptr_t)so->so_pcb;
170 	if (kread((uintptr_t)so->so_proto, &proto, sizeof(proto)) != 0)
171 		return (-1);
172 	xso->xso_protocol = proto.pr_protocol;
173 	if (kread((uintptr_t)proto.pr_domain, &domain, sizeof(domain)) != 0)
174 		return (-1);
175 	xso->xso_family = domain.dom_family;
176 	xso->so_timeo = so->so_timeo;
177 	xso->so_error = so->so_error;
178 	if ((so->so_options & SO_ACCEPTCONN) != 0) {
179 		xso->so_qlen = so->sol_qlen;
180 		xso->so_incqlen = so->sol_incqlen;
181 		xso->so_qlimit = so->sol_qlimit;
182 	} else {
183 		sbtoxsockbuf(&so->so_snd, &xso->so_snd);
184 		sbtoxsockbuf(&so->so_rcv, &xso->so_rcv);
185 		xso->so_oobmark = so->so_oobmark;
186 	}
187 	return (0);
188 }
189 
190 /*
191  * Print a summary of connections related to an Internet
192  * protocol.  For TCP, also give state of connection.
193  * Listening processes (aflag) are suppressed unless the
194  * -a (all) flag is specified.
195  */
196 void
197 protopr(u_long off, const char *name, int af1, int proto)
198 {
199 	static int first = 1;
200 	int istcp;
201 	char *buf;
202 	const char *vchar;
203 	struct xtcpcb *tp;
204 	struct xinpcb *inp;
205 	struct xinpgen *xig, *oxig;
206 	struct xsocket *so;
207 
208 	istcp = 0;
209 	switch (proto) {
210 	case IPPROTO_TCP:
211 #ifdef INET6
212 		if (strncmp(name, "sdp", 3) != 0) {
213 			if (tcp_done != 0)
214 				return;
215 			else
216 				tcp_done = 1;
217 		} else {
218 			if (sdp_done != 0)
219 				return;
220 			else
221 				sdp_done = 1;
222 		}
223 #endif
224 		istcp = 1;
225 		break;
226 	case IPPROTO_UDP:
227 #ifdef INET6
228 		if (udp_done != 0)
229 			return;
230 		else
231 			udp_done = 1;
232 #endif
233 		break;
234 	}
235 
236 	if (!pcblist_sysctl(proto, name, &buf))
237 		return;
238 
239 	oxig = xig = (struct xinpgen *)buf;
240 	for (xig = (struct xinpgen *)((char *)xig + xig->xig_len);
241 	    xig->xig_len > sizeof(struct xinpgen);
242 	    xig = (struct xinpgen *)((char *)xig + xig->xig_len)) {
243 		if (istcp) {
244 			tp = (struct xtcpcb *)xig;
245 			inp = &tp->xt_inp;
246 		} else {
247 			inp = (struct xinpcb *)xig;
248 		}
249 		so = &inp->xi_socket;
250 
251 		/* Ignore sockets for protocols other than the desired one. */
252 		if (so->xso_protocol != proto)
253 			continue;
254 
255 		/* Ignore PCBs which were freed during copyout. */
256 		if (inp->inp_gencnt > oxig->xig_gen)
257 			continue;
258 
259 		if ((af1 == AF_INET && (inp->inp_vflag & INP_IPV4) == 0)
260 #ifdef INET6
261 		    || (af1 == AF_INET6 && (inp->inp_vflag & INP_IPV6) == 0)
262 #endif /* INET6 */
263 		    || (af1 == AF_UNSPEC && ((inp->inp_vflag & INP_IPV4) == 0
264 #ifdef INET6
265 					  && (inp->inp_vflag & INP_IPV6) == 0
266 #endif /* INET6 */
267 			))
268 		    )
269 			continue;
270 		if (!aflag &&
271 		    (
272 		     (istcp && tp->t_state == TCPS_LISTEN)
273 		     || (af1 == AF_INET &&
274 		      inet_lnaof(inp->inp_laddr) == INADDR_ANY)
275 #ifdef INET6
276 		     || (af1 == AF_INET6 &&
277 			 IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_laddr))
278 #endif /* INET6 */
279 		     || (af1 == AF_UNSPEC &&
280 			 (((inp->inp_vflag & INP_IPV4) != 0 &&
281 			   inet_lnaof(inp->inp_laddr) == INADDR_ANY)
282 #ifdef INET6
283 			  || ((inp->inp_vflag & INP_IPV6) != 0 &&
284 			      IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_laddr))
285 #endif
286 			  ))
287 		     ))
288 			continue;
289 
290 		if (first) {
291 			if (!Lflag) {
292 				xo_emit("Active Internet connections");
293 				if (aflag)
294 					xo_emit(" (including servers)");
295 			} else
296 				xo_emit(
297 	"Current listen queue sizes (qlen/incqlen/maxqlen)");
298 			xo_emit("\n");
299 			if (Aflag)
300 				xo_emit("{T:/%-*s} ", 2 * (int)sizeof(void *),
301 				    "Tcpcb");
302 			if (Lflag)
303 				xo_emit((Aflag && !Wflag) ?
304 				    "{T:/%-5.5s} {T:/%-32.32s} {T:/%-18.18s}" :
305 				    ((!Wflag || af1 == AF_INET) ?
306 				    "{T:/%-5.5s} {T:/%-32.32s} {T:/%-22.22s}" :
307 				    "{T:/%-5.5s} {T:/%-32.32s} {T:/%-45.45s}"),
308 				    "Proto", "Listen", "Local Address");
309 			else if (Tflag)
310 				xo_emit((Aflag && !Wflag) ?
311     "{T:/%-5.5s} {T:/%-6.6s} {T:/%-6.6s} {T:/%-6.6s} {T:/%-18.18s} {T:/%s}" :
312 				    ((!Wflag || af1 == AF_INET) ?
313     "{T:/%-5.5s} {T:/%-6.6s} {T:/%-6.6s} {T:/%-6.6s} {T:/%-22.22s} {T:/%s}" :
314     "{T:/%-5.5s} {T:/%-6.6s} {T:/%-6.6s} {T:/%-6.6s} {T:/%-45.45s} {T:/%s}"),
315 				    "Proto", "Rexmit", "OOORcv", "0-win",
316 				    "Local Address", "Foreign Address");
317 			else {
318 				xo_emit((Aflag && !Wflag) ?
319     "{T:/%-5.5s} {T:/%-6.6s} {T:/%-6.6s} {T:/%-18.18s} {T:/%-18.18s}" :
320 				    ((!Wflag || af1 == AF_INET) ?
321     "{T:/%-5.5s} {T:/%-6.6s} {T:/%-6.6s} {T:/%-22.22s} {T:/%-22.22s}" :
322     "{T:/%-5.5s} {T:/%-6.6s} {T:/%-6.6s} {T:/%-45.45s} {T:/%-45.45s}"),
323 				    "Proto", "Recv-Q", "Send-Q",
324 				    "Local Address", "Foreign Address");
325 				if (!xflag && !Rflag)
326 					xo_emit(" {T:/%-11.11s}", "(state)");
327 			}
328 			if (xflag) {
329 				xo_emit(" {T:/%-6.6s} {T:/%-6.6s} {T:/%-6.6s} "
330 				    "{T:/%-6.6s} {T:/%-6.6s} {T:/%-6.6s} "
331 				    "{T:/%-6.6s} {T:/%-6.6s} {T:/%-6.6s} "
332 				    "{T:/%-6.6s} {T:/%-6.6s} {T:/%-6.6s}",
333 				    "R-MBUF", "S-MBUF", "R-CLUS", "S-CLUS",
334 				    "R-HIWA", "S-HIWA", "R-LOWA", "S-LOWA",
335 				    "R-BCNT", "S-BCNT", "R-BMAX", "S-BMAX");
336 				xo_emit(" {T:/%7.7s} {T:/%7.7s} {T:/%7.7s} "
337 				    "{T:/%7.7s} {T:/%7.7s} {T:/%7.7s}",
338 				    "rexmt", "persist", "keep", "2msl",
339 				    "delack", "rcvtime");
340 			} else if (Rflag) {
341 				xo_emit("  {T:/%8.8s} {T:/%5.5s}",
342 				    "flowid", "ftype");
343 			}
344 			if (Pflag)
345 				xo_emit(" {T:/%s}", "Log ID");
346 			xo_emit("\n");
347 			first = 0;
348 		}
349 		if (Lflag && so->so_qlimit == 0)
350 			continue;
351 		xo_open_instance("socket");
352 		if (Aflag) {
353 			if (istcp)
354 				xo_emit("{q:address/%*lx} ",
355 				    2 * (int)sizeof(void *),
356 				    (u_long)inp->inp_ppcb);
357 			else
358 				xo_emit("{q:address/%*lx} ",
359 				    2 * (int)sizeof(void *),
360 				    (u_long)so->so_pcb);
361 		}
362 #ifdef INET6
363 		if ((inp->inp_vflag & INP_IPV6) != 0)
364 			vchar = ((inp->inp_vflag & INP_IPV4) != 0) ?
365 			    "46" : "6";
366 		else
367 #endif
368 		vchar = ((inp->inp_vflag & INP_IPV4) != 0) ?
369 		    "4" : "";
370 		if (istcp && (tp->t_flags & TF_TOE) != 0)
371 			xo_emit("{:protocol/%-3.3s%-2.2s/%s%s} ", "toe", vchar);
372 		else
373 			xo_emit("{:protocol/%-3.3s%-2.2s/%s%s} ", name, vchar);
374 		if (Lflag) {
375 			char buf1[33];
376 
377 			snprintf(buf1, sizeof buf1, "%u/%u/%u", so->so_qlen,
378 			    so->so_incqlen, so->so_qlimit);
379 			xo_emit("{:listen-queue-sizes/%-32.32s} ", buf1);
380 		} else if (Tflag) {
381 			if (istcp)
382 				xo_emit("{:sent-retransmit-packets/%6u} "
383 				    "{:received-out-of-order-packets/%6u} "
384 				    "{:sent-zero-window/%6u} ",
385 				    tp->t_sndrexmitpack, tp->t_rcvoopack,
386 				    tp->t_sndzerowin);
387 			else
388 				xo_emit("{P:/%21s}", "");
389 		} else {
390 			xo_emit("{:receive-bytes-waiting/%6u} "
391 			    "{:send-bytes-waiting/%6u} ",
392 			    so->so_rcv.sb_cc, so->so_snd.sb_cc);
393 		}
394 		if (numeric_port) {
395 #ifdef INET
396 			if (inp->inp_vflag & INP_IPV4) {
397 				inetprint("local", &inp->inp_laddr,
398 				    (int)inp->inp_lport, name, 1, af1);
399 				if (!Lflag)
400 					inetprint("remote", &inp->inp_faddr,
401 					    (int)inp->inp_fport, name, 1, af1);
402 			}
403 #endif
404 #if defined(INET) && defined(INET6)
405 			else
406 #endif
407 #ifdef INET6
408 			if (inp->inp_vflag & INP_IPV6) {
409 				inet6print("local", &inp->in6p_laddr,
410 				    (int)inp->inp_lport, name, 1);
411 				if (!Lflag)
412 					inet6print("remote", &inp->in6p_faddr,
413 					    (int)inp->inp_fport, name, 1);
414 			} /* else nothing printed now */
415 #endif /* INET6 */
416 		} else if (inp->inp_flags & INP_ANONPORT) {
417 #ifdef INET
418 			if (inp->inp_vflag & INP_IPV4) {
419 				inetprint("local", &inp->inp_laddr,
420 				    (int)inp->inp_lport, name, 1, af1);
421 				if (!Lflag)
422 					inetprint("remote", &inp->inp_faddr,
423 					    (int)inp->inp_fport, name, 0, af1);
424 			}
425 #endif
426 #if defined(INET) && defined(INET6)
427 			else
428 #endif
429 #ifdef INET6
430 			if (inp->inp_vflag & INP_IPV6) {
431 				inet6print("local", &inp->in6p_laddr,
432 				    (int)inp->inp_lport, name, 1);
433 				if (!Lflag)
434 					inet6print("remote", &inp->in6p_faddr,
435 					    (int)inp->inp_fport, name, 0);
436 			} /* else nothing printed now */
437 #endif /* INET6 */
438 		} else {
439 #ifdef INET
440 			if (inp->inp_vflag & INP_IPV4) {
441 				inetprint("local", &inp->inp_laddr,
442 				    (int)inp->inp_lport, name, 0, af1);
443 				if (!Lflag)
444 					inetprint("remote", &inp->inp_faddr,
445 					    (int)inp->inp_fport, name,
446 					    inp->inp_lport != inp->inp_fport,
447 					    af1);
448 			}
449 #endif
450 #if defined(INET) && defined(INET6)
451 			else
452 #endif
453 #ifdef INET6
454 			if (inp->inp_vflag & INP_IPV6) {
455 				inet6print("local", &inp->in6p_laddr,
456 				    (int)inp->inp_lport, name, 0);
457 				if (!Lflag)
458 					inet6print("remote", &inp->in6p_faddr,
459 					    (int)inp->inp_fport, name,
460 					    inp->inp_lport != inp->inp_fport);
461 			} /* else nothing printed now */
462 #endif /* INET6 */
463 		}
464 		if (xflag) {
465 			xo_emit("{:receive-mbufs/%6u} {:send-mbufs/%6u} "
466 			    "{:receive-clusters/%6u} {:send-clusters/%6u} "
467 			    "{:receive-high-water/%6u} {:send-high-water/%6u} "
468 			    "{:receive-low-water/%6u} {:send-low-water/%6u} "
469 			    "{:receive-mbuf-bytes/%6u} {:send-mbuf-bytes/%6u} "
470 			    "{:receive-mbuf-bytes-max/%6u} "
471 			    "{:send-mbuf-bytes-max/%6u}",
472 			    so->so_rcv.sb_mcnt, so->so_snd.sb_mcnt,
473 			    so->so_rcv.sb_ccnt, so->so_snd.sb_ccnt,
474 			    so->so_rcv.sb_hiwat, so->so_snd.sb_hiwat,
475 			    so->so_rcv.sb_lowat, so->so_snd.sb_lowat,
476 			    so->so_rcv.sb_mbcnt, so->so_snd.sb_mbcnt,
477 			    so->so_rcv.sb_mbmax, so->so_snd.sb_mbmax);
478 			if (istcp)
479 				xo_emit(" {:retransmit-timer/%4d.%02d} "
480 				    "{:persist-timer/%4d.%02d} "
481 				    "{:keepalive-timer/%4d.%02d} "
482 				    "{:msl2-timer/%4d.%02d} "
483 				    "{:delay-ack-timer/%4d.%02d} "
484 				    "{:inactivity-timer/%4d.%02d}",
485 				    tp->tt_rexmt / 1000,
486 				    (tp->tt_rexmt % 1000) / 10,
487 				    tp->tt_persist / 1000,
488 				    (tp->tt_persist % 1000) / 10,
489 				    tp->tt_keep / 1000,
490 				    (tp->tt_keep % 1000) / 10,
491 				    tp->tt_2msl / 1000,
492 				    (tp->tt_2msl % 1000) / 10,
493 				    tp->tt_delack / 1000,
494 				    (tp->tt_delack % 1000) / 10,
495 				    tp->t_rcvtime / 1000,
496 				    (tp->t_rcvtime % 1000) / 10);
497 		}
498 		if (istcp && !Lflag && !xflag && !Tflag && !Rflag) {
499 			if (tp->t_state < 0 || tp->t_state >= TCP_NSTATES)
500 				xo_emit("{:tcp-state/%-11d}", tp->t_state);
501 			else {
502 				xo_emit("{:tcp-state/%-11s}",
503 				    tcpstates[tp->t_state]);
504 #if defined(TF_NEEDSYN) && defined(TF_NEEDFIN)
505 				/* Show T/TCP `hidden state' */
506 				if (tp->t_flags & (TF_NEEDSYN|TF_NEEDFIN))
507 					xo_emit("{:need-syn-or-fin/*}");
508 #endif /* defined(TF_NEEDSYN) && defined(TF_NEEDFIN) */
509 			}
510 		}
511 		if (Rflag) {
512 			/* XXX: is this right Alfred */
513 			xo_emit(" {:flow-id/%08x} {:flow-type/%5d}",
514 			    inp->inp_flowid,
515 			    inp->inp_flowtype);
516 		}
517 		if (istcp && Pflag)
518 			xo_emit(" {:log-id/%s}", tp->xt_logid[0] == '\0' ?
519 			    "-" : tp->xt_logid);
520 		xo_emit("\n");
521 		xo_close_instance("socket");
522 	}
523 	if (xig != oxig && xig->xig_gen != oxig->xig_gen) {
524 		if (oxig->xig_count > xig->xig_count) {
525 			xo_emit("Some {d:lost/%s} sockets may have been "
526 			    "deleted.\n", name);
527 		} else if (oxig->xig_count < xig->xig_count) {
528 			xo_emit("Some {d:created/%s} sockets may have been "
529 			    "created.\n", name);
530 		} else {
531 			xo_emit("Some {d:changed/%s} sockets may have been "
532 			    "created or deleted.\n", name);
533 		}
534 	}
535 	free(buf);
536 }
537 
538 /*
539  * Dump TCP statistics structure.
540  */
541 void
542 tcp_stats(u_long off, const char *name, int af1 __unused, int proto __unused)
543 {
544 	struct tcpstat tcpstat;
545 	uint64_t tcps_states[TCP_NSTATES];
546 
547 #ifdef INET6
548 	if (tcp_done != 0)
549 		return;
550 	else
551 		tcp_done = 1;
552 #endif
553 
554 	if (fetch_stats("net.inet.tcp.stats", off, &tcpstat,
555 	    sizeof(tcpstat), kread_counters) != 0)
556 		return;
557 
558 	if (fetch_stats_ro("net.inet.tcp.states", nl[N_TCPS_STATES].n_value,
559 	    &tcps_states, sizeof(tcps_states), kread_counters) != 0)
560 		return;
561 
562 	xo_open_container("tcp");
563 	xo_emit("{T:/%s}:\n", name);
564 
565 #define	p(f, m) if (tcpstat.f || sflag <= 1)				\
566 	xo_emit(m, (uintmax_t )tcpstat.f, plural(tcpstat.f))
567 #define	p1a(f, m) if (tcpstat.f || sflag <= 1)				\
568 	xo_emit(m, (uintmax_t )tcpstat.f)
569 #define	p2(f1, f2, m) if (tcpstat.f1 || tcpstat.f2 || sflag <= 1)	\
570 	xo_emit(m, (uintmax_t )tcpstat.f1, plural(tcpstat.f1),		\
571 	    (uintmax_t )tcpstat.f2, plural(tcpstat.f2))
572 #define	p2a(f1, f2, m) if (tcpstat.f1 || tcpstat.f2 || sflag <= 1)	\
573 	xo_emit(m, (uintmax_t )tcpstat.f1, plural(tcpstat.f1),		\
574 	    (uintmax_t )tcpstat.f2)
575 #define	p3(f, m) if (tcpstat.f || sflag <= 1)				\
576 	xo_emit(m, (uintmax_t )tcpstat.f, pluralies(tcpstat.f))
577 
578 	p(tcps_sndtotal, "\t{:sent-packets/%ju} {N:/packet%s sent}\n");
579 	p2(tcps_sndpack,tcps_sndbyte, "\t\t{:sent-data-packets/%ju} "
580 	    "{N:/data packet%s} ({:sent-data-bytes/%ju} {N:/byte%s})\n");
581 	p2(tcps_sndrexmitpack, tcps_sndrexmitbyte, "\t\t"
582 	    "{:sent-retransmitted-packets/%ju} {N:/data packet%s} "
583 	    "({:sent-retransmitted-bytes/%ju} {N:/byte%s}) "
584 	    "{N:retransmitted}\n");
585 	p(tcps_sndrexmitbad, "\t\t"
586 	    "{:sent-unnecessary-retransmitted-packets/%ju} "
587 	    "{N:/data packet%s unnecessarily retransmitted}\n");
588 	p(tcps_mturesent, "\t\t{:sent-resends-by-mtu-discovery/%ju} "
589 	    "{N:/resend%s initiated by MTU discovery}\n");
590 	p2a(tcps_sndacks, tcps_delack, "\t\t{:sent-ack-only-packets/%ju} "
591 	    "{N:/ack-only packet%s/} ({:sent-packets-delayed/%ju} "
592 	    "{N:delayed})\n");
593 	p(tcps_sndurg, "\t\t{:sent-urg-only-packets/%ju} "
594 	    "{N:/URG only packet%s}\n");
595 	p(tcps_sndprobe, "\t\t{:sent-window-probe-packets/%ju} "
596 	    "{N:/window probe packet%s}\n");
597 	p(tcps_sndwinup, "\t\t{:sent-window-update-packets/%ju} "
598 	    "{N:/window update packet%s}\n");
599 	p(tcps_sndctrl, "\t\t{:sent-control-packets/%ju} "
600 	    "{N:/control packet%s}\n");
601 	p(tcps_rcvtotal, "\t{:received-packets/%ju} "
602 	    "{N:/packet%s received}\n");
603 	p2(tcps_rcvackpack, tcps_rcvackbyte, "\t\t"
604 	    "{:received-ack-packets/%ju} {N:/ack%s} "
605 	    "{N:(for} {:received-ack-bytes/%ju} {N:/byte%s})\n");
606 	p(tcps_rcvdupack, "\t\t{:received-duplicate-acks/%ju} "
607 	    "{N:/duplicate ack%s}\n");
608 	p(tcps_rcvacktoomuch, "\t\t{:received-acks-for-unsent-data/%ju} "
609 	    "{N:/ack%s for unsent data}\n");
610 	p2(tcps_rcvpack, tcps_rcvbyte, "\t\t"
611 	    "{:received-in-sequence-packets/%ju} {N:/packet%s} "
612 	    "({:received-in-sequence-bytes/%ju} {N:/byte%s}) "
613 	    "{N:received in-sequence}\n");
614 	p2(tcps_rcvduppack, tcps_rcvdupbyte, "\t\t"
615 	    "{:received-completely-duplicate-packets/%ju} "
616 	    "{N:/completely duplicate packet%s} "
617 	    "({:received-completely-duplicate-bytes/%ju} {N:/byte%s})\n");
618 	p(tcps_pawsdrop, "\t\t{:received-old-duplicate-packets/%ju} "
619 	    "{N:/old duplicate packet%s}\n");
620 	p2(tcps_rcvpartduppack, tcps_rcvpartdupbyte, "\t\t"
621 	    "{:received-some-duplicate-packets/%ju} "
622 	    "{N:/packet%s with some dup. data} "
623 	    "({:received-some-duplicate-bytes/%ju} {N:/byte%s duped/})\n");
624 	p2(tcps_rcvoopack, tcps_rcvoobyte, "\t\t{:received-out-of-order/%ju} "
625 	    "{N:/out-of-order packet%s} "
626 	    "({:received-out-of-order-bytes/%ju} {N:/byte%s})\n");
627 	p2(tcps_rcvpackafterwin, tcps_rcvbyteafterwin, "\t\t"
628 	    "{:received-after-window-packets/%ju} {N:/packet%s} "
629 	    "({:received-after-window-bytes/%ju} {N:/byte%s}) "
630 	    "{N:of data after window}\n");
631 	p(tcps_rcvwinprobe, "\t\t{:received-window-probes/%ju} "
632 	    "{N:/window probe%s}\n");
633 	p(tcps_rcvwinupd, "\t\t{:receive-window-update-packets/%ju} "
634 	    "{N:/window update packet%s}\n");
635 	p(tcps_rcvafterclose, "\t\t{:received-after-close-packets/%ju} "
636 	    "{N:/packet%s received after close}\n");
637 	p(tcps_rcvbadsum, "\t\t{:discard-bad-checksum/%ju} "
638 	    "{N:/discarded for bad checksum%s}\n");
639 	p(tcps_rcvbadoff, "\t\t{:discard-bad-header-offset/%ju} "
640 	    "{N:/discarded for bad header offset field%s}\n");
641 	p1a(tcps_rcvshort, "\t\t{:discard-too-short/%ju} "
642 	    "{N:discarded because packet too short}\n");
643 	p1a(tcps_rcvmemdrop, "\t\t{:discard-memory-problems/%ju} "
644 	    "{N:discarded due to memory problems}\n");
645 	p(tcps_connattempt, "\t{:connection-requests/%ju} "
646 	    "{N:/connection request%s}\n");
647 	p(tcps_accepts, "\t{:connections-accepts/%ju} "
648 	    "{N:/connection accept%s}\n");
649 	p(tcps_badsyn, "\t{:bad-connection-attempts/%ju} "
650 	    "{N:/bad connection attempt%s}\n");
651 	p(tcps_listendrop, "\t{:listen-queue-overflows/%ju} "
652 	    "{N:/listen queue overflow%s}\n");
653 	p(tcps_badrst, "\t{:ignored-in-window-resets/%ju} "
654 	    "{N:/ignored RSTs in the window%s}\n");
655 	p(tcps_connects, "\t{:connections-established/%ju} "
656 	    "{N:/connection%s established (including accepts)}\n");
657 	p(tcps_usedrtt, "\t\t{:connections-hostcache-rtt/%ju} "
658 	    "{N:/time%s used RTT from hostcache}\n");
659 	p(tcps_usedrttvar, "\t\t{:connections-hostcache-rttvar/%ju} "
660 	    "{N:/time%s used RTT variance from hostcache}\n");
661 	p(tcps_usedssthresh, "\t\t{:connections-hostcache-ssthresh/%ju} "
662 	    "{N:/time%s used slow-start threshold from hostcache}\n");
663 	p2(tcps_closed, tcps_drops, "\t{:connections-closed/%ju} "
664 	    "{N:/connection%s closed (including} "
665 	    "{:connection-drops/%ju} {N:/drop%s})\n");
666 	p(tcps_cachedrtt, "\t\t{:connections-updated-rtt-on-close/%ju} "
667 	    "{N:/connection%s updated cached RTT on close}\n");
668 	p(tcps_cachedrttvar, "\t\t"
669 	    "{:connections-updated-variance-on-close/%ju} "
670 	    "{N:/connection%s updated cached RTT variance on close}\n");
671 	p(tcps_cachedssthresh, "\t\t"
672 	    "{:connections-updated-ssthresh-on-close/%ju} "
673 	    "{N:/connection%s updated cached ssthresh on close}\n");
674 	p(tcps_conndrops, "\t{:embryonic-connections-dropped/%ju} "
675 	    "{N:/embryonic connection%s dropped}\n");
676 	p2(tcps_rttupdated, tcps_segstimed, "\t{:segments-updated-rtt/%ju} "
677 	    "{N:/segment%s updated rtt (of} "
678 	    "{:segment-update-attempts/%ju} {N:/attempt%s})\n");
679 	p(tcps_rexmttimeo, "\t{:retransmit-timeouts/%ju} "
680 	    "{N:/retransmit timeout%s}\n");
681 	p(tcps_timeoutdrop, "\t\t"
682 	    "{:connections-dropped-by-retransmit-timeout/%ju} "
683 	    "{N:/connection%s dropped by rexmit timeout}\n");
684 	p(tcps_persisttimeo, "\t{:persist-timeout/%ju} "
685 	    "{N:/persist timeout%s}\n");
686 	p(tcps_persistdrop, "\t\t"
687 	    "{:connections-dropped-by-persist-timeout/%ju} "
688 	    "{N:/connection%s dropped by persist timeout}\n");
689 	p(tcps_finwait2_drops, "\t"
690 	    "{:connections-dropped-by-finwait2-timeout/%ju} "
691 	    "{N:/Connection%s (fin_wait_2) dropped because of timeout}\n");
692 	p(tcps_keeptimeo, "\t{:keepalive-timeout/%ju} "
693 	    "{N:/keepalive timeout%s}\n");
694 	p(tcps_keepprobe, "\t\t{:keepalive-probes/%ju} "
695 	    "{N:/keepalive probe%s sent}\n");
696 	p(tcps_keepdrops, "\t\t{:connections-dropped-by-keepalives/%ju} "
697 	    "{N:/connection%s dropped by keepalive}\n");
698 	p(tcps_predack, "\t{:ack-header-predictions/%ju} "
699 	    "{N:/correct ACK header prediction%s}\n");
700 	p(tcps_preddat, "\t{:data-packet-header-predictions/%ju} "
701 	    "{N:/correct data packet header prediction%s}\n");
702 
703 	xo_open_container("syncache");
704 
705 	p3(tcps_sc_added, "\t{:entries-added/%ju} "
706 	    "{N:/syncache entr%s added}\n");
707 	p1a(tcps_sc_retransmitted, "\t\t{:retransmitted/%ju} "
708 	    "{N:/retransmitted}\n");
709 	p1a(tcps_sc_dupsyn, "\t\t{:duplicates/%ju} {N:/dupsyn}\n");
710 	p1a(tcps_sc_dropped, "\t\t{:dropped/%ju} {N:/dropped}\n");
711 	p1a(tcps_sc_completed, "\t\t{:completed/%ju} {N:/completed}\n");
712 	p1a(tcps_sc_bucketoverflow, "\t\t{:bucket-overflow/%ju} "
713 	    "{N:/bucket overflow}\n");
714 	p1a(tcps_sc_cacheoverflow, "\t\t{:cache-overflow/%ju} "
715 	    "{N:/cache overflow}\n");
716 	p1a(tcps_sc_reset, "\t\t{:reset/%ju} {N:/reset}\n");
717 	p1a(tcps_sc_stale, "\t\t{:stale/%ju} {N:/stale}\n");
718 	p1a(tcps_sc_aborted, "\t\t{:aborted/%ju} {N:/aborted}\n");
719 	p1a(tcps_sc_badack, "\t\t{:bad-ack/%ju} {N:/badack}\n");
720 	p1a(tcps_sc_unreach, "\t\t{:unreachable/%ju} {N:/unreach}\n");
721 	p(tcps_sc_zonefail, "\t\t{:zone-failures/%ju} {N:/zone failure%s}\n");
722 	p(tcps_sc_sendcookie, "\t{:sent-cookies/%ju} {N:/cookie%s sent}\n");
723 	p(tcps_sc_recvcookie, "\t{:receivd-cookies/%ju} "
724 	    "{N:/cookie%s received}\n");
725 
726 	xo_close_container("syncache");
727 
728 	xo_open_container("hostcache");
729 
730 	p3(tcps_hc_added, "\t{:entries-added/%ju} "
731 	    "{N:/hostcache entr%s added}\n");
732 	p1a(tcps_hc_bucketoverflow, "\t\t{:buffer-overflows/%ju} "
733 	    "{N:/bucket overflow}\n");
734 
735 	xo_close_container("hostcache");
736 
737 	xo_open_container("sack");
738 
739 	p(tcps_sack_recovery_episode, "\t{:recovery-episodes/%ju} "
740 	    "{N:/SACK recovery episode%s}\n");
741  	p(tcps_sack_rexmits, "\t{:segment-retransmits/%ju} "
742 	    "{N:/segment rexmit%s in SACK recovery episodes}\n");
743  	p(tcps_sack_rexmit_bytes, "\t{:byte-retransmits/%ju} "
744 	    "{N:/byte rexmit%s in SACK recovery episodes}\n");
745  	p(tcps_sack_rcv_blocks, "\t{:received-blocks/%ju} "
746 	    "{N:/SACK option%s (SACK blocks) received}\n");
747 	p(tcps_sack_send_blocks, "\t{:sent-option-blocks/%ju} "
748 	    "{N:/SACK option%s (SACK blocks) sent}\n");
749 	p1a(tcps_sack_sboverflow, "\t{:scoreboard-overflows/%ju} "
750 	    "{N:/SACK scoreboard overflow}\n");
751 
752 	xo_close_container("sack");
753 	xo_open_container("ecn");
754 
755 	p(tcps_ecn_ce, "\t{:ce-packets/%ju} "
756 	    "{N:/packet%s with ECN CE bit set}\n");
757 	p(tcps_ecn_ect0, "\t{:ect0-packets/%ju} "
758 	    "{N:/packet%s with ECN ECT(0) bit set}\n");
759 	p(tcps_ecn_ect1, "\t{:ect1-packets/%ju} "
760 	    "{N:/packet%s with ECN ECT(1) bit set}\n");
761 	p(tcps_ecn_shs, "\t{:handshakes/%ju} "
762 	    "{N:/successful ECN handshake%s}\n");
763 	p(tcps_ecn_rcwnd, "\t{:congestion-reductions/%ju} "
764 	    "{N:/time%s ECN reduced the congestion window}\n");
765 
766 	xo_close_container("ecn");
767 	xo_open_container("tcp-signature");
768 	p(tcps_sig_rcvgoodsig, "\t{:received-good-signature/%ju} "
769 	    "{N:/packet%s with matching signature received}\n");
770 	p(tcps_sig_rcvbadsig, "\t{:received-bad-signature/%ju} "
771 	    "{N:/packet%s with bad signature received}\n");
772 	p(tcps_sig_err_buildsig, "\t{:failed-make-signature/%ju} "
773 	    "{N:/time%s failed to make signature due to no SA}\n");
774 	p(tcps_sig_err_sigopt, "\t{:no-signature-expected/%ju} "
775 	    "{N:/time%s unexpected signature received}\n");
776 	p(tcps_sig_err_nosigopt, "\t{:no-signature-provided/%ju} "
777 	    "{N:/time%s no signature provided by segment}\n");
778 
779 	xo_close_container("tcp-signature");
780 	xo_open_container("pmtud");
781 
782 	p(tcps_pmtud_blackhole_activated, "\t{:pmtud-activated/%ju} "
783 	    "{N:/Path MTU discovery black hole detection activation%s}\n");
784 	p(tcps_pmtud_blackhole_activated_min_mss,
785 	    "\t{:pmtud-activated-min-mss/%ju} "
786 	    "{N:/Path MTU discovery black hole detection min MSS activation%s}\n");
787 	p(tcps_pmtud_blackhole_failed, "\t{:pmtud-failed/%ju} "
788 	    "{N:/Path MTU discovery black hole detection failure%s}\n");
789  #undef p
790  #undef p1a
791  #undef p2
792  #undef p2a
793  #undef p3
794 	xo_close_container("pmtud");
795 
796 
797 	xo_open_container("TCP connection count by state");
798 	xo_emit("{T:/TCP connection count by state}:\n");
799 	for (int i = 0; i < TCP_NSTATES; i++) {
800 		/*
801 		 * XXXGL: is there a way in libxo to use %s
802 		 * in the "content string" of a format
803 		 * string? I failed to do that, that's why
804 		 * a temporary buffer is used to construct
805 		 * format string for xo_emit().
806 		 */
807 		char fmtbuf[80];
808 
809 		if (sflag > 1 && tcps_states[i] == 0)
810 			continue;
811 		snprintf(fmtbuf, sizeof(fmtbuf), "\t{:%s/%%ju} "
812                     "{Np:/connection ,connections} in %s state\n",
813 		    tcpstates[i], tcpstates[i]);
814 		xo_emit(fmtbuf, (uintmax_t )tcps_states[i]);
815 	}
816 	xo_close_container("TCP connection count by state");
817 
818 	xo_close_container("tcp");
819 }
820 
821 /*
822  * Dump UDP statistics structure.
823  */
824 void
825 udp_stats(u_long off, const char *name, int af1 __unused, int proto __unused)
826 {
827 	struct udpstat udpstat;
828 	uint64_t delivered;
829 
830 #ifdef INET6
831 	if (udp_done != 0)
832 		return;
833 	else
834 		udp_done = 1;
835 #endif
836 
837 	if (fetch_stats("net.inet.udp.stats", off, &udpstat,
838 	    sizeof(udpstat), kread_counters) != 0)
839 		return;
840 
841 	xo_open_container("udp");
842 	xo_emit("{T:/%s}:\n", name);
843 
844 #define	p(f, m) if (udpstat.f || sflag <= 1) \
845 	xo_emit("\t" m, (uintmax_t)udpstat.f, plural(udpstat.f))
846 #define	p1a(f, m) if (udpstat.f || sflag <= 1) \
847 	xo_emit("\t" m, (uintmax_t)udpstat.f)
848 
849 	p(udps_ipackets, "{:received-datagrams/%ju} "
850 	    "{N:/datagram%s received}\n");
851 	p1a(udps_hdrops, "{:dropped-incomplete-headers/%ju} "
852 	    "{N:/with incomplete header}\n");
853 	p1a(udps_badlen, "{:dropped-bad-data-length/%ju} "
854 	    "{N:/with bad data length field}\n");
855 	p1a(udps_badsum, "{:dropped-bad-checksum/%ju} "
856 	    "{N:/with bad checksum}\n");
857 	p1a(udps_nosum, "{:dropped-no-checksum/%ju} "
858 	    "{N:/with no checksum}\n");
859 	p1a(udps_noport, "{:dropped-no-socket/%ju} "
860 	    "{N:/dropped due to no socket}\n");
861 	p(udps_noportbcast, "{:dropped-broadcast-multicast/%ju} "
862 	    "{N:/broadcast\\/multicast datagram%s undelivered}\n");
863 	p1a(udps_fullsock, "{:dropped-full-socket-buffer/%ju} "
864 	    "{N:/dropped due to full socket buffers}\n");
865 	p1a(udpps_pcbhashmiss, "{:not-for-hashed-pcb/%ju} "
866 	    "{N:/not for hashed pcb}\n");
867 	delivered = udpstat.udps_ipackets -
868 		    udpstat.udps_hdrops -
869 		    udpstat.udps_badlen -
870 		    udpstat.udps_badsum -
871 		    udpstat.udps_noport -
872 		    udpstat.udps_noportbcast -
873 		    udpstat.udps_fullsock;
874 	if (delivered || sflag <= 1)
875 		xo_emit("\t{:delivered-packets/%ju} {N:/delivered}\n",
876 		    (uint64_t)delivered);
877 	p(udps_opackets, "{:output-packets/%ju} {N:/datagram%s output}\n");
878 	/* the next statistic is cumulative in udps_noportbcast */
879 	p(udps_filtermcast, "{:multicast-source-filter-matches/%ju} "
880 	    "{N:/time%s multicast source filter matched}\n");
881 #undef p
882 #undef p1a
883 	xo_close_container("udp");
884 }
885 
886 /*
887  * Dump CARP statistics structure.
888  */
889 void
890 carp_stats(u_long off, const char *name, int af1 __unused, int proto __unused)
891 {
892 	struct carpstats carpstat;
893 
894 	if (fetch_stats("net.inet.carp.stats", off, &carpstat,
895 	    sizeof(carpstat), kread_counters) != 0)
896 		return;
897 
898 	xo_open_container(name);
899 	xo_emit("{T:/%s}:\n", name);
900 
901 #define	p(f, m) if (carpstat.f || sflag <= 1) \
902 	xo_emit(m, (uintmax_t)carpstat.f, plural(carpstat.f))
903 #define	p2(f, m) if (carpstat.f || sflag <= 1) \
904 	xo_emit(m, (uintmax_t)carpstat.f)
905 
906 	p(carps_ipackets, "\t{:received-inet-packets/%ju} "
907 	    "{N:/packet%s received (IPv4)}\n");
908 	p(carps_ipackets6, "\t{:received-inet6-packets/%ju} "
909 	    "{N:/packet%s received (IPv6)}\n");
910 	p(carps_badttl, "\t\t{:dropped-wrong-ttl/%ju} "
911 	    "{N:/packet%s discarded for wrong TTL}\n");
912 	p(carps_hdrops, "\t\t{:dropped-short-header/%ju} "
913 	    "{N:/packet%s shorter than header}\n");
914 	p(carps_badsum, "\t\t{:dropped-bad-checksum/%ju} "
915 	    "{N:/discarded for bad checksum%s}\n");
916 	p(carps_badver,	"\t\t{:dropped-bad-version/%ju} "
917 	    "{N:/discarded packet%s with a bad version}\n");
918 	p2(carps_badlen, "\t\t{:dropped-short-packet/%ju} "
919 	    "{N:/discarded because packet too short}\n");
920 	p2(carps_badauth, "\t\t{:dropped-bad-authentication/%ju} "
921 	    "{N:/discarded for bad authentication}\n");
922 	p2(carps_badvhid, "\t\t{:dropped-bad-vhid/%ju} "
923 	    "{N:/discarded for bad vhid}\n");
924 	p2(carps_badaddrs, "\t\t{:dropped-bad-address-list/%ju} "
925 	    "{N:/discarded because of a bad address list}\n");
926 	p(carps_opackets, "\t{:sent-inet-packets/%ju} "
927 	    "{N:/packet%s sent (IPv4)}\n");
928 	p(carps_opackets6, "\t{:sent-inet6-packets/%ju} "
929 	    "{N:/packet%s sent (IPv6)}\n");
930 	p2(carps_onomem, "\t\t{:send-failed-memory-error/%ju} "
931 	    "{N:/send failed due to mbuf memory error}\n");
932 #if notyet
933 	p(carps_ostates, "\t\t{:send-state-updates/%s} "
934 	    "{N:/state update%s sent}\n");
935 #endif
936 #undef p
937 #undef p2
938 	xo_close_container(name);
939 }
940 
941 /*
942  * Dump IP statistics structure.
943  */
944 void
945 ip_stats(u_long off, const char *name, int af1 __unused, int proto __unused)
946 {
947 	struct ipstat ipstat;
948 
949 	if (fetch_stats("net.inet.ip.stats", off, &ipstat,
950 	    sizeof(ipstat), kread_counters) != 0)
951 		return;
952 
953 	xo_open_container(name);
954 	xo_emit("{T:/%s}:\n", name);
955 
956 #define	p(f, m) if (ipstat.f || sflag <= 1) \
957 	xo_emit(m, (uintmax_t )ipstat.f, plural(ipstat.f))
958 #define	p1a(f, m) if (ipstat.f || sflag <= 1) \
959 	xo_emit(m, (uintmax_t )ipstat.f)
960 
961 	p(ips_total, "\t{:received-packets/%ju} "
962 	    "{N:/total packet%s received}\n");
963 	p(ips_badsum, "\t{:dropped-bad-checksum/%ju} "
964 	    "{N:/bad header checksum%s}\n");
965 	p1a(ips_toosmall, "\t{:dropped-below-minimum-size/%ju} "
966 	    "{N:/with size smaller than minimum}\n");
967 	p1a(ips_tooshort, "\t{:dropped-short-packets/%ju} "
968 	    "{N:/with data size < data length}\n");
969 	p1a(ips_toolong, "\t{:dropped-too-long/%ju} "
970 	    "{N:/with ip length > max ip packet size}\n");
971 	p1a(ips_badhlen, "\t{:dropped-short-header-length/%ju} "
972 	    "{N:/with header length < data size}\n");
973 	p1a(ips_badlen, "\t{:dropped-short-data/%ju} "
974 	    "{N:/with data length < header length}\n");
975 	p1a(ips_badoptions, "\t{:dropped-bad-options/%ju} "
976 	    "{N:/with bad options}\n");
977 	p1a(ips_badvers, "\t{:dropped-bad-version/%ju} "
978 	    "{N:/with incorrect version number}\n");
979 	p(ips_fragments, "\t{:received-fragments/%ju} "
980 	    "{N:/fragment%s received}\n");
981 	p(ips_fragdropped, "\t{:dropped-fragments/%ju} "
982 	    "{N:/fragment%s dropped (dup or out of space)}\n");
983 	p(ips_fragtimeout, "\t{:dropped-fragments-after-timeout/%ju} "
984 	    "{N:/fragment%s dropped after timeout}\n");
985 	p(ips_reassembled, "\t{:reassembled-packets/%ju} "
986 	    "{N:/packet%s reassembled ok}\n");
987 	p(ips_delivered, "\t{:received-local-packets/%ju} "
988 	    "{N:/packet%s for this host}\n");
989 	p(ips_noproto, "\t{:dropped-unknown-protocol/%ju} "
990 	    "{N:/packet%s for unknown\\/unsupported protocol}\n");
991 	p(ips_forward, "\t{:forwarded-packets/%ju} "
992 	    "{N:/packet%s forwarded}");
993 	p(ips_fastforward, " ({:fast-forwarded-packets/%ju} "
994 	    "{N:/packet%s fast forwarded})");
995 	if (ipstat.ips_forward || sflag <= 1)
996 		xo_emit("\n");
997 	p(ips_cantforward, "\t{:packets-cannot-forward/%ju} "
998 	    "{N:/packet%s not forwardable}\n");
999 	p(ips_notmember, "\t{:received-unknown-multicast-group/%ju} "
1000 	    "{N:/packet%s received for unknown multicast group}\n");
1001 	p(ips_redirectsent, "\t{:redirects-sent/%ju} "
1002 	    "{N:/redirect%s sent}\n");
1003 	p(ips_localout, "\t{:sent-packets/%ju} "
1004 	    "{N:/packet%s sent from this host}\n");
1005 	p(ips_rawout, "\t{:send-packets-fabricated-header/%ju} "
1006 	    "{N:/packet%s sent with fabricated ip header}\n");
1007 	p(ips_odropped, "\t{:discard-no-mbufs/%ju} "
1008 	    "{N:/output packet%s dropped due to no bufs, etc.}\n");
1009 	p(ips_noroute, "\t{:discard-no-route/%ju} "
1010 	    "{N:/output packet%s discarded due to no route}\n");
1011 	p(ips_fragmented, "\t{:sent-fragments/%ju} "
1012 	    "{N:/output datagram%s fragmented}\n");
1013 	p(ips_ofragments, "\t{:fragments-created/%ju} "
1014 	    "{N:/fragment%s created}\n");
1015 	p(ips_cantfrag, "\t{:discard-cannot-fragment/%ju} "
1016 	    "{N:/datagram%s that can't be fragmented}\n");
1017 	p(ips_nogif, "\t{:discard-tunnel-no-gif/%ju} "
1018 	    "{N:/tunneling packet%s that can't find gif}\n");
1019 	p(ips_badaddr, "\t{:discard-bad-address/%ju} "
1020 	    "{N:/datagram%s with bad address in header}\n");
1021 #undef p
1022 #undef p1a
1023 	xo_close_container(name);
1024 }
1025 
1026 /*
1027  * Dump ARP statistics structure.
1028  */
1029 void
1030 arp_stats(u_long off, const char *name, int af1 __unused, int proto __unused)
1031 {
1032 	struct arpstat arpstat;
1033 
1034 	if (fetch_stats("net.link.ether.arp.stats", off, &arpstat,
1035 	    sizeof(arpstat), kread_counters) != 0)
1036 		return;
1037 
1038 	xo_open_container(name);
1039 	xo_emit("{T:/%s}:\n", name);
1040 
1041 #define	p(f, m) if (arpstat.f || sflag <= 1) \
1042 	xo_emit("\t" m, (uintmax_t)arpstat.f, plural(arpstat.f))
1043 #define	p2(f, m) if (arpstat.f || sflag <= 1) \
1044 	xo_emit("\t" m, (uintmax_t)arpstat.f, pluralies(arpstat.f))
1045 
1046 	p(txrequests, "{:sent-requests/%ju} {N:/ARP request%s sent}\n");
1047 	p(txerrors, "{:sent-failures/%ju} {N:/ARP request%s failed to sent}\n");
1048 	p2(txreplies, "{:sent-replies/%ju} {N:/ARP repl%s sent}\n");
1049 	p(rxrequests, "{:received-requests/%ju} "
1050 	    "{N:/ARP request%s received}\n");
1051 	p2(rxreplies, "{:received-replies/%ju} "
1052 	    "{N:/ARP repl%s received}\n");
1053 	p(received, "{:received-packers/%ju} "
1054 	    "{N:/ARP packet%s received}\n");
1055 	p(dropped, "{:dropped-no-entry/%ju} "
1056 	    "{N:/total packet%s dropped due to no ARP entry}\n");
1057 	p(timeouts, "{:entries-timeout/%ju} "
1058 	    "{N:/ARP entry%s timed out}\n");
1059 	p(dupips, "{:dropped-duplicate-address/%ju} "
1060 	    "{N:/Duplicate IP%s seen}\n");
1061 #undef p
1062 #undef p2
1063 	xo_close_container(name);
1064 }
1065 
1066 
1067 
1068 static	const char *icmpnames[ICMP_MAXTYPE + 1] = {
1069 	"echo reply",			/* RFC 792 */
1070 	"#1",
1071 	"#2",
1072 	"destination unreachable",	/* RFC 792 */
1073 	"source quench",		/* RFC 792 */
1074 	"routing redirect",		/* RFC 792 */
1075 	"#6",
1076 	"#7",
1077 	"echo",				/* RFC 792 */
1078 	"router advertisement",		/* RFC 1256 */
1079 	"router solicitation",		/* RFC 1256 */
1080 	"time exceeded",		/* RFC 792 */
1081 	"parameter problem",		/* RFC 792 */
1082 	"time stamp",			/* RFC 792 */
1083 	"time stamp reply",		/* RFC 792 */
1084 	"information request",		/* RFC 792 */
1085 	"information request reply",	/* RFC 792 */
1086 	"address mask request",		/* RFC 950 */
1087 	"address mask reply",		/* RFC 950 */
1088 	"#19",
1089 	"#20",
1090 	"#21",
1091 	"#22",
1092 	"#23",
1093 	"#24",
1094 	"#25",
1095 	"#26",
1096 	"#27",
1097 	"#28",
1098 	"#29",
1099 	"icmp traceroute",		/* RFC 1393 */
1100 	"datagram conversion error",	/* RFC 1475 */
1101 	"mobile host redirect",
1102 	"IPv6 where-are-you",
1103 	"IPv6 i-am-here",
1104 	"mobile registration req",
1105 	"mobile registration reply",
1106 	"domain name request",		/* RFC 1788 */
1107 	"domain name reply",		/* RFC 1788 */
1108 	"icmp SKIP",
1109 	"icmp photuris",		/* RFC 2521 */
1110 };
1111 
1112 /*
1113  * Dump ICMP statistics.
1114  */
1115 void
1116 icmp_stats(u_long off, const char *name, int af1 __unused, int proto __unused)
1117 {
1118 	struct icmpstat icmpstat;
1119 	size_t len;
1120 	int i, first;
1121 
1122 	if (fetch_stats("net.inet.icmp.stats", off, &icmpstat,
1123 	    sizeof(icmpstat), kread_counters) != 0)
1124 		return;
1125 
1126 	xo_open_container(name);
1127 	xo_emit("{T:/%s}:\n", name);
1128 
1129 #define	p(f, m) if (icmpstat.f || sflag <= 1) \
1130 	xo_emit(m, icmpstat.f, plural(icmpstat.f))
1131 #define	p1a(f, m) if (icmpstat.f || sflag <= 1) \
1132 	xo_emit(m, icmpstat.f)
1133 #define	p2(f, m) if (icmpstat.f || sflag <= 1) \
1134 	xo_emit(m, icmpstat.f, plurales(icmpstat.f))
1135 
1136 	p(icps_error, "\t{:icmp-calls/%lu} "
1137 	    "{N:/call%s to icmp_error}\n");
1138 	p(icps_oldicmp, "\t{:errors-not-from-message/%lu} "
1139 	    "{N:/error%s not generated in response to an icmp message}\n");
1140 
1141 	for (first = 1, i = 0; i < ICMP_MAXTYPE + 1; i++) {
1142 		if (icmpstat.icps_outhist[i] != 0) {
1143 			if (first) {
1144 				xo_open_list("output-histogram");
1145 				xo_emit("\tOutput histogram:\n");
1146 				first = 0;
1147 			}
1148 			xo_open_instance("output-histogram");
1149 			if (icmpnames[i] != NULL)
1150 				xo_emit("\t\t{k:name/%s}: {:count/%lu}\n",
1151 				    icmpnames[i], icmpstat.icps_outhist[i]);
1152 			else
1153 				xo_emit("\t\tunknown ICMP #{k:name/%d}: "
1154 				    "{:count/%lu}\n",
1155 				    i, icmpstat.icps_outhist[i]);
1156 			xo_close_instance("output-histogram");
1157 		}
1158 	}
1159 	if (!first)
1160 		xo_close_list("output-histogram");
1161 
1162 	p(icps_badcode, "\t{:dropped-bad-code/%lu} "
1163 	    "{N:/message%s with bad code fields}\n");
1164 	p(icps_tooshort, "\t{:dropped-too-short/%lu} "
1165 	    "{N:/message%s less than the minimum length}\n");
1166 	p(icps_checksum, "\t{:dropped-bad-checksum/%lu} "
1167 	    "{N:/message%s with bad checksum}\n");
1168 	p(icps_badlen, "\t{:dropped-bad-length/%lu} "
1169 	    "{N:/message%s with bad length}\n");
1170 	p1a(icps_bmcastecho, "\t{:dropped-multicast-echo/%lu} "
1171 	    "{N:/multicast echo requests ignored}\n");
1172 	p1a(icps_bmcasttstamp, "\t{:dropped-multicast-timestamp/%lu} "
1173 	    "{N:/multicast timestamp requests ignored}\n");
1174 
1175 	for (first = 1, i = 0; i < ICMP_MAXTYPE + 1; i++) {
1176 		if (icmpstat.icps_inhist[i] != 0) {
1177 			if (first) {
1178 				xo_open_list("input-histogram");
1179 				xo_emit("\tInput histogram:\n");
1180 				first = 0;
1181 			}
1182 			xo_open_instance("input-histogram");
1183 			if (icmpnames[i] != NULL)
1184 				xo_emit("\t\t{k:name/%s}: {:count/%lu}\n",
1185 					icmpnames[i],
1186 					icmpstat.icps_inhist[i]);
1187 			else
1188 				xo_emit(
1189 			"\t\tunknown ICMP #{k:name/%d}: {:count/%lu}\n",
1190 					i, icmpstat.icps_inhist[i]);
1191 			xo_close_instance("input-histogram");
1192 		}
1193 	}
1194 	if (!first)
1195 		xo_close_list("input-histogram");
1196 
1197 	p(icps_reflect, "\t{:sent-packets/%lu} "
1198 	    "{N:/message response%s generated}\n");
1199 	p2(icps_badaddr, "\t{:discard-invalid-return-address/%lu} "
1200 	    "{N:/invalid return address%s}\n");
1201 	p(icps_noroute, "\t{:discard-no-route/%lu} "
1202 	    "{N:/no return route%s}\n");
1203 #undef p
1204 #undef p1a
1205 #undef p2
1206 	if (live) {
1207 		len = sizeof i;
1208 		if (sysctlbyname("net.inet.icmp.maskrepl", &i, &len, NULL, 0) <
1209 		    0)
1210 			return;
1211 		xo_emit("\tICMP address mask responses are "
1212 		    "{q:icmp-address-responses/%sabled}\n", i ? "en" : "dis");
1213 	}
1214 
1215 	xo_close_container(name);
1216 }
1217 
1218 /*
1219  * Dump IGMP statistics structure.
1220  */
1221 void
1222 igmp_stats(u_long off, const char *name, int af1 __unused, int proto __unused)
1223 {
1224 	struct igmpstat igmpstat;
1225 
1226 	if (fetch_stats("net.inet.igmp.stats", 0, &igmpstat,
1227 	    sizeof(igmpstat), kread) != 0)
1228 		return;
1229 
1230 	if (igmpstat.igps_version != IGPS_VERSION_3) {
1231 		xo_warnx("%s: version mismatch (%d != %d)", __func__,
1232 		    igmpstat.igps_version, IGPS_VERSION_3);
1233 	}
1234 	if (igmpstat.igps_len != IGPS_VERSION3_LEN) {
1235 		xo_warnx("%s: size mismatch (%d != %d)", __func__,
1236 		    igmpstat.igps_len, IGPS_VERSION3_LEN);
1237 	}
1238 
1239 	xo_open_container(name);
1240 	xo_emit("{T:/%s}:\n", name);
1241 
1242 #define	p64(f, m) if (igmpstat.f || sflag <= 1) \
1243 	xo_emit(m, (uintmax_t) igmpstat.f, plural(igmpstat.f))
1244 #define	py64(f, m) if (igmpstat.f || sflag <= 1) \
1245 	xo_emit(m, (uintmax_t) igmpstat.f, pluralies(igmpstat.f))
1246 
1247 	p64(igps_rcv_total, "\t{:received-messages/%ju} "
1248 	    "{N:/message%s received}\n");
1249 	p64(igps_rcv_tooshort, "\t{:dropped-too-short/%ju} "
1250 	    "{N:/message%s received with too few bytes}\n");
1251 	p64(igps_rcv_badttl, "\t{:dropped-wrong-ttl/%ju} "
1252 	    "{N:/message%s received with wrong TTL}\n");
1253 	p64(igps_rcv_badsum, "\t{:dropped-bad-checksum/%ju} "
1254 	    "{N:/message%s received with bad checksum}\n");
1255 	py64(igps_rcv_v1v2_queries, "\t{:received-membership-queries/%ju} "
1256 	    "{N:/V1\\/V2 membership quer%s received}\n");
1257 	py64(igps_rcv_v3_queries, "\t{:received-v3-membership-queries/%ju} "
1258 	    "{N:/V3 membership quer%s received}\n");
1259 	py64(igps_rcv_badqueries, "\t{:dropped-membership-queries/%ju} "
1260 	    "{N:/membership quer%s received with invalid field(s)}\n");
1261 	py64(igps_rcv_gen_queries, "\t{:received-general-queries/%ju} "
1262 	    "{N:/general quer%s received}\n");
1263 	py64(igps_rcv_group_queries, "\t{:received-group-queries/%ju} "
1264 	    "{N:/group quer%s received}\n");
1265 	py64(igps_rcv_gsr_queries, "\t{:received-group-source-queries/%ju} "
1266 	    "{N:/group-source quer%s received}\n");
1267 	py64(igps_drop_gsr_queries, "\t{:dropped-group-source-queries/%ju} "
1268 	    "{N:/group-source quer%s dropped}\n");
1269 	p64(igps_rcv_reports, "\t{:received-membership-requests/%ju} "
1270 	    "{N:/membership report%s received}\n");
1271 	p64(igps_rcv_badreports, "\t{:dropped-membership-reports/%ju} "
1272 	    "{N:/membership report%s received with invalid field(s)}\n");
1273 	p64(igps_rcv_ourreports, "\t"
1274 	    "{:received-membership-reports-matching/%ju} "
1275 	    "{N:/membership report%s received for groups to which we belong}"
1276 	    "\n");
1277 	p64(igps_rcv_nora, "\t{:received-v3-reports-no-router-alert/%ju} "
1278 	    "{N:/V3 report%s received without Router Alert}\n");
1279 	p64(igps_snd_reports, "\t{:sent-membership-reports/%ju} "
1280 	    "{N:/membership report%s sent}\n");
1281 #undef p64
1282 #undef py64
1283 	xo_close_container(name);
1284 }
1285 
1286 /*
1287  * Dump PIM statistics structure.
1288  */
1289 void
1290 pim_stats(u_long off __unused, const char *name, int af1 __unused,
1291     int proto __unused)
1292 {
1293 	struct pimstat pimstat;
1294 
1295 	if (fetch_stats("net.inet.pim.stats", off, &pimstat,
1296 	    sizeof(pimstat), kread_counters) != 0)
1297 		return;
1298 
1299 	xo_open_container(name);
1300 	xo_emit("{T:/%s}:\n", name);
1301 
1302 #define	p(f, m) if (pimstat.f || sflag <= 1) \
1303 	xo_emit(m, (uintmax_t)pimstat.f, plural(pimstat.f))
1304 #define	py(f, m) if (pimstat.f || sflag <= 1) \
1305 	xo_emit(m, (uintmax_t)pimstat.f, pimstat.f != 1 ? "ies" : "y")
1306 
1307 	p(pims_rcv_total_msgs, "\t{:received-messages/%ju} "
1308 	    "{N:/message%s received}\n");
1309 	p(pims_rcv_total_bytes, "\t{:received-bytes/%ju} "
1310 	    "{N:/byte%s received}\n");
1311 	p(pims_rcv_tooshort, "\t{:dropped-too-short/%ju} "
1312 	    "{N:/message%s received with too few bytes}\n");
1313 	p(pims_rcv_badsum, "\t{:dropped-bad-checksum/%ju} "
1314 	    "{N:/message%s received with bad checksum}\n");
1315 	p(pims_rcv_badversion, "\t{:dropped-bad-version/%ju} "
1316 	    "{N:/message%s received with bad version}\n");
1317 	p(pims_rcv_registers_msgs, "\t{:received-data-register-messages/%ju} "
1318 	    "{N:/data register message%s received}\n");
1319 	p(pims_rcv_registers_bytes, "\t{:received-data-register-bytes/%ju} "
1320 	    "{N:/data register byte%s received}\n");
1321 	p(pims_rcv_registers_wrongiif, "\t"
1322 	    "{:received-data-register-wrong-interface/%ju} "
1323 	    "{N:/data register message%s received on wrong iif}\n");
1324 	p(pims_rcv_badregisters, "\t{:received-bad-registers/%ju} "
1325 	    "{N:/bad register%s received}\n");
1326 	p(pims_snd_registers_msgs, "\t{:sent-data-register-messages/%ju} "
1327 	    "{N:/data register message%s sent}\n");
1328 	p(pims_snd_registers_bytes, "\t{:sent-data-register-bytes/%ju} "
1329 	    "{N:/data register byte%s sent}\n");
1330 #undef p
1331 #undef py
1332 	xo_close_container(name);
1333 }
1334 
1335 #ifdef INET
1336 /*
1337  * Pretty print an Internet address (net address + port).
1338  */
1339 static void
1340 inetprint(const char *container, struct in_addr *in, int port,
1341     const char *proto, int num_port, const int af1)
1342 {
1343 	struct servent *sp = 0;
1344 	char line[80], *cp;
1345 	int width;
1346 	size_t alen, plen;
1347 
1348 	if (container)
1349 		xo_open_container(container);
1350 
1351 	if (Wflag)
1352 	    snprintf(line, sizeof(line), "%s.", inetname(in));
1353 	else
1354 	    snprintf(line, sizeof(line), "%.*s.",
1355 		(Aflag && !num_port) ? 12 : 16, inetname(in));
1356 	alen = strlen(line);
1357 	cp = line + alen;
1358 	if (!num_port && port)
1359 		sp = getservbyport((int)port, proto);
1360 	if (sp || port == 0)
1361 		snprintf(cp, sizeof(line) - alen,
1362 		    "%.15s ", sp ? sp->s_name : "*");
1363 	else
1364 		snprintf(cp, sizeof(line) - alen,
1365 		    "%d ", ntohs((u_short)port));
1366 	width = (Aflag && !Wflag) ? 18 :
1367 		((!Wflag || af1 == AF_INET) ? 22 : 45);
1368 	if (Wflag)
1369 		xo_emit("{d:target/%-*s} ", width, line);
1370 	else
1371 		xo_emit("{d:target/%-*.*s} ", width, width, line);
1372 
1373 	plen = strlen(cp) - 1;
1374 	alen--;
1375 	xo_emit("{e:address/%*.*s}{e:port/%*.*s}", alen, alen, line, plen,
1376 	    plen, cp);
1377 
1378 	if (container)
1379 		xo_close_container(container);
1380 }
1381 
1382 /*
1383  * Construct an Internet address representation.
1384  * If numeric_addr has been supplied, give
1385  * numeric value, otherwise try for symbolic name.
1386  */
1387 char *
1388 inetname(struct in_addr *inp)
1389 {
1390 	char *cp;
1391 	static char line[MAXHOSTNAMELEN];
1392 	struct hostent *hp;
1393 	struct netent *np;
1394 
1395 	cp = 0;
1396 	if (!numeric_addr && inp->s_addr != INADDR_ANY) {
1397 		int net = inet_netof(*inp);
1398 		int lna = inet_lnaof(*inp);
1399 
1400 		if (lna == INADDR_ANY) {
1401 			np = getnetbyaddr(net, AF_INET);
1402 			if (np)
1403 				cp = np->n_name;
1404 		}
1405 		if (cp == NULL) {
1406 			hp = gethostbyaddr((char *)inp, sizeof (*inp), AF_INET);
1407 			if (hp) {
1408 				cp = hp->h_name;
1409 				trimdomain(cp, strlen(cp));
1410 			}
1411 		}
1412 	}
1413 	if (inp->s_addr == INADDR_ANY)
1414 		strcpy(line, "*");
1415 	else if (cp) {
1416 		strlcpy(line, cp, sizeof(line));
1417 	} else {
1418 		inp->s_addr = ntohl(inp->s_addr);
1419 #define	C(x)	((u_int)((x) & 0xff))
1420 		snprintf(line, sizeof(line), "%u.%u.%u.%u",
1421 		    C(inp->s_addr >> 24), C(inp->s_addr >> 16),
1422 		    C(inp->s_addr >> 8), C(inp->s_addr));
1423 	}
1424 	return (line);
1425 }
1426 #endif
1427