xref: /freebsd/usr.bin/netstat/if.c (revision a64729f5077d77e13b9497cb33ecb3c82e606ee8)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 2013 Gleb Smirnoff <glebius@FreeBSD.org>
5  * Copyright (c) 1983, 1988, 1993
6  *	The Regents of the University of California.  All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. Neither the name of the University nor the names of its contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  */
32 
33 #include <sys/param.h>
34 #include <sys/protosw.h>
35 #include <sys/socket.h>
36 #include <sys/socketvar.h>
37 #include <sys/time.h>
38 
39 #include <net/if.h>
40 #include <net/if_dl.h>
41 #include <net/if_types.h>
42 #include <net/ethernet.h>
43 #include <netinet/in.h>
44 #include <netinet/in_var.h>
45 #include <arpa/inet.h>
46 #ifdef PF
47 #include <net/pfvar.h>
48 #include <net/pflow.h>
49 #include <net/if_pfsync.h>
50 #endif
51 
52 #include <errno.h>
53 #include <ifaddrs.h>
54 #include <libutil.h>
55 #ifdef INET6
56 #include <netdb.h>
57 #endif
58 #include <signal.h>
59 #include <stdbool.h>
60 #include <stdint.h>
61 #include <stdio.h>
62 #include <stdlib.h>
63 #include <string.h>
64 #include <sysexits.h>
65 #include <unistd.h>
66 #include <libxo/xo.h>
67 
68 #include "netstat.h"
69 
70 static void sidewaysintpr(void);
71 
72 #ifdef PF
73 static const char* pfsyncacts[] = {
74 	/* PFSYNC_ACT_CLR */		"clear all request",
75 	/* PFSYNC_ACT_INS_1301 */	"13.1 state insert",
76 	/* PFSYNC_ACT_INS_ACK */	"state inserted ack",
77 	/* PFSYNC_ACT_UPD_1301 */	"13.1 state update",
78 	/* PFSYNC_ACT_UPD_C */		"compressed state update",
79 	/* PFSYNC_ACT_UPD_REQ */	"uncompressed state request",
80 	/* PFSYNC_ACT_DEL */		"state delete",
81 	/* PFSYNC_ACT_DEL_C */		"compressed state delete",
82 	/* PFSYNC_ACT_INS_F */		"fragment insert",
83 	/* PFSYNC_ACT_DEL_F */		"fragment delete",
84 	/* PFSYNC_ACT_BUS */		"bulk update mark",
85 	/* PFSYNC_ACT_TDB */		"TDB replay counter update",
86 	/* PFSYNC_ACT_EOF */		"end of frame mark",
87 	/* PFSYNC_ACT_INS_1400 */	"state insert",
88 	/* PFSYNC_ACT_UPD_1400 */	"state update",
89 };
90 
91 static const char* pfsyncacts_name[] = {
92 	/* PFSYNC_ACT_CLR */		"clear-all-request",
93 	/* PFSYNC_ACT_INS_1301 */	"state-insert-1301",
94 	/* PFSYNC_ACT_INS_ACK */	"state-inserted-ack",
95 	/* PFSYNC_ACT_UPD_1301 */	"state-update-1301",
96 	/* PFSYNC_ACT_UPD_C */		"compressed-state-update",
97 	/* PFSYNC_ACT_UPD_REQ */	"uncompressed-state-request",
98 	/* PFSYNC_ACT_DEL */		"state-delete",
99 	/* PFSYNC_ACT_DEL_C */		"compressed-state-delete",
100 	/* PFSYNC_ACT_INS_F */		"fragment-insert",
101 	/* PFSYNC_ACT_DEL_F */		"fragment-delete",
102 	/* PFSYNC_ACT_BUS */		"bulk-update-mark",
103 	/* PFSYNC_ACT_TDB */		"TDB-replay-counter-update",
104 	/* PFSYNC_ACT_EOF */		"end-of-frame-mark",
105 	/* PFSYNC_ACT_INS_1400 */	"state-insert",
106 	/* PFSYNC_ACT_UPD_1400 */	"state-update",
107 };
108 
109 static void
110 pfsync_acts_stats(const char *list, const char *desc, uint64_t *a)
111 {
112 	int i;
113 
114 	xo_open_list(list);
115 	for (i = 0; i < PFSYNC_ACT_MAX; i++, a++) {
116 		if (*a || sflag <= 1) {
117 			xo_open_instance(list);
118 			xo_emit("\t\t{e:name}{:count/%ju} {N:/%s%s %s}\n",
119 			    pfsyncacts_name[i], (uintmax_t)(*a),
120 			    pfsyncacts[i], plural(*a), desc);
121 			xo_close_instance(list);
122 		}
123 	}
124 	xo_close_list(list);
125 }
126 
127 /*
128  * Dump pfsync statistics structure.
129  */
130 void
131 pfsync_stats(u_long off, const char *name, int af1 __unused, int proto __unused)
132 {
133 	struct pfsyncstats pfsyncstat;
134 
135 	if (fetch_stats("net.pfsync.stats", off, &pfsyncstat,
136 	    sizeof(pfsyncstat), kread) != 0)
137 		return;
138 
139 	xo_emit("{T:/%s}:\n", name);
140 	xo_open_container(name);
141 
142 #define	p(f, m) if (pfsyncstat.f || sflag <= 1) \
143 	xo_emit(m, (uintmax_t)pfsyncstat.f, plural(pfsyncstat.f))
144 
145 	p(pfsyncs_ipackets, "\t{:received-inet-packets/%ju} "
146 	    "{N:/packet%s received (IPv4)}\n");
147 	p(pfsyncs_ipackets6, "\t{:received-inet6-packets/%ju} "
148 	    "{N:/packet%s received (IPv6)}\n");
149 	pfsync_acts_stats("input-histogram", "received",
150 	    &pfsyncstat.pfsyncs_iacts[0]);
151 	p(pfsyncs_badif, "\t\t{:dropped-bad-interface/%ju} "
152 	    "{N:/packet%s discarded for bad interface}\n");
153 	p(pfsyncs_badttl, "\t\t{:dropped-bad-ttl/%ju} "
154 	    "{N:/packet%s discarded for bad ttl}\n");
155 	p(pfsyncs_hdrops, "\t\t{:dropped-short-header/%ju} "
156 	    "{N:/packet%s shorter than header}\n");
157 	p(pfsyncs_badver, "\t\t{:dropped-bad-version/%ju} "
158 	    "{N:/packet%s discarded for bad version}\n");
159 	p(pfsyncs_badauth, "\t\t{:dropped-bad-auth/%ju} "
160 	    "{N:/packet%s discarded for bad HMAC}\n");
161 	p(pfsyncs_badact,"\t\t{:dropped-bad-action/%ju} "
162 	    "{N:/packet%s discarded for bad action}\n");
163 	p(pfsyncs_badlen, "\t\t{:dropped-short/%ju} "
164 	    "{N:/packet%s discarded for short packet}\n");
165 	p(pfsyncs_badval, "\t\t{:dropped-bad-values/%ju} "
166 	    "{N:/state%s discarded for bad values}\n");
167 	p(pfsyncs_stale, "\t\t{:dropped-stale-state/%ju} "
168 	    "{N:/stale state%s}\n");
169 	p(pfsyncs_badstate, "\t\t{:dropped-failed-lookup/%ju} "
170 	    "{N:/failed state lookup\\/insert%s}\n");
171 	p(pfsyncs_opackets, "\t{:sent-inet-packets/%ju} "
172 	    "{N:/packet%s sent (IPv4})\n");
173 	p(pfsyncs_opackets6, "\t{:send-inet6-packets/%ju} "
174 	    "{N:/packet%s sent (IPv6})\n");
175 	pfsync_acts_stats("output-histogram", "sent",
176 	    &pfsyncstat.pfsyncs_oacts[0]);
177 	p(pfsyncs_onomem, "\t\t{:discarded-no-memory/%ju} "
178 	    "{N:/failure%s due to mbuf memory error}\n");
179 	p(pfsyncs_oerrors, "\t\t{:send-errors/%ju} "
180 	    "{N:/send error%s}\n");
181 #undef p
182 	xo_close_container(name);
183 }
184 
185 void
186 pflow_stats(u_long off, const char *name, int af1 __unused, int proto __unused)
187 {
188 	struct pflowstats pflowstat;
189 
190 	if (fetch_stats("net.pflow.stats", off, &pflowstat,
191 	    sizeof(pflowstat), kread) != 0)
192 		return;
193 
194 	xo_emit("{T:/%s}:\n", name);
195 	xo_open_container(name);
196 
197 #define	p(f, m) if (pflowstat.f || sflag <= 1) \
198 	xo_emit(m, (uintmax_t)pflowstat.f, plural(pflowstat.f))
199 
200 	p(pflow_flows, "\t{:flows/%ju} {N:/flow%s sent}\n");
201 	p(pflow_packets, "\t{:packets/%ju} {N:/packet%s sent}\n");
202 	p(pflow_onomem, "\t{:nomem/%ju} "
203 	    "{N:/send failed due to mbuf memory error}\n");
204 	p(pflow_oerrors, "\t{:send-error/%ju} {N:/send error}\n");
205 #undef p
206 
207 	xo_close_container(name);
208 }
209 #endif /* PF */
210 
211 /*
212  * Display a formatted value, or a '-' in the same space.
213  */
214 static void
215 show_stat(const char *fmt, int width, const char *name,
216     u_long value, short showvalue, int div1000)
217 {
218 	const char *lsep, *rsep;
219 	char newfmt[64];
220 
221 	lsep = "";
222 	if (strncmp(fmt, "LS", 2) == 0) {
223 		lsep = " ";
224 		fmt += 2;
225 	}
226 	rsep = " ";
227 	if (strncmp(fmt, "NRS", 3) == 0) {
228 		rsep = "";
229 		fmt += 3;
230 	}
231 	if (showvalue == 0) {
232 		/* Print just dash. */
233 		xo_emit("{P:/%s}{D:/%*s}{P:/%s}", lsep, width, "-", rsep);
234 		return;
235 	}
236 
237 	/*
238 	 * XXX: workaround {P:} modifier can't be empty and doesn't seem to
239 	 * take args... so we need to conditionally include it in the format.
240 	 */
241 #define maybe_pad(pad)	do {						    \
242 	if (strlen(pad)) {						    \
243 		snprintf(newfmt, sizeof(newfmt), "{P:%s}", pad);	    \
244 		xo_emit(newfmt);					    \
245 	}								    \
246 } while (0)
247 
248 	if (hflag) {
249 		char buf[5];
250 
251 		/* Format in human readable form. */
252 		humanize_number(buf, sizeof(buf), (int64_t)value, "",
253 		    HN_AUTOSCALE, HN_NOSPACE | HN_DECIMAL | \
254 		    ((div1000) ? HN_DIVISOR_1000 : 0));
255 		maybe_pad(lsep);
256 		snprintf(newfmt, sizeof(newfmt), "{:%s/%%%ds}", name, width);
257 		xo_emit(newfmt, buf);
258 		maybe_pad(rsep);
259 	} else {
260 		/* Construct the format string. */
261 		maybe_pad(lsep);
262 		snprintf(newfmt, sizeof(newfmt), "{:%s/%%%d%s}",
263 		    name, width, fmt);
264 		xo_emit(newfmt, value);
265 		maybe_pad(rsep);
266 	}
267 }
268 
269 /*
270  * Find next multiaddr for a given interface name.
271  */
272 static struct ifmaddrs *
273 next_ifma(struct ifmaddrs *ifma, const char *name, const sa_family_t family)
274 {
275 
276 	for(; ifma != NULL; ifma = ifma->ifma_next) {
277 		struct sockaddr_dl *sdl;
278 
279 		sdl = (struct sockaddr_dl *)ifma->ifma_name;
280 		if (ifma->ifma_addr->sa_family == family &&
281 		    strcmp(sdl->sdl_data, name) == 0)
282 			break;
283 	}
284 
285 	return (ifma);
286 }
287 
288 enum process_op { MEASURE, EMIT };
289 
290 static void
291 process_ifa_addr(enum process_op op, struct ifaddrs *ifa, int *max_net_len,
292     int *max_addr_len, bool *network, bool *link)
293 {
294 	int net_len, addr_len;
295 	const char *nn, *rn;
296 
297 	if (op == EMIT) {
298 		net_len = *max_net_len;
299 		addr_len = *max_addr_len;
300 	}
301 
302 	switch (ifa->ifa_addr->sa_family) {
303 	case AF_UNSPEC:
304 		if (op == MEASURE) {
305 			net_len = strlen("none");
306 			addr_len = strlen("none");
307 		} else {
308 			xo_emit("{:network/%-*.*s}  ", net_len, net_len,
309 			    "none");
310 			xo_emit("{:address/%-*.*s} ", addr_len, addr_len,
311 			    "none");
312 		}
313 		break;
314 	case AF_INET:
315 #ifdef INET6
316 	case AF_INET6:
317 #endif /* INET6 */
318 		nn = netname(ifa->ifa_addr, ifa->ifa_netmask);
319 		rn = routename(ifa->ifa_addr, numeric_addr);
320 		if (op == MEASURE) {
321 			net_len = strlen(nn);
322 			addr_len = strlen(rn);
323 		} else {
324 			xo_emit("{t:network/%-*s}  ", net_len, nn);
325 			xo_emit("{t:address/%-*s} ", addr_len, rn);
326 		}
327 
328 		if (network != NULL)
329 			*network = true;
330 		break;
331 	case AF_LINK:
332 	    {
333 		struct sockaddr_dl *sdl;
334 		char linknum[sizeof("<Link#32767>")];
335 
336 		sdl = (struct sockaddr_dl *)ifa->ifa_addr;
337 		snprintf(linknum, sizeof(linknum), "<Link#%d>", sdl->sdl_index);
338 		if (op == MEASURE) {
339 			net_len = strlen(linknum);
340 			if (sdl->sdl_nlen == 0 &&
341 			    sdl->sdl_alen == 0 &&
342 			    sdl->sdl_slen == 0)
343 				addr_len = 1;
344 			else
345 				addr_len = strlen(routename(ifa->ifa_addr, 1));
346 		} else {
347 			xo_emit("{t:network/%-*.*s}  ", net_len, net_len,
348 			    linknum);
349 			if (sdl->sdl_nlen == 0 &&
350 			    sdl->sdl_alen == 0 &&
351 			    sdl->sdl_slen == 0)
352 				xo_emit("{P:/%*s} ", addr_len, "");
353 			else
354 				xo_emit("{t:address/%-*.*s} ", addr_len,
355 				    addr_len, routename(ifa->ifa_addr, 1));
356 		}
357 		if (link != NULL)
358 			*link = true;
359 		break;
360 	    }
361 	}
362 
363 	if (op == MEASURE) {
364 		if (net_len > *max_net_len)
365 			*max_net_len = net_len;
366 		if (addr_len > *max_addr_len)
367 			*max_addr_len = addr_len;
368 	}
369 }
370 
371 static int
372 max_num_len(int max_len, u_long num)
373 {
374 	int len = 2;		/* include space */
375 
376 	for (; num > 10; len++)
377 		num /= 10;
378 	return (MAX(max_len, len));
379 }
380 
381 /*
382  * Print a description of the network interfaces.
383  */
384 void
385 intpr(void (*pfunc)(char *), int af)
386 {
387 	struct ifaddrs *ifap, *ifa;
388 	struct ifmaddrs *ifmap, *ifma;
389 	u_int ifn_len_max = 5, ifn_len;
390 	u_int net_len = strlen("Network "), addr_len = strlen("Address ");
391 	u_int npkt_len = 8, nbyte_len = 10, nerr_len = 5;
392 
393 	if (interval)
394 		return sidewaysintpr();
395 
396 	if (getifaddrs(&ifap) != 0)
397 		xo_err(EX_OSERR, "getifaddrs");
398 	if (aflag && getifmaddrs(&ifmap) != 0)
399 		xo_err(EX_OSERR, "getifmaddrs");
400 
401 	for (ifa = ifap; ifa; ifa = ifa->ifa_next) {
402 		if (interface != NULL &&
403 		    strcmp(ifa->ifa_name, interface) != 0)
404 			continue;
405 		if (af != AF_UNSPEC && ifa->ifa_addr->sa_family != af)
406 			continue;
407 		ifn_len = strlen(ifa->ifa_name);
408 		if ((ifa->ifa_flags & IFF_UP) == 0)
409 			++ifn_len;
410 		ifn_len_max = MAX(ifn_len_max, ifn_len);
411 		process_ifa_addr(MEASURE, ifa, &net_len, &addr_len,
412 		    NULL, NULL);
413 
414 #define	IFA_STAT(s)	(((struct if_data *)ifa->ifa_data)->ifi_ ## s)
415 		if (!hflag) {
416 			npkt_len = max_num_len(npkt_len, IFA_STAT(ipackets));
417 			npkt_len = max_num_len(npkt_len, IFA_STAT(opackets));
418 			nerr_len = max_num_len(nerr_len, IFA_STAT(ierrors));
419 			nerr_len = max_num_len(nerr_len, IFA_STAT(iqdrops));
420 			nerr_len = max_num_len(nerr_len, IFA_STAT(collisions));
421 			if (dflag)
422 				nerr_len = max_num_len(nerr_len,
423 				    IFA_STAT(oqdrops));
424 			if (bflag) {
425 				nbyte_len = max_num_len(nbyte_len,
426 				    IFA_STAT(ibytes));
427 				nbyte_len = max_num_len(nbyte_len,
428 				    IFA_STAT(obytes));
429 			}
430 		}
431 	}
432 
433 	xo_open_list("interface");
434 	if (!pfunc) {
435 		xo_emit("{T:/%-*.*s}", ifn_len_max, ifn_len_max, "Name");
436 		xo_emit(" {T:/%5.5s} {T:/%-*.*s}  {T:/%-*.*s} {T:/%*.*s} "
437 		    "{T:/%*.*s} {T:/%*.*s}",
438 		    "Mtu", net_len, net_len, "Network", addr_len, addr_len,
439 		    "Address", npkt_len, npkt_len, "Ipkts",
440 		    nerr_len, nerr_len, "Ierrs", nerr_len, nerr_len, "Idrop");
441 		if (bflag)
442 			xo_emit(" {T:/%*.*s}", nbyte_len, nbyte_len, "Ibytes");
443 		xo_emit(" {T:/%*.*s} {T:/%*.*s}", npkt_len, npkt_len, "Opkts",
444 		    nerr_len, nerr_len, "Oerrs");
445 		if (bflag)
446 			xo_emit(" {T:/%*.*s}", nbyte_len, nbyte_len, "Obytes");
447 		xo_emit(" {T:/%*s}", nerr_len, "Coll");
448 		if (dflag)
449 			xo_emit(" {T:/%*.*s}", nerr_len, nerr_len, "Drop");
450 		xo_emit("\n");
451 	}
452 
453 	for (ifa = ifap; ifa; ifa = ifa->ifa_next) {
454 		bool network = false, link = false;
455 		char *name, *xname, buf[IFNAMSIZ+1];
456 
457 		if (interface != NULL && strcmp(ifa->ifa_name, interface) != 0)
458 			continue;
459 
460 		name = ifa->ifa_name;
461 
462 		if (pfunc) {
463 
464 			(*pfunc)(name);
465 
466 			/*
467 			 * Skip all ifaddrs belonging to same interface.
468 			 */
469 			while(ifa->ifa_next != NULL &&
470 			    (strcmp(ifa->ifa_next->ifa_name, name) == 0)) {
471 				ifa = ifa->ifa_next;
472 			}
473 			continue;
474 		}
475 
476 		if (af != AF_UNSPEC && ifa->ifa_addr->sa_family != af)
477 			continue;
478 
479 		xo_open_instance("interface");
480 
481 		if ((ifa->ifa_flags & IFF_UP) == 0) {
482 			xname = stpcpy(buf, name);
483 			*xname++ = '*';
484 			*xname = '\0';
485 			xname = buf;
486 		} else
487 			xname = name;
488 
489 		xo_emit("{d:/%-*.*s}{etk:name}{eq:flags/0x%x}",
490 		    ifn_len_max, ifn_len_max, xname, name, ifa->ifa_flags);
491 
492 #define IFA_MTU(ifa)	(((struct if_data *)(ifa)->ifa_data)->ifi_mtu)
493 		show_stat("lu", 6, "mtu", IFA_MTU(ifa), IFA_MTU(ifa), 0);
494 #undef IFA_MTU
495 
496 		process_ifa_addr(EMIT, ifa, &net_len, &addr_len,
497 		    &network, &link);
498 
499 		show_stat("lu", npkt_len, "received-packets",
500 		    IFA_STAT(ipackets), link|network, 1);
501 		show_stat("lu", nerr_len, "received-errors", IFA_STAT(ierrors),
502 		    link, 1);
503 		show_stat("lu", nerr_len, "dropped-packets", IFA_STAT(iqdrops),
504 		    link, 1);
505 		if (bflag)
506 			show_stat("lu", nbyte_len, "received-bytes",
507 			    IFA_STAT(ibytes), link|network, 0);
508 		show_stat("lu", npkt_len, "sent-packets", IFA_STAT(opackets),
509 		    link|network, 1);
510 		show_stat("lu", nerr_len, "send-errors", IFA_STAT(oerrors),
511 		    link, 1);
512 		if (bflag)
513 			show_stat("lu", nbyte_len, "sent-bytes",
514 			    IFA_STAT(obytes), link|network, 0);
515 		show_stat("NRSlu", nerr_len, "collisions", IFA_STAT(collisions),
516 		    link, 1);
517 		if (dflag)
518 			show_stat("LSlu", nerr_len, "dropped-packets",
519 			    IFA_STAT(oqdrops), link, 1);
520 		xo_emit("\n");
521 
522 		if (!aflag) {
523 			xo_close_instance("interface");
524 			continue;
525 		}
526 
527 		/*
528 		 * Print family's multicast addresses.
529 		 */
530 		xo_open_list("multicast-address");
531 		for (ifma = next_ifma(ifmap, ifa->ifa_name,
532 		    ifa->ifa_addr->sa_family);
533 		    ifma != NULL;
534 		    ifma = next_ifma(ifma, ifa->ifa_name,
535 		    ifa->ifa_addr->sa_family)) {
536 			const char *fmt = NULL;
537 
538 			xo_open_instance("multicast-address");
539 			switch (ifma->ifma_addr->sa_family) {
540 			case AF_LINK:
541 			    {
542 				struct sockaddr_dl *sdl;
543 
544 				sdl = (struct sockaddr_dl *)ifma->ifma_addr;
545 				if (sdl->sdl_type != IFT_ETHER &&
546 				    sdl->sdl_type != IFT_FDDI)
547 					break;
548 			    }
549 				/* FALLTHROUGH */
550 			case AF_INET:
551 #ifdef INET6
552 			case AF_INET6:
553 #endif /* INET6 */
554 				fmt = routename(ifma->ifma_addr, numeric_addr);
555 				break;
556 			}
557 			if (fmt) {
558 				if (Wflag)
559 					xo_emit("{P:/%27s }"
560 					    "{t:address/%-17s/}", "", fmt);
561 				else
562 					xo_emit("{P:/%25s }"
563 					    "{t:address/%-17.17s/}", "", fmt);
564 				if (ifma->ifma_addr->sa_family == AF_LINK) {
565 					xo_emit(" {:received-packets/%8lu}",
566 					    IFA_STAT(imcasts));
567 					xo_emit("{P:/%*s}", bflag? 17 : 6, "");
568 					xo_emit(" {:sent-packets/%8lu}",
569 					    IFA_STAT(omcasts));
570  				}
571 				xo_emit("\n");
572 			}
573 			xo_close_instance("multicast-address");
574 			ifma = ifma->ifma_next;
575 		}
576 		xo_close_list("multicast-address");
577 		xo_close_instance("interface");
578 	}
579 	xo_close_list("interface");
580 
581 	freeifaddrs(ifap);
582 	if (aflag)
583 		freeifmaddrs(ifmap);
584 }
585 
586 struct iftot {
587 	u_long	ift_ip;			/* input packets */
588 	u_long	ift_ie;			/* input errors */
589 	u_long	ift_id;			/* input drops */
590 	u_long	ift_op;			/* output packets */
591 	u_long	ift_oe;			/* output errors */
592 	u_long	ift_od;			/* output drops */
593 	u_long	ift_co;			/* collisions */
594 	u_long	ift_ib;			/* input bytes */
595 	u_long	ift_ob;			/* output bytes */
596 };
597 
598 /*
599  * Obtain stats for interface(s).
600  */
601 static void
602 fill_iftot(struct iftot *st)
603 {
604 	struct ifaddrs *ifap, *ifa;
605 	bool found = false;
606 
607 	if (getifaddrs(&ifap) != 0)
608 		xo_err(EX_OSERR, "getifaddrs");
609 
610 	bzero(st, sizeof(*st));
611 
612 	for (ifa = ifap; ifa; ifa = ifa->ifa_next) {
613 		if (ifa->ifa_addr->sa_family != AF_LINK)
614 			continue;
615 		if (interface) {
616 			if (strcmp(ifa->ifa_name, interface) == 0)
617 				found = true;
618 			else
619 				continue;
620 		}
621 
622 		st->ift_ip += IFA_STAT(ipackets);
623 		st->ift_ie += IFA_STAT(ierrors);
624 		st->ift_id += IFA_STAT(iqdrops);
625 		st->ift_ib += IFA_STAT(ibytes);
626 		st->ift_op += IFA_STAT(opackets);
627 		st->ift_oe += IFA_STAT(oerrors);
628 		st->ift_od += IFA_STAT(oqdrops);
629 		st->ift_ob += IFA_STAT(obytes);
630  		st->ift_co += IFA_STAT(collisions);
631 	}
632 
633 	if (interface && found == false)
634 		xo_err(EX_DATAERR, "interface %s not found", interface);
635 
636 	freeifaddrs(ifap);
637 }
638 
639 /*
640  * Set a flag to indicate that a signal from the periodic itimer has been
641  * caught.
642  */
643 static sig_atomic_t signalled;
644 static void
645 catchalarm(int signo __unused)
646 {
647 	signalled = true;
648 }
649 
650 /*
651  * Print a running summary of interface statistics.
652  * Repeat display every interval seconds, showing statistics
653  * collected over that interval.  Assumes that interval is non-zero.
654  * First line printed at top of screen is always cumulative.
655  */
656 static void
657 sidewaysintpr(void)
658 {
659 	struct iftot ift[2], *new, *old;
660 	struct itimerval interval_it;
661 	int oldmask, line;
662 
663 	new = &ift[0];
664 	old = &ift[1];
665 	fill_iftot(old);
666 
667 	(void)signal(SIGALRM, catchalarm);
668 	signalled = false;
669 	interval_it.it_interval.tv_sec = interval;
670 	interval_it.it_interval.tv_usec = 0;
671 	interval_it.it_value = interval_it.it_interval;
672 	setitimer(ITIMER_REAL, &interval_it, NULL);
673 	xo_open_list("interface-statistics");
674 
675 banner:
676 	xo_emit("{T:/%17s} {T:/%14s} {T:/%16s}\n", "input",
677 	    interface != NULL ? interface : "(Total)", "output");
678 	xo_emit("{T:/%10s} {T:/%5s} {T:/%5s} {T:/%10s} {T:/%10s} {T:/%5s} "
679 	    "{T:/%10s} {T:/%5s}",
680 	    "packets", "errs", "idrops", "bytes", "packets", "errs", "bytes",
681 	    "colls");
682 	if (dflag)
683 		xo_emit(" {T:/%5.5s}", "drops");
684 	xo_emit("\n");
685 	xo_flush();
686 	line = 0;
687 
688 loop:
689 	if ((noutputs != 0) && (--noutputs == 0)) {
690 		xo_close_list("interface-statistics");
691 		return;
692 	}
693 	oldmask = sigblock(sigmask(SIGALRM));
694 	while (!signalled)
695 		sigpause(0);
696 	signalled = false;
697 	sigsetmask(oldmask);
698 	line++;
699 
700 	fill_iftot(new);
701 
702 	xo_open_instance("stats");
703 	show_stat("lu", 10, "received-packets",
704 	    new->ift_ip - old->ift_ip, 1, 1);
705 	show_stat("lu", 5, "received-errors",
706 	    new->ift_ie - old->ift_ie, 1, 1);
707 	show_stat("lu", 5, "dropped-packets",
708 	    new->ift_id - old->ift_id, 1, 1);
709 	show_stat("lu", 10, "received-bytes",
710 	    new->ift_ib - old->ift_ib, 1, 0);
711 	show_stat("lu", 10, "sent-packets",
712 	    new->ift_op - old->ift_op, 1, 1);
713 	show_stat("lu", 5, "send-errors",
714 	    new->ift_oe - old->ift_oe, 1, 1);
715 	show_stat("lu", 10, "sent-bytes",
716 	    new->ift_ob - old->ift_ob, 1, 0);
717 	show_stat("NRSlu", 5, "collisions",
718 	    new->ift_co - old->ift_co, 1, 1);
719 	if (dflag)
720 		show_stat("LSlu", 5, "dropped-packets",
721 		    new->ift_od - old->ift_od, 1, 1);
722 	xo_close_instance("stats");
723 	xo_emit("\n");
724 	xo_flush();
725 
726 	if (new == &ift[0]) {
727 		new = &ift[1];
728 		old = &ift[0];
729 	} else {
730 		new = &ift[0];
731 		old = &ift[1];
732 	}
733 
734 	if (line == 21)
735 		goto banner;
736 	else
737 		goto loop;
738 
739 	/* NOTREACHED */
740 }
741