]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - usr.bin/systat/ifstat.c
atrtc: Add a required include
[FreeBSD/FreeBSD.git] / usr.bin / systat / ifstat.c
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 2003, Trent Nelson, <trent@arpa.com>.
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. The name of the author may not be used to endorse or promote products
16  *    derived from this software without specific prior written permission.
17  *
18  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
19  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
22  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
24  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTIFSTAT_ERRUPTION)
25  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
26  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
27  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
28  * SUCH DAMAGE.
29  */
30
31 #include <sys/types.h>
32 #include <sys/socket.h>
33 #include <sys/queue.h>
34 #include <sys/sysctl.h>
35 #include <net/if.h>
36 #include <net/if_mib.h>
37
38 #include <stdbool.h>
39 #include <stdlib.h>
40 #include <string.h>
41 #include <err.h>
42 #include <errno.h>
43 #include <fnmatch.h>
44
45 #include "systat.h"
46 #include "extern.h"
47 #include "convtbl.h"
48
49                                 /* Column numbers */
50
51 #define C1      0               /*  0-19 */
52 #define C2      20              /* 20-39 */
53 #define C3      40              /* 40-59 */
54 #define C4      60              /* 60-80 */
55 #define C5      80              /* Used for label positioning. */
56
57 static const int col0 = 0;
58 static const int col1 = C1;
59 static const int col2 = C2;
60 static const int col3 = C3;
61 static const int col4 = C4;
62 static const int col5 = C5;
63
64 SLIST_HEAD(, if_stat)           curlist;
65 SLIST_HEAD(, if_stat_disp)      displist;
66
67 struct if_stat {
68         SLIST_ENTRY(if_stat)     link;
69         char    display_name[IF_NAMESIZE];
70         char    dev_name[IFNAMSIZ];     /* copied from ifmibdata */
71         struct  ifmibdata if_mib;
72         struct  timeval tv;
73         struct  timeval tv_lastchanged;
74         uint64_t if_in_curtraffic;
75         uint64_t if_out_curtraffic;
76         uint64_t if_in_traffic_peak;
77         uint64_t if_out_traffic_peak;
78         uint64_t if_in_curpps;
79         uint64_t if_out_curpps;
80         uint64_t if_in_pps_peak;
81         uint64_t if_out_pps_peak;
82         u_int   if_row;                 /* Index into ifmib sysctl */
83         int     if_ypos;                /* -1 if not being displayed */
84         bool    display;
85         u_int   match;
86 };
87
88 extern   int curscale;
89 extern   char *matchline;
90 extern   int showpps;
91 extern   int needsort;
92
93 static   int needclear = 0;
94 static   bool displayall = false;
95
96 static   void  format_device_name(struct if_stat *);
97 static   int   getifmibdata(const int, struct ifmibdata *);
98 static   void  sort_interface_list(void);
99 static   u_int getifnum(void);
100 static   void  clearifstat(void);
101
102 #define IFSTAT_ERR(n, s)        do {                                    \
103         putchar('\014');                                                \
104         closeifstat(wnd);                                               \
105         err((n), (s));                                                  \
106 } while (0)
107
108 #define TOPLINE 3
109 #define TOPLABEL \
110 "      Interface           Traffic               Peak                Total"
111
112 #define STARTING_ROW    (TOPLINE + 1)
113 #define ROW_SPACING     (3)
114
115 #define IN_col2         (showpps ? ifp->if_in_curpps : ifp->if_in_curtraffic)
116 #define OUT_col2        (showpps ? ifp->if_out_curpps : ifp->if_out_curtraffic)
117 #define IN_col3         (showpps ? \
118                 ifp->if_in_pps_peak : ifp->if_in_traffic_peak)
119 #define OUT_col3        (showpps ? \
120                 ifp->if_out_pps_peak : ifp->if_out_traffic_peak)
121 #define IN_col4         (showpps ? \
122         ifp->if_mib.ifmd_data.ifi_ipackets : ifp->if_mib.ifmd_data.ifi_ibytes)
123 #define OUT_col4        (showpps ? \
124         ifp->if_mib.ifmd_data.ifi_opackets : ifp->if_mib.ifmd_data.ifi_obytes)
125
126 #define EMPTY_COLUMN    "                    "
127 #define CLEAR_COLUMN(y, x)      mvprintw((y), (x), "%20s", EMPTY_COLUMN);
128
129 #define DOPUTRATE(c, r, d)      do {                                    \
130         CLEAR_COLUMN(r, c);                                             \
131         if (showpps) {                                                  \
132                 mvprintw(r, (c), "%10.3f %cp%s  ",                      \
133                          convert(d##_##c, curscale),                    \
134                          *get_string(d##_##c, curscale),                \
135                          "/s");                                         \
136         }                                                               \
137         else {                                                          \
138                 mvprintw(r, (c), "%10.3f %s%s  ",                       \
139                          convert(d##_##c, curscale),                    \
140                          get_string(d##_##c, curscale),                 \
141                          "/s");                                         \
142         }                                                               \
143 } while (0)
144
145 #define DOPUTTOTAL(c, r, d)     do {                                    \
146         CLEAR_COLUMN((r), (c));                                         \
147         if (showpps) {                                                  \
148                 mvprintw((r), (c), "%12.3f %cp  ",                      \
149                          convert(d##_##c, SC_AUTO),                     \
150                          *get_string(d##_##c, SC_AUTO));                \
151         }                                                               \
152         else {                                                          \
153                 mvprintw((r), (c), "%12.3f %s  ",                       \
154                          convert(d##_##c, SC_AUTO),                     \
155                          get_string(d##_##c, SC_AUTO));                 \
156         }                                                               \
157 } while (0)
158
159 #define PUTRATE(c, r)   do {                                            \
160         DOPUTRATE(c, (r), IN);                                          \
161         DOPUTRATE(c, (r)+1, OUT);                                       \
162 } while (0)
163
164 #define PUTTOTAL(c, r)  do {                                            \
165         DOPUTTOTAL(c, (r), IN);                                         \
166         DOPUTTOTAL(c, (r)+1, OUT);                                      \
167 } while (0)
168
169 #define PUTNAME(p) do {                                                 \
170         mvprintw(p->if_ypos, 0, "%s", p->display_name);                 \
171         mvprintw(p->if_ypos, col2-3, "%s", (const char *)"in");         \
172         mvprintw(p->if_ypos+1, col2-3, "%s", (const char *)"out");      \
173 } while (0)
174
175 WINDOW *
176 openifstat(void)
177 {
178         return (subwin(stdscr, LINES-3-1, 0, MAINWIN_ROW, 0));
179 }
180
181 void
182 closeifstat(WINDOW *w)
183 {
184         struct if_stat  *node = NULL;
185
186         while (!SLIST_EMPTY(&curlist)) {
187                 node = SLIST_FIRST(&curlist);
188                 SLIST_REMOVE_HEAD(&curlist, link);
189                 free(node);
190         }
191
192         if (w != NULL) {
193                 wclear(w);
194                 wrefresh(w);
195                 delwin(w);
196         }
197
198         return;
199 }
200
201 void
202 labelifstat(void)
203 {
204
205         wmove(wnd, TOPLINE, 0);
206         wclrtoeol(wnd);
207         mvprintw(TOPLINE, 0, "%s", TOPLABEL);
208
209         return;
210 }
211
212 void
213 showifstat(void)
214 {
215         struct  if_stat *ifp = NULL;
216         
217         SLIST_FOREACH(ifp, &curlist, link) {
218                 if (ifp->if_ypos < LINES - 3 && ifp->if_ypos != -1)
219                         if (!ifp->display || ifp->match == 0) {
220                                         wmove(wnd, ifp->if_ypos, 0);
221                                         wclrtoeol(wnd);
222                                         wmove(wnd, ifp->if_ypos + 1, 0);
223                                         wclrtoeol(wnd);
224                         }
225                         else {
226                                 PUTNAME(ifp);
227                                 PUTRATE(col2, ifp->if_ypos);
228                                 PUTRATE(col3, ifp->if_ypos);
229                                 PUTTOTAL(col4, ifp->if_ypos);
230                         }
231         }
232
233         return;
234 }
235
236 int
237 initifstat(void)
238 {
239         struct   if_stat *p = NULL;
240         u_int    n, i;
241
242         n = getifnum();
243         if (n <= 0)
244                 return (-1);
245
246         SLIST_INIT(&curlist);
247
248         for (i = 0; i < n; i++) {
249                 p = (struct if_stat *)calloc(1, sizeof(struct if_stat));
250                 if (p == NULL)
251                         IFSTAT_ERR(1, "out of memory");
252                 p->if_row = i+1;
253                 if (getifmibdata(p->if_row, &p->if_mib) == -1) {
254                         free(p);
255                         continue;
256                 }
257                 SLIST_INSERT_HEAD(&curlist, p, link);
258                 format_device_name(p);
259                 p->match = 1;
260
261                 /*
262                  * Initially, we only display interfaces that have
263                  * received some traffic unless display-all is on.
264                  */
265                 if (displayall || p->if_mib.ifmd_data.ifi_ibytes != 0)
266                         p->display = true;
267         }
268
269         sort_interface_list();
270
271         return (1);
272 }
273
274 void
275 fetchifstat(void)
276 {
277         struct  if_stat *ifp = NULL, *temp_var;
278         struct  timeval tv, new_tv, old_tv;
279         double  elapsed = 0.0;
280         uint64_t new_inb, new_outb, old_inb, old_outb = 0;
281         uint64_t new_inp, new_outp, old_inp, old_outp = 0;
282
283         SLIST_FOREACH_SAFE(ifp, &curlist, link, temp_var) {
284                 /*
285                  * Grab a copy of the old input/output values before we
286                  * call getifmibdata().
287                  */
288                 old_inb = ifp->if_mib.ifmd_data.ifi_ibytes;
289                 old_outb = ifp->if_mib.ifmd_data.ifi_obytes;
290                 old_inp = ifp->if_mib.ifmd_data.ifi_ipackets;
291                 old_outp = ifp->if_mib.ifmd_data.ifi_opackets;
292                 ifp->tv_lastchanged = ifp->if_mib.ifmd_data.ifi_lastchange;
293
294                 (void)gettimeofday(&new_tv, NULL);
295                 if (getifmibdata(ifp->if_row, &ifp->if_mib) == -1 ) {
296                         /* if a device was removed */
297                         SLIST_REMOVE(&curlist, ifp, if_stat, link);
298                         free(ifp);
299                         needsort = 1;
300                         continue;
301                 } else if (strcmp(ifp->dev_name, ifp->if_mib.ifmd_name) != 0 ) {
302                         /* a device was removed and another one was added */
303                         format_device_name(ifp);
304                         /* clear to the current value for the new device */
305                         old_inb = ifp->if_mib.ifmd_data.ifi_ibytes;
306                         old_outb = ifp->if_mib.ifmd_data.ifi_obytes;
307                         old_inp = ifp->if_mib.ifmd_data.ifi_ipackets;
308                         old_outp = ifp->if_mib.ifmd_data.ifi_opackets;
309                         needsort = 1;
310                 }
311
312                 new_inb = ifp->if_mib.ifmd_data.ifi_ibytes;
313                 new_outb = ifp->if_mib.ifmd_data.ifi_obytes;
314                 new_inp = ifp->if_mib.ifmd_data.ifi_ipackets;
315                 new_outp = ifp->if_mib.ifmd_data.ifi_opackets;
316
317                 /* Display interface if it's received some traffic. */
318                 if (!ifp->display && new_inb > 0 && old_inb == 0) {
319                         ifp->display = true;
320                         needsort = 1;
321                 }
322
323                 /*
324                  * The rest is pretty trivial.  Calculate the new values
325                  * for our current traffic rates, and while we're there,
326                  * see if we have new peak rates.
327                  */
328                 old_tv = ifp->tv;
329                 timersub(&new_tv, &old_tv, &tv);
330                 elapsed = tv.tv_sec + (tv.tv_usec * 1e-6);
331
332                 ifp->if_in_curtraffic = new_inb - old_inb;
333                 ifp->if_out_curtraffic = new_outb - old_outb;
334
335                 ifp->if_in_curpps = new_inp - old_inp;
336                 ifp->if_out_curpps = new_outp - old_outp;
337
338                 /*
339                  * Rather than divide by the time specified on the comm-
340                  * and line, we divide by ``elapsed'' as this is likely
341                  * to be more accurate.
342                  */
343                 ifp->if_in_curtraffic /= elapsed;
344                 ifp->if_out_curtraffic /= elapsed;
345                 ifp->if_in_curpps /= elapsed;
346                 ifp->if_out_curpps /= elapsed;
347
348                 if (ifp->if_in_curtraffic > ifp->if_in_traffic_peak)
349                         ifp->if_in_traffic_peak = ifp->if_in_curtraffic;
350
351                 if (ifp->if_out_curtraffic > ifp->if_out_traffic_peak)
352                         ifp->if_out_traffic_peak = ifp->if_out_curtraffic;
353
354                 if (ifp->if_in_curpps > ifp->if_in_pps_peak)
355                         ifp->if_in_pps_peak = ifp->if_in_curpps;
356
357                 if (ifp->if_out_curpps > ifp->if_out_pps_peak)
358                         ifp->if_out_pps_peak = ifp->if_out_curpps;
359
360                 ifp->tv.tv_sec = new_tv.tv_sec;
361                 ifp->tv.tv_usec = new_tv.tv_usec;
362
363         }
364
365         if (needsort)
366                 sort_interface_list();
367
368         return;
369 }
370
371 /*
372  * We want to right justify our interface names against the first column
373  * (first sixteen or so characters), so we need to do some alignment.
374  * We save original name so that we can find a same spot is take by a
375  * different device.
376  */
377 static void
378 format_device_name(struct if_stat *ifp)
379 {
380
381         if (ifp != NULL ) {
382                 snprintf(ifp->display_name, IF_NAMESIZE, "%*s", IF_NAMESIZE-1,
383                     ifp->if_mib.ifmd_name);
384                 strcpy(ifp->dev_name, ifp->if_mib.ifmd_name);
385         }
386 }
387
388 static int
389 check_match(const char *ifname) 
390 {
391         char *p = matchline, *c, t;
392         int match = 0, mlen;
393         
394         if (matchline == NULL)
395                 return (0);
396
397         /* Strip leading whitespaces */
398         while (*p == ' ')
399                 p ++;
400
401         c = p;
402         while ((mlen = strcspn(c, " ;,")) != 0) {
403                 p = c + mlen;
404                 t = *p;
405                 if (p - c > 0) {
406                         *p = '\0';
407                         if (fnmatch(c, ifname, FNM_CASEFOLD) == 0) {
408                                 *p = t;
409                                 return (1);
410                         }
411                         *p = t;
412                         c = p + strspn(p, " ;,");
413                 }
414                 else {
415                         c = p + strspn(p, " ;,");
416                 }
417         }
418
419         return (match);
420 }
421
422 /*
423  * This function iterates through our list of interfaces, identifying
424  * those that are to be displayed (ifp->display = 1).  For each interf-
425  * rface that we're displaying, we generate an appropriate position for
426  * it on the screen (ifp->if_ypos).
427  *
428  * This function is called any time a change is made to an interface's
429  * ``display'' state.
430  */
431 void
432 sort_interface_list(void)
433 {
434         struct  if_stat *ifp = NULL;
435         u_int   y = 0;
436
437         y = STARTING_ROW;
438         SLIST_FOREACH(ifp, &curlist, link) {
439                 if (matchline && !check_match(ifp->if_mib.ifmd_name))
440                         ifp->match = 0;
441                 else
442                         ifp->match = 1;
443                 if (ifp->display && ifp->match) {
444                         ifp->if_ypos = y;
445                         y += ROW_SPACING;
446                 }
447                 else
448                         ifp->if_ypos = -1;
449         }
450         
451         needsort = 0;
452         needclear = 1;
453 }
454
455 static
456 unsigned int
457 getifnum(void)
458 {
459         u_int   data    = 0;
460         size_t  datalen = 0;
461         static  int name[] = { CTL_NET,
462                                PF_LINK,
463                                NETLINK_GENERIC,
464                                IFMIB_SYSTEM,
465                                IFMIB_IFCOUNT };
466
467         datalen = sizeof(data);
468         if (sysctl(name, 5, (void *)&data, (size_t *)&datalen, (void *)NULL,
469             (size_t)0) != 0)
470                 IFSTAT_ERR(1, "sysctl error");
471         return (data);
472 }
473
474 static int
475 getifmibdata(int row, struct ifmibdata *data)
476 {
477         int     ret = 0;
478         size_t  datalen = 0;
479         static  int name[] = { CTL_NET,
480                                PF_LINK,
481                                NETLINK_GENERIC,
482                                IFMIB_IFDATA,
483                                0,
484                                IFDATA_GENERAL };
485         datalen = sizeof(*data);
486         name[4] = row;
487
488         ret = sysctl(name, 6, (void *)data, (size_t *)&datalen, (void *)NULL,
489             (size_t)0);
490         if ((ret != 0) && (errno != ENOENT))
491                 IFSTAT_ERR(2, "sysctl error getting interface data");
492
493         return (ret);
494 }
495
496 int
497 cmdifstat(const char *cmd, const char *args)
498 {
499         int     retval = 0;
500
501         retval = ifcmd(cmd, args);
502         /* ifcmd() returns 1 on success */
503         if (retval == 1) {
504                 if (needclear)
505                         clearifstat();
506         }
507         else if (prefix(cmd, "all")) {
508                 retval = 1;
509                 displayall = true;
510         }
511         return (retval);
512 }
513
514 static void
515 clearifstat(void)
516 {
517
518         showifstat();
519         refresh();
520         werase(wnd);
521         labelifstat();
522         needclear = 0;
523 }