]> git.proxmox.com Git - mirror_iproute2.git/blob - misc/ifstat.c
03327af83ae8e6619545d5610962ad605d12b7f8
[mirror_iproute2.git] / misc / ifstat.c
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>
29 #include <getopt.h>
30
31 #include <linux/if.h>
32 #include <linux/if_link.h>
33
34 #include "libnetlink.h"
35 #include "json_writer.h"
36 #include "SNAPSHOT.h"
37 #include "utils.h"
38
39 int dump_zeros;
40 int reset_history;
41 int ignore_history;
42 int no_output;
43 int json_output;
44 int no_update;
45 int scan_interval;
46 int time_constant;
47 int show_errors;
48 double W;
49 char **patterns;
50 int npatterns;
51 bool is_extended;
52 int filter_type;
53 int sub_type;
54
55 char info_source[128];
56 int source_mismatch;
57
58 #define MAXS (sizeof(struct rtnl_link_stats)/sizeof(__u32))
59 #define NO_SUB_TYPE 0xffff
60
61 struct ifstat_ent {
62 struct ifstat_ent *next;
63 char *name;
64 int ifindex;
65 __u64 val[MAXS];
66 double rate[MAXS];
67 __u32 ival[MAXS];
68 };
69
70 static 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
96 struct ifstat_ent *kern_db;
97 struct ifstat_ent *hist_db;
98
99 static int match(const char *id)
100 {
101 int i;
102
103 if (npatterns == 0)
104 return 1;
105
106 for (i = 0; i < npatterns; i++) {
107 if (!fnmatch(patterns[i], id, FNM_CASEFOLD))
108 return 1;
109 }
110 return 0;
111 }
112
113 static int get_nlmsg_extended(struct nlmsghdr *m, void *arg)
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]);
144 if (attr == NULL) {
145 free(n);
146 return 0;
147 }
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
156 static int get_nlmsg(struct nlmsghdr *m, void *arg)
157 {
158 struct ifinfomsg *ifi = NLMSG_DATA(m);
159 struct rtattr *tb[IFLA_MAX+1];
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
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));
185 for (i = 0; i < MAXS; i++)
186 n->val[i] = n->ival[i];
187 n->next = kern_db;
188 kern_db = n;
189 return 0;
190 }
191
192 static void load_info(void)
193 {
194 struct ifstat_ent *db, *n;
195 struct rtnl_handle rth;
196 __u32 filter_mask;
197
198 if (rtnl_open(&rth, 0) < 0)
199 exit(1);
200
201 if (is_extended) {
202 ll_init_map(&rth);
203 filter_mask = IFLA_STATS_FILTER_BIT(filter_type);
204 if (rtnl_statsdump_req_filter(&rth, AF_UNSPEC,
205 filter_mask) < 0) {
206 perror("Cannot send dump request");
207 exit(1);
208 }
209
210 if (rtnl_dump_filter(&rth, get_nlmsg_extended, NULL) < 0) {
211 fprintf(stderr, "Dump terminated\n");
212 exit(1);
213 }
214 } else {
215 if (rtnl_linkdump_req(&rth, AF_INET) < 0) {
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 }
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
239 static void load_raw_table(FILE *fp)
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;
254 strncpy(info_source, buf+1, sizeof(info_source)-1);
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
273 for (i = 0; i < MAXS; i++) {
274 unsigned int rate;
275
276 if (!(next = strchr(p, ' ')))
277 abort();
278 *next++ = 0;
279 if (sscanf(p, "%llu", n->val+i) != 1)
280 abort();
281 n->ival[i] = (__u32)n->val[i];
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
303 static void dump_raw_db(FILE *fp, int to_hist)
304 {
305 json_writer_t *jw = json_output ? jsonw_new(fp) : NULL;
306 struct ifstat_ent *n, *h;
307
308 h = hist_db;
309 if (jw) {
310 jsonw_start_object(jw);
311 jsonw_pretty(jw, pretty);
312 jsonw_name(jw, info_source);
313 jsonw_start_object(jw);
314 } else
315 fprintf(fp, "#%s\n", info_source);
316
317 for (n = kern_db; n; n = n->next) {
318 int i;
319 unsigned long long *vals = n->val;
320 double *rates = n->rate;
321
322 if (!match(n->name)) {
323 struct ifstat_ent *h1;
324
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 }
336
337 if (jw) {
338 jsonw_name(jw, n->name);
339 jsonw_start_object(jw);
340
341 for (i = 0; i < MAXS && stats[i]; i++)
342 jsonw_uint_field(jw, stats[i], vals[i]);
343 jsonw_end_object(jw);
344 } else {
345 fprintf(fp, "%d %s ", n->ifindex, n->name);
346 for (i = 0; i < MAXS; i++)
347 fprintf(fp, "%llu %u ", vals[i],
348 (unsigned int)rates[i]);
349 fprintf(fp, "\n");
350 }
351 }
352 if (jw) {
353 jsonw_end_object(jw);
354
355 jsonw_end_object(jw);
356 jsonw_destroy(&jw);
357 }
358 }
359
360 /* use communication definitions of meg/kilo etc */
361 static const unsigned long long giga = 1000000000ull;
362 static const unsigned long long mega = 1000000;
363 static const unsigned long long kilo = 1000;
364
365 static void format_rate(FILE *fp, const unsigned long long *vals,
366 const double *rates, int i)
367 {
368 char temp[64];
369
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);
374 else
375 fprintf(fp, "%8llu ", vals[i]);
376
377 if (rates[i] > mega) {
378 sprintf(temp, "%uM", (unsigned int)(rates[i]/mega));
379 fprintf(fp, "%-6s ", temp);
380 } else if (rates[i] > kilo) {
381 sprintf(temp, "%uK", (unsigned int)(rates[i]/kilo));
382 fprintf(fp, "%-6s ", temp);
383 } else
384 fprintf(fp, "%-6u ", (unsigned int)rates[i]);
385 }
386
387 static void format_pair(FILE *fp, const unsigned long long *vals, int i, int k)
388 {
389 char temp[64];
390
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);
395 else
396 fprintf(fp, "%8llu ", vals[i]);
397
398 if (vals[k] > giga) {
399 sprintf(temp, "%uM", (unsigned int)(vals[k]/mega));
400 fprintf(fp, "%-6s ", temp);
401 } else if (vals[k] > mega) {
402 sprintf(temp, "%uK", (unsigned int)(vals[k]/kilo));
403 fprintf(fp, "%-6s ", temp);
404 } else
405 fprintf(fp, "%-6u ", (unsigned int)vals[k]);
406 }
407
408 static void print_head(FILE *fp)
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");
416 fprintf(fp, "%8s/%-6s\n", "TX Data", "Rate");
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");
423 fprintf(fp, "%8s/%-6s\n", "TX Coll", "Rate");
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");
429 fprintf(fp, "%8s/%-6s\n", "RX Leng", "Rate");
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");
435 fprintf(fp, "%8s/%-6s\n", "RX Miss", "Rate");
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");
441 fprintf(fp, "%8s/%-6s\n", "TX Carr", "Rate");
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");
447 fprintf(fp, "%8s/%-6s\n", "TX Wind", "Rate");
448 }
449 }
450
451 static void print_one_json(json_writer_t *jw, const struct ifstat_ent *n,
452 const unsigned long long *vals)
453 {
454 int i, m = show_errors ? 20 : 10;
455
456 jsonw_name(jw, n->name);
457 jsonw_start_object(jw);
458
459 for (i = 0; i < m && stats[i]; i++)
460 jsonw_uint_field(jw, stats[i], vals[i]);
461
462 jsonw_end_object(jw);
463 }
464
465 static void print_one_if(FILE *fp, const struct ifstat_ent *n,
466 const unsigned long long *vals)
467 {
468 int i;
469
470 fprintf(fp, "%-15s ", n->name);
471 for (i = 0; i < 4; i++)
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
513 static void dump_kern_db(FILE *fp)
514 {
515 json_writer_t *jw = json_output ? jsonw_new(fp) : NULL;
516 struct ifstat_ent *n;
517
518 if (jw) {
519 jsonw_start_object(jw);
520 jsonw_pretty(jw, pretty);
521 jsonw_name(jw, info_source);
522 jsonw_start_object(jw);
523 } else
524 print_head(fp);
525
526 for (n = kern_db; n; n = n->next) {
527 if (!match(n->name))
528 continue;
529
530 if (jw)
531 print_one_json(jw, n, n->val);
532 else
533 print_one_if(fp, n, n->val);
534 }
535 if (jw) {
536 jsonw_end_object(jw);
537
538 jsonw_end_object(jw);
539 jsonw_destroy(&jw);
540 }
541 }
542
543 static void dump_incr_db(FILE *fp)
544 {
545 struct ifstat_ent *n, *h;
546 json_writer_t *jw = json_output ? jsonw_new(fp) : NULL;
547
548 h = hist_db;
549 if (jw) {
550 jsonw_start_object(jw);
551 jsonw_pretty(jw, pretty);
552 jsonw_name(jw, info_source);
553 jsonw_start_object(jw);
554 } else
555 print_head(fp);
556
557 for (n = kern_db; n; n = n->next) {
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;
574
575 if (jw)
576 print_one_json(jw, n, n->val);
577 else
578 print_one_if(fp, n, vals);
579 }
580
581 if (jw) {
582 jsonw_end_object(jw);
583
584 jsonw_end_object(jw);
585 jsonw_destroy(&jw);
586 }
587 }
588
589 static int children;
590
591 static void sigchild(int signo)
592 {
593 }
594
595 static void update_db(int interval)
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;
609
610 for (h1 = h; h1; h1 = h1->next) {
611 if (h1->ifindex == n->ifindex) {
612 int i;
613
614 for (i = 0; i < MAXS; i++) {
615 if ((long)(h1->ival[i] - n->ival[i]) < 0) {
616 memset(n->ival, 0, sizeof(n->ival));
617 break;
618 }
619 }
620 for (i = 0; i < MAXS; i++) {
621 double sample;
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 }
632
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;
641
642 n->rate[i] += w*(sample-n->rate[i]);
643 }
644 }
645 }
646
647 while (h != h1) {
648 struct ifstat_ent *tmp = h;
649
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
663 #define T_DIFF(a, b) (((a).tv_sec-(b).tv_sec)*1000 + ((a).tv_usec-(b).tv_usec)/1000)
664
665
666 static void server_loop(int fd)
667 {
668 struct timeval snaptime = { 0 };
669 struct pollfd p;
670
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;
681 time_t tdiff;
682 struct timeval now;
683
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 }
691
692 if (poll(&p, 1, scan_interval - tdiff) > 0
693 && (p.revents&POLLIN)) {
694 int clnt = accept(fd, NULL, NULL);
695
696 if (clnt >= 0) {
697 pid_t pid;
698
699 if (children >= 5) {
700 close(clnt);
701 } else if ((pid = fork()) != 0) {
702 if (pid > 0)
703 children++;
704 close(clnt);
705 } else {
706 FILE *fp = fdopen(clnt, "w");
707
708 if (fp)
709 dump_raw_db(fp, 0);
710 exit(0);
711 }
712 }
713 }
714 while (children && waitpid(-1, &status, WNOHANG) > 0)
715 children--;
716 }
717 }
718
719 static int verify_forging(int fd)
720 {
721 struct ucred cred;
722 socklen_t olen = sizeof(cred);
723
724 if (getsockopt(fd, SOL_SOCKET, SO_PEERCRED, (void *)&cred, &olen) ||
725 olen < sizeof(cred))
726 return -1;
727 if (cred.uid == getuid() || cred.uid == 0)
728 return 0;
729 return -1;
730 }
731
732 static void xstat_usage(void)
733 {
734 fprintf(stderr,
735 "Usage: ifstat supported xstats:\n"
736 " cpu_hits Counts only packets that went via the CPU.\n");
737 }
738
739 struct 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 */
749 static const struct extended_stats_options_t extended_stats_options[] = {
750 {"cpu_hits", IFLA_STATS_LINK_OFFLOAD_XSTATS, IFLA_OFFLOAD_XSTATS_CPU_HIT},
751 };
752
753 static 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
775 static void usage(void) __attribute__((noreturn));
776
777 static void usage(void)
778 {
779 fprintf(stderr,
780 "Usage: ifstat [OPTION] [ PATTERN [ PATTERN ] ]\n"
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"
792 " -z, --zeros show entries with zero activity\n"
793 " -x, --extended=TYPE show extended stats of TYPE\n");
794
795 exit(-1);
796 }
797
798 static 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' },
804 { "json", 0, 0, 'j' },
805 { "reset", 0, 0, 'r' },
806 { "pretty", 0, 0, 'p' },
807 { "noupdate", 0, 0, 's' },
808 { "interval", 1, 0, 't' },
809 { "version", 0, 0, 'V' },
810 { "zeros", 0, 0, 'z' },
811 { "extended", 1, 0, 'x'},
812 { 0 }
813 };
814
815 int main(int argc, char *argv[])
816 {
817 char hist_name[128];
818 struct sockaddr_un sun;
819 FILE *hist_fp = NULL;
820 const char *stats_type = NULL;
821 int ch;
822 int fd;
823
824 is_extended = false;
825 while ((ch = getopt_long(argc, argv, "hjpvVzrnasd:t:ex:",
826 longopts, NULL)) != EOF) {
827 switch (ch) {
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;
846 case 'j':
847 json_output = 1;
848 break;
849 case 'p':
850 pretty = 1;
851 break;
852 case 'd':
853 scan_interval = atoi(optarg) * 1000;
854 if (scan_interval <= 0) {
855 fprintf(stderr, "ifstat: invalid scan interval\n");
856 exit(-1);
857 }
858 break;
859 case 't':
860 time_constant = atoi(optarg);
861 if (time_constant <= 0) {
862 fprintf(stderr, "ifstat: invalid time constant divisor\n");
863 exit(-1);
864 }
865 break;
866 case 'x':
867 stats_type = optarg;
868 is_extended = true;
869 break;
870 case 'v':
871 case 'V':
872 printf("ifstat utility, iproute2-ss%s\n", SNAPSHOT);
873 exit(0);
874 case 'h':
875 case '?':
876 default:
877 usage();
878 }
879 }
880
881 argc -= optind;
882 argv += optind;
883
884 if (stats_type) {
885 stats_type = get_filter_type(stats_type);
886 if (!stats_type)
887 exit(-1);
888 }
889
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 }
903 if (bind(fd, (struct sockaddr *)&sun, 2+1+strlen(sun.sun_path+1)) < 0) {
904 perror("ifstat: bind");
905 exit(-1);
906 }
907 if (listen(fd, 5) < 0) {
908 perror("ifstat: listen");
909 exit(-1);
910 }
911 if (daemon(0, 0)) {
912 perror("ifstat: daemon");
913 exit(-1);
914 }
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"))
925 snprintf(hist_name, sizeof(hist_name),
926 "%s", getenv("IFSTAT_HISTORY"));
927 else
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());
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;
965 long uptime = -1;
966
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");
974 if (ftruncate(fileno(hist_fp), 0))
975 perror("ifstat: ftruncate");
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 &&
986 (connect(fd, (struct sockaddr *)&sun, 2+1+strlen(sun.sun_path+1)) == 0
987 || (strcpy(sun.sun_path+1, "ifstat0"),
988 connect(fd, (struct sockaddr *)&sun, 2+1+strlen(sun.sun_path+1)) == 0))
989 && verify_forging(fd) == 0) {
990 FILE *sfp = fdopen(fd, "r");
991
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);
1003 }
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 }
1023
1024 if (!no_update) {
1025 if (ftruncate(fileno(hist_fp), 0))
1026 perror("ifstat: ftruncate");
1027 rewind(hist_fp);
1028
1029 json_output = 0;
1030 dump_raw_db(hist_fp, 1);
1031 fclose(hist_fp);
1032 }
1033 exit(0);
1034 }