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