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