1FANOTIFY(7)                Linux Programmer's Manual               FANOTIFY(7)
2
3
4

NAME

6       fanotify - monitoring filesystem events
7

DESCRIPTION

9       The  fanotify  API provides notification and interception of filesystem
10       events.  Use cases include virus scanning and hierarchical storage man‐
11       agement.   Currently,  only  a  limited set of events is supported.  In
12       particular, there is no support for create, delete,  and  move  events.
13       (See inotify(7) for details of an API that does notify those events.)
14
15       Additional  capabilities  compared  to  the  inotify(7) API include the
16       ability to monitor all of the objects  in  a  mounted  filesystem,  the
17       ability  to  make  access  permission decisions, and the possibility to
18       read or modify files before access by other applications.
19
20       The following system calls are used with  this  API:  fanotify_init(2),
21       fanotify_mark(2), read(2), write(2), and close(2).
22
23   fanotify_init(), fanotify_mark(), and notification groups
24       The  fanotify_init(2)  system  call creates and initializes an fanotify
25       notification group and returns a file descriptor referring to it.
26
27       An fanotify notification group is a kernel-internal object that holds a
28       list  of files, directories, and mount points for which events shall be
29       created.
30
31       For each entry in an fanotify notification group, two bit masks  exist:
32       the  mark mask and the ignore mask.  The mark mask defines file activi‐
33       ties for which an event shall be  created.   The  ignore  mask  defines
34       activities  for  which  no  event shall be generated.  Having these two
35       types of masks permits a mount point or  directory  to  be  marked  for
36       receiving  events,  while at the same time ignoring events for specific
37       objects under that mount point or directory.
38
39       The fanotify_mark(2) system call adds a file, directory, or mount to  a
40       notification  group  and  specifies  which events shall be reported (or
41       ignored), or removes or modifies such an entry.
42
43       A possible usage of the ignore mask is for a  file  cache.   Events  of
44       interest for a file cache are modification of a file and closing of the
45       same.  Hence, the cached directory or mount point is to  be  marked  to
46       receive these events.  After receiving the first event informing that a
47       file has been modified, the corresponding cache entry will  be  invali‐
48       dated.   No  further  modification events for this file are of interest
49       until the file is closed.  Hence, the modify event can be added to  the
50       ignore  mask.   Upon receiving the close event, the modify event can be
51       removed from the ignore mask and the file cache entry can be updated.
52
53       The entries in the fanotify notification  groups  refer  to  files  and
54       directories  via  their  inode number and to mounts via their mount ID.
55       If files or directories are renamed or moved within the same mount, the
56       respective  entries  survive.   If  files or directories are deleted or
57       moved to another mount or if mounts are  unmounted,  the  corresponding
58       entries are deleted.
59
60   The event queue
61       As  events  occur on the filesystem objects monitored by a notification
62       group, the fanotify system generates events that  are  collected  in  a
63       queue.   These  events can then be read (using read(2) or similar) from
64       the fanotify file descriptor returned by fanotify_init(2).
65
66       Two types of events are generated: notification events  and  permission
67       events.   Notification  events  are  merely  informative and require no
68       action to be taken by the receiving application except for closing  the
69       file descriptor passed in the event (see below).  Permission events are
70       requests to the receiving application to decide whether permission  for
71       a  file  access shall be granted.  For these events, the recipient must
72       write a response which decides whether access is granted or not.
73
74       An event is removed from the event queue of the fanotify group when  it
75       has  been  read.   Permission events that have been read are kept in an
76       internal list of the fanotify group until either a permission  decision
77       has  been  taken by writing to the fanotify file descriptor or the fan‐
78       otify file descriptor is closed.
79
80   Reading fanotify events
81       Calling read(2) for the file descriptor  returned  by  fanotify_init(2)
82       blocks  (if  the flag FAN_NONBLOCK is not specified in the call to fan‐
83       otify_init(2)) until either a file event occurs or the call  is  inter‐
84       rupted by a signal (see signal(7)).
85
86       After a successful read(2), the read buffer contains one or more of the
87       following structures:
88
89           struct fanotify_event_metadata {
90               __u32 event_len;
91               __u8 vers;
92               __u8 reserved;
93               __u16 metadata_len;
94               __aligned_u64 mask;
95               __s32 fd;
96               __s32 pid;
97           };
98
99       For performance reasons, it is recommended to use a large  buffer  size
100       (for  example, 4096 bytes), so that multiple events can be retrieved by
101       a single read(2).
102
103       The return value of read(2) is the number of bytes placed in  the  buf‐
104       fer, or -1 in case of an error (but see BUGS).
105
106       The fields of the fanotify_event_metadata structure are as follows:
107
108       event_len
109              This  is  the  length  of the data for the current event and the
110              offset to the next event in the buffer.  In the  current  imple‐
111              mentation,  the  value  of  event_len  is always FAN_EVENT_META‐
112              DATA_LEN.  However, the API is designed to allow variable-length
113              structures to be returned in the future.
114
115       vers   This field holds a version number for the structure.  It must be
116              compared to FANOTIFY_METADATA_VERSION to verify that the  struc‐
117              tures  returned at run time match the structures defined at com‐
118              pile time.  In case of a mismatch, the application should  aban‐
119              don trying to use the fanotify file descriptor.
120
121       reserved
122              This field is not used.
123
124       metadata_len
125              This  is  the length of the structure.  The field was introduced
126              to facilitate the implementation of optional headers  per  event
127              type.  No such optional headers exist in the current implementa‐
128              tion.
129
130       mask   This is a bit mask describing the event (see below).
131
132       fd     This is an open file descriptor for the object  being  accessed,
133              or  FAN_NOFD  if a queue overflow occurred.  The file descriptor
134              can be used to access the contents  of  the  monitored  file  or
135              directory.   The  reading application is responsible for closing
136              this file descriptor.
137
138              When calling fanotify_init(2), the caller may specify  (via  the
139              event_f_flags argument) various file status flags that are to be
140              set on the open file description that corresponds to  this  file
141              descriptor.   In  addition, the (kernel-internal) FMODE_NONOTIFY
142              file status flag is set on the open file description.  This flag
143              suppresses  fanotify event generation.  Hence, when the receiver
144              of the fanotify event accesses the notified  file  or  directory
145              using  this  file  descriptor, no additional events will be cre‐
146              ated.
147
148       pid    This is the ID of the process that caused the event.  A  program
149              listening  to  fanotify  events  can compare this PID to the PID
150              returned by getpid(2), to determine whether the event is  caused
151              by  the  listener  itself, or is due to a file access by another
152              process.
153
154       The bit mask in mask indicates which events have occurred for a  single
155       filesystem object.  Multiple bits may be set in this mask, if more than
156       one event occurred for the monitored filesystem object.  In particular,
157       consecutive  events for the same filesystem object and originating from
158       the same process may be merged into a single event, with the  exception
159       that two permission events are never merged into one queue entry.
160
161       The bits that may appear in mask are as follows:
162
163       FAN_ACCESS
164              A file or a directory (but see BUGS) was accessed (read).
165
166       FAN_OPEN
167              A file or a directory was opened.
168
169       FAN_MODIFY
170              A file was modified.
171
172       FAN_CLOSE_WRITE
173              A  file  that  was  opened  for writing (O_WRONLY or O_RDWR) was
174              closed.
175
176       FAN_CLOSE_NOWRITE
177              A file or directory that was  opened  read-only  (O_RDONLY)  was
178              closed.
179
180       FAN_Q_OVERFLOW
181              The event queue exceeded the limit of 16384 entries.  This limit
182              can be overridden by  specifying  the  FAN_UNLIMITED_QUEUE  flag
183              when calling fanotify_init(2).
184
185       FAN_ACCESS_PERM
186              An  application  wants  to read a file or directory, for example
187              using read(2) or readdir(2).  The reader must write  a  response
188              (as  described  below) that determines whether the permission to
189              access the filesystem object shall be granted.
190
191       FAN_OPEN_PERM
192              An application wants to open a file or  directory.   The  reader
193              must  write a response that determines whether the permission to
194              open the filesystem object shall be granted.
195
196       To check for any close event, the following bit mask may be used:
197
198       FAN_CLOSE
199              A file was closed.  This is a synonym for:
200
201                  FAN_CLOSE_WRITE | FAN_CLOSE_NOWRITE
202
203       The following macros are provided to iterate over a  buffer  containing
204       fanotify  event  metadata  returned  by a read(2) from an fanotify file
205       descriptor:
206
207       FAN_EVENT_OK(meta, len)
208              This macro checks the remaining length len of  the  buffer  meta
209              against  the  length of the metadata structure and the event_len
210              field of the first metadata structure in the buffer.
211
212       FAN_EVENT_NEXT(meta, len)
213              This macro uses the length indicated in the event_len  field  of
214              the  metadata  structure  pointed  to  by  meta to calculate the
215              address of the next metadata structure that follows  meta.   len
216              is  the number of bytes of metadata that currently remain in the
217              buffer.  The macro returns a pointer to the next metadata struc‐
218              ture  that  follows meta, and reduces len by the number of bytes
219              in the metadata structure that has been skipped over  (i.e.,  it
220              subtracts meta->event_len from len).
221
222       In addition, there is:
223
224       FAN_EVENT_METADATA_LEN
225              This  macro  returns  the  size (in bytes) of the structure fan‐
226              otify_event_metadata.  This is the minimum size  (and  currently
227              the only size) of any event metadata.
228
229   Monitoring an fanotify file descriptor for events
230       When  an  fanotify event occurs, the fanotify file descriptor indicates
231       as readable when passed to epoll(7), poll(2), or select(2).
232
233   Dealing with permission events
234       For permission events, the application must write(2) a structure of the
235       following form to the fanotify file descriptor:
236
237           struct fanotify_response {
238               __s32 fd;
239               __u32 response;
240           };
241
242       The fields of this structure are as follows:
243
244       fd     This   is   the   file   descriptor   from  the  structure  fan‐
245              otify_event_metadata.
246
247       response
248              This field indicates whether or not  the  permission  is  to  be
249              granted.   Its  value must be either FAN_ALLOW to allow the file
250              operation or FAN_DENY to deny the file operation.
251
252       If access is denied, the requesting application call  will  receive  an
253       EPERM error.
254
255   Closing the fanotify file descriptor
256       When  all file descriptors referring to the fanotify notification group
257       are closed, the fanotify group is released and its resources are  freed
258       for  reuse by the kernel.  Upon close(2), outstanding permission events
259       will be set to allowed.
260
261   /proc/[pid]/fdinfo
262       The file /proc/[pid]/fdinfo/[fd] contains  information  about  fanotify
263       marks for file descriptor fd of process pid.  See proc(5) for details.
264

ERRORS

266       In  addition  to the usual errors for read(2), the following errors can
267       occur when reading from the fanotify file descriptor:
268
269       EINVAL The buffer is too small to hold the event.
270
271       EMFILE The per-process limit on the  number  of  open  files  has  been
272              reached.  See the description of RLIMIT_NOFILE in getrlimit(2).
273
274       ENFILE The system-wide limit on the total number of open files has been
275              reached.  See /proc/sys/fs/file-max in proc(5).
276
277       ETXTBSY
278              This error is returned by read(2)  if  O_RDWR  or  O_WRONLY  was
279              specified  in  the  event_f_flags  argument  when  calling  fan‐
280              otify_init(2) and an event occurred for a monitored file that is
281              currently being executed.
282
283       In  addition to the usual errors for write(2), the following errors can
284       occur when writing to the fanotify file descriptor:
285
286       EINVAL Fanotify access permissions are not enabled in the  kernel  con‐
287              figuration or the value of response in the response structure is
288              not valid.
289
290       ENOENT The file descriptor fd in the response structure is  not  valid.
291              This  may  occur  when  a  response for the permission event has
292              already been written.
293

VERSIONS

295       The fanotify API was introduced in version 2.6.36 of the  Linux  kernel
296       and  enabled  in  version  2.6.37.  Fdinfo support was added in version
297       3.8.
298

CONFORMING TO

300       The fanotify API is Linux-specific.
301

NOTES

303       The fanotify API is available only if the kernel  was  built  with  the
304       CONFIG_FANOTIFY  configuration  option  enabled.  In addition, fanotify
305       permission   handling   is   available   only   if   the    CONFIG_FAN‐
306       OTIFY_ACCESS_PERMISSIONS configuration option is enabled.
307
308   Limitations and caveats
309       Fanotify reports only events that a user-space program triggers through
310       the filesystem API.  As a result, it does not catch remote events  that
311       occur on network filesystems.
312
313       The  fanotify  API does not report file accesses and modifications that
314       may occur because of mmap(2), msync(2), and munmap(2).
315
316       Events for directories are created only  if  the  directory  itself  is
317       opened,  read, and closed.  Adding, removing, or changing children of a
318       marked directory does not create events  for  the  monitored  directory
319       itself.
320
321       Fanotify  monitoring of directories is not recursive: to monitor subdi‐
322       rectories under a directory, additional marks must  be  created.   (But
323       note  that  the fanotify API provides no way of detecting when a subdi‐
324       rectory has been created under a marked directory, which  makes  recur‐
325       sive monitoring difficult.)  Monitoring mounts offers the capability to
326       monitor a whole directory tree.
327
328       The event queue can overflow.  In this case, events are lost.
329

BUGS

331       Before Linux 3.19,  fallocate(2)  did  not  generate  fanotify  events.
332       Since Linux 3.19, calls to fallocate(2) generate FAN_MODIFY events.
333
334       As of Linux 3.17, the following bugs exist:
335
336       *  On  Linux,  a  filesystem  object may be accessible through multiple
337          paths, for example, a part of a filesystem may  be  remounted  using
338          the  --bind option of mount(8).  A listener that marked a mount will
339          be notified only of events that  were  triggered  for  a  filesystem
340          object using the same mount.  Any other event will pass unnoticed.
341
342       *  When an event is generated, no check is made to see whether the user
343          ID of the receiving process has authorization to read or  write  the
344          file  before  passing a file descriptor for that file.  This poses a
345          security risk, when the CAP_SYS_ADMIN capability is set for programs
346          executed by unprivileged users.
347
348       *  If  a  call  to  read(2) processes multiple events from the fanotify
349          queue and an error occurs, the return value will be the total length
350          of  the  events  successfully copied to the user-space buffer before
351          the error occurred.  The return value will not be -1, and errno will
352          not  be set.  Thus, the reading application has no way to detect the
353          error.
354

EXAMPLE

356       The following program demonstrates the usage of the fanotify  API.   It
357       marks  the  mount point passed as a command-line argument and waits for
358       events of type FAN_PERM_OPEN and FAN_CLOSE_WRITE.   When  a  permission
359       event occurs, a FAN_ALLOW response is given.
360
361       The   following   output   was   recorded   while   editing   the  file
362       /home/user/temp/notes.  Before the file  was  opened,  a  FAN_OPEN_PERM
363       event  occurred.   After  the  file was closed, a FAN_CLOSE_WRITE event
364       occurred.  Execution of the program ends  when  the  user  presses  the
365       ENTER key.
366
367   Example output
368           # ./fanotify_example /home
369           Press enter key to terminate.
370           Listening for events.
371           FAN_OPEN_PERM: File /home/user/temp/notes
372           FAN_CLOSE_WRITE: File /home/user/temp/notes
373
374           Listening for events stopped.
375
376   Program source
377
378       #define _GNU_SOURCE     /* Needed to get O_LARGEFILE definition */
379       #include <errno.h>
380       #include <fcntl.h>
381       #include <limits.h>
382       #include <poll.h>
383       #include <stdio.h>
384       #include <stdlib.h>
385       #include <sys/fanotify.h>
386       #include <unistd.h>
387
388       /* Read all available fanotify events from the file descriptor 'fd' */
389
390       static void
391       handle_events(int fd)
392       {
393           const struct fanotify_event_metadata *metadata;
394           struct fanotify_event_metadata buf[200];
395           ssize_t len;
396           char path[PATH_MAX];
397           ssize_t path_len;
398           char procfd_path[PATH_MAX];
399           struct fanotify_response response;
400
401           /* Loop while events can be read from fanotify file descriptor */
402
403           for(;;) {
404
405               /* Read some events */
406
407               len = read(fd, (void *) &buf, sizeof(buf));
408               if (len == -1 && errno != EAGAIN) {
409                   perror("read");
410                   exit(EXIT_FAILURE);
411               }
412
413               /* Check if end of available data reached */
414
415               if (len <= 0)
416                   break;
417
418               /* Point to the first event in the buffer */
419
420               metadata = buf;
421
422               /* Loop over all events in the buffer */
423
424               while (FAN_EVENT_OK(metadata, len)) {
425
426                   /* Check that run-time and compile-time structures match */
427
428                   if (metadata->vers != FANOTIFY_METADATA_VERSION) {
429                       fprintf(stderr,
430                               "Mismatch of fanotify metadata version.\n");
431                       exit(EXIT_FAILURE);
432                   }
433
434                   /* metadata->fd contains either FAN_NOFD, indicating a
435                      queue overflow, or a file descriptor (a nonnegative
436                      integer). Here, we simply ignore queue overflow. */
437
438                   if (metadata->fd >= 0) {
439
440                       /* Handle open permission event */
441
442                       if (metadata->mask & FAN_OPEN_PERM) {
443                           printf("FAN_OPEN_PERM: ");
444
445                           /* Allow file to be opened */
446
447                           response.fd = metadata->fd;
448                           response.response = FAN_ALLOW;
449                           write(fd, &response,
450                                 sizeof(struct fanotify_response));
451                       }
452
453                       /* Handle closing of writable file event */
454
455                       if (metadata->mask & FAN_CLOSE_WRITE)
456                           printf("FAN_CLOSE_WRITE: ");
457
458                       /* Retrieve and print pathname of the accessed file */
459
460                       snprintf(procfd_path, sizeof(procfd_path),
461                                "/proc/self/fd/%d", metadata->fd);
462                       path_len = readlink(procfd_path, path,
463                                           sizeof(path) - 1);
464                       if (path_len == -1) {
465                           perror("readlink");
466                           exit(EXIT_FAILURE);
467                       }
468
469                       path[path_len] = '\0';
470                       printf("File %s\n", path);
471
472                       /* Close the file descriptor of the event */
473
474                       close(metadata->fd);
475                   }
476
477                   /* Advance to next event */
478
479                   metadata = FAN_EVENT_NEXT(metadata, len);
480               }
481           }
482       }
483
484       int
485       main(int argc, char *argv[])
486       {
487           char buf;
488           int fd, poll_num;
489           nfds_t nfds;
490           struct pollfd fds[2];
491
492           /* Check mount point is supplied */
493
494           if (argc != 2) {
495               fprintf(stderr, "Usage: %s MOUNT\n", argv[0]);
496               exit(EXIT_FAILURE);
497           }
498
499           printf("Press enter key to terminate.\n");
500
501           /* Create the file descriptor for accessing the fanotify API */
502
503           fd = fanotify_init(FAN_CLOEXEC | FAN_CLASS_CONTENT | FAN_NONBLOCK,
504                              O_RDONLY | O_LARGEFILE);
505           if (fd == -1) {
506               perror("fanotify_init");
507               exit(EXIT_FAILURE);
508           }
509
510           /* Mark the mount for:
511              - permission events before opening files
512              - notification events after closing a write-enabled
513                file descriptor */
514
515           if (fanotify_mark(fd, FAN_MARK_ADD | FAN_MARK_MOUNT,
516                             FAN_OPEN_PERM | FAN_CLOSE_WRITE, AT_FDCWD,
517                             argv[1]) == -1) {
518               perror("fanotify_mark");
519               exit(EXIT_FAILURE);
520           }
521
522           /* Prepare for polling */
523
524           nfds = 2;
525
526           /* Console input */
527
528           fds[0].fd = STDIN_FILENO;
529           fds[0].events = POLLIN;
530
531           /* Fanotify input */
532
533           fds[1].fd = fd;
534           fds[1].events = POLLIN;
535
536           /* This is the loop to wait for incoming events */
537
538           printf("Listening for events.\n");
539
540           while (1) {
541               poll_num = poll(fds, nfds, -1);
542               if (poll_num == -1) {
543                   if (errno == EINTR)     /* Interrupted by a signal */
544                       continue;           /* Restart poll() */
545
546                   perror("poll");         /* Unexpected error */
547                   exit(EXIT_FAILURE);
548               }
549
550               if (poll_num > 0) {
551                   if (fds[0].revents & POLLIN) {
552
553                       /* Console input is available: empty stdin and quit */
554
555                       while (read(STDIN_FILENO, &buf, 1) > 0 && buf != '\n')
556                           continue;
557                       break;
558                   }
559
560                   if (fds[1].revents & POLLIN) {
561
562                       /* Fanotify events are available */
563
564                       handle_events(fd);
565                   }
566               }
567           }
568
569           printf("Listening for events stopped.\n");
570           exit(EXIT_SUCCESS);
571       }
572

SEE ALSO

574       fanotify_init(2), fanotify_mark(2), inotify(7)
575

COLOPHON

577       This page is part of release 4.16 of the Linux man-pages project.  A
578       description of the project, information about reporting bugs, and the
579       latest version of this page, can be found at
580       https://www.kernel.org/doc/man-pages/.
581
582
583
584Linux                             2017-09-15                       FANOTIFY(7)
Impressum