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