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