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