]> git.proxmox.com Git - mirror_iproute2.git/blobdiff - misc/ifstat.c
Merge branch 'iproute2-master' into iproute2-next
[mirror_iproute2.git] / misc / ifstat.c
index 1cd55c480bba453485de7ef31f241e128e9bbf6b..50b906e86d5d08e20b8d995e992634cd5f9b4be2 100644 (file)
 #include <math.h>
 #include <getopt.h>
 
-#include <libnetlink.h>
 #include <linux/if.h>
 #include <linux/if_link.h>
 
-#include <SNAPSHOT.h>
-
-int dump_zeros = 0;
-int reset_history = 0;
-int ignore_history = 0;
-int no_output = 0;
-int no_update = 0;
-int scan_interval = 0;
-int time_constant = 0;
-int show_errors = 0;
+#include "libnetlink.h"
+#include "json_writer.h"
+#include "SNAPSHOT.h"
+#include "utils.h"
+
+int dump_zeros;
+int reset_history;
+int ignore_history;
+int no_output;
+int json_output;
+int no_update;
+int scan_interval;
+int time_constant;
+int show_errors;
 double W;
 char **patterns;
 int npatterns;
+bool is_extended;
+int filter_type;
+int sub_type;
 
 char info_source[128];
 int source_mismatch;
 
 #define MAXS (sizeof(struct rtnl_link_stats)/sizeof(__u32))
+#define NO_SUB_TYPE 0xffff
 
-struct ifstat_ent
-{
+struct ifstat_ent {
        struct ifstat_ent       *next;
        char                    *name;
        int                     ifindex;
-       unsigned long long      val[MAXS];
+       __u64                   val[MAXS];
        double                  rate[MAXS];
        __u32                   ival[MAXS];
 };
 
+static const char *stats[MAXS] = {
+       "rx_packets",
+       "tx_packets",
+       "rx_bytes",
+       "tx_bytes",
+       "rx_errors",
+       "tx_errors",
+       "rx_dropped",
+       "tx_dropped",
+       "multicast",
+       "collisions",
+       "rx_length_errors",
+       "rx_over_errors",
+       "rx_crc_errors",
+       "rx_frame_errors",
+       "rx_fifo_errors",
+       "rx_missed_errors",
+       "tx_aborted_errors",
+       "tx_carrier_errors",
+       "tx_fifo_errors",
+       "tx_heartbeat_errors",
+       "tx_window_errors",
+       "rx_compressed",
+       "tx_compressed"
+};
+
 struct ifstat_ent *kern_db;
 struct ifstat_ent *hist_db;
 
@@ -71,18 +103,62 @@ static int match(const char *id)
        if (npatterns == 0)
                return 1;
 
-       for (i=0; i<npatterns; i++) {
+       for (i = 0; i < npatterns; i++) {
                if (!fnmatch(patterns[i], id, 0))
                        return 1;
        }
        return 0;
 }
 
+static int get_nlmsg_extended(const struct sockaddr_nl *who,
+                             struct nlmsghdr *m, void *arg)
+{
+       struct if_stats_msg *ifsm = NLMSG_DATA(m);
+       struct rtattr *tb[IFLA_STATS_MAX+1];
+       int len = m->nlmsg_len;
+       struct ifstat_ent *n;
+
+       if (m->nlmsg_type != RTM_NEWSTATS)
+               return 0;
+
+       len -= NLMSG_LENGTH(sizeof(*ifsm));
+       if (len < 0)
+               return -1;
+
+       parse_rtattr(tb, IFLA_STATS_MAX, IFLA_STATS_RTA(ifsm), len);
+       if (tb[filter_type] == NULL)
+               return 0;
+
+       n = malloc(sizeof(*n));
+       if (!n)
+               abort();
+
+       n->ifindex = ifsm->ifindex;
+       n->name = strdup(ll_index_to_name(ifsm->ifindex));
+
+       if (sub_type == NO_SUB_TYPE) {
+               memcpy(&n->val, RTA_DATA(tb[filter_type]), sizeof(n->val));
+       } else {
+               struct rtattr *attr;
+
+               attr = parse_rtattr_one_nested(sub_type, tb[filter_type]);
+               if (attr == NULL) {
+                       free(n);
+                       return 0;
+               }
+               memcpy(&n->val, RTA_DATA(attr), sizeof(n->val));
+       }
+       memset(&n->rate, 0, sizeof(n->rate));
+       n->next = kern_db;
+       kern_db = n;
+       return 0;
+}
+
 static int get_nlmsg(const struct sockaddr_nl *who,
                     struct nlmsghdr *m, void *arg)
 {
        struct ifinfomsg *ifi = NLMSG_DATA(m);
-       struct rtattr * tb[IFLA_MAX+1];
+       struct rtattr *tb[IFLA_MAX+1];
        int len = m->nlmsg_len;
        struct ifstat_ent *n;
        int i;
@@ -108,29 +184,45 @@ static int get_nlmsg(const struct sockaddr_nl *who,
        n->name = strdup(RTA_DATA(tb[IFLA_IFNAME]));
        memcpy(&n->ival, RTA_DATA(tb[IFLA_STATS]), sizeof(n->ival));
        memset(&n->rate, 0, sizeof(n->rate));
-       for (i=0; i<MAXS; i++)
+       for (i = 0; i < MAXS; i++)
                n->val[i] = n->ival[i];
        n->next = kern_db;
        kern_db = n;
        return 0;
 }
 
-void load_info(void)
+static void load_info(void)
 {
        struct ifstat_ent *db, *n;
        struct rtnl_handle rth;
+       __u32 filter_mask;
 
        if (rtnl_open(&rth, 0) < 0)
                exit(1);
 
-       if (rtnl_wilddump_request(&rth, AF_INET, RTM_GETLINK) < 0) {
-               perror("Cannot send dump request");
-               exit(1);
-       }
+       if (is_extended) {
+               ll_init_map(&rth);
+               filter_mask = IFLA_STATS_FILTER_BIT(filter_type);
+               if (rtnl_wilddump_stats_req_filter(&rth, AF_UNSPEC, RTM_GETSTATS,
+                                                  filter_mask) < 0) {
+                       perror("Cannot send dump request");
+                       exit(1);
+               }
 
-       if (rtnl_dump_filter(&rth, get_nlmsg, NULL, NULL, NULL) < 0) {
-               fprintf(stderr, "Dump terminated\n");
-               exit(1);
+               if (rtnl_dump_filter(&rth, get_nlmsg_extended, NULL) < 0) {
+                       fprintf(stderr, "Dump terminated\n");
+                       exit(1);
+               }
+       } else {
+               if (rtnl_wilddump_request(&rth, AF_INET, RTM_GETLINK) < 0) {
+                       perror("Cannot send dump request");
+                       exit(1);
+               }
+
+               if (rtnl_dump_filter(&rth, get_nlmsg, NULL) < 0) {
+                       fprintf(stderr, "Dump terminated\n");
+                       exit(1);
+               }
        }
 
        rtnl_close(&rth);
@@ -146,7 +238,7 @@ void load_info(void)
        }
 }
 
-void load_raw_table(FILE *fp)
+static void load_raw_table(FILE *fp)
 {
        char buf[4096];
        struct ifstat_ent *db = NULL;
@@ -180,8 +272,9 @@ void load_raw_table(FILE *fp)
                n->name = strdup(p);
                p = next;
 
-               for (i=0; i<MAXS; i++) {
-                       unsigned rate;
+               for (i = 0; i < MAXS; i++) {
+                       unsigned int rate;
+
                        if (!(next = strchr(p, ' ')))
                                abort();
                        *next++ = 0;
@@ -209,18 +302,28 @@ void load_raw_table(FILE *fp)
        }
 }
 
-void dump_raw_db(FILE *fp, int to_hist)
+static void dump_raw_db(FILE *fp, int to_hist)
 {
+       json_writer_t *jw = json_output ? jsonw_new(fp) : NULL;
        struct ifstat_ent *n, *h;
+
        h = hist_db;
-       fprintf(fp, "#%s\n", info_source);
+       if (jw) {
+               jsonw_start_object(jw);
+               jsonw_pretty(jw, pretty);
+               jsonw_name(jw, info_source);
+               jsonw_start_object(jw);
+       } else
+               fprintf(fp, "#%s\n", info_source);
 
-       for (n=kern_db; n; n=n->next) {
+       for (n = kern_db; n; n = n->next) {
                int i;
                unsigned long long *vals = n->val;
                double *rates = n->rate;
+
                if (!match(n->name)) {
                        struct ifstat_ent *h1;
+
                        if (!to_hist)
                                continue;
                        for (h1 = h; h1; h1 = h1->next) {
@@ -232,10 +335,27 @@ void dump_raw_db(FILE *fp, int to_hist)
                                }
                        }
                }
-               fprintf(fp, "%d %s ", n->ifindex, n->name);
-               for (i=0; i<MAXS; i++)
-                       fprintf(fp, "%llu %u ", vals[i], (unsigned)rates[i]);
-               fprintf(fp, "\n");
+
+               if (jw) {
+                       jsonw_name(jw, n->name);
+                       jsonw_start_object(jw);
+
+                       for (i = 0; i < MAXS && stats[i]; i++)
+                               jsonw_uint_field(jw, stats[i], vals[i]);
+                       jsonw_end_object(jw);
+               } else {
+                       fprintf(fp, "%d %s ", n->ifindex, n->name);
+                       for (i = 0; i < MAXS; i++)
+                               fprintf(fp, "%llu %u ", vals[i],
+                                       (unsigned int)rates[i]);
+                       fprintf(fp, "\n");
+               }
+       }
+       if (jw) {
+               jsonw_end_object(jw);
+
+               jsonw_end_object(jw);
+               jsonw_destroy(&jw);
        }
 }
 
@@ -244,9 +364,11 @@ static const unsigned long long giga = 1000000000ull;
 static const unsigned long long mega = 1000000;
 static const unsigned long long kilo = 1000;
 
-void format_rate(FILE *fp, unsigned long long *vals, double *rates, int i)
+static void format_rate(FILE *fp, const unsigned long long *vals,
+                       const double *rates, int i)
 {
        char temp[64];
+
        if (vals[i] > giga)
                fprintf(fp, "%7lluM ", vals[i]/mega);
        else if (vals[i] > mega)
@@ -255,18 +377,19 @@ void format_rate(FILE *fp, unsigned long long *vals, double *rates, int i)
                fprintf(fp, "%8llu ", vals[i]);
 
        if (rates[i] > mega) {
-               sprintf(temp, "%uM", (unsigned)(rates[i]/mega));
+               sprintf(temp, "%uM", (unsigned int)(rates[i]/mega));
                fprintf(fp, "%-6s ", temp);
        } else if (rates[i] > kilo) {
-               sprintf(temp, "%uK", (unsigned)(rates[i]/kilo));
+               sprintf(temp, "%uK", (unsigned int)(rates[i]/kilo));
                fprintf(fp, "%-6s ", temp);
        } else
-               fprintf(fp, "%-6u ", (unsigned)rates[i]);
+               fprintf(fp, "%-6u ", (unsigned int)rates[i]);
 }
 
-void format_pair(FILE *fp, unsigned long long *vals, int i, int k)
+static void format_pair(FILE *fp, const unsigned long long *vals, int i, int k)
 {
        char temp[64];
+
        if (vals[i] > giga)
                fprintf(fp, "%7lluM ", vals[i]/mega);
        else if (vals[i] > mega)
@@ -275,16 +398,16 @@ void format_pair(FILE *fp, unsigned long long *vals, int i, int k)
                fprintf(fp, "%8llu ", vals[i]);
 
        if (vals[k] > giga) {
-               sprintf(temp, "%uM", (unsigned)(vals[k]/mega));
+               sprintf(temp, "%uM", (unsigned int)(vals[k]/mega));
                fprintf(fp, "%-6s ", temp);
        } else if (vals[k] > mega) {
-               sprintf(temp, "%uK", (unsigned)(vals[k]/kilo));
+               sprintf(temp, "%uK", (unsigned int)(vals[k]/kilo));
                fprintf(fp, "%-6s ", temp);
        } else
-               fprintf(fp, "%-6u ", (unsigned)vals[k]);
+               fprintf(fp, "%-6u ", (unsigned int)vals[k]);
 }
 
-void print_head(FILE *fp)
+static void print_head(FILE *fp)
 {
        fprintf(fp, "#%s\n", info_source);
        fprintf(fp, "%-15s ", "Interface");
@@ -292,46 +415,62 @@ void print_head(FILE *fp)
        fprintf(fp, "%8s/%-6s ", "RX Pkts", "Rate");
        fprintf(fp, "%8s/%-6s ", "TX Pkts", "Rate");
        fprintf(fp, "%8s/%-6s ", "RX Data", "Rate");
-       fprintf(fp, "%8s/%-6s\n","TX Data", "Rate");
+       fprintf(fp, "%8s/%-6s\n", "TX Data", "Rate");
 
        if (!show_errors) {
                fprintf(fp, "%-15s ", "");
                fprintf(fp, "%8s/%-6s ", "RX Errs", "Drop");
                fprintf(fp, "%8s/%-6s ", "TX Errs", "Drop");
                fprintf(fp, "%8s/%-6s ", "RX Over", "Rate");
-               fprintf(fp, "%8s/%-6s\n","TX Coll", "Rate");
+               fprintf(fp, "%8s/%-6s\n", "TX Coll", "Rate");
        } else {
                fprintf(fp, "%-15s ", "");
                fprintf(fp, "%8s/%-6s ", "RX Errs", "Rate");
                fprintf(fp, "%8s/%-6s ", "RX Drop", "Rate");
                fprintf(fp, "%8s/%-6s ", "RX Over", "Rate");
-               fprintf(fp, "%8s/%-6s\n","RX Leng", "Rate");
+               fprintf(fp, "%8s/%-6s\n", "RX Leng", "Rate");
 
                fprintf(fp, "%-15s ", "");
                fprintf(fp, "%8s/%-6s ", "RX Crc", "Rate");
                fprintf(fp, "%8s/%-6s ", "RX Frm", "Rate");
                fprintf(fp, "%8s/%-6s ", "RX Fifo", "Rate");
-               fprintf(fp, "%8s/%-6s\n","RX Miss", "Rate");
+               fprintf(fp, "%8s/%-6s\n", "RX Miss", "Rate");
 
                fprintf(fp, "%-15s ", "");
                fprintf(fp, "%8s/%-6s ", "TX Errs", "Rate");
                fprintf(fp, "%8s/%-6s ", "TX Drop", "Rate");
                fprintf(fp, "%8s/%-6s ", "TX Coll", "Rate");
-               fprintf(fp, "%8s/%-6s\n","TX Carr", "Rate");
+               fprintf(fp, "%8s/%-6s\n", "TX Carr", "Rate");
 
                fprintf(fp, "%-15s ", "");
                fprintf(fp, "%8s/%-6s ", "TX Abrt", "Rate");
                fprintf(fp, "%8s/%-6s ", "TX Fifo", "Rate");
                fprintf(fp, "%8s/%-6s ", "TX Hear", "Rate");
-               fprintf(fp, "%8s/%-6s\n","TX Wind", "Rate");
+               fprintf(fp, "%8s/%-6s\n", "TX Wind", "Rate");
        }
 }
 
-void print_one_if(FILE *fp, struct ifstat_ent *n, unsigned long long *vals)
+static void print_one_json(json_writer_t *jw, const struct ifstat_ent *n,
+                          const unsigned long long *vals)
+{
+       int i, m = show_errors ? 20 : 10;
+
+       jsonw_name(jw, n->name);
+       jsonw_start_object(jw);
+
+       for (i = 0; i < m && stats[i]; i++)
+               jsonw_uint_field(jw, stats[i], vals[i]);
+
+       jsonw_end_object(jw);
+}
+
+static void print_one_if(FILE *fp, const struct ifstat_ent *n,
+                        const unsigned long long *vals)
 {
        int i;
+
        fprintf(fp, "%-15s ", n->name);
-       for (i=0; i<4; i++)
+       for (i = 0; i < 4; i++)
                format_rate(fp, vals, n->rate, i);
        fprintf(fp, "\n");
 
@@ -373,29 +512,51 @@ void print_one_if(FILE *fp, struct ifstat_ent *n, unsigned long long *vals)
        }
 }
 
-
-void dump_kern_db(FILE *fp)
+static void dump_kern_db(FILE *fp)
 {
+       json_writer_t *jw = json_output ? jsonw_new(fp) : NULL;
        struct ifstat_ent *n;
 
-       print_head(fp);
+       if (jw) {
+               jsonw_start_object(jw);
+               jsonw_pretty(jw, pretty);
+               jsonw_name(jw, info_source);
+               jsonw_start_object(jw);
+       } else
+               print_head(fp);
 
-       for (n=kern_db; n; n=n->next) {
+       for (n = kern_db; n; n = n->next) {
                if (!match(n->name))
                        continue;
-               print_one_if(fp, n, n->val);
+
+               if (jw)
+                       print_one_json(jw, n, n->val);
+               else
+                       print_one_if(fp, n, n->val);
        }
-}
+       if (jw) {
+               jsonw_end_object(jw);
 
+               jsonw_end_object(jw);
+               jsonw_destroy(&jw);
+       }
+}
 
-void dump_incr_db(FILE *fp)
+static void dump_incr_db(FILE *fp)
 {
        struct ifstat_ent *n, *h;
-       h = hist_db;
+       json_writer_t *jw = json_output ? jsonw_new(fp) : NULL;
 
-       print_head(fp);
+       h = hist_db;
+       if (jw) {
+               jsonw_start_object(jw);
+               jsonw_pretty(jw, pretty);
+               jsonw_name(jw, info_source);
+               jsonw_start_object(jw);
+       } else
+               print_head(fp);
 
-       for (n=kern_db; n; n=n->next) {
+       for (n = kern_db; n; n = n->next) {
                int i;
                unsigned long long vals[MAXS];
                struct ifstat_ent *h1;
@@ -412,18 +573,28 @@ void dump_incr_db(FILE *fp)
                }
                if (!match(n->name))
                        continue;
-               print_one_if(fp, n, vals);
+
+               if (jw)
+                       print_one_json(jw, n, n->val);
+               else
+                       print_one_if(fp, n, vals);
        }
-}
 
+       if (jw) {
+               jsonw_end_object(jw);
+
+               jsonw_end_object(jw);
+               jsonw_destroy(&jw);
+       }
+}
 
 static int children;
 
-void sigchild(int signo)
+static void sigchild(int signo)
 {
 }
 
-void update_db(int interval)
+static void update_db(int interval)
 {
        struct ifstat_ent *n, *h;
 
@@ -437,9 +608,11 @@ void update_db(int interval)
 
        for (n = kern_db; n; n = n->next) {
                struct ifstat_ent *h1;
+
                for (h1 = h; h1; h1 = h1->next) {
                        if (h1->ifindex == n->ifindex) {
                                int i;
+
                                for (i = 0; i < MAXS; i++) {
                                        if ((long)(h1->ival[i] - n->ival[i]) < 0) {
                                                memset(n->ival, 0, sizeof(n->ival));
@@ -448,9 +621,17 @@ void update_db(int interval)
                                }
                                for (i = 0; i < MAXS; i++) {
                                        double sample;
-                                       unsigned long incr = h1->ival[i] - n->ival[i];
-                                       n->val[i] += incr;
-                                       n->ival[i] = h1->ival[i];
+                                       __u64 incr;
+
+                                       if (is_extended) {
+                                               incr = h1->val[i] - n->val[i];
+                                               n->val[i] = h1->val[i];
+                                       } else {
+                                               incr = (__u32) (h1->ival[i] - n->ival[i]);
+                                               n->val[i] += incr;
+                                               n->ival[i] = h1->ival[i];
+                                       }
+
                                        sample = (double)(incr*1000)/interval;
                                        if (interval >= scan_interval) {
                                                n->rate[i] += W*(sample-n->rate[i]);
@@ -459,6 +640,7 @@ void update_db(int interval)
                                                        n->rate[i] = sample;
                                                } else {
                                                        double w = W*(double)interval/scan_interval;
+
                                                        n->rate[i] += w*(sample-n->rate[i]);
                                                }
                                        }
@@ -466,6 +648,7 @@ void update_db(int interval)
 
                                while (h != h1) {
                                        struct ifstat_ent *tmp = h;
+
                                        h = h->next;
                                        free(tmp->name);
                                        free(tmp);
@@ -479,13 +662,14 @@ void update_db(int interval)
        }
 }
 
-#define T_DIFF(a,b) (((a).tv_sec-(b).tv_sec)*1000 + ((a).tv_usec-(b).tv_usec)/1000)
+#define T_DIFF(a, b) (((a).tv_sec-(b).tv_sec)*1000 + ((a).tv_usec-(b).tv_usec)/1000)
 
 
-void server_loop(int fd)
+static void server_loop(int fd)
 {
        struct timeval snaptime = { 0 };
        struct pollfd p;
+
        p.fd = fd;
        p.events = p.revents = POLLIN;
 
@@ -496,7 +680,7 @@ void server_loop(int fd)
 
        for (;;) {
                int status;
-               int tdiff;
+               time_t tdiff;
                struct timeval now;
 
                gettimeofday(&now, NULL);
@@ -507,24 +691,24 @@ void server_loop(int fd)
                        tdiff = 0;
                }
 
-               if (poll(&p, 1, tdiff + scan_interval) > 0
+               if (poll(&p, 1, scan_interval - tdiff) > 0
                    && (p.revents&POLLIN)) {
                        int clnt = accept(fd, NULL, NULL);
+
                        if (clnt >= 0) {
                                pid_t pid;
+
                                if (children >= 5) {
                                        close(clnt);
                                } else if ((pid = fork()) != 0) {
-                                       if (pid>0)
+                                       if (pid > 0)
                                                children++;
                                        close(clnt);
                                } else {
                                        FILE *fp = fdopen(clnt, "w");
-                                       if (fp) {
-                                               if (tdiff > 0)
-                                                       update_db(tdiff);
+
+                                       if (fp)
                                                dump_raw_db(fp, 0);
-                                       }
                                        exit(0);
                                }
                        }
@@ -534,12 +718,12 @@ void server_loop(int fd)
        }
 }
 
-int verify_forging(int fd)
+static int verify_forging(int fd)
 {
        struct ucred cred;
        socklen_t olen = sizeof(cred);
 
-       if (getsockopt(fd, SOL_SOCKET, SO_PEERCRED, (void*)&cred, &olen) ||
+       if (getsockopt(fd, SOL_SOCKET, SO_PEERCRED, (void *)&cred, &olen) ||
            olen < sizeof(cred))
                return -1;
        if (cred.uid == getuid() || cred.uid == 0)
@@ -547,22 +731,68 @@ int verify_forging(int fd)
        return -1;
 }
 
+static void xstat_usage(void)
+{
+       fprintf(stderr,
+"Usage: ifstat supported xstats:\n"
+"       cpu_hits       Counts only packets that went via the CPU.\n");
+}
+
+struct extended_stats_options_t {
+       char *name;
+       int id;
+       int sub_type;
+};
+
+/* Note: if one xstat name is subset of another, it should be before it in this
+ * list.
+ * Name length must be under 64 chars.
+ */
+static const struct extended_stats_options_t extended_stats_options[] = {
+       {"cpu_hits",  IFLA_STATS_LINK_OFFLOAD_XSTATS, IFLA_OFFLOAD_XSTATS_CPU_HIT},
+};
+
+static const char *get_filter_type(const char *name)
+{
+       int name_len;
+       int i;
+
+       name_len = strlen(name);
+       for (i = 0; i < ARRAY_SIZE(extended_stats_options); i++) {
+               const struct extended_stats_options_t *xstat;
+
+               xstat = &extended_stats_options[i];
+               if (strncmp(name, xstat->name, name_len) == 0) {
+                       filter_type = xstat->id;
+                       sub_type = xstat->sub_type;
+                       return xstat->name;
+               }
+       }
+
+       fprintf(stderr, "invalid ifstat extension %s\n", name);
+       xstat_usage();
+       return NULL;
+}
+
 static void usage(void) __attribute__((noreturn));
 
 static void usage(void)
 {
        fprintf(stderr,
 "Usage: ifstat [OPTION] [ PATTERN [ PATTERN ] ]\n"
-"   -h, --help         this message\n"
-"   -a, --ignore       ignore history\n"
-"   -d, --scan=SECS    sample every statistics every SECS\n"
-"   -e, --errors       show errors\n"
-"   -n, --nooutput     do history only\n"
-"   -r, --reset                reset history\n"
-"   -s, --noupdate     don;t update history\n"
-"   -t, --interval=SECS        report average over the last SECS\n"
-"   -V, --version      output version information\n"
-"   -z, --zeros                show entries with zero activity\n");
+"   -h, --help           this message\n"
+"   -a, --ignore         ignore history\n"
+"   -d, --scan=SECS      sample every statistics every SECS\n"
+"   -e, --errors         show errors\n"
+"   -j, --json           format output in JSON\n"
+"   -n, --nooutput       do history only\n"
+"   -p, --pretty         pretty print\n"
+"   -r, --reset          reset history\n"
+"   -s, --noupdate       don't update history\n"
+"   -t, --interval=SECS  report average over the last SECS\n"
+"   -V, --version        output version information\n"
+"   -z, --zeros          show entries with zero activity\n"
+"   -x, --extended=TYPE  show extended stats of TYPE\n");
 
        exit(-1);
 }
@@ -573,11 +803,14 @@ static const struct option longopts[] = {
        { "scan", 1, 0, 'd'},
        { "errors", 0, 0, 'e' },
        { "nooutput", 0, 0, 'n' },
+       { "json", 0, 0, 'j' },
        { "reset", 0, 0, 'r' },
+       { "pretty", 0, 0, 'p' },
        { "noupdate", 0, 0, 's' },
        { "interval", 1, 0, 't' },
        { "version", 0, 0, 'V' },
        { "zeros", 0, 0, 'z' },
+       { "extended", 1, 0, 'x'},
        { 0 }
 };
 
@@ -586,12 +819,14 @@ int main(int argc, char *argv[])
        char hist_name[128];
        struct sockaddr_un sun;
        FILE *hist_fp = NULL;
+       const char *stats_type = NULL;
        int ch;
        int fd;
 
-       while ((ch = getopt_long(argc, argv, "hvVzrnasd:t:eK",
+       is_extended = false;
+       while ((ch = getopt_long(argc, argv, "hjpvVzrnasd:t:ex:",
                        longopts, NULL)) != EOF) {
-               switch(ch) {
+               switch (ch) {
                case 'z':
                        dump_zeros = 1;
                        break;
@@ -610,6 +845,12 @@ int main(int argc, char *argv[])
                case 'e':
                        show_errors = 1;
                        break;
+               case 'j':
+                       json_output = 1;
+                       break;
+               case 'p':
+                       pretty = 1;
+                       break;
                case 'd':
                        scan_interval = atoi(optarg) * 1000;
                        if (scan_interval <= 0) {
@@ -624,6 +865,10 @@ int main(int argc, char *argv[])
                                exit(-1);
                        }
                        break;
+               case 'x':
+                       stats_type = optarg;
+                       is_extended = true;
+                       break;
                case 'v':
                case 'V':
                        printf("ifstat utility, iproute2-ss%s\n", SNAPSHOT);
@@ -638,6 +883,12 @@ int main(int argc, char *argv[])
        argc -= optind;
        argv += optind;
 
+       if (stats_type) {
+               stats_type = get_filter_type(stats_type);
+               if (!stats_type)
+                       exit(-1);
+       }
+
        sun.sun_family = AF_UNIX;
        sun.sun_path[0] = 0;
        sprintf(sun.sun_path+1, "ifstat%d", getuid());
@@ -651,7 +902,7 @@ int main(int argc, char *argv[])
                        perror("ifstat: socket");
                        exit(-1);
                }
-               if (bind(fd, (struct sockaddr*)&sun, 2+1+strlen(sun.sun_path+1)) < 0) {
+               if (bind(fd, (struct sockaddr *)&sun, 2+1+strlen(sun.sun_path+1)) < 0) {
                        perror("ifstat: bind");
                        exit(-1);
                }
@@ -676,8 +927,13 @@ int main(int argc, char *argv[])
                snprintf(hist_name, sizeof(hist_name),
                         "%s", getenv("IFSTAT_HISTORY"));
        else
-               snprintf(hist_name, sizeof(hist_name),
-                        "%s/.ifstat.u%d", P_tmpdir, getuid());
+               if (!stats_type)
+                       snprintf(hist_name, sizeof(hist_name),
+                                "%s/.ifstat.u%d", P_tmpdir, getuid());
+               else
+                       snprintf(hist_name, sizeof(hist_name),
+                                "%s/.%s_ifstat.u%d", P_tmpdir, stats_type,
+                                getuid());
 
        if (reset_history)
                unlink(hist_name);
@@ -708,7 +964,8 @@ int main(int argc, char *argv[])
                }
                if (!ignore_history) {
                        FILE *tfp;
-                       long uptime;
+                       long uptime = -1;
+
                        if ((tfp = fopen("/proc/uptime", "r")) != NULL) {
                                if (fscanf(tfp, "%ld", &uptime) != 1)
                                        uptime = -1;
@@ -716,7 +973,8 @@ int main(int argc, char *argv[])
                        }
                        if (uptime >= 0 && time(NULL) >= stb.st_mtime+uptime) {
                                fprintf(stderr, "ifstat: history is aged out, resetting\n");
-                               ftruncate(fileno(hist_fp), 0);
+                               if (ftruncate(fileno(hist_fp), 0))
+                                       perror("ifstat: ftruncate");
                        }
                }
 
@@ -727,17 +985,24 @@ int main(int argc, char *argv[])
        }
 
        if ((fd = socket(AF_UNIX, SOCK_STREAM, 0)) >= 0 &&
-           (connect(fd, (struct sockaddr*)&sun, 2+1+strlen(sun.sun_path+1)) == 0
+           (connect(fd, (struct sockaddr *)&sun, 2+1+strlen(sun.sun_path+1)) == 0
             || (strcpy(sun.sun_path+1, "ifstat0"),
-                connect(fd, (struct sockaddr*)&sun, 2+1+strlen(sun.sun_path+1)) == 0))
+                connect(fd, (struct sockaddr *)&sun, 2+1+strlen(sun.sun_path+1)) == 0))
            && verify_forging(fd) == 0) {
                FILE *sfp = fdopen(fd, "r");
-               load_raw_table(sfp);
-               if (hist_db && source_mismatch) {
-                       fprintf(stderr, "ifstat: history is stale, ignoring it.\n");
-                       hist_db = NULL;
+
+               if (!sfp) {
+                       fprintf(stderr, "ifstat: fdopen failed: %s\n",
+                               strerror(errno));
+                       close(fd);
+               } else  {
+                       load_raw_table(sfp);
+                       if (hist_db && source_mismatch) {
+                               fprintf(stderr, "ifstat: history is stale, ignoring it.\n");
+                               hist_db = NULL;
+                       }
+                       fclose(sfp);
                }
-               fclose(sfp);
        } else {
                if (fd >= 0)
                        close(fd);
@@ -757,11 +1022,15 @@ int main(int argc, char *argv[])
                else
                        dump_incr_db(stdout);
        }
+
        if (!no_update) {
-               ftruncate(fileno(hist_fp), 0);
+               if (ftruncate(fileno(hist_fp), 0))
+                       perror("ifstat: ftruncate");
                rewind(hist_fp);
+
+               json_output = 0;
                dump_raw_db(hist_fp, 1);
-               fflush(hist_fp);
+               fclose(hist_fp);
        }
        exit(0);
 }