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