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