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