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