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