1 .\" Copyright (C) 2013, Heinrich Schuchardt <xypron.glpk@gmx.de>
2 .\" and Copyright (C) 2014, Michael Kerrisk <mtk.manpages@gmail.com>
4 .\" %%%LICENSE_START(VERBATIM)
5 .\" Permission is granted to make and distribute verbatim copies of this
6 .\" manual provided the copyright notice and this permission notice are
7 .\" preserved on all copies.
9 .\" Permission is granted to copy and distribute modified versions of
10 .\" this manual under the conditions for verbatim copying, provided that
11 .\" the entire resulting derived work is distributed under the terms of
12 .\" a permission notice identical to this one.
14 .\" Since the Linux kernel and libraries are constantly changing, this
15 .\" manual page may be incorrect or out-of-date. The author(s) assume.
16 .\" no responsibility for errors or omissions, or for damages resulting.
17 .\" from the use of the information contained herein. The author(s) may.
18 .\" not have taken the same level of care in the production of this.
19 .\" manual, which is licensed free of charge, as they might when working.
22 .\" Formatted or processed versions of this manual, if unaccompanied by
23 .\" the source, must acknowledge the copyright and authors of this work.
25 .TH FANOTIFY 7 2016-03-15 "Linux" "Linux Programmer's Manual"
27 fanotify \- monitoring filesystem events
29 The fanotify API provides notification and interception of
31 Use cases include virus scanning and hierarchical storage management.
32 Currently, only a limited set of events is supported.
33 In particular, there is no support for create, delete, and move events.
36 for details of an API that does notify those events.)
38 Additional capabilities compared to the
40 API include the ability to monitor all of the objects
41 in a mounted filesystem,
42 the ability to make access permission decisions, and the
43 possibility to read or modify files before access by other applications.
45 The following system calls are used with this API:
46 .BR fanotify_init (2),
47 .BR fanotify_mark (2),
52 .SS fanotify_init(), fanotify_mark(), and notification groups
55 system call creates and initializes an fanotify notification group
56 and returns a file descriptor referring to it.
58 An fanotify notification group is a kernel-internal object that holds
59 a list of files, directories, and mount points for which events shall be
62 For each entry in an fanotify notification group, two bit masks exist: the
67 The mark mask defines file activities for which an event shall be created.
68 The ignore mask defines activities for which no event shall be generated.
69 Having these two types of masks permits a mount point or directory to be
70 marked for receiving events, while at the same time ignoring events for
71 specific objects under that mount point or directory.
75 system call adds a file, directory, or mount to a notification group
76 and specifies which events
77 shall be reported (or ignored), or removes or modifies such an entry.
79 A possible usage of the ignore mask is for a file cache.
80 Events of interest for a file cache are modification of a file and closing
82 Hence, the cached directory or mount point is to be marked to receive these
84 After receiving the first event informing that a file has been modified,
85 the corresponding cache entry will be invalidated.
86 No further modification events for this file are of interest until the file
88 Hence, the modify event can be added to the ignore mask.
89 Upon receiving the close event, the modify event can be removed from the
90 ignore mask and the file cache entry can be updated.
92 The entries in the fanotify notification groups refer to files and
93 directories via their inode number and to mounts via their mount ID.
94 If files or directories are renamed or moved within the same mount,
95 the respective entries survive.
96 If files or directories are deleted or moved to another mount or if mounts are
97 unmounted, the corresponding entries are deleted.
99 As events occur on the filesystem objects monitored by a notification group,
100 the fanotify system generates events that are collected in a queue.
101 These events can then be read (using
104 from the fanotify file descriptor
106 .BR fanotify_init (2).
108 Two types of events are generated:
113 Notification events are merely informative
114 and require no action to be taken by
115 the receiving application except for closing the file descriptor passed
116 in the event (see below).
117 Permission events are requests to the receiving application to decide
118 whether permission for a file access shall be granted.
119 For these events, the recipient must write a response which decides whether
120 access is granted or not.
122 An event is removed from the event queue of the fanotify group
123 when it has been read.
124 Permission events that have been read are kept in an internal list of the
125 fanotify group until either a permission decision has been taken by
126 writing to the fanotify file descriptor or the fanotify file descriptor
128 .SS Reading fanotify events
131 for the file descriptor returned by
132 .BR fanotify_init (2)
135 is not specified in the call to
136 .BR fanotify_init (2))
137 until either a file event occurs or the call is interrupted by a signal
143 the read buffer contains one or more of the following structures:
147 struct fanotify_event_metadata {
159 For performance reasons, it is recommended to use a large
160 buffer size (for example, 4096 bytes),
161 so that multiple events can be retrieved by a single
166 is the number of bytes placed in the buffer,
167 or \-1 in case of an error (but see BUGS).
170 .I fanotify_event_metadata
171 structure are as follows:
174 This is the length of the data for the current event and the offset
175 to the next event in the buffer.
176 In the current implementation, the value of
179 .BR FAN_EVENT_METADATA_LEN .
180 However, the API is designed to allow
181 variable-length structures to be returned in the future.
184 This field holds a version number for the structure.
185 It must be compared to
186 .B FANOTIFY_METADATA_VERSION
187 to verify that the structures returned at runtime match
188 the structures defined at compile time.
189 In case of a mismatch, the application should abandon trying to use the
190 fanotify file descriptor.
193 This field is not used.
196 This is the length of the structure.
197 The field was introduced to facilitate the implementation of
198 optional headers per event type.
199 No such optional headers exist in the current implementation.
202 This is a bit mask describing the event (see below).
205 This is an open file descriptor for the object being accessed, or
207 if a queue overflow occurred.
208 The file descriptor can be used to access the contents
209 of the monitored file or directory.
210 The reading application is responsible for closing this file descriptor.
213 .BR fanotify_init (2),
214 the caller may specify (via the
216 argument) various file status flags that are to be set
217 on the open file description that corresponds to this file descriptor.
218 In addition, the (kernel-internal)
220 file status flag is set on the open file description.
221 This flag suppresses fanotify event generation.
222 Hence, when the receiver of the fanotify event accesses the notified file or
223 directory using this file descriptor, no additional events will be created.
226 This is the ID of the process that caused the event.
227 A program listening to fanotify events can compare this PID
228 to the PID returned by
230 to determine whether the event is caused by the listener itself,
231 or is due to a file access by another process.
235 indicates which events have occurred for a single filesystem object.
236 Multiple bits may be set in this mask,
237 if more than one event occurred for the monitored filesystem object.
239 consecutive events for the same filesystem object and originating from the
240 same process may be merged into a single event, with the exception that two
241 permission events are never merged into one queue entry.
243 The bits that may appear in
248 A file or a directory (but see BUGS) was accessed (read).
251 A file or a directory was opened.
257 A file that was opened for writing
264 A file or directory that was opened read-only
269 The event queue exceeded the limit of 16384 entries.
270 This limit can be overridden by specifying the
271 .BR FAN_UNLIMITED_QUEUE
273 .BR fanotify_init (2).
276 An application wants to read a file or directory, for example using
280 The reader must write a response (as described below)
281 that determines whether the permission to
282 access the filesystem object shall be granted.
285 An application wants to open a file or directory.
286 The reader must write a response that determines whether the permission to
287 open the filesystem object shall be granted.
289 To check for any close event, the following bit mask may be used:
293 This is a synonym for:
295 FAN_CLOSE_WRITE | FAN_CLOSE_NOWRITE
297 The following macros are provided to iterate over a buffer containing
298 fanotify event metadata returned by a
300 from an fanotify file descriptor:
302 .B FAN_EVENT_OK(meta, len)
303 This macro checks the remaining length
307 against the length of the metadata structure and the
309 field of the first metadata structure in the buffer.
311 .B FAN_EVENT_NEXT(meta, len)
312 This macro uses the length indicated in the
314 field of the metadata structure pointed to by
316 to calculate the address of the next metadata structure that follows
319 is the number of bytes of metadata that currently remain in the buffer.
320 The macro returns a pointer to the next metadata structure that follows
324 by the number of bytes in the metadata structure that
325 has been skipped over (i.e., it subtracts
330 In addition, there is:
332 .B FAN_EVENT_METADATA_LEN
333 This macro returns the size (in bytes) of the structure
334 .IR fanotify_event_metadata .
335 This is the minimum size (and currently the only size) of any event metadata.
337 .SS Monitoring an fanotify file descriptor for events
338 When an fanotify event occurs, the fanotify file descriptor indicates as
339 readable when passed to
344 .SS Dealing with permission events
345 For permission events, the application must
347 a structure of the following form to the
348 fanotify file descriptor:
352 struct fanotify_response {
359 The fields of this structure are as follows:
362 This is the file descriptor from the structure
363 .IR fanotify_event_metadata .
366 This field indicates whether or not the permission is to be granted.
367 Its value must be either
369 to allow the file operation or
371 to deny the file operation.
373 If access is denied, the requesting application call will receive an
376 .SS Closing the fanotify file descriptor
378 When all file descriptors referring to the fanotify notification group are
379 closed, the fanotify group is released and its resources
380 are freed for reuse by the kernel.
383 outstanding permission events will be set to allowed.
384 .SS /proc/[pid]/fdinfo
386 .I /proc/[pid]/fdinfo/[fd]
387 contains information about fanotify marks for file descriptor
395 In addition to the usual errors for
397 the following errors can occur when reading from the
398 fanotify file descriptor:
401 The buffer is too small to hold the event.
404 The per-process limit on the number of open files has been reached.
405 See the description of
411 The system-wide limit on the total number of open files has been reached.
413 .I /proc/sys/fs/file-max
418 This error is returned by
426 argument when calling
427 .BR fanotify_init (2)
428 and an event occurred for a monitored file that is currently being executed.
430 In addition to the usual errors for
432 the following errors can occur when writing to the fanotify file descriptor:
435 Fanotify access permissions are not enabled in the kernel configuration
438 in the response structure is not valid.
443 in the response structure is not valid.
444 This may occur when a response for the permission event has already been
447 The fanotify API was introduced in version 2.6.36 of the Linux kernel and
448 enabled in version 2.6.37.
449 Fdinfo support was added in version 3.8.
451 The fanotify API is Linux-specific.
453 The fanotify API is available only if the kernel was built with the
455 configuration option enabled.
456 In addition, fanotify permission handling is available only if the
457 .B CONFIG_FANOTIFY_ACCESS_PERMISSIONS
458 configuration option is enabled.
459 .SS Limitations and caveats
460 Fanotify reports only events that a user-space program triggers through the
463 it does not catch remote events that occur on network filesystems.
465 The fanotify API does not report file accesses and modifications that
472 Events for directories are created only if the directory itself is opened,
474 Adding, removing, or changing children of a marked directory does not create
475 events for the monitored directory itself.
477 Fanotify monitoring of directories is not recursive:
478 to monitor subdirectories under a directory,
479 additional marks must be created.
480 (But note that the fanotify API provides no way of detecting when a
481 subdirectory has been created under a marked directory,
482 which makes recursive monitoring difficult.)
483 Monitoring mounts offers the capability to monitor a whole directory tree.
485 The event queue can overflow.
486 In this case, events are lost.
490 did not generate fanotify events.
492 .\" commit 820c12d5d6c0890bc93dd63893924a13041fdc35
500 the following bugs exist:
502 On Linux, a filesystem object may be accessible through multiple paths,
503 for example, a part of a filesystem may be remounted using the
507 A listener that marked a mount will be notified only of events that were
508 triggered for a filesystem object using the same mount.
509 Any other event will pass unnoticed.
511 .\" FIXME . A patch was proposed.
512 When an event is generated,
513 no check is made to see whether the user ID of the
514 receiving process has authorization to read or write the file
515 before passing a file descriptor for that file.
516 This poses a security risk, when the
518 capability is set for programs executed by unprivileged users.
522 processes multiple events from the fanotify queue and an error occurs,
523 the return value will be the total length of the events successfully
524 copied to the user-space buffer before the error occurred.
525 The return value will not be \-1, and
528 Thus, the reading application has no way to detect the error.
530 The following program demonstrates the usage of the fanotify API.
531 It marks the mount point passed as a command-line argument
532 and waits for events of type
535 .BR FAN_CLOSE_WRITE .
536 When a permission event occurs, a
540 The following output was recorded while editing the file
541 .IR /home/user/temp/notes .
542 Before the file was opened, a
545 After the file was closed, a
548 Execution of the program ends when the user presses the ENTER key.
552 # ./fanotify_example /home
553 Press enter key to terminate.
554 Listening for events.
555 FAN_OPEN_PERM: File /home/user/temp/notes
556 FAN_CLOSE_WRITE: File /home/user/temp/notes
558 Listening for events stopped.
563 #define _GNU_SOURCE /* Needed to get O_LARGEFILE definition */
570 #include <sys/fanotify.h>
573 /* Read all available fanotify events from the file descriptor 'fd' */
576 handle_events(int fd)
578 const struct fanotify_event_metadata *metadata;
579 struct fanotify_event_metadata buf[200];
583 char procfd_path[PATH_MAX];
584 struct fanotify_response response;
586 /* Loop while events can be read from fanotify file descriptor */
590 /* Read some events */
592 len = read(fd, (void *) &buf, sizeof(buf));
593 if (len == \-1 && errno != EAGAIN) {
598 /* Check if end of available data reached */
603 /* Point to the first event in the buffer */
607 /* Loop over all events in the buffer */
609 while (FAN_EVENT_OK(metadata, len)) {
611 /* Check that run\-time and compile\-time structures match */
613 if (metadata\->vers != FANOTIFY_METADATA_VERSION) {
615 "Mismatch of fanotify metadata version.\\n");
619 /* metadata\->fd contains either FAN_NOFD, indicating a
620 queue overflow, or a file descriptor (a nonnegative
621 integer). Here, we simply ignore queue overflow. */
623 if (metadata\->fd >= 0) {
625 /* Handle open permission event */
627 if (metadata\->mask & FAN_OPEN_PERM) {
628 printf("FAN_OPEN_PERM: ");
630 /* Allow file to be opened */
632 response.fd = metadata\->fd;
633 response.response = FAN_ALLOW;
635 sizeof(struct fanotify_response));
638 /* Handle closing of writable file event */
640 if (metadata\->mask & FAN_CLOSE_WRITE)
641 printf("FAN_CLOSE_WRITE: ");
643 /* Retrieve and print pathname of the accessed file */
645 snprintf(procfd_path, sizeof(procfd_path),
646 "/proc/self/fd/%d", metadata\->fd);
647 path_len = readlink(procfd_path, path,
649 if (path_len == \-1) {
654 path[path_len] = '\\0';
655 printf("File %s\\n", path);
657 /* Close the file descriptor of the event */
659 close(metadata\->fd);
662 /* Advance to next event */
664 metadata = FAN_EVENT_NEXT(metadata, len);
670 main(int argc, char *argv[])
675 struct pollfd fds[2];
677 /* Check mount point is supplied */
680 fprintf(stderr, "Usage: %s MOUNT\\n", argv[0]);
684 printf("Press enter key to terminate.\\n");
686 /* Create the file descriptor for accessing the fanotify API */
688 fd = fanotify_init(FAN_CLOEXEC | FAN_CLASS_CONTENT | FAN_NONBLOCK,
689 O_RDONLY | O_LARGEFILE);
691 perror("fanotify_init");
695 /* Mark the mount for:
696 \- permission events before opening files
697 \- notification events after closing a write\-enabled
700 if (fanotify_mark(fd, FAN_MARK_ADD | FAN_MARK_MOUNT,
701 FAN_OPEN_PERM | FAN_CLOSE_WRITE, AT_FDCWD,
703 perror("fanotify_mark");
707 /* Prepare for polling */
713 fds[0].fd = STDIN_FILENO;
714 fds[0].events = POLLIN;
719 fds[1].events = POLLIN;
721 /* This is the loop to wait for incoming events */
723 printf("Listening for events.\\n");
726 poll_num = poll(fds, nfds, \-1);
727 if (poll_num == \-1) {
728 if (errno == EINTR) /* Interrupted by a signal */
729 continue; /* Restart poll() */
731 perror("poll"); /* Unexpected error */
736 if (fds[0].revents & POLLIN) {
738 /* Console input is available: empty stdin and quit */
740 while (read(STDIN_FILENO, &buf, 1) > 0 && buf != '\\n')
745 if (fds[1].revents & POLLIN) {
747 /* Fanotify events are available */
754 printf("Listening for events stopped.\\n");
760 .BR fanotify_init (2),
761 .BR fanotify_mark (2),