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