xref: /freebsd/usr.bin/netstat/if.c (revision 4d65a7c6951cea0333f1a0c1b32c38489cdfa6c5)
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/if_pfsync.h>
49 #endif
50 
51 #include <err.h>
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 #endif /* PF */
185 
186 /*
187  * Display a formatted value, or a '-' in the same space.
188  */
189 static void
190 show_stat(const char *fmt, int width, const char *name,
191     u_long value, short showvalue, int div1000)
192 {
193 	const char *lsep, *rsep;
194 	char newfmt[64];
195 
196 	lsep = "";
197 	if (strncmp(fmt, "LS", 2) == 0) {
198 		lsep = " ";
199 		fmt += 2;
200 	}
201 	rsep = " ";
202 	if (strncmp(fmt, "NRS", 3) == 0) {
203 		rsep = "";
204 		fmt += 3;
205 	}
206 	if (showvalue == 0) {
207 		/* Print just dash. */
208 		xo_emit("{P:/%s}{D:/%*s}{P:/%s}", lsep, width, "-", rsep);
209 		return;
210 	}
211 
212 	/*
213 	 * XXX: workaround {P:} modifier can't be empty and doesn't seem to
214 	 * take args... so we need to conditionally include it in the format.
215 	 */
216 #define maybe_pad(pad)	do {						    \
217 	if (strlen(pad)) {						    \
218 		snprintf(newfmt, sizeof(newfmt), "{P:%s}", pad);	    \
219 		xo_emit(newfmt);					    \
220 	}								    \
221 } while (0)
222 
223 	if (hflag) {
224 		char buf[5];
225 
226 		/* Format in human readable form. */
227 		humanize_number(buf, sizeof(buf), (int64_t)value, "",
228 		    HN_AUTOSCALE, HN_NOSPACE | HN_DECIMAL | \
229 		    ((div1000) ? HN_DIVISOR_1000 : 0));
230 		maybe_pad(lsep);
231 		snprintf(newfmt, sizeof(newfmt), "{:%s/%%%ds}", name, width);
232 		xo_emit(newfmt, buf);
233 		maybe_pad(rsep);
234 	} else {
235 		/* Construct the format string. */
236 		maybe_pad(lsep);
237 		snprintf(newfmt, sizeof(newfmt), "{:%s/%%%d%s}",
238 		    name, width, fmt);
239 		xo_emit(newfmt, value);
240 		maybe_pad(rsep);
241 	}
242 }
243 
244 /*
245  * Find next multiaddr for a given interface name.
246  */
247 static struct ifmaddrs *
248 next_ifma(struct ifmaddrs *ifma, const char *name, const sa_family_t family)
249 {
250 
251 	for(; ifma != NULL; ifma = ifma->ifma_next) {
252 		struct sockaddr_dl *sdl;
253 
254 		sdl = (struct sockaddr_dl *)ifma->ifma_name;
255 		if (ifma->ifma_addr->sa_family == family &&
256 		    strcmp(sdl->sdl_data, name) == 0)
257 			break;
258 	}
259 
260 	return (ifma);
261 }
262 
263 enum process_op { MEASURE, EMIT };
264 
265 static void
266 process_ifa_addr(enum process_op op, struct ifaddrs *ifa, int *max_net_len,
267     int *max_addr_len, bool *network, bool *link)
268 {
269 	int net_len, addr_len;
270 	const char *nn, *rn;
271 
272 	if (op == EMIT) {
273 		net_len = *max_net_len;
274 		addr_len = *max_addr_len;
275 	}
276 
277 	switch (ifa->ifa_addr->sa_family) {
278 	case AF_UNSPEC:
279 		if (op == MEASURE) {
280 			net_len = strlen("none");
281 			addr_len = strlen("none");
282 		} else {
283 			xo_emit("{:network/%-*.*s}  ", net_len, net_len,
284 			    "none");
285 			xo_emit("{:address/%-*.*s} ", addr_len, addr_len,
286 			    "none");
287 		}
288 		break;
289 	case AF_INET:
290 #ifdef INET6
291 	case AF_INET6:
292 #endif /* INET6 */
293 		nn = netname(ifa->ifa_addr, ifa->ifa_netmask);
294 		rn = routename(ifa->ifa_addr, numeric_addr);
295 		if (op == MEASURE) {
296 			net_len = strlen(nn);
297 			addr_len = strlen(rn);
298 		} else {
299 			xo_emit("{t:network/%-*s}  ", net_len, nn);
300 			xo_emit("{t:address/%-*s} ", addr_len, rn);
301 		}
302 
303 		if (network != NULL)
304 			*network = true;
305 		break;
306 	case AF_LINK:
307 	    {
308 		struct sockaddr_dl *sdl;
309 		char linknum[sizeof("<Link#32767>")];
310 
311 		sdl = (struct sockaddr_dl *)ifa->ifa_addr;
312 		snprintf(linknum, sizeof(linknum), "<Link#%d>", sdl->sdl_index);
313 		if (op == MEASURE) {
314 			net_len = strlen(linknum);
315 			if (sdl->sdl_nlen == 0 &&
316 			    sdl->sdl_alen == 0 &&
317 			    sdl->sdl_slen == 0)
318 				addr_len = 1;
319 			else
320 				addr_len = strlen(routename(ifa->ifa_addr, 1));
321 		} else {
322 			xo_emit("{t:network/%-*.*s}  ", net_len, net_len,
323 			    linknum);
324 			if (sdl->sdl_nlen == 0 &&
325 			    sdl->sdl_alen == 0 &&
326 			    sdl->sdl_slen == 0)
327 				xo_emit("{P:/%*s} ", addr_len, "");
328 			else
329 				xo_emit("{t:address/%-*.*s} ", addr_len,
330 				    addr_len, routename(ifa->ifa_addr, 1));
331 		}
332 		if (link != NULL)
333 			*link = true;
334 		break;
335 	    }
336 	}
337 
338 	if (op == MEASURE) {
339 		if (net_len > *max_net_len)
340 			*max_net_len = net_len;
341 		if (addr_len > *max_addr_len)
342 			*max_addr_len = addr_len;
343 	}
344 }
345 
346 static int
347 max_num_len(int max_len, u_long num)
348 {
349 	int len = 2;		/* include space */
350 
351 	for (; num > 10; len++)
352 		num /= 10;
353 	return (MAX(max_len, len));
354 }
355 
356 /*
357  * Print a description of the network interfaces.
358  */
359 void
360 intpr(void (*pfunc)(char *), int af)
361 {
362 	struct ifaddrs *ifap, *ifa;
363 	struct ifmaddrs *ifmap, *ifma;
364 	u_int ifn_len_max = 5, ifn_len;
365 	u_int net_len = strlen("Network "), addr_len = strlen("Address ");
366 	u_int npkt_len = 8, nbyte_len = 10, nerr_len = 5;
367 
368 	if (interval)
369 		return sidewaysintpr();
370 
371 	if (getifaddrs(&ifap) != 0)
372 		err(EX_OSERR, "getifaddrs");
373 	if (aflag && getifmaddrs(&ifmap) != 0)
374 		err(EX_OSERR, "getifmaddrs");
375 
376 	for (ifa = ifap; ifa; ifa = ifa->ifa_next) {
377 		if (interface != NULL &&
378 		    strcmp(ifa->ifa_name, interface) != 0)
379 			continue;
380 		if (af != AF_UNSPEC && ifa->ifa_addr->sa_family != af)
381 			continue;
382 		ifn_len = strlen(ifa->ifa_name);
383 		if ((ifa->ifa_flags & IFF_UP) == 0)
384 			++ifn_len;
385 		ifn_len_max = MAX(ifn_len_max, ifn_len);
386 		process_ifa_addr(MEASURE, ifa, &net_len, &addr_len,
387 		    NULL, NULL);
388 
389 #define	IFA_STAT(s)	(((struct if_data *)ifa->ifa_data)->ifi_ ## s)
390 		if (!hflag) {
391 			npkt_len = max_num_len(npkt_len, IFA_STAT(ipackets));
392 			npkt_len = max_num_len(npkt_len, IFA_STAT(opackets));
393 			nerr_len = max_num_len(nerr_len, IFA_STAT(ierrors));
394 			nerr_len = max_num_len(nerr_len, IFA_STAT(iqdrops));
395 			nerr_len = max_num_len(nerr_len, IFA_STAT(collisions));
396 			if (dflag)
397 				nerr_len = max_num_len(nerr_len,
398 				    IFA_STAT(oqdrops));
399 			if (bflag) {
400 				nbyte_len = max_num_len(nbyte_len,
401 				    IFA_STAT(ibytes));
402 				nbyte_len = max_num_len(nbyte_len,
403 				    IFA_STAT(obytes));
404 			}
405 		}
406 	}
407 
408 	xo_open_list("interface");
409 	if (!pfunc) {
410 		xo_emit("{T:/%-*.*s}", ifn_len_max, ifn_len_max, "Name");
411 		xo_emit(" {T:/%5.5s} {T:/%-*.*s}  {T:/%-*.*s} {T:/%*.*s} "
412 		    "{T:/%*.*s} {T:/%*.*s}",
413 		    "Mtu", net_len, net_len, "Network", addr_len, addr_len,
414 		    "Address", npkt_len, npkt_len, "Ipkts",
415 		    nerr_len, nerr_len, "Ierrs", nerr_len, nerr_len, "Idrop");
416 		if (bflag)
417 			xo_emit(" {T:/%*.*s}", nbyte_len, nbyte_len, "Ibytes");
418 		xo_emit(" {T:/%*.*s} {T:/%*.*s}", npkt_len, npkt_len, "Opkts",
419 		    nerr_len, nerr_len, "Oerrs");
420 		if (bflag)
421 			xo_emit(" {T:/%*.*s}", nbyte_len, nbyte_len, "Obytes");
422 		xo_emit(" {T:/%*s}", nerr_len, "Coll");
423 		if (dflag)
424 			xo_emit(" {T:/%*.*s}", nerr_len, nerr_len, "Drop");
425 		xo_emit("\n");
426 	}
427 
428 	for (ifa = ifap; ifa; ifa = ifa->ifa_next) {
429 		bool network = false, link = false;
430 		char *name, *xname, buf[IFNAMSIZ+1];
431 
432 		if (interface != NULL && strcmp(ifa->ifa_name, interface) != 0)
433 			continue;
434 
435 		name = ifa->ifa_name;
436 
437 		if (pfunc) {
438 
439 			(*pfunc)(name);
440 
441 			/*
442 			 * Skip all ifaddrs belonging to same interface.
443 			 */
444 			while(ifa->ifa_next != NULL &&
445 			    (strcmp(ifa->ifa_next->ifa_name, name) == 0)) {
446 				ifa = ifa->ifa_next;
447 			}
448 			continue;
449 		}
450 
451 		if (af != AF_UNSPEC && ifa->ifa_addr->sa_family != af)
452 			continue;
453 
454 		xo_open_instance("interface");
455 
456 		if ((ifa->ifa_flags & IFF_UP) == 0) {
457 			xname = stpcpy(buf, name);
458 			*xname++ = '*';
459 			*xname = '\0';
460 			xname = buf;
461 		} else
462 			xname = name;
463 
464 		xo_emit("{d:/%-*.*s}{etk:name}{eq:flags/0x%x}",
465 		    ifn_len_max, ifn_len_max, xname, name, ifa->ifa_flags);
466 
467 #define IFA_MTU(ifa)	(((struct if_data *)(ifa)->ifa_data)->ifi_mtu)
468 		show_stat("lu", 6, "mtu", IFA_MTU(ifa), IFA_MTU(ifa), 0);
469 #undef IFA_MTU
470 
471 		process_ifa_addr(EMIT, ifa, &net_len, &addr_len,
472 		    &network, &link);
473 
474 		show_stat("lu", npkt_len, "received-packets",
475 		    IFA_STAT(ipackets), link|network, 1);
476 		show_stat("lu", nerr_len, "received-errors", IFA_STAT(ierrors),
477 		    link, 1);
478 		show_stat("lu", nerr_len, "dropped-packets", IFA_STAT(iqdrops),
479 		    link, 1);
480 		if (bflag)
481 			show_stat("lu", nbyte_len, "received-bytes",
482 			    IFA_STAT(ibytes), link|network, 0);
483 		show_stat("lu", npkt_len, "sent-packets", IFA_STAT(opackets),
484 		    link|network, 1);
485 		show_stat("lu", nerr_len, "send-errors", IFA_STAT(oerrors),
486 		    link, 1);
487 		if (bflag)
488 			show_stat("lu", nbyte_len, "sent-bytes",
489 			    IFA_STAT(obytes), link|network, 0);
490 		show_stat("NRSlu", nerr_len, "collisions", IFA_STAT(collisions),
491 		    link, 1);
492 		if (dflag)
493 			show_stat("LSlu", nerr_len, "dropped-packets",
494 			    IFA_STAT(oqdrops), link, 1);
495 		xo_emit("\n");
496 
497 		if (!aflag) {
498 			xo_close_instance("interface");
499 			continue;
500 		}
501 
502 		/*
503 		 * Print family's multicast addresses.
504 		 */
505 		xo_open_list("multicast-address");
506 		for (ifma = next_ifma(ifmap, ifa->ifa_name,
507 		    ifa->ifa_addr->sa_family);
508 		    ifma != NULL;
509 		    ifma = next_ifma(ifma, ifa->ifa_name,
510 		    ifa->ifa_addr->sa_family)) {
511 			const char *fmt = NULL;
512 
513 			xo_open_instance("multicast-address");
514 			switch (ifma->ifma_addr->sa_family) {
515 			case AF_LINK:
516 			    {
517 				struct sockaddr_dl *sdl;
518 
519 				sdl = (struct sockaddr_dl *)ifma->ifma_addr;
520 				if (sdl->sdl_type != IFT_ETHER &&
521 				    sdl->sdl_type != IFT_FDDI)
522 					break;
523 			    }
524 				/* FALLTHROUGH */
525 			case AF_INET:
526 #ifdef INET6
527 			case AF_INET6:
528 #endif /* INET6 */
529 				fmt = routename(ifma->ifma_addr, numeric_addr);
530 				break;
531 			}
532 			if (fmt) {
533 				if (Wflag)
534 					xo_emit("{P:/%27s }"
535 					    "{t:address/%-17s/}", "", fmt);
536 				else
537 					xo_emit("{P:/%25s }"
538 					    "{t:address/%-17.17s/}", "", fmt);
539 				if (ifma->ifma_addr->sa_family == AF_LINK) {
540 					xo_emit(" {:received-packets/%8lu}",
541 					    IFA_STAT(imcasts));
542 					xo_emit("{P:/%*s}", bflag? 17 : 6, "");
543 					xo_emit(" {:sent-packets/%8lu}",
544 					    IFA_STAT(omcasts));
545  				}
546 				xo_emit("\n");
547 			}
548 			xo_close_instance("multicast-address");
549 			ifma = ifma->ifma_next;
550 		}
551 		xo_close_list("multicast-address");
552 		xo_close_instance("interface");
553 	}
554 	xo_close_list("interface");
555 
556 	freeifaddrs(ifap);
557 	if (aflag)
558 		freeifmaddrs(ifmap);
559 }
560 
561 struct iftot {
562 	u_long	ift_ip;			/* input packets */
563 	u_long	ift_ie;			/* input errors */
564 	u_long	ift_id;			/* input drops */
565 	u_long	ift_op;			/* output packets */
566 	u_long	ift_oe;			/* output errors */
567 	u_long	ift_od;			/* output drops */
568 	u_long	ift_co;			/* collisions */
569 	u_long	ift_ib;			/* input bytes */
570 	u_long	ift_ob;			/* output bytes */
571 };
572 
573 /*
574  * Obtain stats for interface(s).
575  */
576 static void
577 fill_iftot(struct iftot *st)
578 {
579 	struct ifaddrs *ifap, *ifa;
580 	bool found = false;
581 
582 	if (getifaddrs(&ifap) != 0)
583 		xo_err(EX_OSERR, "getifaddrs");
584 
585 	bzero(st, sizeof(*st));
586 
587 	for (ifa = ifap; ifa; ifa = ifa->ifa_next) {
588 		if (ifa->ifa_addr->sa_family != AF_LINK)
589 			continue;
590 		if (interface) {
591 			if (strcmp(ifa->ifa_name, interface) == 0)
592 				found = true;
593 			else
594 				continue;
595 		}
596 
597 		st->ift_ip += IFA_STAT(ipackets);
598 		st->ift_ie += IFA_STAT(ierrors);
599 		st->ift_id += IFA_STAT(iqdrops);
600 		st->ift_ib += IFA_STAT(ibytes);
601 		st->ift_op += IFA_STAT(opackets);
602 		st->ift_oe += IFA_STAT(oerrors);
603 		st->ift_od += IFA_STAT(oqdrops);
604 		st->ift_ob += IFA_STAT(obytes);
605  		st->ift_co += IFA_STAT(collisions);
606 	}
607 
608 	if (interface && found == false)
609 		xo_err(EX_DATAERR, "interface %s not found", interface);
610 
611 	freeifaddrs(ifap);
612 }
613 
614 /*
615  * Set a flag to indicate that a signal from the periodic itimer has been
616  * caught.
617  */
618 static sig_atomic_t signalled;
619 static void
620 catchalarm(int signo __unused)
621 {
622 	signalled = true;
623 }
624 
625 /*
626  * Print a running summary of interface statistics.
627  * Repeat display every interval seconds, showing statistics
628  * collected over that interval.  Assumes that interval is non-zero.
629  * First line printed at top of screen is always cumulative.
630  */
631 static void
632 sidewaysintpr(void)
633 {
634 	struct iftot ift[2], *new, *old;
635 	struct itimerval interval_it;
636 	int oldmask, line;
637 
638 	new = &ift[0];
639 	old = &ift[1];
640 	fill_iftot(old);
641 
642 	(void)signal(SIGALRM, catchalarm);
643 	signalled = false;
644 	interval_it.it_interval.tv_sec = interval;
645 	interval_it.it_interval.tv_usec = 0;
646 	interval_it.it_value = interval_it.it_interval;
647 	setitimer(ITIMER_REAL, &interval_it, NULL);
648 	xo_open_list("interface-statistics");
649 
650 banner:
651 	xo_emit("{T:/%17s} {T:/%14s} {T:/%16s}\n", "input",
652 	    interface != NULL ? interface : "(Total)", "output");
653 	xo_emit("{T:/%10s} {T:/%5s} {T:/%5s} {T:/%10s} {T:/%10s} {T:/%5s} "
654 	    "{T:/%10s} {T:/%5s}",
655 	    "packets", "errs", "idrops", "bytes", "packets", "errs", "bytes",
656 	    "colls");
657 	if (dflag)
658 		xo_emit(" {T:/%5.5s}", "drops");
659 	xo_emit("\n");
660 	xo_flush();
661 	line = 0;
662 
663 loop:
664 	if ((noutputs != 0) && (--noutputs == 0)) {
665 		xo_close_list("interface-statistics");
666 		return;
667 	}
668 	oldmask = sigblock(sigmask(SIGALRM));
669 	while (!signalled)
670 		sigpause(0);
671 	signalled = false;
672 	sigsetmask(oldmask);
673 	line++;
674 
675 	fill_iftot(new);
676 
677 	xo_open_instance("stats");
678 	show_stat("lu", 10, "received-packets",
679 	    new->ift_ip - old->ift_ip, 1, 1);
680 	show_stat("lu", 5, "received-errors",
681 	    new->ift_ie - old->ift_ie, 1, 1);
682 	show_stat("lu", 5, "dropped-packets",
683 	    new->ift_id - old->ift_id, 1, 1);
684 	show_stat("lu", 10, "received-bytes",
685 	    new->ift_ib - old->ift_ib, 1, 0);
686 	show_stat("lu", 10, "sent-packets",
687 	    new->ift_op - old->ift_op, 1, 1);
688 	show_stat("lu", 5, "send-errors",
689 	    new->ift_oe - old->ift_oe, 1, 1);
690 	show_stat("lu", 10, "sent-bytes",
691 	    new->ift_ob - old->ift_ob, 1, 0);
692 	show_stat("NRSlu", 5, "collisions",
693 	    new->ift_co - old->ift_co, 1, 1);
694 	if (dflag)
695 		show_stat("LSlu", 5, "dropped-packets",
696 		    new->ift_od - old->ift_od, 1, 1);
697 	xo_close_instance("stats");
698 	xo_emit("\n");
699 	xo_flush();
700 
701 	if (new == &ift[0]) {
702 		new = &ift[1];
703 		old = &ift[0];
704 	} else {
705 		new = &ift[0];
706 		old = &ift[1];
707 	}
708 
709 	if (line == 21)
710 		goto banner;
711 	else
712 		goto loop;
713 
714 	/* NOTREACHED */
715 }
716