]> git.proxmox.com Git - mirror_iproute2.git/blame - misc/ifstat.c
ss: mptcp: fix add_addr_accepted stat print
[mirror_iproute2.git] / misc / ifstat.c
CommitLineData
aba5acdf
SH
1/*
2 * ifstat.c handy utility to read net interface statistics
3 *
4 * This program is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU General Public License
6 * as published by the Free Software Foundation; either version
7 * 2 of the License, or (at your option) any later version.
8 *
9 * Authors: Alexey Kuznetsov, <kuznet@ms2.inr.ac.ru>
10 */
11
12#include <stdio.h>
13#include <stdlib.h>
14#include <unistd.h>
15#include <fcntl.h>
16#include <string.h>
17#include <errno.h>
18#include <time.h>
19#include <sys/time.h>
20#include <fnmatch.h>
21#include <sys/file.h>
22#include <sys/socket.h>
23#include <sys/un.h>
24#include <sys/poll.h>
25#include <sys/wait.h>
26#include <sys/stat.h>
27#include <signal.h>
28#include <math.h>
9f3ea250 29#include <getopt.h>
aba5acdf 30
daf7bd5c
SH
31#include <linux/if.h>
32#include <linux/if_link.h>
aba5acdf 33
3d8048dc
NF
34#include "libnetlink.h"
35#include "json_writer.h"
fbef6555 36#include "version.h"
5a52102b 37#include "utils.h"
aba5acdf 38
acd1e437
SH
39int dump_zeros;
40int reset_history;
41int ignore_history;
42int no_output;
43int json_output;
44int no_update;
45int scan_interval;
46int time_constant;
47int show_errors;
aba5acdf
SH
48double W;
49char **patterns;
50int npatterns;
5a52102b
NF
51bool is_extended;
52int filter_type;
53int sub_type;
aba5acdf
SH
54
55char info_source[128];
56int source_mismatch;
57
a571587d 58#define MAXS (sizeof(struct rtnl_link_stats)/sizeof(__u32))
5a52102b 59#define NO_SUB_TYPE 0xffff
aba5acdf 60
acd1e437 61struct ifstat_ent {
aba5acdf
SH
62 struct ifstat_ent *next;
63 char *name;
64 int ifindex;
5a52102b 65 __u64 val[MAXS];
aba5acdf 66 double rate[MAXS];
a571587d 67 __u32 ival[MAXS];
aba5acdf
SH
68};
69
ec3e625c
SH
70static const char *stats[MAXS] = {
71 "rx_packets",
72 "tx_packets",
73 "rx_bytes",
74 "tx_bytes",
75 "rx_errors",
76 "tx_errors",
77 "rx_dropped",
78 "tx_dropped",
79 "multicast",
80 "collisions",
81 "rx_length_errors",
82 "rx_over_errors",
83 "rx_crc_errors",
84 "rx_frame_errors",
85 "rx_fifo_errors",
86 "rx_missed_errors",
87 "tx_aborted_errors",
88 "tx_carrier_errors",
89 "tx_fifo_errors",
90 "tx_heartbeat_errors",
91 "tx_window_errors",
92 "rx_compressed",
93 "tx_compressed"
94};
95
aba5acdf
SH
96struct ifstat_ent *kern_db;
97struct ifstat_ent *hist_db;
98
50772dc5 99static int match(const char *id)
aba5acdf
SH
100{
101 int i;
102
103 if (npatterns == 0)
104 return 1;
105
acd1e437 106 for (i = 0; i < npatterns; i++) {
8f5a602f 107 if (!fnmatch(patterns[i], id, FNM_CASEFOLD))
aba5acdf
SH
108 return 1;
109 }
110 return 0;
111}
112
cd554f2c 113static int get_nlmsg_extended(struct nlmsghdr *m, void *arg)
5a52102b
NF
114{
115 struct if_stats_msg *ifsm = NLMSG_DATA(m);
116 struct rtattr *tb[IFLA_STATS_MAX+1];
117 int len = m->nlmsg_len;
118 struct ifstat_ent *n;
119
120 if (m->nlmsg_type != RTM_NEWSTATS)
121 return 0;
122
123 len -= NLMSG_LENGTH(sizeof(*ifsm));
124 if (len < 0)
125 return -1;
126
127 parse_rtattr(tb, IFLA_STATS_MAX, IFLA_STATS_RTA(ifsm), len);
128 if (tb[filter_type] == NULL)
129 return 0;
130
131 n = malloc(sizeof(*n));
132 if (!n)
133 abort();
134
135 n->ifindex = ifsm->ifindex;
136 n->name = strdup(ll_index_to_name(ifsm->ifindex));
137
138 if (sub_type == NO_SUB_TYPE) {
139 memcpy(&n->val, RTA_DATA(tb[filter_type]), sizeof(n->val));
140 } else {
141 struct rtattr *attr;
142
143 attr = parse_rtattr_one_nested(sub_type, tb[filter_type]);
35f6adef
PS
144 if (attr == NULL) {
145 free(n);
5a52102b 146 return 0;
35f6adef 147 }
5a52102b
NF
148 memcpy(&n->val, RTA_DATA(attr), sizeof(n->val));
149 }
150 memset(&n->rate, 0, sizeof(n->rate));
151 n->next = kern_db;
152 kern_db = n;
153 return 0;
154}
155
cd554f2c 156static int get_nlmsg(struct nlmsghdr *m, void *arg)
aba5acdf
SH
157{
158 struct ifinfomsg *ifi = NLMSG_DATA(m);
acd1e437 159 struct rtattr *tb[IFLA_MAX+1];
aba5acdf
SH
160 int len = m->nlmsg_len;
161 struct ifstat_ent *n;
162 int i;
163
164 if (m->nlmsg_type != RTM_NEWLINK)
165 return 0;
166
167 len -= NLMSG_LENGTH(sizeof(*ifi));
168 if (len < 0)
169 return -1;
170
171 if (!(ifi->ifi_flags&IFF_UP))
172 return 0;
173
aba5acdf
SH
174 parse_rtattr(tb, IFLA_MAX, IFLA_RTA(ifi), len);
175 if (tb[IFLA_IFNAME] == NULL || tb[IFLA_STATS] == NULL)
176 return 0;
177
178 n = malloc(sizeof(*n));
179 if (!n)
180 abort();
181 n->ifindex = ifi->ifi_index;
182 n->name = strdup(RTA_DATA(tb[IFLA_IFNAME]));
183 memcpy(&n->ival, RTA_DATA(tb[IFLA_STATS]), sizeof(n->ival));
184 memset(&n->rate, 0, sizeof(n->rate));
acd1e437 185 for (i = 0; i < MAXS; i++)
aba5acdf
SH
186 n->val[i] = n->ival[i];
187 n->next = kern_db;
188 kern_db = n;
189 return 0;
190}
191
d1f28cf1 192static void load_info(void)
aba5acdf
SH
193{
194 struct ifstat_ent *db, *n;
195 struct rtnl_handle rth;
5a52102b 196 __u32 filter_mask;
aba5acdf
SH
197
198 if (rtnl_open(&rth, 0) < 0)
199 exit(1);
200
5a52102b
NF
201 if (is_extended) {
202 ll_init_map(&rth);
203 filter_mask = IFLA_STATS_FILTER_BIT(filter_type);
56eeeda9
DA
204 if (rtnl_statsdump_req_filter(&rth, AF_UNSPEC,
205 filter_mask) < 0) {
5a52102b
NF
206 perror("Cannot send dump request");
207 exit(1);
208 }
aba5acdf 209
5a52102b
NF
210 if (rtnl_dump_filter(&rth, get_nlmsg_extended, NULL) < 0) {
211 fprintf(stderr, "Dump terminated\n");
212 exit(1);
213 }
214 } else {
31ae2912 215 if (rtnl_linkdump_req(&rth, AF_INET) < 0) {
5a52102b
NF
216 perror("Cannot send dump request");
217 exit(1);
218 }
219
220 if (rtnl_dump_filter(&rth, get_nlmsg, NULL) < 0) {
221 fprintf(stderr, "Dump terminated\n");
222 exit(1);
223 }
aba5acdf
SH
224 }
225
226 rtnl_close(&rth);
227
228 db = kern_db;
229 kern_db = NULL;
230
231 while (db) {
232 n = db;
233 db = db->next;
234 n->next = kern_db;
235 kern_db = n;
236 }
237}
238
d1f28cf1 239static void load_raw_table(FILE *fp)
aba5acdf
SH
240{
241 char buf[4096];
242 struct ifstat_ent *db = NULL;
243 struct ifstat_ent *n;
244
245 while (fgets(buf, sizeof(buf), fp) != NULL) {
246 char *p;
247 char *next;
248 int i;
249
250 if (buf[0] == '#') {
251 buf[strlen(buf)-1] = 0;
252 if (info_source[0] && strcmp(info_source, buf+1))
253 source_mismatch = 1;
c0149839 254 strlcpy(info_source, buf+1, sizeof(info_source));
aba5acdf
SH
255 continue;
256 }
257 if ((n = malloc(sizeof(*n))) == NULL)
258 abort();
259
260 if (!(p = strchr(buf, ' ')))
261 abort();
262 *p++ = 0;
263
264 if (sscanf(buf, "%d", &n->ifindex) != 1)
265 abort();
266 if (!(next = strchr(p, ' ')))
267 abort();
268 *next++ = 0;
269
270 n->name = strdup(p);
271 p = next;
272
acd1e437
SH
273 for (i = 0; i < MAXS; i++) {
274 unsigned int rate;
275
aba5acdf
SH
276 if (!(next = strchr(p, ' ')))
277 abort();
278 *next++ = 0;
279 if (sscanf(p, "%llu", n->val+i) != 1)
280 abort();
a571587d 281 n->ival[i] = (__u32)n->val[i];
aba5acdf
SH
282 p = next;
283 if (!(next = strchr(p, ' ')))
284 abort();
285 *next++ = 0;
286 if (sscanf(p, "%u", &rate) != 1)
287 abort();
288 n->rate[i] = rate;
289 p = next;
290 }
291 n->next = db;
292 db = n;
293 }
294
295 while (db) {
296 n = db;
297 db = db->next;
298 n->next = kern_db;
299 kern_db = n;
300 }
301}
302
d1f28cf1 303static void dump_raw_db(FILE *fp, int to_hist)
aba5acdf 304{
fcc16c22 305 json_writer_t *jw = json_output ? jsonw_new(fp) : NULL;
aba5acdf 306 struct ifstat_ent *n, *h;
ec3e625c 307
aba5acdf 308 h = hist_db;
fcc16c22 309 if (jw) {
d721a145 310 jsonw_start_object(jw);
fcc16c22
SH
311 jsonw_pretty(jw, pretty);
312 jsonw_name(jw, info_source);
313 jsonw_start_object(jw);
314 } else
ec3e625c 315 fprintf(fp, "#%s\n", info_source);
aba5acdf 316
acd1e437 317 for (n = kern_db; n; n = n->next) {
aba5acdf
SH
318 int i;
319 unsigned long long *vals = n->val;
320 double *rates = n->rate;
acd1e437 321
aba5acdf
SH
322 if (!match(n->name)) {
323 struct ifstat_ent *h1;
acd1e437 324
aba5acdf
SH
325 if (!to_hist)
326 continue;
327 for (h1 = h; h1; h1 = h1->next) {
328 if (h1->ifindex == n->ifindex) {
329 vals = h1->val;
330 rates = h1->rate;
331 h = h1->next;
332 break;
333 }
334 }
335 }
ec3e625c 336
fcc16c22
SH
337 if (jw) {
338 jsonw_name(jw, n->name);
339 jsonw_start_object(jw);
1473bda9 340
acd1e437 341 for (i = 0; i < MAXS && stats[i]; i++)
fcc16c22
SH
342 jsonw_uint_field(jw, stats[i], vals[i]);
343 jsonw_end_object(jw);
ec3e625c
SH
344 } else {
345 fprintf(fp, "%d %s ", n->ifindex, n->name);
acd1e437 346 for (i = 0; i < MAXS; i++)
3d0b7439 347 fprintf(fp, "%llu %u ", vals[i],
acd1e437 348 (unsigned int)rates[i]);
ec3e625c
SH
349 fprintf(fp, "\n");
350 }
aba5acdf 351 }
fcc16c22 352 if (jw) {
d721a145
AK
353 jsonw_end_object(jw);
354
fcc16c22
SH
355 jsonw_end_object(jw);
356 jsonw_destroy(&jw);
357 }
aba5acdf
SH
358}
359
9f3ea250
SH
360/* use communication definitions of meg/kilo etc */
361static const unsigned long long giga = 1000000000ull;
bb6a21a4
SH
362static const unsigned long long mega = 1000000;
363static const unsigned long long kilo = 1000;
aba5acdf 364
ec3e625c
SH
365static void format_rate(FILE *fp, const unsigned long long *vals,
366 const double *rates, int i)
aba5acdf
SH
367{
368 char temp[64];
ec3e625c 369
9f3ea250
SH
370 if (vals[i] > giga)
371 fprintf(fp, "%7lluM ", vals[i]/mega);
372 else if (vals[i] > mega)
373 fprintf(fp, "%7lluK ", vals[i]/kilo);
aba5acdf
SH
374 else
375 fprintf(fp, "%8llu ", vals[i]);
376
9f3ea250 377 if (rates[i] > mega) {
acd1e437 378 sprintf(temp, "%uM", (unsigned int)(rates[i]/mega));
aba5acdf 379 fprintf(fp, "%-6s ", temp);
9f3ea250 380 } else if (rates[i] > kilo) {
acd1e437 381 sprintf(temp, "%uK", (unsigned int)(rates[i]/kilo));
aba5acdf
SH
382 fprintf(fp, "%-6s ", temp);
383 } else
acd1e437 384 fprintf(fp, "%-6u ", (unsigned int)rates[i]);
aba5acdf
SH
385}
386
ec3e625c 387static void format_pair(FILE *fp, const unsigned long long *vals, int i, int k)
aba5acdf
SH
388{
389 char temp[64];
acd1e437 390
9f3ea250
SH
391 if (vals[i] > giga)
392 fprintf(fp, "%7lluM ", vals[i]/mega);
393 else if (vals[i] > mega)
394 fprintf(fp, "%7lluK ", vals[i]/kilo);
aba5acdf
SH
395 else
396 fprintf(fp, "%8llu ", vals[i]);
397
9f3ea250 398 if (vals[k] > giga) {
acd1e437 399 sprintf(temp, "%uM", (unsigned int)(vals[k]/mega));
aba5acdf 400 fprintf(fp, "%-6s ", temp);
9f3ea250 401 } else if (vals[k] > mega) {
acd1e437 402 sprintf(temp, "%uK", (unsigned int)(vals[k]/kilo));
aba5acdf
SH
403 fprintf(fp, "%-6s ", temp);
404 } else
acd1e437 405 fprintf(fp, "%-6u ", (unsigned int)vals[k]);
aba5acdf
SH
406}
407
d1f28cf1 408static void print_head(FILE *fp)
aba5acdf
SH
409{
410 fprintf(fp, "#%s\n", info_source);
411 fprintf(fp, "%-15s ", "Interface");
412
413 fprintf(fp, "%8s/%-6s ", "RX Pkts", "Rate");
414 fprintf(fp, "%8s/%-6s ", "TX Pkts", "Rate");
415 fprintf(fp, "%8s/%-6s ", "RX Data", "Rate");
acd1e437 416 fprintf(fp, "%8s/%-6s\n", "TX Data", "Rate");
aba5acdf
SH
417
418 if (!show_errors) {
419 fprintf(fp, "%-15s ", "");
420 fprintf(fp, "%8s/%-6s ", "RX Errs", "Drop");
421 fprintf(fp, "%8s/%-6s ", "TX Errs", "Drop");
422 fprintf(fp, "%8s/%-6s ", "RX Over", "Rate");
acd1e437 423 fprintf(fp, "%8s/%-6s\n", "TX Coll", "Rate");
aba5acdf
SH
424 } else {
425 fprintf(fp, "%-15s ", "");
426 fprintf(fp, "%8s/%-6s ", "RX Errs", "Rate");
427 fprintf(fp, "%8s/%-6s ", "RX Drop", "Rate");
428 fprintf(fp, "%8s/%-6s ", "RX Over", "Rate");
acd1e437 429 fprintf(fp, "%8s/%-6s\n", "RX Leng", "Rate");
aba5acdf
SH
430
431 fprintf(fp, "%-15s ", "");
432 fprintf(fp, "%8s/%-6s ", "RX Crc", "Rate");
433 fprintf(fp, "%8s/%-6s ", "RX Frm", "Rate");
434 fprintf(fp, "%8s/%-6s ", "RX Fifo", "Rate");
acd1e437 435 fprintf(fp, "%8s/%-6s\n", "RX Miss", "Rate");
aba5acdf
SH
436
437 fprintf(fp, "%-15s ", "");
438 fprintf(fp, "%8s/%-6s ", "TX Errs", "Rate");
439 fprintf(fp, "%8s/%-6s ", "TX Drop", "Rate");
440 fprintf(fp, "%8s/%-6s ", "TX Coll", "Rate");
acd1e437 441 fprintf(fp, "%8s/%-6s\n", "TX Carr", "Rate");
aba5acdf
SH
442
443 fprintf(fp, "%-15s ", "");
444 fprintf(fp, "%8s/%-6s ", "TX Abrt", "Rate");
445 fprintf(fp, "%8s/%-6s ", "TX Fifo", "Rate");
446 fprintf(fp, "%8s/%-6s ", "TX Hear", "Rate");
acd1e437 447 fprintf(fp, "%8s/%-6s\n", "TX Wind", "Rate");
aba5acdf
SH
448 }
449}
450
fcc16c22 451static void print_one_json(json_writer_t *jw, const struct ifstat_ent *n,
ec3e625c
SH
452 const unsigned long long *vals)
453{
fcc16c22
SH
454 int i, m = show_errors ? 20 : 10;
455
456 jsonw_name(jw, n->name);
457 jsonw_start_object(jw);
458
acd1e437 459 for (i = 0; i < m && stats[i]; i++)
fcc16c22
SH
460 jsonw_uint_field(jw, stats[i], vals[i]);
461
462 jsonw_end_object(jw);
ec3e625c
SH
463}
464
465static void print_one_if(FILE *fp, const struct ifstat_ent *n,
466 const unsigned long long *vals)
aba5acdf
SH
467{
468 int i;
ec3e625c 469
aba5acdf 470 fprintf(fp, "%-15s ", n->name);
acd1e437 471 for (i = 0; i < 4; i++)
aba5acdf
SH
472 format_rate(fp, vals, n->rate, i);
473 fprintf(fp, "\n");
474
475 if (!show_errors) {
476 fprintf(fp, "%-15s ", "");
477 format_pair(fp, vals, 4, 6);
478 format_pair(fp, vals, 5, 7);
479 format_rate(fp, vals, n->rate, 11);
480 format_rate(fp, vals, n->rate, 9);
481 fprintf(fp, "\n");
482 } else {
483 fprintf(fp, "%-15s ", "");
484 format_rate(fp, vals, n->rate, 4);
485 format_rate(fp, vals, n->rate, 6);
486 format_rate(fp, vals, n->rate, 11);
487 format_rate(fp, vals, n->rate, 10);
488 fprintf(fp, "\n");
489
490 fprintf(fp, "%-15s ", "");
491 format_rate(fp, vals, n->rate, 12);
492 format_rate(fp, vals, n->rate, 13);
493 format_rate(fp, vals, n->rate, 14);
494 format_rate(fp, vals, n->rate, 15);
495 fprintf(fp, "\n");
496
497 fprintf(fp, "%-15s ", "");
498 format_rate(fp, vals, n->rate, 5);
499 format_rate(fp, vals, n->rate, 7);
500 format_rate(fp, vals, n->rate, 9);
501 format_rate(fp, vals, n->rate, 17);
502 fprintf(fp, "\n");
503
504 fprintf(fp, "%-15s ", "");
505 format_rate(fp, vals, n->rate, 16);
506 format_rate(fp, vals, n->rate, 18);
507 format_rate(fp, vals, n->rate, 19);
508 format_rate(fp, vals, n->rate, 20);
509 fprintf(fp, "\n");
510 }
511}
512
d1f28cf1 513static void dump_kern_db(FILE *fp)
aba5acdf 514{
fcc16c22 515 json_writer_t *jw = json_output ? jsonw_new(fp) : NULL;
dc484542 516 struct ifstat_ent *n;
aba5acdf 517
fcc16c22 518 if (jw) {
d721a145 519 jsonw_start_object(jw);
fcc16c22
SH
520 jsonw_pretty(jw, pretty);
521 jsonw_name(jw, info_source);
522 jsonw_start_object(jw);
523 } else
ec3e625c 524 print_head(fp);
aba5acdf 525
acd1e437 526 for (n = kern_db; n; n = n->next) {
aba5acdf
SH
527 if (!match(n->name))
528 continue;
ec3e625c 529
fcc16c22
SH
530 if (jw)
531 print_one_json(jw, n, n->val);
532 else
ec3e625c 533 print_one_if(fp, n, n->val);
aba5acdf 534 }
b530cef0
PS
535 if (jw) {
536 jsonw_end_object(jw);
537
538 jsonw_end_object(jw);
539 jsonw_destroy(&jw);
540 }
aba5acdf
SH
541}
542
d1f28cf1 543static void dump_incr_db(FILE *fp)
aba5acdf
SH
544{
545 struct ifstat_ent *n, *h;
fcc16c22 546 json_writer_t *jw = json_output ? jsonw_new(fp) : NULL;
aba5acdf 547
ec3e625c 548 h = hist_db;
fcc16c22 549 if (jw) {
d721a145 550 jsonw_start_object(jw);
fcc16c22
SH
551 jsonw_pretty(jw, pretty);
552 jsonw_name(jw, info_source);
553 jsonw_start_object(jw);
554 } else
ec3e625c 555 print_head(fp);
aba5acdf 556
acd1e437 557 for (n = kern_db; n; n = n->next) {
aba5acdf
SH
558 int i;
559 unsigned long long vals[MAXS];
560 struct ifstat_ent *h1;
561
562 memcpy(vals, n->val, sizeof(vals));
563
564 for (h1 = h; h1; h1 = h1->next) {
565 if (h1->ifindex == n->ifindex) {
566 for (i = 0; i < MAXS; i++)
567 vals[i] -= h1->val[i];
568 h = h1->next;
569 break;
570 }
571 }
572 if (!match(n->name))
573 continue;
ec3e625c 574
fcc16c22
SH
575 if (jw)
576 print_one_json(jw, n, n->val);
577 else
ec3e625c 578 print_one_if(fp, n, vals);
aba5acdf 579 }
aba5acdf 580
fcc16c22 581 if (jw) {
d721a145
AK
582 jsonw_end_object(jw);
583
fcc16c22
SH
584 jsonw_end_object(jw);
585 jsonw_destroy(&jw);
586 }
587}
aba5acdf
SH
588
589static int children;
590
d1f28cf1 591static void sigchild(int signo)
aba5acdf
SH
592{
593}
594
d1f28cf1 595static void update_db(int interval)
aba5acdf
SH
596{
597 struct ifstat_ent *n, *h;
598
599 n = kern_db;
600 kern_db = NULL;
601
602 load_info();
603
604 h = kern_db;
605 kern_db = n;
606
607 for (n = kern_db; n; n = n->next) {
608 struct ifstat_ent *h1;
acd1e437 609
aba5acdf
SH
610 for (h1 = h; h1; h1 = h1->next) {
611 if (h1->ifindex == n->ifindex) {
612 int i;
acd1e437 613
aba5acdf
SH
614 for (i = 0; i < MAXS; i++) {
615 if ((long)(h1->ival[i] - n->ival[i]) < 0) {
ae665a52 616 memset(n->ival, 0, sizeof(n->ival));
aba5acdf
SH
617 break;
618 }
619 }
ae665a52 620 for (i = 0; i < MAXS; i++) {
aba5acdf 621 double sample;
5a52102b
NF
622 __u64 incr;
623
624 if (is_extended) {
625 incr = h1->val[i] - n->val[i];
626 n->val[i] = h1->val[i];
627 } else {
628 incr = (__u32) (h1->ival[i] - n->ival[i]);
629 n->val[i] += incr;
630 n->ival[i] = h1->ival[i];
631 }
acd1e437 632
aba5acdf
SH
633 sample = (double)(incr*1000)/interval;
634 if (interval >= scan_interval) {
635 n->rate[i] += W*(sample-n->rate[i]);
636 } else if (interval >= 1000) {
637 if (interval >= time_constant) {
638 n->rate[i] = sample;
639 } else {
640 double w = W*(double)interval/scan_interval;
acd1e437 641
aba5acdf
SH
642 n->rate[i] += w*(sample-n->rate[i]);
643 }
644 }
645 }
646
647 while (h != h1) {
648 struct ifstat_ent *tmp = h;
acd1e437 649
aba5acdf
SH
650 h = h->next;
651 free(tmp->name);
652 free(tmp);
653 };
654 h = h1->next;
655 free(h1->name);
656 free(h1);
657 break;
658 }
659 }
660 }
661}
662
acd1e437 663#define T_DIFF(a, b) (((a).tv_sec-(b).tv_sec)*1000 + ((a).tv_usec-(b).tv_usec)/1000)
aba5acdf
SH
664
665
d1f28cf1 666static void server_loop(int fd)
aba5acdf 667{
737f15f6 668 struct timeval snaptime = { 0 };
aba5acdf 669 struct pollfd p;
acd1e437 670
aba5acdf
SH
671 p.fd = fd;
672 p.events = p.revents = POLLIN;
673
674 sprintf(info_source, "%d.%lu sampling_interval=%d time_const=%d",
675 getpid(), (unsigned long)random(), scan_interval/1000, time_constant/1000);
676
677 load_info();
678
679 for (;;) {
680 int status;
dd81ee04 681 time_t tdiff;
aba5acdf 682 struct timeval now;
737f15f6 683
aba5acdf
SH
684 gettimeofday(&now, NULL);
685 tdiff = T_DIFF(now, snaptime);
686 if (tdiff >= scan_interval) {
687 update_db(tdiff);
688 snaptime = now;
689 tdiff = 0;
690 }
737f15f6 691
dd81ee04 692 if (poll(&p, 1, scan_interval - tdiff) > 0
aba5acdf
SH
693 && (p.revents&POLLIN)) {
694 int clnt = accept(fd, NULL, NULL);
acd1e437 695
aba5acdf
SH
696 if (clnt >= 0) {
697 pid_t pid;
acd1e437 698
aba5acdf
SH
699 if (children >= 5) {
700 close(clnt);
701 } else if ((pid = fork()) != 0) {
acd1e437 702 if (pid > 0)
aba5acdf
SH
703 children++;
704 close(clnt);
705 } else {
706 FILE *fp = fdopen(clnt, "w");
acd1e437 707
dd81ee04 708 if (fp)
aba5acdf 709 dump_raw_db(fp, 0);
aba5acdf
SH
710 exit(0);
711 }
712 }
713 }
714 while (children && waitpid(-1, &status, WNOHANG) > 0)
715 children--;
716 }
717}
718
d1f28cf1 719static int verify_forging(int fd)
aba5acdf
SH
720{
721 struct ucred cred;
737f15f6
SH
722 socklen_t olen = sizeof(cred);
723
acd1e437 724 if (getsockopt(fd, SOL_SOCKET, SO_PEERCRED, (void *)&cred, &olen) ||
aba5acdf
SH
725 olen < sizeof(cred))
726 return -1;
727 if (cred.uid == getuid() || cred.uid == 0)
728 return 0;
729 return -1;
730}
731
5a52102b
NF
732static void xstat_usage(void)
733{
734 fprintf(stderr,
1c2df613
NF
735"Usage: ifstat supported xstats:\n"
736" cpu_hits Counts only packets that went via the CPU.\n");
5a52102b
NF
737}
738
739struct extended_stats_options_t {
740 char *name;
741 int id;
742 int sub_type;
743};
744
745/* Note: if one xstat name is subset of another, it should be before it in this
746 * list.
747 * Name length must be under 64 chars.
748 */
749static const struct extended_stats_options_t extended_stats_options[] = {
1c2df613 750 {"cpu_hits", IFLA_STATS_LINK_OFFLOAD_XSTATS, IFLA_OFFLOAD_XSTATS_CPU_HIT},
5a52102b
NF
751};
752
753static const char *get_filter_type(const char *name)
754{
755 int name_len;
756 int i;
757
758 name_len = strlen(name);
759 for (i = 0; i < ARRAY_SIZE(extended_stats_options); i++) {
760 const struct extended_stats_options_t *xstat;
761
762 xstat = &extended_stats_options[i];
763 if (strncmp(name, xstat->name, name_len) == 0) {
764 filter_type = xstat->id;
765 sub_type = xstat->sub_type;
766 return xstat->name;
767 }
768 }
769
770 fprintf(stderr, "invalid ifstat extension %s\n", name);
771 xstat_usage();
772 return NULL;
773}
774
d7e0809e
SH
775static void usage(void) __attribute__((noreturn));
776
aba5acdf
SH
777static void usage(void)
778{
d7e0809e
SH
779 fprintf(stderr,
780"Usage: ifstat [OPTION] [ PATTERN [ PATTERN ] ]\n"
eca7a742
MF
781" -h, --help this message\n"
782" -a, --ignore ignore history\n"
783" -d, --scan=SECS sample every statistics every SECS\n"
784" -e, --errors show errors\n"
785" -j, --json format output in JSON\n"
786" -n, --nooutput do history only\n"
787" -p, --pretty pretty print\n"
788" -r, --reset reset history\n"
789" -s, --noupdate don't update history\n"
790" -t, --interval=SECS report average over the last SECS\n"
791" -V, --version output version information\n"
5a52102b
NF
792" -z, --zeros show entries with zero activity\n"
793" -x, --extended=TYPE show extended stats of TYPE\n");
d7e0809e
SH
794
795 exit(-1);
aba5acdf
SH
796}
797
9f3ea250
SH
798static const struct option longopts[] = {
799 { "help", 0, 0, 'h' },
800 { "ignore", 0, 0, 'a' },
801 { "scan", 1, 0, 'd'},
802 { "errors", 0, 0, 'e' },
803 { "nooutput", 0, 0, 'n' },
ec3e625c 804 { "json", 0, 0, 'j' },
9f3ea250 805 { "reset", 0, 0, 'r' },
fcc16c22 806 { "pretty", 0, 0, 'p' },
9f3ea250
SH
807 { "noupdate", 0, 0, 's' },
808 { "interval", 1, 0, 't' },
809 { "version", 0, 0, 'V' },
810 { "zeros", 0, 0, 'z' },
5a52102b 811 { "extended", 1, 0, 'x'},
9f3ea250
SH
812 { 0 }
813};
aba5acdf
SH
814
815int main(int argc, char *argv[])
816{
817 char hist_name[128];
818 struct sockaddr_un sun;
819 FILE *hist_fp = NULL;
5a52102b 820 const char *stats_type = NULL;
aba5acdf
SH
821 int ch;
822 int fd;
823
5a52102b
NF
824 is_extended = false;
825 while ((ch = getopt_long(argc, argv, "hjpvVzrnasd:t:ex:",
9f3ea250 826 longopts, NULL)) != EOF) {
acd1e437 827 switch (ch) {
aba5acdf
SH
828 case 'z':
829 dump_zeros = 1;
830 break;
831 case 'r':
832 reset_history = 1;
833 break;
834 case 'a':
835 ignore_history = 1;
836 break;
837 case 's':
838 no_update = 1;
839 break;
840 case 'n':
841 no_output = 1;
842 break;
843 case 'e':
844 show_errors = 1;
845 break;
ec3e625c
SH
846 case 'j':
847 json_output = 1;
848 break;
fcc16c22
SH
849 case 'p':
850 pretty = 1;
851 break;
aba5acdf 852 case 'd':
9f3ea250
SH
853 scan_interval = atoi(optarg) * 1000;
854 if (scan_interval <= 0) {
855 fprintf(stderr, "ifstat: invalid scan interval\n");
856 exit(-1);
857 }
aba5acdf
SH
858 break;
859 case 't':
9f3ea250
SH
860 time_constant = atoi(optarg);
861 if (time_constant <= 0) {
aba5acdf
SH
862 fprintf(stderr, "ifstat: invalid time constant divisor\n");
863 exit(-1);
864 }
865 break;
5a52102b
NF
866 case 'x':
867 stats_type = optarg;
868 is_extended = true;
869 break;
aba5acdf
SH
870 case 'v':
871 case 'V':
fbef6555 872 printf("ifstat utility, iproute2-%s\n", version);
aba5acdf
SH
873 exit(0);
874 case 'h':
875 case '?':
876 default:
877 usage();
878 }
879 }
880
881 argc -= optind;
882 argv += optind;
883
5a52102b
NF
884 if (stats_type) {
885 stats_type = get_filter_type(stats_type);
886 if (!stats_type)
887 exit(-1);
888 }
889
aba5acdf
SH
890 sun.sun_family = AF_UNIX;
891 sun.sun_path[0] = 0;
892 sprintf(sun.sun_path+1, "ifstat%d", getuid());
893
894 if (scan_interval > 0) {
895 if (time_constant == 0)
896 time_constant = 60;
897 time_constant *= 1000;
898 W = 1 - 1/exp(log(10)*(double)scan_interval/time_constant);
899 if ((fd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) {
900 perror("ifstat: socket");
901 exit(-1);
902 }
acd1e437 903 if (bind(fd, (struct sockaddr *)&sun, 2+1+strlen(sun.sun_path+1)) < 0) {
aba5acdf
SH
904 perror("ifstat: bind");
905 exit(-1);
906 }
907 if (listen(fd, 5) < 0) {
908 perror("ifstat: listen");
909 exit(-1);
910 }
a7a9ddbb
MF
911 if (daemon(0, 0)) {
912 perror("ifstat: daemon");
913 exit(-1);
914 }
aba5acdf
SH
915 signal(SIGPIPE, SIG_IGN);
916 signal(SIGCHLD, sigchild);
917 server_loop(fd);
918 exit(0);
919 }
920
921 patterns = argv;
922 npatterns = argc;
923
924 if (getenv("IFSTAT_HISTORY"))
daf7bd5c
SH
925 snprintf(hist_name, sizeof(hist_name),
926 "%s", getenv("IFSTAT_HISTORY"));
aba5acdf 927 else
5a52102b
NF
928 if (!stats_type)
929 snprintf(hist_name, sizeof(hist_name),
930 "%s/.ifstat.u%d", P_tmpdir, getuid());
931 else
932 snprintf(hist_name, sizeof(hist_name),
933 "%s/.%s_ifstat.u%d", P_tmpdir, stats_type,
934 getuid());
aba5acdf
SH
935
936 if (reset_history)
937 unlink(hist_name);
938
939 if (!ignore_history || !no_update) {
940 struct stat stb;
941
942 fd = open(hist_name, O_RDWR|O_CREAT|O_NOFOLLOW, 0600);
943 if (fd < 0) {
944 perror("ifstat: open history file");
945 exit(-1);
946 }
947 if ((hist_fp = fdopen(fd, "r+")) == NULL) {
948 perror("ifstat: fdopen history file");
949 exit(-1);
950 }
951 if (flock(fileno(hist_fp), LOCK_EX)) {
952 perror("ifstat: flock history file");
953 exit(-1);
954 }
955 if (fstat(fileno(hist_fp), &stb) != 0) {
956 perror("ifstat: fstat history file");
957 exit(-1);
958 }
959 if (stb.st_nlink != 1 || stb.st_uid != getuid()) {
960 fprintf(stderr, "ifstat: something is so wrong with history file, that I prefer not to proceed.\n");
961 exit(-1);
962 }
963 if (!ignore_history) {
964 FILE *tfp;
9a230771 965 long uptime = -1;
acd1e437 966
aba5acdf
SH
967 if ((tfp = fopen("/proc/uptime", "r")) != NULL) {
968 if (fscanf(tfp, "%ld", &uptime) != 1)
969 uptime = -1;
970 fclose(tfp);
971 }
972 if (uptime >= 0 && time(NULL) >= stb.st_mtime+uptime) {
973 fprintf(stderr, "ifstat: history is aged out, resetting\n");
d572ed4d
PS
974 if (ftruncate(fileno(hist_fp), 0))
975 perror("ifstat: ftruncate");
aba5acdf
SH
976 }
977 }
978
979 load_raw_table(hist_fp);
980
981 hist_db = kern_db;
982 kern_db = NULL;
983 }
984
985 if ((fd = socket(AF_UNIX, SOCK_STREAM, 0)) >= 0 &&
acd1e437 986 (connect(fd, (struct sockaddr *)&sun, 2+1+strlen(sun.sun_path+1)) == 0
aba5acdf 987 || (strcpy(sun.sun_path+1, "ifstat0"),
acd1e437 988 connect(fd, (struct sockaddr *)&sun, 2+1+strlen(sun.sun_path+1)) == 0))
aba5acdf
SH
989 && verify_forging(fd) == 0) {
990 FILE *sfp = fdopen(fd, "r");
acd1e437 991
6d02518f
PS
992 if (!sfp) {
993 fprintf(stderr, "ifstat: fdopen failed: %s\n",
994 strerror(errno));
995 close(fd);
996 } else {
997 load_raw_table(sfp);
998 if (hist_db && source_mismatch) {
999 fprintf(stderr, "ifstat: history is stale, ignoring it.\n");
1000 hist_db = NULL;
1001 }
1002 fclose(sfp);
aba5acdf 1003 }
aba5acdf
SH
1004 } else {
1005 if (fd >= 0)
1006 close(fd);
1007 if (hist_db && info_source[0] && strcmp(info_source, "kernel")) {
1008 fprintf(stderr, "ifstat: history is stale, ignoring it.\n");
1009 hist_db = NULL;
1010 info_source[0] = 0;
1011 }
1012 load_info();
1013 if (info_source[0] == 0)
1014 strcpy(info_source, "kernel");
1015 }
1016
1017 if (!no_output) {
1018 if (ignore_history || hist_db == NULL)
1019 dump_kern_db(stdout);
1020 else
1021 dump_incr_db(stdout);
1022 }
ec3e625c 1023
aba5acdf 1024 if (!no_update) {
d572ed4d
PS
1025 if (ftruncate(fileno(hist_fp), 0))
1026 perror("ifstat: ftruncate");
aba5acdf 1027 rewind(hist_fp);
ec3e625c
SH
1028
1029 json_output = 0;
aba5acdf 1030 dump_raw_db(hist_fp, 1);
ec3e625c 1031 fclose(hist_fp);
aba5acdf
SH
1032 }
1033 exit(0);
1034}