xref: /freebsd/usr.bin/systat/ifstat.c (revision 2a664c03e55254b0f3b32dcdfc78179c0a57a8d2)
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 
42 #include "systat.h"
43 #include "extern.h"
44 #include "convtbl.h"
45 
46 				/* Column numbers */
47 
48 #define C1	0		/*  0-19 */
49 #define C2	20		/* 20-39 */
50 #define C3	40		/* 40-59 */
51 #define C4	60		/* 60-80 */
52 #define C5	80		/* Used for label positioning. */
53 
54 static const int col0 = 0;
55 static const int col1 = C1;
56 static const int col2 = C2;
57 static const int col3 = C3;
58 static const int col4 = C4;
59 static const int col5 = C5;
60 
61 SLIST_HEAD(, if_stat)		curlist;
62 SLIST_HEAD(, if_stat_disp)	displist;
63 
64 struct if_stat {
65 	SLIST_ENTRY(if_stat)	 link;
66 	char	if_name[IF_NAMESIZE];
67 	struct	ifmibdata if_mib;
68 	struct	timeval tv;
69 	struct	timeval tv_lastchanged;
70 	u_long	if_in_curtraffic;
71 	u_long	if_out_curtraffic;
72 	u_long	if_in_traffic_peak;
73 	u_long	if_out_traffic_peak;
74 	u_int	if_row;			/* Index into ifmib sysctl */
75 	u_int	if_ypos;		/* 0 if not being displayed */
76 	u_int	display;
77 };
78 
79 extern	 u_int curscale;
80 
81 static	 void  right_align_string(struct if_stat *);
82 static	 void  getifmibdata(const int, struct ifmibdata *);
83 static	 void  sort_interface_list(void);
84 static	 u_int getifnum(void);
85 
86 #define IFSTAT_ERR(n, s)	do {					\
87 	putchar('\014');						\
88 	closeifstat(wnd);						\
89 	err((n), (s));							\
90 } while (0)
91 
92 #define TOPLINE 3
93 #define TOPLABEL \
94 "      Interface           Traffic               Peak                Total"
95 
96 #define STARTING_ROW	(TOPLINE + 1)
97 #define ROW_SPACING	(3)
98 
99 #define CLEAR_LINE(y, x)	do {					\
100 	wmove(wnd, y, x);						\
101 	wclrtoeol(wnd);							\
102 } while (0)
103 
104 #define IN_col2		(ifp->if_in_curtraffic)
105 #define OUT_col2	(ifp->if_out_curtraffic)
106 #define IN_col3		(ifp->if_in_traffic_peak)
107 #define OUT_col3	(ifp->if_out_traffic_peak)
108 #define IN_col4		(ifp->if_mib.ifmd_data.ifi_ibytes)
109 #define OUT_col4	(ifp->if_mib.ifmd_data.ifi_obytes)
110 
111 #define EMPTY_COLUMN 	"                    "
112 #define CLEAR_COLUMN(y, x)	mvprintw((y), (x), "%20s", EMPTY_COLUMN);
113 
114 #define DOPUTRATE(c, r, d)	do {					\
115 	CLEAR_COLUMN(r, c);						\
116 	mvprintw(r, (c), "%10.3f %s%s  ",				\
117 		 convert(d##_##c, curscale),				\
118 		 get_string(d##_##c, curscale),				\
119 		 "/s");							\
120 } while (0)
121 
122 #define DOPUTTOTAL(c, r, d)	do {					\
123 	CLEAR_COLUMN((r), (c));						\
124 	mvprintw((r), (c), "%12.3f %s  ",				\
125 		 convert(d##_##c, SC_AUTO),				\
126 		 get_string(d##_##c, SC_AUTO));				\
127 } while (0)
128 
129 #define PUTRATE(c, r)	do {						\
130 	DOPUTRATE(c, (r), IN);						\
131 	DOPUTRATE(c, (r)+1, OUT);					\
132 } while (0)
133 
134 #define PUTTOTAL(c, r)	do {						\
135 	DOPUTTOTAL(c, (r), IN);						\
136 	DOPUTTOTAL(c, (r)+1, OUT);					\
137 } while (0)
138 
139 #define PUTNAME(p) do {							\
140 	mvprintw(p->if_ypos, 0, "%s", p->if_name);			\
141 	mvprintw(p->if_ypos, col2-3, "%s", (const char *)"in");		\
142 	mvprintw(p->if_ypos+1, col2-3, "%s", (const char *)"out");	\
143 } while (0)
144 
145 WINDOW *
146 openifstat(void)
147 {
148 	return (subwin(stdscr, LINES-3-1, 0, MAINWIN_ROW, 0));
149 }
150 
151 void
152 closeifstat(WINDOW *w)
153 {
154 	struct if_stat	*node = NULL;
155 
156 	while (!SLIST_EMPTY(&curlist)) {
157 		node = SLIST_FIRST(&curlist);
158 		SLIST_REMOVE_HEAD(&curlist, link);
159 		free(node);
160 	}
161 
162 	if (w != NULL) {
163 		wclear(w);
164 		wrefresh(w);
165 		delwin(w);
166 	}
167 
168 	return;
169 }
170 
171 void
172 labelifstat(void)
173 {
174 
175 	wmove(wnd, TOPLINE, 0);
176 	wclrtoeol(wnd);
177 	mvprintw(TOPLINE, 0, "%s", TOPLABEL);
178 
179 	return;
180 }
181 
182 void
183 showifstat(void)
184 {
185 	struct	if_stat *ifp = NULL;
186 	SLIST_FOREACH(ifp, &curlist, link) {
187 		if (ifp->display == 0)
188 			continue;
189 		PUTNAME(ifp);
190 		PUTRATE(col2, ifp->if_ypos);
191 		PUTRATE(col3, ifp->if_ypos);
192 		PUTTOTAL(col4, ifp->if_ypos);
193 	}
194 
195 	return;
196 }
197 
198 int
199 initifstat(void)
200 {
201 	struct   if_stat *p = NULL;
202 	u_int	 n = 0, i = 0;
203 
204 	n = getifnum();
205 	if (n <= 0)
206 		return -1;
207 
208 	SLIST_INIT(&curlist);
209 
210 	for (i = 0; i < n; i++) {
211 		p = (struct if_stat *)calloc(1, sizeof(struct if_stat));
212 		if (p == NULL)
213 			IFSTAT_ERR(1, "out of memory");
214 		SLIST_INSERT_HEAD(&curlist, p, link);
215 		p->if_row = i+1;
216 		getifmibdata(p->if_row, &p->if_mib);
217 		right_align_string(p);
218 
219 		/*
220 		 * Initially, we only display interfaces that have
221 		 * received some traffic.
222 		 */
223 		if (p->if_mib.ifmd_data.ifi_ibytes != 0)
224 			p->display = 1;
225 	}
226 
227 	sort_interface_list();
228 
229 	return 1;
230 }
231 
232 void
233 fetchifstat(void)
234 {
235 	struct	if_stat *ifp = NULL;
236 	struct	timeval tv, new_tv, old_tv;
237 	double	elapsed = 0.0;
238 	u_int	new_inb, new_outb, old_inb, old_outb = 0;
239 	u_int	we_need_to_sort_interface_list = 0;
240 
241 	SLIST_FOREACH(ifp, &curlist, link) {
242 		/*
243 		 * Grab a copy of the old input/output values before we
244 		 * call getifmibdata().
245 		 */
246 		old_inb = ifp->if_mib.ifmd_data.ifi_ibytes;
247 		old_outb = ifp->if_mib.ifmd_data.ifi_obytes;
248 		ifp->tv_lastchanged = ifp->if_mib.ifmd_data.ifi_lastchange;
249 
250 		(void)gettimeofday(&new_tv, NULL);
251 		(void)getifmibdata(ifp->if_row, &ifp->if_mib);
252 
253 		new_inb = ifp->if_mib.ifmd_data.ifi_ibytes;
254 		new_outb = ifp->if_mib.ifmd_data.ifi_obytes;
255 
256 		/* Display interface if it's received some traffic. */
257 		if (new_inb > 0 && old_inb == 0) {
258 			ifp->display = 1;
259 			we_need_to_sort_interface_list++;
260 		}
261 
262 		/*
263 		 * The rest is pretty trivial.  Calculate the new values
264 		 * for our current traffic rates, and while we're there,
265 		 * see if we have new peak rates.
266 		 */
267 		old_tv = ifp->tv;
268 		timersub(&new_tv, &old_tv, &tv);
269 		elapsed = tv.tv_sec + (tv.tv_usec * 1e-6);
270 
271 		ifp->if_in_curtraffic = new_inb - old_inb;
272 		ifp->if_out_curtraffic = new_outb - old_outb;
273 
274 		/*
275 		 * Rather than divide by the time specified on the comm-
276 		 * and line, we divide by ``elapsed'' as this is likely
277 		 * to be more accurate.
278 		 */
279 		ifp->if_in_curtraffic /= elapsed;
280 		ifp->if_out_curtraffic /= elapsed;
281 
282 		if (ifp->if_in_curtraffic > ifp->if_in_traffic_peak)
283 			ifp->if_in_traffic_peak = ifp->if_in_curtraffic;
284 
285 		if (ifp->if_out_curtraffic > ifp->if_out_traffic_peak)
286 			ifp->if_out_traffic_peak = ifp->if_out_curtraffic;
287 
288 		ifp->tv.tv_sec = new_tv.tv_sec;
289 		ifp->tv.tv_usec = new_tv.tv_usec;
290 
291 	}
292 
293 	if (we_need_to_sort_interface_list)
294 		sort_interface_list();
295 
296 	return;
297 }
298 
299 /*
300  * We want to right justify our interface names against the first column
301  * (first sixteen or so characters), so we need to do some alignment.
302  */
303 static void
304 right_align_string(struct if_stat *ifp)
305 {
306 	int	 str_len = 0, pad_len = 0;
307 	char	*newstr = NULL, *ptr = NULL;
308 
309 	if (ifp == NULL || ifp->if_mib.ifmd_name == NULL)
310 		return;
311 	else {
312 		/* string length + '\0' */
313 		str_len = strlen(ifp->if_mib.ifmd_name)+1;
314 		pad_len = IF_NAMESIZE-(str_len);
315 
316 		newstr = ifp->if_name;
317 		ptr = newstr + pad_len;
318 		(void)memset((void *)newstr, (int)' ', IF_NAMESIZE);
319 		(void)strncpy(ptr, (const char *)&ifp->if_mib.ifmd_name,
320 			      str_len);
321 	}
322 
323 	return;
324 }
325 
326 /*
327  * This function iterates through our list of interfaces, identifying
328  * those that are to be displayed (ifp->display = 1).  For each interf-
329  * rface that we're displaying, we generate an appropriate position for
330  * it on the screen (ifp->if_ypos).
331  *
332  * This function is called any time a change is made to an interface's
333  * ``display'' state.
334  */
335 void
336 sort_interface_list(void)
337 {
338 	struct	if_stat	*ifp = NULL;
339 	u_int	y = 0;
340 
341 	y = STARTING_ROW;
342 	SLIST_FOREACH(ifp, &curlist, link) {
343 		if (ifp->display) {
344 			ifp->if_ypos = y;
345 			y += ROW_SPACING;
346 		}
347 	}
348 }
349 
350 static
351 unsigned int
352 getifnum(void)
353 {
354 	u_int	data    = 0;
355 	size_t	datalen = 0;
356 	static	int name[] = { CTL_NET,
357 			       PF_LINK,
358 			       NETLINK_GENERIC,
359 			       IFMIB_SYSTEM,
360 			       IFMIB_IFCOUNT };
361 
362 	datalen = sizeof(data);
363 	if (sysctl(name, 5, (void *)&data, (size_t *)&datalen, (void *)NULL,
364 	    (size_t)0) != 0)
365 		IFSTAT_ERR(1, "sysctl error");
366 	return data;
367 }
368 
369 static void
370 getifmibdata(int row, struct ifmibdata *data)
371 {
372 	size_t	datalen = 0;
373 	static	int name[] = { CTL_NET,
374 			       PF_LINK,
375 			       NETLINK_GENERIC,
376 			       IFMIB_IFDATA,
377 			       0,
378 			       IFDATA_GENERAL };
379 	datalen = sizeof(*data);
380 	name[4] = row;
381 
382 	if ((sysctl(name, 6, (void *)data, (size_t *)&datalen, (void *)NULL,
383 	    (size_t)0) != 0) && (errno != ENOENT))
384 		IFSTAT_ERR(2, "sysctl error getting interface data");
385 }
386 
387 int
388 cmdifstat(const char *cmd, const char *args)
389 {
390 	int	retval = 0;
391 
392 	retval = ifcmd(cmd, args);
393 	/* ifcmd() returns 1 on success */
394 	if (retval == 1) {
395 		showifstat();
396 		refresh();
397 	}
398 
399 	return retval;
400 }
401