xref: /freebsd/usr.bin/systat/ifstat.c (revision 297c1ec1248b127230cb3eef2be3692102ca7c88)
1 /*
2  * Copyright (c) 2003, Trent Nelson, <trent@arpa.com>.
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. The name of the author may not be used to endorse or promote products
14  *    derived from this software without specific prior written permission.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
20  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTIFSTAT_ERRUPTION)
23  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26  * SUCH DAMAGE.
27  *
28  * $FreeBSD$
29  */
30 
31 #include <sys/types.h>
32 #include <sys/socket.h>
33 #include <sys/sysctl.h>
34 #include <net/if.h>
35 #include <net/if_mib.h>
36 
37 #include <stdlib.h>
38 #include <string.h>
39 #include <err.h>
40 #include <errno.h>
41 #include <fnmatch.h>
42 
43 #include "systat.h"
44 #include "extern.h"
45 #include "convtbl.h"
46 
47 				/* Column numbers */
48 
49 #define C1	0		/*  0-19 */
50 #define C2	20		/* 20-39 */
51 #define C3	40		/* 40-59 */
52 #define C4	60		/* 60-80 */
53 #define C5	80		/* Used for label positioning. */
54 
55 static const int col0 = 0;
56 static const int col1 = C1;
57 static const int col2 = C2;
58 static const int col3 = C3;
59 static const int col4 = C4;
60 static const int col5 = C5;
61 
62 SLIST_HEAD(, if_stat)		curlist;
63 SLIST_HEAD(, if_stat_disp)	displist;
64 
65 struct if_stat {
66 	SLIST_ENTRY(if_stat)	 link;
67 	char	if_name[IF_NAMESIZE];
68 	struct	ifmibdata if_mib;
69 	struct	timeval tv;
70 	struct	timeval tv_lastchanged;
71 	u_long	if_in_curtraffic;
72 	u_long	if_out_curtraffic;
73 	u_long	if_in_traffic_peak;
74 	u_long	if_out_traffic_peak;
75 	u_long	if_in_curpps;
76 	u_long	if_out_curpps;
77 	u_long	if_in_pps_peak;
78 	u_long	if_out_pps_peak;
79 	u_int	if_row;			/* Index into ifmib sysctl */
80 	u_int	if_ypos;		/* 0 if not being displayed */
81 	u_int	display;
82 	u_int	match;
83 };
84 
85 extern	 int curscale;
86 extern	 char *matchline;
87 extern	 int showpps;
88 extern	 int needsort;
89 
90 static	 int needclear = 0;
91 
92 static	 void  right_align_string(struct if_stat *);
93 static	 void  getifmibdata(const int, struct ifmibdata *);
94 static	 void  sort_interface_list(void);
95 static	 u_int getifnum(void);
96 
97 #define IFSTAT_ERR(n, s)	do {					\
98 	putchar('\014');						\
99 	closeifstat(wnd);						\
100 	err((n), (s));							\
101 } while (0)
102 
103 #define TOPLINE 3
104 #define TOPLABEL \
105 "      Interface           Traffic               Peak                Total"
106 
107 #define STARTING_ROW	(TOPLINE + 1)
108 #define ROW_SPACING	(3)
109 
110 #define IN_col2		(showpps ? ifp->if_in_curpps : ifp->if_in_curtraffic)
111 #define OUT_col2	(showpps ? ifp->if_out_curpps : ifp->if_out_curtraffic)
112 #define IN_col3		(showpps ? \
113 		ifp->if_in_pps_peak : ifp->if_in_traffic_peak)
114 #define OUT_col3	(showpps ? \
115 		ifp->if_out_pps_peak : ifp->if_out_traffic_peak)
116 #define IN_col4		(showpps ? \
117 	ifp->if_mib.ifmd_data.ifi_ipackets : ifp->if_mib.ifmd_data.ifi_ibytes)
118 #define OUT_col4	(showpps ? \
119 	ifp->if_mib.ifmd_data.ifi_opackets : ifp->if_mib.ifmd_data.ifi_obytes)
120 
121 #define EMPTY_COLUMN 	"                    "
122 #define CLEAR_COLUMN(y, x)	mvprintw((y), (x), "%20s", EMPTY_COLUMN);
123 
124 #define DOPUTRATE(c, r, d)	do {					\
125 	CLEAR_COLUMN(r, c);						\
126 	if (showpps) {							\
127 		mvprintw(r, (c), "%10.3f %cp%s  ",			\
128 			 convert(d##_##c, curscale),			\
129 			 *get_string(d##_##c, curscale),		\
130 			 "/s");						\
131 	}								\
132 	else {								\
133 		mvprintw(r, (c), "%10.3f %s%s  ",			\
134 			 convert(d##_##c, curscale),			\
135 			 get_string(d##_##c, curscale),			\
136 			 "/s");						\
137 	}								\
138 } while (0)
139 
140 #define DOPUTTOTAL(c, r, d)	do {					\
141 	CLEAR_COLUMN((r), (c));						\
142 	if (showpps) {							\
143 		mvprintw((r), (c), "%12.3f %cp  ",			\
144 			 convert(d##_##c, SC_AUTO),			\
145 			 *get_string(d##_##c, SC_AUTO));		\
146 	}								\
147 	else {								\
148 		mvprintw((r), (c), "%12.3f %s  ",			\
149 			 convert(d##_##c, SC_AUTO),			\
150 			 get_string(d##_##c, SC_AUTO));			\
151 	}								\
152 } while (0)
153 
154 #define PUTRATE(c, r)	do {						\
155 	DOPUTRATE(c, (r), IN);						\
156 	DOPUTRATE(c, (r)+1, OUT);					\
157 } while (0)
158 
159 #define PUTTOTAL(c, r)	do {						\
160 	DOPUTTOTAL(c, (r), IN);						\
161 	DOPUTTOTAL(c, (r)+1, OUT);					\
162 } while (0)
163 
164 #define PUTNAME(p) do {							\
165 	mvprintw(p->if_ypos, 0, "%s", p->if_name);			\
166 	mvprintw(p->if_ypos, col2-3, "%s", (const char *)"in");		\
167 	mvprintw(p->if_ypos+1, col2-3, "%s", (const char *)"out");	\
168 } while (0)
169 
170 WINDOW *
171 openifstat(void)
172 {
173 	return (subwin(stdscr, LINES-3-1, 0, MAINWIN_ROW, 0));
174 }
175 
176 void
177 closeifstat(WINDOW *w)
178 {
179 	struct if_stat	*node = NULL;
180 
181 	while (!SLIST_EMPTY(&curlist)) {
182 		node = SLIST_FIRST(&curlist);
183 		SLIST_REMOVE_HEAD(&curlist, link);
184 		free(node);
185 	}
186 
187 	if (w != NULL) {
188 		wclear(w);
189 		wrefresh(w);
190 		delwin(w);
191 	}
192 
193 	return;
194 }
195 
196 void
197 labelifstat(void)
198 {
199 
200 	wmove(wnd, TOPLINE, 0);
201 	wclrtoeol(wnd);
202 	mvprintw(TOPLINE, 0, "%s", TOPLABEL);
203 
204 	return;
205 }
206 
207 void
208 showifstat(void)
209 {
210 	struct	if_stat *ifp = NULL;
211 
212 	SLIST_FOREACH(ifp, &curlist, link) {
213 		if (ifp->display == 0 || (ifp->match == 0) ||
214 			ifp->if_ypos > LINES - 3 - 1)
215 			continue;
216 		PUTNAME(ifp);
217 		PUTRATE(col2, ifp->if_ypos);
218 		PUTRATE(col3, ifp->if_ypos);
219 		PUTTOTAL(col4, ifp->if_ypos);
220 	}
221 
222 	return;
223 }
224 
225 int
226 initifstat(void)
227 {
228 	struct   if_stat *p = NULL;
229 	u_int	 n = 0, i = 0;
230 
231 	n = getifnum();
232 	if (n <= 0)
233 		return (-1);
234 
235 	SLIST_INIT(&curlist);
236 
237 	for (i = 0; i < n; i++) {
238 		p = (struct if_stat *)calloc(1, sizeof(struct if_stat));
239 		if (p == NULL)
240 			IFSTAT_ERR(1, "out of memory");
241 		SLIST_INSERT_HEAD(&curlist, p, link);
242 		p->if_row = i+1;
243 		getifmibdata(p->if_row, &p->if_mib);
244 		right_align_string(p);
245 		p->match = 1;
246 
247 		/*
248 		 * Initially, we only display interfaces that have
249 		 * received some traffic.
250 		 */
251 		if (p->if_mib.ifmd_data.ifi_ibytes != 0)
252 			p->display = 1;
253 	}
254 
255 	sort_interface_list();
256 
257 	return (1);
258 }
259 
260 void
261 fetchifstat(void)
262 {
263 	struct	if_stat *ifp = NULL;
264 	struct	timeval tv, new_tv, old_tv;
265 	double	elapsed = 0.0;
266 	u_int	new_inb, new_outb, old_inb, old_outb = 0;
267 	u_int	new_inp, new_outp, old_inp, old_outp = 0;
268 
269 	SLIST_FOREACH(ifp, &curlist, link) {
270 		/*
271 		 * Grab a copy of the old input/output values before we
272 		 * call getifmibdata().
273 		 */
274 		old_inb = ifp->if_mib.ifmd_data.ifi_ibytes;
275 		old_outb = ifp->if_mib.ifmd_data.ifi_obytes;
276 		old_inp = ifp->if_mib.ifmd_data.ifi_ipackets;
277 		old_outp = ifp->if_mib.ifmd_data.ifi_opackets;
278 		ifp->tv_lastchanged = ifp->if_mib.ifmd_data.ifi_lastchange;
279 
280 		(void)gettimeofday(&new_tv, NULL);
281 		(void)getifmibdata(ifp->if_row, &ifp->if_mib);
282 
283 		new_inb = ifp->if_mib.ifmd_data.ifi_ibytes;
284 		new_outb = ifp->if_mib.ifmd_data.ifi_obytes;
285 		new_inp = ifp->if_mib.ifmd_data.ifi_ipackets;
286 		new_outp = ifp->if_mib.ifmd_data.ifi_opackets;
287 
288 		/* Display interface if it's received some traffic. */
289 		if (new_inb > 0 && old_inb == 0) {
290 			ifp->display = 1;
291 			needsort = 1;
292 		}
293 
294 		/*
295 		 * The rest is pretty trivial.  Calculate the new values
296 		 * for our current traffic rates, and while we're there,
297 		 * see if we have new peak rates.
298 		 */
299 		old_tv = ifp->tv;
300 		timersub(&new_tv, &old_tv, &tv);
301 		elapsed = tv.tv_sec + (tv.tv_usec * 1e-6);
302 
303 		ifp->if_in_curtraffic = new_inb - old_inb;
304 		ifp->if_out_curtraffic = new_outb - old_outb;
305 
306 		ifp->if_in_curpps = new_inp - old_inp;
307 		ifp->if_out_curpps = new_outp - old_outp;
308 
309 		/*
310 		 * Rather than divide by the time specified on the comm-
311 		 * and line, we divide by ``elapsed'' as this is likely
312 		 * to be more accurate.
313 		 */
314 		ifp->if_in_curtraffic /= elapsed;
315 		ifp->if_out_curtraffic /= elapsed;
316 		ifp->if_in_curpps /= elapsed;
317 		ifp->if_out_curpps /= elapsed;
318 
319 		if (ifp->if_in_curtraffic > ifp->if_in_traffic_peak)
320 			ifp->if_in_traffic_peak = ifp->if_in_curtraffic;
321 
322 		if (ifp->if_out_curtraffic > ifp->if_out_traffic_peak)
323 			ifp->if_out_traffic_peak = ifp->if_out_curtraffic;
324 
325 		if (ifp->if_in_curpps > ifp->if_in_pps_peak)
326 			ifp->if_in_pps_peak = ifp->if_in_curpps;
327 
328 		if (ifp->if_out_curpps > ifp->if_out_pps_peak)
329 			ifp->if_out_pps_peak = ifp->if_out_curpps;
330 
331 		ifp->tv.tv_sec = new_tv.tv_sec;
332 		ifp->tv.tv_usec = new_tv.tv_usec;
333 
334 	}
335 
336 	if (needsort)
337 		sort_interface_list();
338 
339 	return;
340 }
341 
342 /*
343  * We want to right justify our interface names against the first column
344  * (first sixteen or so characters), so we need to do some alignment.
345  */
346 static void
347 right_align_string(struct if_stat *ifp)
348 {
349 	int	 str_len = 0, pad_len = 0;
350 	char	*newstr = NULL, *ptr = NULL;
351 
352 	if (ifp == NULL || ifp->if_mib.ifmd_name == NULL)
353 		return;
354 	else {
355 		/* string length + '\0' */
356 		str_len = strlen(ifp->if_mib.ifmd_name)+1;
357 		pad_len = IF_NAMESIZE-(str_len);
358 
359 		newstr = ifp->if_name;
360 		ptr = newstr + pad_len;
361 		(void)memset((void *)newstr, (int)' ', IF_NAMESIZE);
362 		(void)strncpy(ptr, (const char *)&ifp->if_mib.ifmd_name,
363 			      str_len);
364 	}
365 
366 	return;
367 }
368 
369 static int
370 check_match(const char *ifname)
371 {
372 	char *p = matchline, *c, t;
373 	int match = 0, mlen;
374 
375 	if (matchline == NULL)
376 		return (0);
377 
378 	/* Strip leading whitespaces */
379 	while (*p == ' ')
380 		p ++;
381 
382 	c = p;
383 	while ((mlen = strcspn(c, " ;,")) != 0) {
384 		p = c + mlen;
385 		t = *p;
386 		if (p - c > 0) {
387 			*p = '\0';
388 			if (fnmatch(c, ifname, FNM_CASEFOLD) == 0) {
389 				*p = t;
390 				return (1);
391 			}
392 			*p = t;
393 			c = p + strspn(p, " ;,");
394 		}
395 		else {
396 			c = p + strspn(p, " ;,");
397 		}
398 	}
399 
400 	return (match);
401 }
402 
403 /*
404  * This function iterates through our list of interfaces, identifying
405  * those that are to be displayed (ifp->display = 1).  For each interf-
406  * rface that we're displaying, we generate an appropriate position for
407  * it on the screen (ifp->if_ypos).
408  *
409  * This function is called any time a change is made to an interface's
410  * ``display'' state.
411  */
412 void
413 sort_interface_list(void)
414 {
415 	struct	if_stat	*ifp = NULL;
416 	u_int	y = 0;
417 
418 	y = STARTING_ROW;
419 	SLIST_FOREACH(ifp, &curlist, link) {
420 		if (matchline && !check_match(ifp->if_mib.ifmd_name))
421 			ifp->match = 0;
422 		else
423 			ifp->match = 1;
424 		if (ifp->display && ifp->match) {
425 			ifp->if_ypos = y;
426 			y += ROW_SPACING;
427 		}
428 	}
429 
430 	needsort = 0;
431 	needclear = 1;
432 }
433 
434 static
435 unsigned int
436 getifnum(void)
437 {
438 	u_int	data    = 0;
439 	size_t	datalen = 0;
440 	static	int name[] = { CTL_NET,
441 			       PF_LINK,
442 			       NETLINK_GENERIC,
443 			       IFMIB_SYSTEM,
444 			       IFMIB_IFCOUNT };
445 
446 	datalen = sizeof(data);
447 	if (sysctl(name, 5, (void *)&data, (size_t *)&datalen, (void *)NULL,
448 	    (size_t)0) != 0)
449 		IFSTAT_ERR(1, "sysctl error");
450 	return (data);
451 }
452 
453 static void
454 getifmibdata(int row, struct ifmibdata *data)
455 {
456 	size_t	datalen = 0;
457 	static	int name[] = { CTL_NET,
458 			       PF_LINK,
459 			       NETLINK_GENERIC,
460 			       IFMIB_IFDATA,
461 			       0,
462 			       IFDATA_GENERAL };
463 	datalen = sizeof(*data);
464 	name[4] = row;
465 
466 	if ((sysctl(name, 6, (void *)data, (size_t *)&datalen, (void *)NULL,
467 	    (size_t)0) != 0) && (errno != ENOENT))
468 		IFSTAT_ERR(2, "sysctl error getting interface data");
469 }
470 
471 int
472 cmdifstat(const char *cmd, const char *args)
473 {
474 	int	retval = 0;
475 
476 	retval = ifcmd(cmd, args);
477 	/* ifcmd() returns 1 on success */
478 	if (retval == 1) {
479 		showifstat();
480 		refresh();
481 		if (needclear) {
482 			werase(wnd);
483 			labelifstat();
484 			needclear = 0;
485 		}
486 	}
487 
488 	return (retval);
489 }
490