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