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