Debian Codegraph @

misc/rtacct.c

raw
1 /* SPDX-License-Identifier: GPL-2.0-or-later */
2 /*
3 * rtacct.c Applet to display contents of /proc/net/rt_acct.
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 <sys/file.h>
17 #include <sys/socket.h>
18 #include <sys/un.h>
19 #include <poll.h>
20 #include <sys/wait.h>
21 #include <sys/stat.h>
22 #include <sys/mman.h>
23 #include <signal.h>
24 #include <math.h>
25
26 #include "rt_names.h"
27
28 #include "version.h"
29
30 int reset_history;
31 int ignore_history;
32 int no_output;
33 int no_update;
34 int scan_interval;
35 int time_constant;
36 int dump_zeros;
37 unsigned long magic_number;
38 double W;
39
40 static int generic_proc_open(const char *env, const char *name)
41 {
42 char store[1024];
43 char *p = getenv(env);
44
45 if (!p) {
46 p = getenv("PROC_ROOT") ? : "/proc";
47 snprintf(store, sizeof(store)-1, "%s/%s", p, name);
48 p = store;
49 }
50 return open(p, O_RDONLY);
51 }
52
53 static int net_rtacct_open(void)
54 {
55 return generic_proc_open("PROC_NET_RTACCT", "net/rt_acct");
56 }
57
58 static __u32 rmap[256/4];
59
60 struct rtacct_data {
61 __u32 ival[256*4];
62
63 unsigned long long val[256*4];
64 double rate[256*4];
65 char signature[128];
66 };
67
68 static struct rtacct_data kern_db_static;
69
70 static struct rtacct_data *kern_db = &kern_db_static;
71 static struct rtacct_data *hist_db;
72
73 static void nread(int fd, char *buf, int tot)
74 {
75 int count = 0;
76
77 while (count < tot) {
78 int n = read(fd, buf+count, tot-count);
79
80 if (n < 0) {
81 if (errno == EINTR)
82 continue;
83 exit(-1);
84 }
85 if (n == 0)
86 exit(-1);
87 count += n;
88 }
89 }
90
91 static __u32 *read_kern_table(__u32 *tbl)
92 {
93 static __u32 *tbl_ptr;
94 int fd;
95
96 if (magic_number) {
97 if (tbl_ptr != NULL)
98 return tbl_ptr;
99
100 fd = open("/dev/mem", O_RDONLY);
101 if (fd < 0) {
102 perror("magic open");
103 exit(-1);
104 }
105 tbl_ptr = mmap(NULL, 4096,
106 PROT_READ,
107 MAP_SHARED,
108 fd, magic_number);
109 if ((unsigned long)tbl_ptr == ~0UL) {
110 perror("magic mmap");
111 exit(-1);
112 }
113 close(fd);
114 return tbl_ptr;
115 }
116
117 fd = net_rtacct_open();
118 if (fd >= 0) {
119 nread(fd, (char *)tbl, 256*16);
120 close(fd);
121 } else {
122 memset(tbl, 0, 256*16);
123 }
124 return tbl;
125 }
126
127 static void format_rate(FILE *fp, double rate)
128 {
129 char temp[64];
130
131 if (rate > 1024*1024) {
132 sprintf(temp, "%uM", (unsigned int)rint(rate/(1024*1024)));
133 fprintf(fp, " %-10s", temp);
134 } else if (rate > 1024) {
135 sprintf(temp, "%uK", (unsigned int)rint(rate/1024));
136 fprintf(fp, " %-10s", temp);
137 } else
138 fprintf(fp, " %-10u", (unsigned int)rate);
139 }
140
141 static void format_count(FILE *fp, unsigned long long val)
142 {
143 if (val > 1024*1024*1024)
144 fprintf(fp, " %10lluM", val/(1024*1024));
145 else if (val > 1024*1024)
146 fprintf(fp, " %10lluK", val/1024);
147 else
148 fprintf(fp, " %10llu", val);
149 }
150
151 static void dump_abs_db(FILE *fp)
152 {
153 int realm;
154 char b1[16];
155
156 if (!no_output) {
157 fprintf(fp, "#%s\n", kern_db->signature);
158 fprintf(fp,
159 "%-10s %-10s "
160 "%-10s %-10s "
161 "%-10s \n"
162 , "Realm", "BytesTo", "PktsTo", "BytesFrom", "PktsFrom");
163 fprintf(fp,
164 "%-10s %-10s "
165 "%-10s %-10s "
166 "%-10s \n"
167 , "", "BPSTo", "PPSTo", "BPSFrom", "PPSFrom");
168
169 }
170
171 for (realm = 0; realm < 256; realm++) {
172 int i;
173 unsigned long long *val;
174 double *rate;
175
176 if (!(rmap[realm>>5] & (1<<(realm&0x1f))))
177 continue;
178
179 val = &kern_db->val[realm*4];
180 rate = &kern_db->rate[realm*4];
181
182 if (!dump_zeros &&
183 !val[0] && !rate[0] &&
184 !val[1] && !rate[1] &&
185 !val[2] && !rate[2] &&
186 !val[3] && !rate[3])
187 continue;
188
189 if (hist_db) {
190 memcpy(&hist_db->val[realm*4], val, sizeof(*val)*4);
191 }
192
193 if (no_output)
194 continue;
195
196 fprintf(fp, "%-10s", rtnl_rtrealm_n2a(realm, b1, sizeof(b1)));
197 for (i = 0; i < 4; i++)
198 format_count(fp, val[i]);
199 fprintf(fp, "\n%-10s", "");
200 for (i = 0; i < 4; i++)
201 format_rate(fp, rate[i]);
202 fprintf(fp, "\n");
203 }
204 }
205
206
207 static void dump_incr_db(FILE *fp)
208 {
209 int k, realm;
210 char b1[16];
211
212 if (!no_output) {
213 fprintf(fp, "#%s\n", kern_db->signature);
214 fprintf(fp,
215 "%-10s %-10s "
216 "%-10s %-10s "
217 "%-10s \n"
218 , "Realm", "BytesTo", "PktsTo", "BytesFrom", "PktsFrom");
219 fprintf(fp,
220 "%-10s %-10s "
221 "%-10s %-10s "
222 "%-10s \n"
223 , "", "BPSTo", "PPSTo", "BPSFrom", "PPSFrom");
224 }
225
226 for (realm = 0; realm < 256; realm++) {
227 int ovfl = 0;
228 int i;
229 unsigned long long *val;
230 double *rate;
231 unsigned long long rval[4];
232
233 if (!(rmap[realm>>5] & (1<<(realm&0x1f))))
234 continue;
235
236 val = &kern_db->val[realm*4];
237 rate = &kern_db->rate[realm*4];
238
239 for (k = 0; k < 4; k++) {
240 rval[k] = val[k];
241 if (rval[k] < hist_db->val[realm*4+k])
242 ovfl = 1;
243 else
244 rval[k] -= hist_db->val[realm*4+k];
245 }
246 if (ovfl) {
247 for (k = 0; k < 4; k++)
248 rval[k] = val[k];
249 }
250 if (hist_db) {
251 memcpy(&hist_db->val[realm*4], val, sizeof(*val)*4);
252 }
253
254 if (no_output)
255 continue;
256
257 if (!dump_zeros &&
258 !rval[0] && !rate[0] &&
259 !rval[1] && !rate[1] &&
260 !rval[2] && !rate[2] &&
261 !rval[3] && !rate[3])
262 continue;
263
264
265 fprintf(fp, "%-10s", rtnl_rtrealm_n2a(realm, b1, sizeof(b1)));
266 for (i = 0; i < 4; i++)
267 format_count(fp, rval[i]);
268 fprintf(fp, "\n%-10s", "");
269 for (i = 0; i < 4; i++)
270 format_rate(fp, rate[i]);
271 fprintf(fp, "\n");
272 }
273 }
274
275
276 static int children;
277
278 static void sigchild(int signo)
279 {
280 }
281
282 /* Server side only: read kernel data, update tables, calculate rates. */
283
284 static void update_db(int interval)
285 {
286 int i;
287 __u32 *ival;
288 __u32 _ival[256*4];
289
290 ival = read_kern_table(_ival);
291
292 for (i = 0; i < 256*4; i++) {
293 double sample;
294 __u32 incr = ival[i] - kern_db->ival[i];
295
296 if (ival[i] == 0 && incr == 0 &&
297 kern_db->val[i] == 0 && kern_db->rate[i] == 0)
298 continue;
299
300 kern_db->val[i] += incr;
301 kern_db->ival[i] = ival[i];
302 sample = (double)(incr*1000)/interval;
303 if (interval >= scan_interval) {
304 kern_db->rate[i] += W*(sample-kern_db->rate[i]);
305 } else if (interval >= 1000) {
306 if (interval >= time_constant) {
307 kern_db->rate[i] = sample;
308 } else {
309 double w = W*(double)interval/scan_interval;
310
311 kern_db->rate[i] += w*(sample-kern_db->rate[i]);
312 }
313 }
314 }
315 }
316
317 static void send_db(int fd)
318 {
319 int tot = 0;
320
321 while (tot < sizeof(*kern_db)) {
322 int n = write(fd, ((char *)kern_db) + tot, sizeof(*kern_db)-tot);
323
324 if (n < 0) {
325 if (errno == EINTR)
326 continue;
327 return;
328 }
329 tot += n;
330 }
331 }
332
333
334
335 #define T_DIFF(a, b) (((a).tv_sec-(b).tv_sec)*1000 + ((a).tv_usec-(b).tv_usec)/1000)
336
337
338 static void pad_kern_table(struct rtacct_data *dat, __u32 *ival)
339 {
340 int i;
341
342 memset(dat->rate, 0, sizeof(dat->rate));
343 if (dat->ival != ival)
344 memcpy(dat->ival, ival, sizeof(dat->ival));
345 for (i = 0; i < 256*4; i++)
346 dat->val[i] = ival[i];
347 }
348
349 static void server_loop(int fd)
350 {
351 struct timeval snaptime = { 0 };
352 struct pollfd p;
353
354 p.fd = fd;
355 p.events = p.revents = POLLIN;
356
357 sprintf(kern_db->signature,
358 "%u.%lu sampling_interval=%d time_const=%d",
359 (unsigned int) getpid(), (unsigned long)random(),
360 scan_interval/1000, time_constant/1000);
361
362 pad_kern_table(kern_db, read_kern_table(kern_db->ival));
363
364 for (;;) {
365 int status;
366 int tdiff;
367 struct timeval now;
368
369 gettimeofday(&now, NULL);
370 tdiff = T_DIFF(now, snaptime);
371 if (tdiff >= scan_interval) {
372 update_db(tdiff);
373 snaptime = now;
374 tdiff = 0;
375 }
376 if (poll(&p, 1, tdiff + scan_interval) > 0
377 && (p.revents&POLLIN)) {
378 int clnt = accept(fd, NULL, NULL);
379
380 if (clnt >= 0) {
381 pid_t pid;
382
383 if (children >= 5) {
384 close(clnt);
385 } else if ((pid = fork()) != 0) {
386 if (pid > 0)
387 children++;
388 close(clnt);
389 } else {
390 if (tdiff > 0)
391 update_db(tdiff);
392 send_db(clnt);
393 exit(0);
394 }
395 }
396 }
397 while (children && waitpid(-1, &status, WNOHANG) > 0)
398 children--;
399 }
400 }
401
402 static int verify_forging(int fd)
403 {
404 struct ucred cred;
405 socklen_t olen = sizeof(cred);
406
407 if (getsockopt(fd, SOL_SOCKET, SO_PEERCRED, (void *)&cred, &olen) ||
408 olen < sizeof(cred))
409 return -1;
410 if (cred.uid == getuid() || cred.uid == 0)
411 return 0;
412 return -1;
413 }
414
415 static void usage(void) __attribute__((noreturn));
416
417 static void usage(void)
418 {
419 fprintf(stderr,
420 "Usage: rtacct [ -h?vVzrnasd:t: ] [ ListOfRealms ]\n"
421 );
422 exit(-1);
423 }
424
425 int main(int argc, char *argv[])
426 {
427 char hist_name[128];
428 struct sockaddr_un sun;
429 int ch;
430 int fd;
431
432 while ((ch = getopt(argc, argv, "h?vVzrM:nasd:t:")) != EOF) {
433 switch (ch) {
434 case 'z':
435 dump_zeros = 1;
436 break;
437 case 'r':
438 reset_history = 1;
439 break;
440 case 'a':
441 ignore_history = 1;
442 break;
443 case 's':
444 no_update = 1;
445 break;
446 case 'n':
447 no_output = 1;
448 break;
449 case 'd':
450 scan_interval = 1000*atoi(optarg);
451 break;
452 case 't':
453 if (sscanf(optarg, "%d", &time_constant) != 1 ||
454 time_constant <= 0) {
455 fprintf(stderr, "rtacct: invalid time constant divisor\n");
456 exit(-1);
457 }
458 break;
459 case 'v':
460 case 'V':
461 printf("rtacct utility, iproute2-%s\n", version);
462 exit(0);
463 case 'M':
464 /* Some secret undocumented option, nobody
465 * is expected to ask about its sense. See?
466 */
467 sscanf(optarg, "%lx", &magic_number);
468 break;
469 case 'h':
470 case '?':
471 default:
472 usage();
473 }
474 }
475
476 argc -= optind;
477 argv += optind;
478
479 if (argc) {
480 while (argc > 0) {
481 __u32 realm;
482
483 if (rtnl_rtrealm_a2n(&realm, argv[0])) {
484 fprintf(stderr, "Warning: realm \"%s\" does not exist.\n", argv[0]);
485 exit(-1);
486 }
487 rmap[realm>>5] |= (1<<(realm&0x1f));
488 argc--; argv++;
489 }
490 } else {
491 memset(rmap, ~0, sizeof(rmap));
492 /* Always suppress zeros. */
493 dump_zeros = 0;
494 }
495
496 sun.sun_family = AF_UNIX;
497 sun.sun_path[0] = 0;
498 sprintf(sun.sun_path+1, "rtacct%d", getuid());
499
500 if (scan_interval > 0) {
501 if (time_constant == 0)
502 time_constant = 60;
503 time_constant *= 1000;
504 W = 1 - 1/exp(log(10)*(double)scan_interval/time_constant);
505 if ((fd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) {
506 perror("rtacct: socket");
507 exit(-1);
508 }
509 if (bind(fd, (struct sockaddr *)&sun, 2+1+strlen(sun.sun_path+1)) < 0) {
510 perror("rtacct: bind");
511 exit(-1);
512 }
513 if (listen(fd, 5) < 0) {
514 perror("rtacct: listen");
515 exit(-1);
516 }
517 if (daemon(0, 0)) {
518 perror("rtacct: daemon");
519 exit(-1);
520 }
521 signal(SIGPIPE, SIG_IGN);
522 signal(SIGCHLD, sigchild);
523 server_loop(fd);
524 exit(0);
525 }
526
527 if (getenv("RTACCT_HISTORY"))
528 snprintf(hist_name, sizeof(hist_name), "%s", getenv("RTACCT_HISTORY"));
529 else
530 sprintf(hist_name, "/tmp/.rtacct.u%d", getuid());
531
532 if (reset_history)
533 unlink(hist_name);
534
535 if (!ignore_history || !no_update) {
536 struct stat stb;
537
538 fd = open(hist_name, O_RDWR|O_CREAT|O_NOFOLLOW, 0600);
539 if (fd < 0) {
540 perror("rtacct: open history file");
541 exit(-1);
542 }
543 if (flock(fd, LOCK_EX)) {
544 perror("rtacct: flock history file");
545 exit(-1);
546 }
547 if (fstat(fd, &stb) != 0) {
548 perror("rtacct: fstat history file");
549 exit(-1);
550 }
551 if (stb.st_nlink != 1 || stb.st_uid != getuid()) {
552 fprintf(stderr, "rtacct: something is so wrong with history file, that I prefer not to proceed.\n");
553 exit(-1);
554 }
555 if (stb.st_size != sizeof(*hist_db))
556 if (write(fd, kern_db, sizeof(*hist_db)) < 0) {
557 perror("rtacct: write history file");
558 exit(-1);
559 }
560
561 hist_db = mmap(NULL, sizeof(*hist_db),
562 PROT_READ|PROT_WRITE,
563 no_update ? MAP_PRIVATE : MAP_SHARED,
564 fd, 0);
565
566 if ((unsigned long)hist_db == ~0UL) {
567 perror("mmap");
568 exit(-1);
569 }
570
571 if (!ignore_history) {
572 FILE *tfp;
573 long uptime = -1;
574
575 if ((tfp = fopen("/proc/uptime", "r")) != NULL) {
576 if (fscanf(tfp, "%ld", &uptime) != 1)
577 uptime = -1;
578 fclose(tfp);
579 }
580
581 if (uptime >= 0 && time(NULL) >= stb.st_mtime+uptime) {
582 fprintf(stderr, "rtacct: history is aged out, resetting\n");
583 memset(hist_db, 0, sizeof(*hist_db));
584 }
585 }
586
587 close(fd);
588 }
589
590 if ((fd = socket(AF_UNIX, SOCK_STREAM, 0)) >= 0 &&
591 (connect(fd, (struct sockaddr *)&sun, 2+1+strlen(sun.sun_path+1)) == 0
592 || (strcpy(sun.sun_path+1, "rtacct0"),
593 connect(fd, (struct sockaddr *)&sun, 2+1+strlen(sun.sun_path+1)) == 0))
594 && verify_forging(fd) == 0) {
595 nread(fd, (char *)kern_db, sizeof(*kern_db));
596 if (hist_db && hist_db->signature[0] &&
597 strcmp(kern_db->signature, hist_db->signature)) {
598 fprintf(stderr, "rtacct: history is stale, ignoring it.\n");
599 hist_db = NULL;
600 }
601 close(fd);
602 } else {
603 if (fd >= 0)
604 close(fd);
605
606 if (hist_db && hist_db->signature[0] &&
607 strcmp(hist_db->signature, "kernel")) {
608 fprintf(stderr, "rtacct: history is stale, ignoring it.\n");
609 hist_db = NULL;
610 }
611
612 pad_kern_table(kern_db, read_kern_table(kern_db->ival));
613 strcpy(kern_db->signature, "kernel");
614 }
615
616 if (ignore_history || hist_db == NULL)
617 dump_abs_db(stdout);
618 else
619 dump_incr_db(stdout);
620
621 exit(0);
622 }