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