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