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