Debian Codegraph @

misc/nstat.c

raw
1 /* SPDX-License-Identifier: GPL-2.0-or-later */
2 /*
3 * nstat.c handy utility to read counters /proc/net/netstat and snmp
4 *
5 * Authors: Alexey Kuznetsov, <[email protected]>
6 */
7
8 #include <stdio.h>
9 #include <stdlib.h>
10 #include <unistd.h>
11 #include <fcntl.h>
12 #include <string.h>
13 #include <errno.h>
14 #include <time.h>
15 #include <sys/time.h>
16 #include <fnmatch.h>
17 #include <sys/file.h>
18 #include <sys/socket.h>
19 #include <sys/un.h>
20 #include <poll.h>
21 #include <sys/wait.h>
22 #include <sys/stat.h>
23 #include <signal.h>
24 #include <math.h>
25 #include <getopt.h>
26
27 #include "json_print.h"
28 #include "version.h"
29 #include "utils.h"
30
31 int dump_zeros;
32 int reset_history;
33 int ignore_history;
34 int no_output;
35 int json_output;
36 int no_update;
37 int scan_interval;
38 int time_constant;
39 double W;
40 char **patterns;
41 int npatterns;
42
43 char info_source[128];
44 int source_mismatch;
45
46 static FILE *net_netstat_open(void)
47 {
48 return generic_proc_open("PROC_NET_NETSTAT", "net/netstat");
49 }
50
51 static FILE *net_snmp_open(void)
52 {
53 return generic_proc_open("PROC_NET_SNMP", "net/snmp");
54 }
55
56 static FILE *net_snmp6_open(void)
57 {
58 return generic_proc_open("PROC_NET_SNMP6", "net/snmp6");
59 }
60
61 static FILE *net_sctp_snmp_open(void)
62 {
63 return generic_proc_open("PROC_NET_SCTP_SNMP", "net/sctp/snmp");
64 }
65
66 struct nstat_ent {
67 struct nstat_ent *next;
68 char *id;
69 unsigned long long val;
70 double rate;
71 };
72
73 struct nstat_ent *kern_db;
74 struct nstat_ent *hist_db;
75
76 static const char *useless_numbers[] = {
77 "IpForwarding", "IpDefaultTTL",
78 "TcpRtoAlgorithm", "TcpRtoMin", "TcpRtoMax",
79 "TcpMaxConn", "TcpCurrEstab"
80 };
81
82 static int useless_number(const char *id)
83 {
84 int i;
85
86 for (i = 0; i < ARRAY_SIZE(useless_numbers); i++)
87 if (strcmp(id, useless_numbers[i]) == 0)
88 return 1;
89 return 0;
90 }
91
92 static int match(const char *id)
93 {
94 int i;
95
96 if (npatterns == 0)
97 return 1;
98
99 for (i = 0; i < npatterns; i++) {
100 if (!fnmatch(patterns[i], id, FNM_CASEFOLD))
101 return 1;
102 }
103 return 0;
104 }
105
106 static void load_good_table(FILE *fp)
107 {
108 char buf[4096];
109 struct nstat_ent *db = NULL;
110 struct nstat_ent *n;
111
112 while (fgets(buf, sizeof(buf), fp) != NULL) {
113 int nr;
114 unsigned long long val;
115 double rate;
116 char idbuf[sizeof(buf)];
117
118 if (buf[0] == '#') {
119 buf[strlen(buf)-1] = 0;
120 if (info_source[0] && strcmp(info_source, buf+1))
121 source_mismatch = 1;
122 strlcpy(info_source, buf + 1, sizeof(info_source));
123 continue;
124 }
125 /* idbuf is as big as buf, so this is safe */
126 nr = sscanf(buf, "%s%llu%lg", idbuf, &val, &rate);
127 if (nr < 2) {
128 fprintf(stderr, "%s:%d: error parsing history file\n",
129 __FILE__, __LINE__);
130 exit(-2);
131 }
132 if (nr < 3)
133 rate = 0;
134 if (useless_number(idbuf))
135 continue;
136 if ((n = malloc(sizeof(*n))) == NULL) {
137 perror("nstat: malloc");
138 exit(-1);
139 }
140 n->id = strdup(idbuf);
141 n->val = val;
142 n->rate = rate;
143 n->next = db;
144 db = n;
145 }
146
147 while (db) {
148 n = db;
149 db = db->next;
150 n->next = kern_db;
151 kern_db = n;
152 }
153 }
154
155 static int count_spaces(const char *line)
156 {
157 int count = 0;
158 char c;
159
160 while ((c = *line++) != 0)
161 count += c == ' ' || c == '\n';
162 return count;
163 }
164
165 static void load_ugly_table(FILE *fp)
166 {
167 char *buf = NULL;
168 size_t buflen = 0;
169 ssize_t nread;
170 struct nstat_ent *db = NULL;
171 struct nstat_ent *n;
172
173 while ((nread = getline(&buf, &buflen, fp)) != -1) {
174 char idbuf[4096];
175 int off;
176 char *p;
177 int count1, count2, skip = 0;
178
179 p = strchr(buf, ':');
180 if (!p) {
181 fprintf(stderr, "%s:%d: error parsing history file\n",
182 __FILE__, __LINE__);
183 exit(-2);
184 }
185 count1 = count_spaces(buf);
186 *p = 0;
187 idbuf[0] = 0;
188 strncat(idbuf, buf, sizeof(idbuf) - 1);
189 off = p - buf;
190 p += 2;
191
192 while (*p) {
193 char *next;
194
195 if ((next = strchr(p, ' ')) != NULL)
196 *next++ = 0;
197 else if ((next = strchr(p, '\n')) != NULL)
198 *next++ = 0;
199 if (off < sizeof(idbuf)) {
200 idbuf[off] = 0;
201 strncat(idbuf, p, sizeof(idbuf) - off - 1);
202 }
203 n = malloc(sizeof(*n));
204 if (!n) {
205 perror("nstat: malloc");
206 exit(-1);
207 }
208 n->id = strdup(idbuf);
209 if (n->id == NULL) {
210 perror("nstat: strdup");
211 exit(-1);
212 }
213 n->rate = 0;
214 n->next = db;
215 db = n;
216 if (next == NULL)
217 break;
218 p = next;
219 }
220 n = db;
221 if (n == NULL) {
222 fprintf(stderr, "Error: Invalid input – line has ':' but no entries. Add values after ':'.\n");
223 exit(-2);
224 }
225 nread = getline(&buf, &buflen, fp);
226 if (nread == -1) {
227 fprintf(stderr, "%s:%d: error parsing history file\n",
228 __FILE__, __LINE__);
229 exit(-2);
230 }
231 count2 = count_spaces(buf);
232 if (count2 > count1)
233 skip = count2 - count1;
234 do {
235 p = strrchr(buf, ' ');
236 if (!p) {
237 fprintf(stderr, "%s:%d: error parsing history file\n",
238 __FILE__, __LINE__);
239 exit(-2);
240 }
241 *p = 0;
242 if (sscanf(p+1, "%llu", &n->val) != 1) {
243 fprintf(stderr, "%s:%d: error parsing history file\n",
244 __FILE__, __LINE__);
245 exit(-2);
246 }
247 /* Trick to skip "dummy" trailing ICMP MIB in 2.4 */
248 if (skip)
249 skip--;
250 else
251 n = n->next;
252 } while (p > buf + off + 2);
253 }
254 free(buf);
255
256 while (db) {
257 n = db;
258 db = db->next;
259 if (useless_number(n->id)) {
260 free(n->id);
261 free(n);
262 } else {
263 n->next = kern_db;
264 kern_db = n;
265 }
266 }
267 }
268
269 static void load_sctp_snmp(void)
270 {
271 FILE *fp = net_sctp_snmp_open();
272
273 if (fp) {
274 load_good_table(fp);
275 fclose(fp);
276 }
277 }
278
279 static void load_snmp(void)
280 {
281 FILE *fp = net_snmp_open();
282
283 if (fp) {
284 load_ugly_table(fp);
285 fclose(fp);
286 }
287 }
288
289 static void load_snmp6(void)
290 {
291 FILE *fp = net_snmp6_open();
292
293 if (fp) {
294 load_good_table(fp);
295 fclose(fp);
296 }
297 }
298
299 static void load_netstat(void)
300 {
301 FILE *fp = net_netstat_open();
302
303 if (fp) {
304 load_ugly_table(fp);
305 fclose(fp);
306 }
307 }
308
309
310 static void dump_kern_db(FILE *fp, int to_hist)
311 {
312 struct nstat_ent *n, *h;
313
314 h = hist_db;
315 new_json_obj_plain(json_output);
316 if (is_json_context()) {
317 open_json_object(NULL);
318 open_json_object(info_source);
319 } else
320 fprintf(fp, "#%s\n", info_source);
321
322 for (n = kern_db; n; n = n->next) {
323 unsigned long long val = n->val;
324
325 if (!dump_zeros && !val && !n->rate)
326 continue;
327 if (!match(n->id)) {
328 struct nstat_ent *h1;
329
330 if (!to_hist)
331 continue;
332 for (h1 = h; h1; h1 = h1->next) {
333 if (strcmp(h1->id, n->id) == 0) {
334 val = h1->val;
335 h = h1->next;
336 break;
337 }
338 }
339 }
340
341 if (is_json_context())
342 print_lluint(PRINT_JSON, n->id, NULL, val);
343 else
344 fprintf(fp, "%-32s%-16llu%6.1f\n", n->id, val, n->rate);
345 }
346
347 if (is_json_context()) {
348 close_json_object();
349 close_json_object();
350 }
351 delete_json_obj_plain();
352 }
353
354 static void dump_incr_db(FILE *fp)
355 {
356 struct nstat_ent *n, *h;
357
358 h = hist_db;
359 new_json_obj_plain(json_output);
360 if (is_json_context()) {
361 open_json_object(NULL);
362 open_json_object(info_source);
363 } else
364 fprintf(fp, "#%s\n", info_source);
365
366 for (n = kern_db; n; n = n->next) {
367 int ovfl = 0;
368 unsigned long long val = n->val;
369 struct nstat_ent *h1;
370
371 for (h1 = h; h1; h1 = h1->next) {
372 if (strcmp(h1->id, n->id) == 0) {
373 if (val < h1->val) {
374 ovfl = 1;
375 val = h1->val;
376 }
377 val -= h1->val;
378 h = h1->next;
379 break;
380 }
381 }
382 if (!dump_zeros && !val && !n->rate)
383 continue;
384 if (!match(n->id))
385 continue;
386
387 if (is_json_context())
388 print_lluint(PRINT_JSON, n->id, NULL, val);
389 else
390 fprintf(fp, "%-32s%-16llu%6.1f%s\n", n->id, val,
391 n->rate, ovfl?" (overflow)":"");
392 }
393
394 if (is_json_context()) {
395 close_json_object();
396 close_json_object();
397 }
398 delete_json_obj_plain();
399 }
400
401 static int children;
402
403 static void sigchild(int signo)
404 {
405 }
406
407 static void update_db(int interval)
408 {
409 struct nstat_ent *n, *h;
410
411 n = kern_db;
412 kern_db = NULL;
413
414 load_netstat();
415 load_snmp6();
416 load_snmp();
417 load_sctp_snmp();
418
419 h = kern_db;
420 kern_db = n;
421
422 for (n = kern_db; n; n = n->next) {
423 struct nstat_ent *h1;
424
425 for (h1 = h; h1; h1 = h1->next) {
426 if (strcmp(h1->id, n->id) == 0) {
427 double sample;
428 unsigned long long incr = h1->val - n->val;
429
430 n->val = h1->val;
431 sample = (double)incr * 1000.0 / interval;
432 if (interval >= scan_interval) {
433 n->rate += W*(sample-n->rate);
434 } else if (interval >= 1000) {
435 if (interval >= time_constant) {
436 n->rate = sample;
437 } else {
438 double w = W*(double)interval/scan_interval;
439
440 n->rate += w*(sample-n->rate);
441 }
442 }
443
444 while (h != h1) {
445 struct nstat_ent *tmp = h;
446
447 h = h->next;
448 free(tmp->id);
449 free(tmp);
450 };
451 h = h1->next;
452 free(h1->id);
453 free(h1);
454 break;
455 }
456 }
457 }
458 }
459
460 #define T_DIFF(a, b) (((a).tv_sec-(b).tv_sec)*1000 + ((a).tv_usec-(b).tv_usec)/1000)
461
462
463 static void server_loop(int fd)
464 {
465 struct timeval snaptime = { 0 };
466 struct pollfd p;
467
468 p.fd = fd;
469 p.events = p.revents = POLLIN;
470
471 snprintf(info_source, sizeof(info_source), "%d.%lu sampling_interval=%d time_const=%d",
472 getpid(), (unsigned long)random(), scan_interval/1000, time_constant/1000);
473
474 load_netstat();
475 load_snmp6();
476 load_snmp();
477 load_sctp_snmp();
478
479 for (;;) {
480 int status;
481 time_t tdiff;
482 struct timeval now;
483
484 gettimeofday(&now, NULL);
485 tdiff = T_DIFF(now, snaptime);
486 if (tdiff >= scan_interval) {
487 update_db(tdiff);
488 snaptime = now;
489 tdiff = 0;
490 }
491 if (poll(&p, 1, scan_interval - tdiff) > 0
492 && (p.revents&POLLIN)) {
493 int clnt = accept(fd, NULL, NULL);
494
495 if (clnt >= 0) {
496 pid_t pid;
497
498 if (children >= 5) {
499 close(clnt);
500 } else if ((pid = fork()) != 0) {
501 if (pid > 0)
502 children++;
503 close(clnt);
504 } else {
505 FILE *fp = fdopen(clnt, "w");
506
507 if (fp)
508 dump_kern_db(fp, 0);
509 exit(0);
510 }
511 }
512 }
513 while (children && waitpid(-1, &status, WNOHANG) > 0)
514 children--;
515 }
516 }
517
518 static int verify_forging(int fd)
519 {
520 struct ucred cred;
521 socklen_t olen = sizeof(cred);
522
523 if (getsockopt(fd, SOL_SOCKET, SO_PEERCRED, (void *)&cred, &olen) ||
524 olen < sizeof(cred))
525 return -1;
526 if (cred.uid == getuid() || cred.uid == 0)
527 return 0;
528 return -1;
529 }
530
531 static void usage(void) __attribute__((noreturn));
532
533 static void usage(void)
534 {
535 fprintf(stderr,
536 "Usage: nstat [OPTION] [ PATTERN [ PATTERN ] ]\n"
537 " -h, --help this message\n"
538 " -a, --ignore ignore history\n"
539 " -d, --scan=SECS sample every statistics every SECS\n"
540 " -j, --json format output in JSON\n"
541 " -n, --nooutput do history only\n"
542 " -p, --pretty pretty print\n"
543 " -r, --reset reset history\n"
544 " -s, --noupdate don't update history\n"
545 " -t, --interval=SECS report average over the last SECS\n"
546 " -V, --version output version information\n"
547 " -z, --zeros show entries with zero activity\n");
548 exit(-1);
549 }
550
551 static const struct option longopts[] = {
552 { "help", 0, 0, 'h' },
553 { "ignore", 0, 0, 'a' },
554 { "scan", 1, 0, 'd'},
555 { "nooutput", 0, 0, 'n' },
556 { "json", 0, 0, 'j' },
557 { "reset", 0, 0, 'r' },
558 { "noupdate", 0, 0, 's' },
559 { "pretty", 0, 0, 'p' },
560 { "interval", 1, 0, 't' },
561 { "version", 0, 0, 'V' },
562 { "zeros", 0, 0, 'z' },
563 { 0 }
564 };
565
566 int main(int argc, char *argv[])
567 {
568 char hist_name[128];
569 struct sockaddr_un sun;
570 FILE *hist_fp = NULL;
571 int ch;
572 int fd;
573
574 while ((ch = getopt_long(argc, argv, "h?vVzrnasd:t:jp",
575 longopts, NULL)) != EOF) {
576 switch (ch) {
577 case 'z':
578 dump_zeros = 1;
579 break;
580 case 'r':
581 reset_history = 1;
582 break;
583 case 'a':
584 ignore_history = 1;
585 break;
586 case 's':
587 no_update = 1;
588 break;
589 case 'n':
590 no_output = 1;
591 break;
592 case 'd':
593 scan_interval = 1000*atoi(optarg);
594 break;
595 case 't':
596 if (sscanf(optarg, "%d", &time_constant) != 1 ||
597 time_constant <= 0) {
598 fprintf(stderr, "nstat: invalid time constant divisor\n");
599 exit(-1);
600 }
601 break;
602 case 'j':
603 json_output = 1;
604 break;
605 case 'p':
606 pretty = 1;
607 break;
608 case 'v':
609 case 'V':
610 printf("nstat utility, iproute2-%s\n", version);
611 exit(0);
612 case 'h':
613 case '?':
614 default:
615 usage();
616 }
617 }
618
619 argc -= optind;
620 argv += optind;
621
622 sun.sun_family = AF_UNIX;
623 sun.sun_path[0] = 0;
624 snprintf(sun.sun_path + 1, sizeof(sun.sun_path) - 1, "nstat%d", getuid());
625
626 if (scan_interval > 0) {
627 if (time_constant == 0)
628 time_constant = 60;
629 time_constant *= 1000;
630 W = 1 - 1/exp(log(10)*(double)scan_interval/time_constant);
631 if ((fd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) {
632 perror("nstat: socket");
633 exit(-1);
634 }
635 if (bind(fd, (struct sockaddr *)&sun, 2+1+strlen(sun.sun_path+1)) < 0) {
636 perror("nstat: bind");
637 exit(-1);
638 }
639 if (listen(fd, 5) < 0) {
640 perror("nstat: listen");
641 exit(-1);
642 }
643 if (daemon(0, 0)) {
644 perror("nstat: daemon");
645 exit(-1);
646 }
647 signal(SIGPIPE, SIG_IGN);
648 signal(SIGCHLD, sigchild);
649 server_loop(fd);
650 exit(0);
651 }
652
653 patterns = argv;
654 npatterns = argc;
655
656 if (getenv("NSTAT_HISTORY"))
657 snprintf(hist_name, sizeof(hist_name),
658 "%s", getenv("NSTAT_HISTORY"));
659 else
660 snprintf(hist_name, sizeof(hist_name), "/tmp/.nstat.u%d", getuid());
661
662 if (reset_history)
663 unlink(hist_name);
664
665 if (!ignore_history || !no_update) {
666 struct stat stb;
667
668 fd = open(hist_name, O_RDWR|O_CREAT|O_NOFOLLOW, 0600);
669 if (fd < 0) {
670 perror("nstat: open history file");
671 exit(-1);
672 }
673 if ((hist_fp = fdopen(fd, "r+")) == NULL) {
674 perror("nstat: fdopen history file");
675 exit(-1);
676 }
677 if (flock(fileno(hist_fp), LOCK_EX)) {
678 perror("nstat: flock history file");
679 exit(-1);
680 }
681 if (fstat(fileno(hist_fp), &stb) != 0) {
682 perror("nstat: fstat history file");
683 exit(-1);
684 }
685 if (stb.st_nlink != 1 || stb.st_uid != getuid()) {
686 fprintf(stderr, "nstat: something is so wrong with history file, that I prefer not to proceed.\n");
687 exit(-1);
688 }
689 if (!ignore_history) {
690 FILE *tfp;
691 long uptime = -1;
692
693 if ((tfp = fopen("/proc/uptime", "r")) != NULL) {
694 if (fscanf(tfp, "%ld", &uptime) != 1)
695 uptime = -1;
696 fclose(tfp);
697 }
698 if (uptime >= 0 && time(NULL) >= stb.st_mtime+uptime) {
699 fprintf(stderr, "nstat: history is aged out, resetting\n");
700 if (ftruncate(fileno(hist_fp), 0) < 0)
701 perror("nstat: ftruncate");
702 }
703 }
704
705 load_good_table(hist_fp);
706
707 hist_db = kern_db;
708 kern_db = NULL;
709 }
710
711 if ((fd = socket(AF_UNIX, SOCK_STREAM, 0)) >= 0 &&
712 (connect(fd, (struct sockaddr *)&sun, 2+1+strlen(sun.sun_path+1)) == 0
713 || (strcpy(sun.sun_path+1, "nstat0"),
714 connect(fd, (struct sockaddr *)&sun, 2+1+strlen(sun.sun_path+1)) == 0))
715 && verify_forging(fd) == 0) {
716 FILE *sfp = fdopen(fd, "r");
717
718 if (!sfp) {
719 fprintf(stderr, "nstat: fdopen failed: %s\n",
720 strerror(errno));
721 close(fd);
722 } else {
723 load_good_table(sfp);
724 if (hist_db && source_mismatch) {
725 fprintf(stderr, "nstat: history is stale, ignoring it.\n");
726 hist_db = NULL;
727 }
728 fclose(sfp);
729 }
730 } else {
731 if (fd >= 0)
732 close(fd);
733 if (hist_db && info_source[0] && strcmp(info_source, "kernel")) {
734 fprintf(stderr, "nstat: history is stale, ignoring it.\n");
735 hist_db = NULL;
736 info_source[0] = 0;
737 }
738 load_netstat();
739 load_snmp6();
740 load_snmp();
741 load_sctp_snmp();
742 if (info_source[0] == 0)
743 strcpy(info_source, "kernel");
744 }
745
746 if (!no_output) {
747 if (ignore_history || hist_db == NULL)
748 dump_kern_db(stdout, 0);
749 else
750 dump_incr_db(stdout);
751 }
752 if (!no_update) {
753 if (ftruncate(fileno(hist_fp), 0) < 0)
754 perror("nstat: ftruncate");
755 rewind(hist_fp);
756
757 json_output = 0;
758 dump_kern_db(hist_fp, 1);
759 fclose(hist_fp);
760 }
761 exit(0);
762 }