-
Notifications
You must be signed in to change notification settings - Fork 0
/
fnotifystat.c
1672 lines (1480 loc) · 36.6 KB
/
fnotifystat.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (C) 2014-2021 Canonical, Ltd.
* Copyright (C) 2021-2025 Colin Ian King.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
* Author: Colin Ian King <[email protected]>
*/
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <inttypes.h>
#include <string.h>
#include <stdbool.h>
#include <unistd.h>
#include <limits.h>
#include <ctype.h>
#include <errno.h>
#include <mntent.h>
#include <time.h>
#include <fcntl.h>
#include <signal.h>
#include <dirent.h>
#include <sys/fanotify.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <sys/sysmacros.h>
#include <sys/types.h>
#define TABLE_SIZE (17627) /* Best if prime */
#define BUFFER_SIZE (4096)
#define DEV_HASH_SIZE (1021)
#define OPT_VERBOSE (0x00000001) /* Verbose mode */
#define OPT_DIRNAME_STRIP (0x00000002) /* Remove leading path */
#define OPT_PID (0x00000004) /* Select by PID */
#define OPT_SORT_BY_PID (0x00000008) /* Sort by PID */
#define OPT_CUMULATIVE (0x00000010) /* Gather cumulative stats */
#define OPT_TIMESTAMP (0x00000020) /* Show timestamp */
#define OPT_SCALE (0x00000040) /* scale data */
#define OPT_NOSTATS (0x00000080) /* No stats mode */
#define OPT_MERGE (0x00000100) /* Merge events */
#define OPT_DEVICE (0x00000200) /* Stats by mount */
#define OPT_INODE (0x00000400) /* Filenames by inode, dev */
#define OPT_FORCE (0x00000800) /* Force output */
#define OPT_SORT_BY_READS (0x00001000) /* Sort by reads */
#define OPT_SORT_BY_WRITES (0x00002000) /* Sort by writes */
#define PROC_CACHE_LIFE (120) /* Refresh cached pid info timeout */
#define CMD_UNKNOWN "<unknown>"
/* fnotify file activity stats */
typedef struct file_stat {
uint64_t open; /* Count of opens */
uint64_t close; /* Count of closes */
uint64_t read; /* Count of reads */
uint64_t write; /* Count of writes */
uint64_t total; /* Total count */
char *path; /* Pathname of file */
struct file_stat *next; /* Next item in hash list */
pid_t pid; /* PID of process touching file */
} file_stat_t;
/* process info */
typedef struct proc_info {
char *cmdline; /* cmdline of process */
struct proc_info *next; /* Next item in hash list */
double whence; /* When data acquired */
pid_t pid; /* pid of process */
} proc_info_t;
/* pathname list info */
typedef struct pathname_t {
char *pathname; /* Pathname */
size_t pathlen; /* Length of path */
struct pathname_t *next; /* Next in list */
} pathname_t;
/* scaling factor */
typedef struct {
const char ch; /* Scaling suffix */
const uint64_t scale; /* Amount to scale by */
} scale_t;
/* stashed context for verbose info */
typedef struct {
char *filename; /* Filename */
uint64_t mask; /* Event mask */
uint64_t count; /* Merged event count */
file_stat_t fs; /* File Info */
struct tm tm; /* Time of previous event */
bool used; /* true if been stashed before */
} stash_info_t;
/* cached dev names */
typedef struct dev_info {
char *name; /* /dev device name */
dev_t dev; /* dev number */
struct dev_info *next; /* next device */
} dev_info_t;
static const char *app_name = "fnotifystat"; /* name of this tool */
static file_stat_t *file_stats[TABLE_SIZE]; /* hash table of file stats */
static proc_info_t *proc_infos[TABLE_SIZE]; /* hash table of proc infos */
static proc_info_t *proc_list; /* processes to monitor */
static size_t file_stats_size; /* number of items in hash table */
static unsigned int opt_flags = OPT_SCALE; /* option flags */
static volatile bool stop_fnotifystat = false; /* true -> stop fnotifystat */
static pid_t my_pid; /* pid of this programme */
static bool named_procs = false;
static pathname_t *paths_include; /* paths to include */
static pathname_t *paths_exclude; /* paths to exclude */
static dev_info_t *dev_cache[DEV_HASH_SIZE]; /* device to device name hash */
/*
* Attempt to catch a range of signals so
* we can clean
*/
static const int signals[] = {
/* POSIX.1-1990 */
#ifdef SIGHUP
SIGHUP,
#endif
#ifdef SIGINT
SIGINT,
#endif
#ifdef SIGQUIT
SIGQUIT,
#endif
#ifdef SIGFPE
SIGFPE,
#endif
#ifdef SIGTERM
SIGTERM,
#endif
#ifdef SIGUSR1
SIGUSR1,
#endif
#ifdef SIGUSR2
SIGUSR2,
/* POSIX.1-2001 */
#endif
#ifdef SIGXCPU
SIGXCPU,
#endif
#ifdef SIGXFSZ
SIGXFSZ,
#endif
/* Linux various */
#ifdef SIGIOT
SIGIOT,
#endif
#ifdef SIGSTKFLT
SIGSTKFLT,
#endif
#ifdef SIGPWR
SIGPWR,
#endif
#ifdef SIGINFO
SIGINFO,
#endif
#ifdef SIGVTALRM
SIGVTALRM,
#endif
-1,
};
/* Time scaling factors */
static const scale_t time_scales[] = {
{ 's', 1 },
{ 'm', 60 },
{ 'h', 3600 },
{ 'd', 24 * 3600 },
{ 'w', 7 * 24 * 3600 },
{ 'y', 365 * 24 * 3600 },
};
/*
* popcount()
* population count (count number of 1 bits) in an unsigned int
*/
static inline int popcount(const unsigned int val)
{
/* Brian Kernighan's count bits */
int j;
unsigned int v = val;
for (j = 0; v; j++)
v &= v - 1;
return j;
}
/*
* dev_hash()
* hash a device number
*/
static inline int dev_hash(const dev_t dev)
{
const int hash = (major(dev) << 16) | minor(dev);
return hash % DEV_HASH_SIZE;
}
/*
* dev_find()
* find a device by dev number in the device cache
*/
static char *dev_find(const dev_t dev)
{
const int hash = dev_hash(dev);
dev_info_t *d = dev_cache[hash];
while (d) {
if (d->dev == dev)
return d->name;
d = d->next;
}
return NULL;
}
/*
* dev_add()
* add a device to the device cache
*/
static void dev_add(const char *name, const dev_t dev)
{
const int hash = dev_hash(dev);
dev_info_t *d = dev_cache[hash];
/* Don't and if we already have it */
while (d) {
if (d->dev == dev)
return;
d = d->next;
}
d = malloc(sizeof(*d));
if (!d)
return;
d->name = strdup(name);
if (!d->name) {
free(d);
return;
}
d->dev = dev;
d->next = dev_cache[hash];
dev_cache[hash] = d;
}
/*
* dev_cache_mounts()
* add dev number of mount points too
*/
static void dev_cache_mounts(void)
{
FILE *fp;
char buffer[1024];
fp = fopen("/proc/mounts", "r");
if (!fp)
return;
while (fgets(buffer, sizeof(buffer), fp)) {
struct stat statbuf;
char *ptr = buffer;
char *path;
while (*ptr && *ptr != ' ' && *ptr != '\n')
ptr++;
if (!*ptr)
continue;
ptr++;
path = ptr;
while (*ptr && *ptr != ' ' && *ptr != '\n')
ptr++;
*ptr = '\0';
if (stat(path, &statbuf) < 0)
continue;
dev_add(path, statbuf.st_dev);
}
(void)fclose(fp);
}
/*
* dev_cache_devs()
* cache the device name of devices based on device number
*/
static void dev_cache_devs(const char *dev_path, const int depth, const int max_depth)
{
DIR *dir;
struct dirent *dirp;
dir = opendir(dev_path);
if (!dir)
return;
while ((dirp = readdir(dir)) != NULL) {
struct stat statbuf;
char path[PATH_MAX];
if (dirp->d_name[0] == '.')
continue;
snprintf(path, sizeof(path), "%s/%s", dev_path, dirp->d_name);
if (stat(path, &statbuf) < 0)
continue;
/* Symlink, ignore */
if ((statbuf.st_mode & S_IFMT) == S_IFLNK)
continue;
if ((depth < max_depth) && ((statbuf.st_mode & S_IFMT) == S_IFDIR)) {
dev_cache_devs(path, depth + 1, max_depth);
continue;
}
/* Not a block dev, ignore */
if ((statbuf.st_mode & S_IFMT) != S_IFBLK)
continue;
dev_add(path, statbuf.st_rdev);
}
(void)closedir(dir);
}
/*
* dev_cache_free()
* free the device cache
*/
static void dev_cache_free(void)
{
size_t i;
for (i = 0; i < DEV_HASH_SIZE; i++) {
dev_info_t *d = dev_cache[i];
while (d) {
dev_info_t *next = d->next;
free(d->name);
free(d);
d = next;
}
}
}
/*
* dev_name()
* find the name relating to a device number
*/
static char *dev_name(const dev_t dev)
{
static char buffer[256];
char devstr[32];
char *devname = dev_find(dev);
snprintf(devstr, sizeof(devstr), "%u:%u", major(dev), minor(dev));
snprintf(buffer, sizeof(buffer), "%-10.10s%s%s",
devstr, devname ? " " : "", devname ? devname : "");
return buffer;
}
/*
* pid_max_digits()
* determine (or guess) maximum digits of pids
*/
static int pid_max_digits(void)
{
static int max_digits;
ssize_t n;
int fd;
const int default_digits = 6;
const int min_digits = 5;
char buf[32];
if (max_digits)
goto ret;
max_digits = default_digits;
fd = open("/proc/sys/kernel/pid_max", O_RDONLY);
if (fd < 0)
goto ret;
n = read(fd, buf, sizeof(buf) - 1);
(void)close(fd);
if (n < 0)
goto ret;
buf[n] = '\0';
max_digits = 0;
while ((max_digits < n) && (buf[max_digits] >= '0') && (buf[max_digits] <= '9'))
max_digits++;
if (max_digits < min_digits)
max_digits = min_digits;
ret:
return max_digits;
}
/*
* handle_siginfo()
* catch SIGUSR1, toggle verbose mode
*/
static void handle_sigusr1(int dummy)
{
(void)dummy;
opt_flags ^= OPT_VERBOSE;
}
/*
* get_double()
* get a double value
*/
static double get_double(const char *const str, size_t *const len)
{
double val;
*len = strlen(str);
errno = 0;
val = strtod(str, NULL);
if (errno) {
(void)fprintf(stderr, "Invalid value %s.\n", str);
exit(EXIT_FAILURE);
}
if (*len == 0) {
(void)fprintf(stderr, "Value %s is an invalid size.\n", str);
exit(EXIT_FAILURE);
}
return val;
}
/*
* get_double_scale()
* get a value and scale it by the given scale factor
*/
static double get_double_scale(
const char *const str,
const scale_t scales[],
const char *const msg)
{
double val;
size_t len = strlen(str);
int i;
char ch;
val = get_double(str, &len);
len--;
ch = str[len];
if (val < 0.0) {
(void)printf("Value %s cannot be negative\n", str);
exit(EXIT_FAILURE);
}
if (isdigit(ch) || ch == '.')
return val;
ch = tolower(ch);
for (i = 0; scales[i].ch; i++) {
if (ch == scales[i].ch)
return val * scales[i].scale;
}
(void)printf("Illegal %s specifier %c\n", msg, str[len]);
exit(EXIT_FAILURE);
}
/*
* get_seconds()
* get time in seconds, with scaling suffix support.
*/
static inline double get_seconds(const char *const str)
{
return get_double_scale(str, time_scales, "time");
}
/*
* count_to_str()
* double precision count values to strings
*/
static char *count_to_str(
const double val,
char *const buf,
const size_t buflen)
{
double v = val;
static const char scales[] = " KMB";
if (opt_flags & OPT_SCALE) {
size_t i;
for (i = 0; i < sizeof(scales) - 1; i++, v /= 1000) {
if (v <= 500)
break;
}
(void)snprintf(buf, buflen, "%5.1f%c", v, scales[i]);
} else {
(void)snprintf(buf, buflen, "%6.1f", v);
}
return buf;
}
/*
* timeval_to_double()
* convert timeval to seconds as a double
*/
static double timeval_to_double(void)
{
struct timeval tv;
redo:
errno = 0; /* clear to be safe */
if (gettimeofday(&tv, NULL) < 0) {
if (errno == EINTR) /* should not occur */
goto redo;
/* Silently fail */
return -1.0;
}
return (double)tv.tv_sec + ((double)tv.tv_usec / 1000000.0);
}
/*
* get_tm()
* fetch tm, will set fields to zero if can't get
*/
static void get_tm(struct tm *tm)
{
time_t now = time(NULL);
if (now == ((time_t) -1)) {
(void)memset(tm, 0, sizeof(struct tm));
} else {
(void)localtime_r(&now, tm);
}
}
/*
* pr_error()
* print error message and exit fatally
*/
static void __attribute__ ((noreturn)) pr_error(const char *msg)
{
(void)fprintf(stderr, "Fatal error: %s: errno=%d (%s)\n",
msg, errno, strerror(errno));
exit(EXIT_FAILURE);
}
/*
* pr_nomem()
* print out of memory error and exit fatally
*/
static void __attribute__ ((noreturn)) pr_nomem(const char *msg)
{
(void)fprintf(stderr, "Fatal error: out of memory: %s\n", msg);
exit(EXIT_FAILURE);
}
/*
* get_pid_cmdline
* get process's /proc/pid/cmdline
*/
static char *get_pid_cmdline(const pid_t pid)
{
char buffer[BUFFER_SIZE];
int fd;
ssize_t ret = 0;
*buffer = '\0';
(void)snprintf(buffer, sizeof(buffer), "/proc/%d/cmdline", pid);
if ((fd = open(buffer, O_RDONLY)) > -1) {
ret = read(fd, buffer, sizeof(buffer) - 1);
(void)close(fd);
if (ret > -1)
buffer[ret] = '\0';
}
/*
* No cmdline, could be a kernel thread, so get the comm
* field instead
*/
if (!*buffer) {
(void)snprintf(buffer, sizeof(buffer), "/proc/%d/comm", pid);
if ((fd = open(buffer, O_RDONLY)) > -1) {
ret = read(fd, buffer, sizeof(buffer) - 1);
(void)close(fd);
if (ret > 0)
buffer[ret - 1] = '\0'; /* remove trailing \n */
}
}
if (ret < 1) {
(void)strncpy(buffer, "<unknown>", sizeof(buffer));
} else {
char *ptr;
for (ptr = buffer; *ptr && (ptr < buffer + ret); ptr++) {
if (*ptr == ' ') {
*ptr = '\0';
break;
}
}
}
return strdup(basename(buffer));
}
/*
* handle_sig()
* catch signals and flag a stop
*/
static void handle_sig(int dummy)
{
(void)dummy; /* Stop unused parameter warning with -Wextra */
stop_fnotifystat = true;
}
/*
* timeval_double()
* timeval to a double
*/
static inline double timeval_double(const struct timeval *tv)
{
return (double)tv->tv_sec + ((double)tv->tv_usec / 1000000.0);
}
/*
* hash_djb2a()
* Hash a string, from Dan Bernstein comp.lang.c (xor version)
*/
static uint32_t hash_djb2a(const char *str, const pid_t pid)
{
register uint32_t hash = 5381 + pid;
register int c;
while ((c = *str++)) {
/* (hash * 33) ^ c */
hash = ((hash << 5) + hash) ^ c;
}
return hash % TABLE_SIZE;
}
/*
* proc_info_get()
* get info about a specific process
*/
static proc_info_t *proc_info_get(const pid_t pid)
{
const unsigned long h = pid % TABLE_SIZE;
proc_info_t *pi = proc_infos[h];
while (pi) {
if (pi->pid == pid) {
double now = timeval_to_double();
char *cmdline;
/* Name lookup failed last time, try again */
if (!strcmp(pi->cmdline, CMD_UNKNOWN)) {
free(pi->cmdline);
goto update;
}
if (now < pi->whence + PROC_CACHE_LIFE)
return pi;
if ((cmdline = get_pid_cmdline(pid)) == NULL)
pr_nomem("allocating process command line");
if (!strcmp(pi->cmdline, CMD_UNKNOWN)) {
/* It's probably died, so no new process name */
free(cmdline);
return pi;
}
/* Deemed "stale", so refresh stats */
free(pi->cmdline);
pi->cmdline = cmdline;
pi->whence = timeval_to_double();
return pi;
}
pi = pi->next;
}
if ((pi = calloc(1, sizeof(*pi))) == NULL)
pr_nomem("allocating process information");
pi->next = proc_infos[h];
proc_infos[h] = pi;
pi->pid = pid;
update:
if ((pi->cmdline = get_pid_cmdline(pid)) == NULL)
pr_nomem("allocating process command line");
pi->whence = timeval_to_double();
return pi;
}
/*
* proc_info_get_all()
* get and cache all processes
*/
static void proc_info_get_all(void)
{
DIR *dir;
struct dirent *dirp;
dir = opendir("/proc");
if (dir == NULL) {
(void)fprintf(stderr, "Cannot open /proc, is it mounted?\n");
exit(EXIT_FAILURE);
}
while ((dirp = readdir(dir)) != NULL) {
if (isdigit(dirp->d_name[0])) {
pid_t pid = atoi(dirp->d_name);
(void)proc_info_get(pid);
}
}
(void)closedir(dir);
}
/*
* proc_list_free()
* free proc list
*/
static void proc_list_free(proc_info_t **list)
{
proc_info_t *pi = *list;
while (pi) {
proc_info_t *next = pi->next;
free(pi->cmdline);
free(pi);
pi = next;
}
*list = NULL;
}
/*
* proc_info_free()
* free process info
*/
static void proc_info_free(void)
{
int i;
for (i = 0; i < TABLE_SIZE; i++)
proc_list_free(&proc_infos[i]);
}
/*
* file_stat_free()
* free file stats hash table
*/
static void file_stat_free(void)
{
int i;
for (i = 0; i < TABLE_SIZE; i++) {
file_stat_t *fs = file_stats[i];
while (fs) {
file_stat_t *next = fs->next;
free(fs->path);
free(fs);
fs = next;
}
file_stats[i] = NULL;
}
}
/*
* file_stat_get()
* get file stats on a file touched by a given process by PID.
* existing stats are returned, new stats are allocated and returned.
*/
static file_stat_t *file_stat_get(const char *str, const pid_t pid)
{
const unsigned long h = hash_djb2a(str, pid);
file_stat_t *fs = file_stats[h];
while (fs) {
if (!strcmp(str, fs->path) && (pid == fs->pid))
return fs;
fs = fs->next;
}
if ((fs = calloc(1, sizeof(*fs))) == NULL)
pr_nomem("allocating file stats");
if ((fs->path = strdup(str)) == NULL) {
free(fs);
pr_nomem("allocating file stats pathname");
}
fs->next = file_stats[h];
fs->pid = pid;
file_stats[h] = fs;
file_stats_size++;
return fs;
}
/*
* filter_out()
* return true if pathname is excluded and not included
* - excludes takes higher priority over includes
*/
static bool filter_out(const char *pathname)
{
pathname_t *pe;
/* Check if pathname is on exclude list */
for (pe = paths_exclude; pe; pe = pe->next) {
if (!strncmp(pe->pathname, pathname, pe->pathlen))
return true;
}
/* No include list, assume include all */
if (!paths_include)
return false;
/* Check if pathname is on the include list */
for (pe = paths_include; pe; pe = pe->next) {
if (!strncmp(pe->pathname, pathname, pe->pathlen))
return false;
}
return true;
}
/*
* mark()
* add a new fanotify mask
*/
static int mark(int fan_fd, const char *pathname, int *count)
{
int ret;
ret = fanotify_mark(fan_fd, FAN_MARK_ADD | FAN_MARK_MOUNT,
FAN_ACCESS| FAN_MODIFY | FAN_OPEN | FAN_CLOSE |
FAN_ONDIR | FAN_EVENT_ON_CHILD, AT_FDCWD, pathname);
if (ret >= 0) {
(*count)++;
return 0;
}
return -1;
}
/*
* fnotify_event_init()
* initialize fnotify
*/
static int fnotify_event_init(void)
{
int fan_fd, count = 0;
FILE* mounts;
struct mntent* mount;
if ((fan_fd = fanotify_init(0, 0)) < 0)
pr_error("cannot initialize fanotify");
/* No paths given, do all mount points */
if ((mounts = setmntent("/proc/self/mounts", "r")) == NULL) {
(void)close(fan_fd);
pr_error("setmntent cannot get mount points from /proc/self/mounts");
}
/*
* Gather all mounted file systems and monitor them
*/
while ((mount = getmntent(mounts)) != NULL)
(void)mark(fan_fd, mount->mnt_dir, &count);
if (endmntent(mounts) < 0) {
(void)close(fan_fd);
pr_error("endmntent failed");
}
/* This really should not happen, / is always mounted */
if (!count) {
(void)fprintf(stderr, "no mount points could be monitored\n");
(void)close(fan_fd);
exit(EXIT_FAILURE);
}
return fan_fd;
}
/*
* fnotify_get_filename()
* look up a in-use file descriptor from a given pid
* and find the associated filename
*/
static char *fnotify_get_filename(const pid_t pid, const int fd)
{
char buf[256];
char path[PATH_MAX];
ssize_t len;
char *filename;
/*
* With fnotifies, fd of the file is added to the process
* fd array, so we just pick them up from /proc/self. Use
* a pid of -1 for self
*/
if (pid == -1)
snprintf(buf, sizeof(buf), "/proc/self/fd/%d", fd);
else
snprintf(buf, sizeof(buf), "/proc/%d/fd/%d", pid, fd);
len = readlink(buf, path, sizeof(path));
if (len < 0) {
filename = strdup("(unknown)");
} else {
if (opt_flags & OPT_INODE) {
struct stat statbuf;
if (fstat(fd, &statbuf) < 0) {
(void)snprintf(buf, sizeof(buf), "%-10.10s %11s",
"(?:?)", "?");
} else {
(void)snprintf(buf, sizeof(buf), "%11lu %s",
statbuf.st_ino, dev_name(statbuf.st_dev));
}
filename = strdup(buf);
}
else if (opt_flags & OPT_DEVICE) {
struct stat statbuf;
if (fstat(fd, &statbuf) < 0) {
(void)snprintf(buf, sizeof(buf), "?:?");
} else {
(void)snprintf(buf, sizeof(buf), "%s", dev_name(statbuf.st_dev));
}
filename = strdup(buf);
} else {
/*
* In an ideal world we should allocate the path
* based on a lstat'd size, but because this can be
* racey on has to re-check, which involves
* re-allocing the buffer. Since we need to be
* fast let's just fetch up to PATH_MAX-1 of data.
*/
path[len >= PATH_MAX ? PATH_MAX - 1 : len] = '\0';
filename = strdup(path);
}
}
return filename;
}
/*
* fnotify_mask_to_str()
* convert fnotify mask to readable string
*/
static const char *fnotify_mask_to_str(const int mask)
{
static char modes[5];
modes[0] = (mask & FAN_OPEN) ? 'O' : '-';
modes[1] = (mask & (FAN_CLOSE_WRITE | FAN_CLOSE_NOWRITE)) ? 'C' : '-';
modes[2] = (mask & FAN_ACCESS) ? 'R' : '-';
modes[3] = (mask & (FAN_MODIFY | FAN_CLOSE_WRITE)) ? 'W' : '-';
modes[4] = '\0';
return modes;
}
/*
* fnotify_stash()
* make a stashed copy of fs and stash data
*/
static void fnotify_stash(
stash_info_t *info,
file_stat_t *fs,
const uint64_t mask,
char *filename,
const struct tm *tm,
uint64_t count)
{
if (fs) {
/*
* fs needs to be copied as it can
* be free'd later on, we don't need