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