]> git.proxmox.com Git - mirror_iproute2.git/blobdiff - misc/nstat.c
nstat: fix load_ugly_table() limits
[mirror_iproute2.git] / misc / nstat.c
index 2e44ed25313d6ce0ecbc283e6f39f1b4c62e96a6..653580eae0603327ea654510ae1f23a79578c1fe 100644 (file)
 #include <sys/stat.h>
 #include <signal.h>
 #include <math.h>
+#include <getopt.h>
 
+#include <json_writer.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;
+#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;
 double W;
 char **patterns;
 int npatterns;
@@ -47,6 +51,7 @@ static int generic_proc_open(const char *env, char *name)
 {
        char store[128];
        char *p = getenv(env);
+
        if (!p) {
                p = getenv("PROC_ROOT") ? : "/proc";
                snprintf(store, sizeof(store)-1, "%s/%s", p, name);
@@ -55,63 +60,67 @@ static int generic_proc_open(const char *env, char *name)
        return open(p, O_RDONLY);
 }
 
-int net_netstat_open(void)
+static int net_netstat_open(void)
 {
        return generic_proc_open("PROC_NET_NETSTAT", "net/netstat");
 }
 
-int net_snmp_open(void)
+static int net_snmp_open(void)
 {
        return generic_proc_open("PROC_NET_SNMP", "net/snmp");
 }
 
-int net_snmp6_open(void)
+static int net_snmp6_open(void)
 {
        return generic_proc_open("PROC_NET_SNMP6", "net/snmp6");
 }
 
-struct nstat_ent
+static int net_sctp_snmp_open(void)
 {
+       return generic_proc_open("PROC_NET_SCTP_SNMP", "net/sctp/snmp");
+}
+
+struct nstat_ent {
        struct nstat_ent *next;
        char             *id;
        unsigned long long val;
-       unsigned long      ival;
        double             rate;
 };
 
 struct nstat_ent *kern_db;
 struct nstat_ent *hist_db;
 
-char *useless_numbers[] = {
-"IpForwarding", "IpDefaultTTL",
-"TcpRtoAlgorithm", "TcpRtoMin", "TcpRtoMax",
-"TcpMaxConn", "TcpCurrEstab"
+static const char *useless_numbers[] = {
+       "IpForwarding", "IpDefaultTTL",
+       "TcpRtoAlgorithm", "TcpRtoMin", "TcpRtoMax",
+       "TcpMaxConn", "TcpCurrEstab"
 };
 
-int useless_number(char *id)
+static int useless_number(const char *id)
 {
        int i;
-       for (i=0; i<sizeof(useless_numbers)/sizeof(*useless_numbers); i++)
+
+       for (i = 0; i < ARRAY_SIZE(useless_numbers); i++)
                if (strcmp(id, useless_numbers[i]) == 0)
                        return 1;
        return 0;
 }
 
-int match(char *id)
+static int match(const char *id)
 {
        int i;
 
        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;
 }
 
-void load_good_table(FILE *fp)
+static void load_good_table(FILE *fp)
 {
        char buf[4096];
        struct nstat_ent *db = NULL;
@@ -122,6 +131,7 @@ void load_good_table(FILE *fp)
                unsigned long long val;
                double rate;
                char idbuf[sizeof(buf)];
+
                if (buf[0] == '#') {
                        buf[strlen(buf)-1] = 0;
                        if (info_source[0] && strcmp(info_source, buf+1))
@@ -141,7 +151,6 @@ void load_good_table(FILE *fp)
                if ((n = malloc(sizeof(*n))) == NULL)
                        abort();
                n->id = strdup(idbuf);
-               n->ival = (unsigned long)val;
                n->val = val;
                n->rate = rate;
                n->next = db;
@@ -156,21 +165,34 @@ void load_good_table(FILE *fp)
        }
 }
 
+static int count_spaces(const char *line)
+{
+       int count = 0;
+       char c;
+
+       while ((c = *line++) != 0)
+               count += c == ' ' || c == '\n';
+       return count;
+}
 
-void load_ugly_table(FILE *fp)
+static void load_ugly_table(FILE *fp)
 {
-       char buf[4096];
+       char *buf = NULL;
+       size_t buflen = 0;
+       ssize_t nread;
        struct nstat_ent *db = NULL;
        struct nstat_ent *n;
 
-       while (fgets(buf, sizeof(buf), fp) != NULL) {
-               char idbuf[sizeof(buf)];
+       while ((nread = getline(&buf, &buflen, fp)) != -1) {
+               char idbuf[4096];
                int  off;
                char *p;
+               int count1, count2, skip = 0;
 
                p = strchr(buf, ':');
                if (!p)
                        abort();
+               count1 = count_spaces(buf);
                *p = 0;
                idbuf[0] = 0;
                strncat(idbuf, buf, sizeof(idbuf) - 1);
@@ -179,6 +201,7 @@ void load_ugly_table(FILE *fp)
 
                while (*p) {
                        char *next;
+
                        if ((next = strchr(p, ' ')) != NULL)
                                *next++ = 0;
                        else if ((next = strchr(p, '\n')) != NULL)
@@ -197,23 +220,27 @@ void load_ugly_table(FILE *fp)
                        p = next;
                }
                n = db;
-               if (fgets(buf, sizeof(buf), fp) == NULL)
+               nread = getline(&buf, &buflen, fp);
+               if (nread == -1)
                        abort();
+               count2 = count_spaces(buf);
+               if (count2 > count1)
+                       skip = count2 - count1;
                do {
                        p = strrchr(buf, ' ');
                        if (!p)
                                abort();
                        *p = 0;
-                       if (sscanf(p+1, "%lu", &n->ival) != 1)
+                       if (sscanf(p+1, "%llu", &n->val) != 1)
                                abort();
-                       n->val = n->ival;
                        /* Trick to skip "dummy" trailing ICMP MIB in 2.4 */
-                       if (strcmp(idbuf, "IcmpOutAddrMaskReps") == 0)
-                               idbuf[5] = 0;
+                       if (skip)
+                               skip--;
                        else
                                n = n->next;
                } while (p > buf + off + 2);
        }
+       free(buf);
 
        while (db) {
                n = db;
@@ -228,44 +255,69 @@ void load_ugly_table(FILE *fp)
        }
 }
 
-void load_snmp(void)
+static void load_sctp_snmp(void)
+{
+       FILE *fp = fdopen(net_sctp_snmp_open(), "r");
+
+       if (fp) {
+               load_good_table(fp);
+               fclose(fp);
+       }
+}
+
+static void load_snmp(void)
 {
        FILE *fp = fdopen(net_snmp_open(), "r");
+
        if (fp) {
                load_ugly_table(fp);
                fclose(fp);
        }
 }
 
-void load_snmp6(void)
+static void load_snmp6(void)
 {
        FILE *fp = fdopen(net_snmp6_open(), "r");
+
        if (fp) {
                load_good_table(fp);
                fclose(fp);
        }
 }
 
-void load_netstat(void)
+static void load_netstat(void)
 {
        FILE *fp = fdopen(net_netstat_open(), "r");
+
        if (fp) {
                load_ugly_table(fp);
                fclose(fp);
        }
 }
 
-void dump_kern_db(FILE *fp, int to_hist)
+
+static void dump_kern_db(FILE *fp, int to_hist)
 {
+       json_writer_t *jw = json_output ? jsonw_new(fp) : NULL;
        struct nstat_ent *n, *h;
+
        h = hist_db;
-       fprintf(fp, "#%s\n", info_source);
-       for (n=kern_db; n; n=n->next) {
+       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) {
                unsigned long long val = n->val;
+
                if (!dump_zeros && !val && !n->rate)
                        continue;
                if (!match(n->id)) {
                        struct nstat_ent *h1;
+
                        if (!to_hist)
                                continue;
                        for (h1 = h; h1; h1 = h1->next) {
@@ -276,19 +328,40 @@ void dump_kern_db(FILE *fp, int to_hist)
                                }
                        }
                }
-               fprintf(fp, "%-32s%-16llu%6.1f\n", n->id, val, n->rate);
+
+               if (jw)
+                       jsonw_uint_field(jw, n->id, val);
+               else
+                       fprintf(fp, "%-32s%-16llu%6.1f\n", n->id, val, n->rate);
+       }
+
+       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)
 {
+       json_writer_t *jw = json_output ? jsonw_new(fp) : NULL;
        struct nstat_ent *n, *h;
+
        h = hist_db;
-       fprintf(fp, "#%s\n", info_source);
-       for (n=kern_db; n; n=n->next) {
+       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) {
                int ovfl = 0;
                unsigned long long val = n->val;
                struct nstat_ent *h1;
+
                for (h1 = h; h1; h1 = h1->next) {
                        if (strcmp(h1->id, n->id) == 0) {
                                if (val < h1->val) {
@@ -304,18 +377,29 @@ void dump_incr_db(FILE *fp)
                        continue;
                if (!match(n->id))
                        continue;
-               fprintf(fp, "%-32s%-16llu%6.1f%s\n", n->id, val,
-                       n->rate, ovfl?" (overflow)":"");
+
+               if (jw)
+                       jsonw_uint_field(jw, n->id, val);
+               else
+                       fprintf(fp, "%-32s%-16llu%6.1f%s\n", n->id, val,
+                               n->rate, ovfl?" (overflow)":"");
+       }
+
+       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 nstat_ent *n, *h;
 
@@ -325,19 +409,21 @@ void update_db(int interval)
        load_netstat();
        load_snmp6();
        load_snmp();
+       load_sctp_snmp();
 
        h = kern_db;
        kern_db = n;
 
        for (n = kern_db; n; n = n->next) {
                struct nstat_ent *h1;
+
                for (h1 = h; h1; h1 = h1->next) {
                        if (strcmp(h1->id, n->id) == 0) {
                                double sample;
-                               unsigned long incr = h1->ival - n->ival;
-                               n->val += incr;
-                               n->ival = h1->ival;
-                               sample = (double)(incr*1000)/interval;
+                               unsigned long long incr = h1->val - n->val;
+
+                               n->val = h1->val;
+                               sample = (double)incr * 1000.0 / interval;
                                if (interval >= scan_interval) {
                                        n->rate += W*(sample-n->rate);
                                } else if (interval >= 1000) {
@@ -345,12 +431,14 @@ void update_db(int interval)
                                                n->rate = sample;
                                        } else {
                                                double w = W*(double)interval/scan_interval;
+
                                                n->rate += w*(sample-n->rate);
                                        }
                                }
 
                                while (h != h1) {
                                        struct nstat_ent *tmp = h;
+
                                        h = h->next;
                                        free(tmp->id);
                                        free(tmp);
@@ -364,13 +452,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;
 
@@ -380,11 +469,13 @@ void server_loop(int fd)
        load_netstat();
        load_snmp6();
        load_snmp();
+       load_sctp_snmp();
 
        for (;;) {
                int status;
-               int tdiff;
+               time_t tdiff;
                struct timeval now;
+
                gettimeofday(&now, NULL);
                tdiff = T_DIFF(now, snaptime);
                if (tdiff >= scan_interval) {
@@ -392,24 +483,24 @@ void server_loop(int fd)
                        snaptime = now;
                        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_kern_db(fp, 0);
-                                       }
                                        exit(0);
                                }
                        }
@@ -419,12 +510,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)
@@ -437,22 +528,47 @@ static void usage(void) __attribute__((noreturn));
 static void usage(void)
 {
        fprintf(stderr,
-"Usage: nstat [ -h?vVzrnasd:t: ] [ PATTERN [ PATTERN ] ]\n"
-               );
+"Usage: nstat [OPTION] [ PATTERN [ PATTERN ] ]\n"
+"   -h, --help           this message\n"
+"   -a, --ignore         ignore history\n"
+"   -d, --scan=SECS      sample every statistics every SECS\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");
        exit(-1);
 }
 
+static const struct option longopts[] = {
+       { "help", 0, 0, 'h' },
+       { "ignore",  0,  0, 'a' },
+       { "scan", 1, 0, 'd'},
+       { "nooutput", 0, 0, 'n' },
+       { "json", 0, 0, 'j' },
+       { "reset", 0, 0, 'r' },
+       { "noupdate", 0, 0, 's' },
+       { "pretty", 0, 0, 'p' },
+       { "interval", 1, 0, 't' },
+       { "version", 0, 0, 'V' },
+       { "zeros", 0, 0, 'z' },
+       { 0 }
+};
 
 int main(int argc, char *argv[])
 {
-       char hist_name[128];
+       char *hist_name;
        struct sockaddr_un sun;
        FILE *hist_fp = NULL;
        int ch;
        int fd;
 
-       while ((ch = getopt(argc, argv, "h?vVzrnasd:t:")) != EOF) {
-               switch(ch) {
+       while ((ch = getopt_long(argc, argv, "h?vVzrnasd:t:jp",
+                                longopts, NULL)) != EOF) {
+               switch (ch) {
                case 'z':
                        dump_zeros = 1;
                        break;
@@ -478,6 +594,12 @@ int main(int argc, char *argv[])
                                exit(-1);
                        }
                        break;
+               case 'j':
+                       json_output = 1;
+                       break;
+               case 'p':
+                       pretty = 1;
+                       break;
                case 'v':
                case 'V':
                        printf("nstat utility, iproute2-ss%s\n", SNAPSHOT);
@@ -505,7 +627,7 @@ int main(int argc, char *argv[])
                        perror("nstat: 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("nstat: bind");
                        exit(-1);
                }
@@ -526,10 +648,10 @@ int main(int argc, char *argv[])
        patterns = argv;
        npatterns = argc;
 
-       if (getenv("NSTAT_HISTORY"))
-               snprintf(hist_name, sizeof(hist_name), getenv("NSTAT_HISTORY"));
-       else
+       if ((hist_name = getenv("NSTAT_HISTORY")) == NULL) {
+               hist_name = malloc(128);
                sprintf(hist_name, "/tmp/.nstat.u%d", getuid());
+       }
 
        if (reset_history)
                unlink(hist_name);
@@ -560,7 +682,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;
@@ -568,7 +691,8 @@ int main(int argc, char *argv[])
                        }
                        if (uptime >= 0 && time(NULL) >= stb.st_mtime+uptime) {
                                fprintf(stderr, "nstat: history is aged out, resetting\n");
-                               ftruncate(fileno(hist_fp), 0);
+                               if (ftruncate(fileno(hist_fp), 0) < 0)
+                                       perror("nstat: ftruncate");
                        }
                }
 
@@ -579,17 +703,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, "nstat0"),
-                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_good_table(sfp);
-               if (hist_db && source_mismatch) {
-                       fprintf(stderr, "nstat: history is stale, ignoring it.\n");
-                       hist_db = NULL;
+
+               if (!sfp) {
+                       fprintf(stderr, "nstat: fdopen failed: %s\n",
+                               strerror(errno));
+                       close(fd);
+               } else {
+                       load_good_table(sfp);
+                       if (hist_db && source_mismatch) {
+                               fprintf(stderr, "nstat: history is stale, ignoring it.\n");
+                               hist_db = NULL;
+                       }
+                       fclose(sfp);
                }
-               fclose(sfp);
        } else {
                if (fd >= 0)
                        close(fd);
@@ -601,6 +732,7 @@ int main(int argc, char *argv[])
                load_netstat();
                load_snmp6();
                load_snmp();
+               load_sctp_snmp();
                if (info_source[0] == 0)
                        strcpy(info_source, "kernel");
        }
@@ -612,10 +744,13 @@ int main(int argc, char *argv[])
                        dump_incr_db(stdout);
        }
        if (!no_update) {
-               ftruncate(fileno(hist_fp), 0);
+               if (ftruncate(fileno(hist_fp), 0) < 0)
+                       perror("nstat: ftruncate");
                rewind(hist_fp);
+
+               json_output = 0;
                dump_kern_db(hist_fp, 1);
-               fflush(hist_fp);
+               fclose(hist_fp);
        }
        exit(0);
 }