1 .\" Copyright (C) 2013, Heinrich Schuchardt <xypron.glpk@gmx.de>
3 .\" %%%LICENSE_START(VERBATIM)
4 .\" Permission is granted to make and distribute verbatim copies of this
5 .\" manual provided the copyright notice and this permission notice are
6 .\" preserved on all copies.
8 .\" Permission is granted to copy and distribute modified versions of
9 .\" this manual under the conditions for verbatim copying, provided that
10 .\" the entire resulting derived work is distributed under the terms of
11 .\" a permission notice identical to this one.
13 .\" Since the Linux kernel and libraries are constantly changing, this
14 .\" manual page may be incorrect or out-of-date. The author(s) assume.
15 .\" no responsibility for errors or omissions, or for damages resulting.
16 .\" from the use of the information contained herein. The author(s) may.
17 .\" not have taken the same level of care in the production of this.
18 .\" manual, which is licensed free of charge, as they might when working.
21 .\" Formatted or processed versions of this manual, if unaccompanied by
22 .\" the source, must acknowledge the copyright and authors of this work.
24 .TH FANOTIFY 7 2014-04-24 "Linux" "Linux Programmer's Manual"
26 fanotify \- monitoring filesystem events
28 The fanotify API provides notification and interception of filesystem events.
29 Use cases include virus scanning and hierarchical storage management.
30 Currently, only a limited set of events is supported.
31 In particular, there is no support for create, delete, and move events.
34 for details of an API that does notify those events.)
36 Additional capabilities compared to the
38 API are monitoring of complete mounts, access permission decisions, and the
39 possibility to read or modify files before access by other applications.
41 The following system calls are used with this API:
42 .BR fanotify_init (2),
43 .BR fanotify_mark (2),
50 .SS fanotify_init(), fanotify_mark(), and notification groups
53 system call creates and initializes an fanotify notification group
54 and returns a file descriptor referring to it.
56 An fanotify notification group is a kernel-internal object that holds
57 a list of files, directories, and mount points for which events shall be
60 For each entry in an fanotify notification group, two bit masks exist: the
65 The mark mask defines file activities for which an event shall be created.
66 The ignore mask defines activities for which no event shall be generated.
67 Having these two types of masks permits a mount point or directory to be
68 marked for receiving events, while at the same time ignoring events for
69 specific objects under that mount point or directory.
73 system call adds a file, directory, or mount to a notification group
74 and specifies which events
75 shall be reported (or ignored), or removes or modifies such an entry.
77 A possible usage of the ignore mask is for a file cache.
78 Events of interest for a file cache are modification of a file and closing
80 Hence, the cached directory or mount point is to be marked to receive these
82 After receiving the first event informing that a file has been modified, the
83 corresponding cache entry will be invalidated.
84 No further modification events for this file are of interest until the file is
86 Hence, the modify event can be added to the ignore mask.
87 Upon receiving the closed event, the modify event can be removed from the
88 ignore mask and the file cache entry can be updated.
90 The entries in the fanotify notification groups refer to files and directories
91 via their inode number and to mounts via their mount ID.
92 If files or directories are renamed or moved, the respective entries survive.
93 If files or directories are deleted or mounts are unmounted, the corresponding
96 As events occur on the filesystem objects monitired by a notification group,
97 the fanotify system generates events that are collected in a queue.
98 These events can then be read (using
101 from the fanotify file descriptor
103 .BR fanotify_init (2).
105 Two types of events are generated:
106 notification events and permission events.
107 Notification events are merely informative
108 and require no action to be taken by
109 the receiving application except for closing the file descriptor passed in the
111 Permission events are requests to the receiving application to decide whether
112 permission for a file access shall be granted.
113 For these events, the recipient must write a response which decides whether
114 access is granted or not.
116 Queue entries for notification events are removed when the event has been
118 Queue entries for permission events are removed when the permission
119 decision has been taken by writing to the fanotify file descriptor.
120 .SS Reading fanotify events
123 for the file descriptor returned by
124 .BR fanotify_init (2)
127 is not specified in the call to
128 .BR fanotify_init (2))
129 until either a file event occurs or the call is interrupted by a signal
135 is the length of the filled buffer, or \-1 in case of an error.
138 the read buffer contains one or more of the following structures:
142 struct fanotify_event_metadata {
154 The fields of this structure as follows:
157 This is the length of the data for the current event and the offset to the next
159 In the current implementation, the value of
162 .BR FAN_EVENT_METADATA_LEN .
163 In principle, the API design would allow to return variable-length structures.
164 Therefore, and for performance reasons, it is recommended to use a larger
165 buffer size when reading, for example 4096 bytes.
168 This field holds a version number for the structure.
169 It must be compared to
170 .B FANOTIFY_METADATA_VERSION
171 to verify that the structures returned at runtime match
172 the structures defined at compile time.
173 In case of a mismatch, the application should abandon trying to use the
174 fanotify file descriptor.
177 This field is not used.
180 This is the length of the structure.
181 The field was introduced to facilitate the implementation of optional headers
183 No such optional headers exist in the current implementation.
186 This is a bit mask describing the event.
189 This is an open file descriptor for the object being accessed, or
191 if a queue overflow occurred.
192 The file descriptor can be used to access the contents of the monitored file or
196 file status flag is set on the corresponding open file description.
197 This flag suppresses fanotify event generation.
198 Hence, when the receiver of the fanotify event accesses the notified file or
199 directory using this file descriptor, no additional events will be created.
200 The reading application is responsible for closing the file descriptor.
203 This is the ID of the process that caused the event.
204 A program listening to fanotify events can compare this PID to the PID returned
207 to determine whether the event is caused by the listener itself, or is due to a
208 file access by another program.
212 signals which events have occurred for a single filesystem object.
213 Multiple bits may be set in this mask,
214 if more than one event occurred for the monitored filesystem obect.
216 consecutive events for the same filesystem object and originating from the
217 same process may be merged into a single event, with the exception that two
218 permission events are never merged into one queue entry.
220 The bits that may appear in
225 A file or a directory (but see BUGS) was accessed (read).
228 A file or a directory was opened.
234 A file that was opened for writing
241 A file or directory that was opened read-only
246 The event queue exceeded the limit of 16384 entries.
247 This limit can be overridden in the call to
248 .BR fanotify_init (2)
250 .BR FAN_UNLIMITED_QUEUE .
253 An application wants to read a file or directory, for example using
257 The reader must write a response that determines whether the permission to
258 access the filesystem object shall be granted.
261 An application wants to open a file or directory.
262 The reader must write a response that determines whether the permission to
263 open the filesystem object shall be granted.
265 To check for any close event, the following bit mask may be used:
269 This is a synonym for;
271 FAN_CLOSE_WRITE | FAN_CLOSE_NOWRITE
273 The following macros are provided to iterate over a buffer containing fanotify
274 event metadata returned by a
276 from an fanotify file descriptor.
278 .B FAN_EVENT_OK(meta, len)
279 This macro checks the remaining length
283 against the length of the metadata structure and the
285 field of the first metadata structure in the buffer.
287 .B FAN_EVENT_NEXT(meta, len)
288 This macro sets the pointer
290 to the next metadata structure using the length indicated in the
292 field of the metadata structure and reduces the remaining length of the
295 .SS Monitoring an fanotify file descriptor for events
296 When an fanotify event occurs, the fanotify file descriptor indicates as
297 readable when passed to
302 .SS Dealing with permission events
303 For permission events, the application must
305 a structure of the following form to the
306 fanotify file descriptor:
310 struct fanotify_response {
317 The fields of this structure are as follows:
320 This is the file descriptor from the structure
321 .IR fanotify_event_metadata .
324 This field indicates whether or not the permission is to be granted.
325 Its value must be either
327 to allow the file operation or
329 to deny the file operation.
331 If access is denied, the requesting application call will receive an
334 .SS Closing the fanotify file descriptor
336 When all file descriptors referring to the fanotify notification group are
337 closed, the fanotify group is released and its resources
338 are freed for reuse by the kernel.
341 outstanding permission events will be set to allowed.
342 .SS /proc/[pid]/fdinfo
344 .I /proc/[pid]/fdinfo/[fd]
345 contains information about fanotify marks for file descriptor
349 See the kernel source file
350 .I Documentation/filesystems/proc.txt
353 In addition to the usual errors for
355 the following errors can occur when reading from the fanotify file descriptor:
358 The buffer is too short to hold the event.
361 The per-process limit on the number of open files has been reached.
362 See the description of
368 The system-wide limit on the number of open files has been reached.
370 .I /proc/sys/fs/file-max
375 This error is returned by
383 argument when calling
384 .BR fanotify_init (2)
385 and an event occurred for a monitored file that is currently being executed.
387 In addition to the usual errors for
389 the following errors can occur when writing to the fanotify file descriptor:
392 Fanotify access permissions are not enabled in the kernel configuration or the
395 in the response structure is not valid.
400 in the response structure is not valid.
401 This might occur because the file was already deleted by another thread or
404 The fanotify API was introduced in version 2.6.36 of the Linux kernel and
405 enabled in version 2.6.37.
406 Fdinfo support was added in version 3.8.
408 The fanotify API is Linux-specific.
410 The fanotify API is available only if the kernel was built with the
412 configuration option enabled.
413 In addition, fanotify permission handling is available only if the
414 .B CONFIG_FANOTIFY_ACCESS_PERMISSIONS
415 configuration option is enabled.
416 .SS Limitations and caveats
417 Fanotify reports only events that a user-space program triggers through the
419 As a result, it does not catch remote events that occur on network filesystems.
421 The fanotify API does not report file accesses and modifications that
428 Events for directories are created only if the directory itself is opened,
430 Adding, removing, or changing children of a marked directory does not create
431 events for the monitored directory itself.
433 Fanotify monitoring of directories is not recursive: to monitor subdirectories
434 under a directory, additional marks must be created.
435 (But note that the fanotify API provides no way of detecting when a
436 subdirectory has been created under a marked directory, which makes recursive
437 monitoring difficult.)
438 Monitoring mounts offers the capability to monitor a whole directory tree.
440 The event queue can overflow.
441 In this case, events are lost.
444 the following bugs exist:
446 .\" FIXME: Patch is in linux-next-20140424.
452 .\" FIXME: A patch was proposed.
453 When an event is generated, no check is made to see whether the user ID of the
454 receiving process has authorization to read or write the file before passing a
455 file descriptor for that file.
456 This poses a security risk, when the
458 capability is set for programs executed by unprivileged users.
460 The following program demonstrates the usage of the fanotify API.
461 It marks the mount point passed as command-line argument
462 and waits for events of type
465 .BR FAN_CLOSE_WRITE .
466 When a permission event occurs, a
470 The following output was recorded while editing the file
471 .IR /home/user/temp/notes .
472 Before the file was opened, a
475 After the file was closed, a
478 Execution of the program ends when the user presses the ENTER key.
482 # ./fanotify_example /home
483 Press enter key to terminate.
484 Listening for events.
485 FAN_OPEN_PERM: File /home/user/temp/notes
486 FAN_CLOSE_WRITE: File /home/user/temp/notes
488 Listening for events stopped.
493 #define _GNU_SOURCE /* Needed to get O_LARGEFILE definition */
500 #include <sys/fanotify.h>
503 /* Read all available fanotify events from the file descriptor 'fd' */
506 handle_events(int fd)
508 const struct fanotify_event_metadata *metadata;
513 char procfd_path[PATH_MAX];
514 struct fanotify_response response;
516 /* Loop while events can be read from fanotify file descriptor */
520 /* Read some events */
522 len = read(fd, (void *) &buf, sizeof(buf));
523 if (len == \-1 && errno != EAGAIN) {
528 /* Check if end of available data reached */
533 /* Point to the first event in the buffer */
535 metadata = (struct fanotify_event_metadata *) buf;
537 /* Loop over all events in the buffer */
539 while (FAN_EVENT_OK(metadata, len)) {
541 /* Check that run\-time and compile\-time structures match */
543 if (metadata\->vers != FANOTIFY_METADATA_VERSION) {
545 "Mismatch of fanotify metadata version.\\n");
549 /* Check that the event contains a file descriptor */
550 .\" FIXME Should the following line actually be:
551 .\" if (metadata\->fd != FANNOFD)
553 .\" Or, more generally, the program has a problem inasmuch as it is not
554 .\" handling queue overflow
555 if (metadata\->fd >= 0) {
557 /* Handle open permission event */
559 if (metadata\->mask & FAN_OPEN_PERM) {
560 printf("FAN_OPEN_PERM: ");
562 /* Allow file to be opened */
564 response.fd = metadata\->fd;
565 response.response = FAN_ALLOW;
567 sizeof(struct fanotify_response));
570 /* Handle closing of writable file event */
572 if (metadata\->mask & FAN_CLOSE_WRITE)
573 printf("FAN_CLOSE_WRITE: ");
575 /* Retrieve and print pathname of the accessed file */
577 snprintf(procfd_path, sizeof(procfd_path),
578 "/proc/self/fd/%d", metadata\->fd);
579 path_len = readlink(procfd_path, path,
581 if (path_len == \-1) {
586 path[path_len] = '\\0';
587 printf("File %s\\n", path);
589 /* Close the file descriptor of the event */
591 close(metadata\->fd);
594 /* Advance to next event */
596 metadata = FAN_EVENT_NEXT(metadata, len);
602 main(int argc, char *argv[])
607 struct pollfd fds[2];
609 /* Check mount point is supplied */
612 fprintf(stderr, "Usage: %s MOUNT\\n", argv[0]);
616 printf("Press enter key to terminate.\\n");
618 /* Create the file descriptor for accessing the fanotify API */
620 fd = fanotify_init(FAN_CLOEXEC | FAN_CLASS_CONTENT | FAN_NONBLOCK,
621 O_RDONLY | O_LARGEFILE);
623 perror("fanotify_init");
627 /* Mark the mount for:
628 \- permission events before opening files
629 \- notification events after closing a write\-enabled
632 if (fanotify_mark(fd, FAN_MARK_ADD | FAN_MARK_MOUNT,
633 FAN_OPEN_PERM | FAN_CLOSE_WRITE, \-1,
635 perror("fanotify_mark");
639 /* Prepare for polling */
645 fds[0].fd = STDIN_FILENO;
646 fds[0].events = POLLIN;
651 fds[1].events = POLLIN;
653 /* This is the loop to wait for incoming events */
655 printf("Listening for events.\\n");
658 poll_num = poll(fds, nfds, \-1);
659 if (poll_num == \-1) {
660 if (errno == EINTR) /* Interrupted by a signal */
661 continue; /* Restart poll() */
663 perror("poll"); /* Unexpected error */
668 if (fds[0].revents & POLLIN) {
670 /* Console input is available: empty stdin and quit */
672 while (read(STDIN_FILENO, &buf, 1) > 0 && buf != '\\n')
677 if (fds[1].revents & POLLIN) {
679 /* Fanotify events are available */
686 printf("Listening for events stopped.\\n");
692 .BR fanotify_init (2),
693 .BR fanotify_mark (2),