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