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() 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.
71 A possible usage of the ignore mask is for a file cache.
72 Events of interest for a file cache are modification of a file and closing
74 Hence, the cached directory or mount point is to be marked to receive these
76 After receiving the first event informing that a file has been modified, the
77 corresponding cache entry will be invalidated.
78 No further modification events for this file are of interest until the file is
80 Hence, the modify event can be added to the ignore mask.
81 Upon receiving the closed event, the modify event can be removed from the
82 ignore mask and the file cache entry can be updated.
84 The entries in the fanotify notification groups refer to files and directories
85 via their inode number and to mounts via their mount ID.
86 If files or directories are renamed or moved, the respective entries survive.
87 If files or directories are deleted or mounts are unmounted, the corresponding
90 Two types of events exist: notification events and permission events.
91 Notification events are only informative and require no action to be taken by
92 the receiving application except for closing the file descriptor passed in the
94 Permission events are requests to the receiving application to decide whether
95 permission for a file access shall be granted.
96 For these events, the recipient must write a response which decides whether
97 access is granted or not.
100 .BR fanotify_mark (2)
101 system call adds a file, directory, or mount to a notification group
102 and specifies which events
103 shall be reported (or ignored), or removes or modifies such an entry.
104 .SS Events, the event queue, and reading events
105 All events for an fanotify group are collected in a queue.
106 Consecutive events for the same filesystem object and originating from the
107 same process may be merged into a single event, with the exception that two
108 permission events are never merged into one queue entry.
109 Queue entries for notification events are removed when the event has been
111 Queue entries for permission events are removed when the permission
112 decision has been taken by writing to the fanotify file descriptor.
116 for the file descriptor returned by
117 .BR fanotify_init (2)
120 is not specified in the call to
121 .BR fanotify_init (2))
122 until either a file event occurs or the call is interrupted by a signal
128 is the length of the filled buffer, or \-1 in case of an error.
131 the read buffer contains one or more of the following structures:
135 struct fanotify_event_metadata {
149 This is the length of the data for the current event and the offset to the next
151 In the current implementation, the value of
154 .BR FAN_EVENT_METADATA_LEN .
155 In principle, the API design would allow to return variable-length structures.
156 Therefore, and for performance reasons, it is recommended to use a larger
157 buffer size when reading, for example 4096 bytes.
160 This field holds a version number for the structure.
161 It must be compared to
162 .B FANOTIFY_METADATA_VERSION
163 to verify that the structures returned at runtime match
164 the structures defined at compile time.
165 In case of a mismatch, the application should abandon trying to use the
166 fanotify file descriptor.
169 This field is not used.
172 This is the length of the structure.
173 The field was introduced to facilitate the implementation of optional headers
175 No such optional headers exist in the current implementation.
178 This is a bit mask describing the event.
181 This is an open file descriptor for the object being accessed, or
183 if a queue overflow occurred.
184 The file descriptor can be used to access the contents of the monitored file or
188 file status flag is set on the corresponding open file description.
189 This flag suppresses fanotify event generation.
190 Hence, when the receiver of the fanotify event accesses the notified file or
191 directory using this file descriptor, no additional events will be created.
192 The reading application is responsible for closing the file descriptor.
195 This is the ID of the process that caused the event.
196 A program listening to fanotify events can compare this PID to the PID returned
199 to determine whether the event is caused by the listener itself, or is due to a
200 file access by another program.
204 signals which events have occurred for a single filesystem object.
205 More than one of the following flags can be set at once in the bit mask.
208 A file or a directory (but see BUGS) was accessed (read).
211 A file or a directory was opened.
217 A file that was opened for writing
224 A file or directory that was opened read-only
229 The event queue exceeded the limit of 16384 entries.
230 This limit can be overridden in the call to
231 .BR fanotify_init (2)
233 .BR FAN_UNLIMITED_QUEUE .
236 An application wants to read a file or directory, for example using
240 The reader must write a response that determines whether the permission to
241 access the filesystem object shall be granted.
244 An application wants to open a file or directory.
245 The reader must write a response that determines whether the permission to
246 open the filesystem object shall be granted.
248 To check for any close event, the following bit mask may be used:
252 (FAN_CLOSE_WRITE | FAN_CLOSE_NOWRITE).
254 The following macros are provided to iterate over a buffer containing fanotify
255 event metadata returned by a
257 from an fanotify file descriptor.
259 .B FAN_EVENT_OK(meta, len)
260 This macro checks the remaining length
264 against the length of the metadata structure and the
266 field of the first metadata structure in the buffer.
268 .B FAN_EVENT_NEXT(meta, len)
269 This macro sets the pointer
271 to the next metadata structure using the length indicated in the
273 field of the metadata structure and reduces the remaining length of the
276 .SS Monitoring an fanotify file descriptor for events
277 When an fanotify event occurs, the fanotify file descriptor indicates as
278 readable when passed to
283 .SS Dealing with permission events
284 For permission events, the application must
286 a structure of the following form to the
287 fanotify file descriptor:
291 struct fanotify_response {
300 This is the file descriptor from the structure
301 .IR fanotify_event_metadata .
304 This field indicates whether or not the permission is to be granted.
305 Its value must be either
307 to allow the file operation or
309 to deny the file operation.
311 If access has been denied, the requesting application call will receive an
314 .SS Closing the fanotify file descriptor
316 When all file descriptors referring to the fanotify notification group are
317 closed, the fanotify group is released and its resources
318 are freed for reuse by the kernel.
321 outstanding permission events will be set to allowed.
324 .I /proc/<pid>/fdinfo/<fd>
325 contains information about fanotify marks for file descriptor
330 .I Documentation/filesystems/proc.txt
333 In addition to the usual errors for
335 the following errors can occur when reading from the fanotify file descriptor:
338 The buffer is too short to hold the event.
341 The per-process limit on the number of open files has been reached.
342 See the description of
348 The system-wide limit on the number of open files has been reached.
350 .I /proc/sys/fs/file-max
355 A write enabled file descriptor shall be created for a file that is executing.
356 This error is returned by
364 argument when calling
365 .BR fanotify_init (2)
366 and the event occurred for a monitored file that is currently being executed.
368 In addition to the usual errors for
370 the following errors can occur when writing to the fanotify file descriptor:
373 Fanotify access permissions are not enabled in the kernel configuration or the
376 in the response structure is not valid.
381 in the response structure is not valid.
382 This might occur because the file was already deleted by another thread or
385 The fanotify API was introduced in version 2.6.36 of the Linux kernel and
386 enabled in version 2.6.37.
387 Fdinfo support was added in version 3.8.
389 The fanotify API is Linux-specific.
391 The fanotify API is available only if the kernel was built with the
393 configuration option enabled.
394 In addition, fanotify permission handling is available only if the
395 .B CONFIG_FANOTIFY_ACCESS_PERMISSIONS
396 configuration option is enabled.
397 .SS Limitations and caveats
398 Fanotify reports only events that a user-space program triggers through the
400 As a result, it does not catch remote events that occur on network filesystems.
402 The fanotify API does not report file accesses and modifications that
409 Events for directories are created only if the directory itself is opened,
411 Adding, removing, or changing children of a marked directory does not create
412 events for the monitored directory itself.
414 Fanotify monitoring of directories is not recursive: to monitor subdirectories
415 under a directory, additional marks must be created.
416 (But note that the fanotify API provides no way of detecting when a
417 subdirectory has been created under a marked directory, which makes recursive
418 monitoring difficult.)
419 Monitoring mounts offers the capability to monitor a whole directory tree.
421 The event queue can overflow.
422 In this case, events are lost.
425 the following bugs exist:
427 .\" FIXME: Patch is in linux-next-20140424.
433 .\" FIXME: A patch was proposed.
434 When an event is generated, no check is made to see whether the user ID of the
435 receiving process has authorization to read or write the file before passing a
436 file descriptor for that file in
437 This poses a security risk, when the
439 capability is set for programs executed by unprivileged users.
441 The following program demonstrates the usage of the fanotify API.
442 It marks the mount point passed as command-line argument
443 and waits for events of type
446 .BR FAN_CLOSE_WRITE .
447 When a permission event occurs, a
451 The following output was recorded while editing the file
452 .IR /home/user/temp/notes .
453 Before the file was opened, a
456 After the file was closed, a
459 Execution of the program ends when the user presses the ENTER key.
463 # ./fanotify_example /home
464 Press enter key to terminate.
465 Listening for events.
466 FAN_OPEN_PERM: File /home/user/temp/notes
467 FAN_CLOSE_WRITE: File /home/user/temp/notes
469 Listening for events stopped.
474 #define _GNU_SOURCE /* Needed to get O_LARGEFILE definition */
481 #include <sys/fanotify.h>
484 /* Read all available fanotify events from the file descriptor 'fd' */
487 handle_events(int fd)
489 const struct fanotify_event_metadata *metadata;
494 char procfd_path[PATH_MAX];
495 struct fanotify_response response;
497 /* Loop while events can be read from fanotify file descriptor */
501 /* Read some events */
503 len = read(fd, (void *) &buf, sizeof(buf));
504 if (len == \-1 && errno != EAGAIN) {
509 /* Check if end of available data reached */
514 /* Point to the first event in the buffer */
516 metadata = (struct fanotify_event_metadata *) buf;
518 /* Loop over all events in the buffer */
520 while (FAN_EVENT_OK(metadata, len)) {
522 /* Check that run\-time and compile\-time structures match */
524 if (metadata\->vers != FANOTIFY_METADATA_VERSION) {
526 "Mismatch of fanotify metadata version.\\n");
530 /* Check that the event contains a file descriptor */
532 if (metadata\->fd >= 0) {
534 /* Handle open permission event */
536 if (metadata\->mask & FAN_OPEN_PERM) {
537 printf("FAN_OPEN_PERM: ");
539 /* Allow file to be opened */
541 response.fd = metadata\->fd;
542 response.response = FAN_ALLOW;
544 sizeof(struct fanotify_response));
547 /* Handle closing of writable file event */
549 if (metadata\->mask & FAN_CLOSE_WRITE)
550 printf("FAN_CLOSE_WRITE: ");
552 /* Retrieve and print pathname of the accessed file */
554 snprintf(procfd_path, sizeof(procfd_path),
555 "/proc/self/fd/%d", metadata\->fd);
556 path_len = readlink(procfd_path, path,
558 if (path_len == \-1) {
563 path[path_len] = '\\0';
564 printf("File %s\\n", path);
566 /* Close the file descriptor of the event */
568 close(metadata\->fd);
571 /* Advance to next event */
573 metadata = FAN_EVENT_NEXT(metadata, len);
579 main(int argc, char *argv[])
584 struct pollfd fds[2];
586 /* Check mount point is supplied */
589 fprintf(stderr, "Usage: %s MOUNT\\n", argv[0]);
593 printf("Press enter key to terminate.\\n");
595 /* Create the file descriptor for accessing the fanotify API */
597 fd = fanotify_init(FAN_CLOEXEC | FAN_CLASS_CONTENT | FAN_NONBLOCK,
598 O_RDONLY | O_LARGEFILE);
600 perror("fanotify_init");
604 /* Mark the mount for:
605 \- permission events before opening files
606 \- notification events after closing a write\-enabled
609 if (fanotify_mark(fd, FAN_MARK_ADD | FAN_MARK_MOUNT,
610 FAN_OPEN_PERM | FAN_CLOSE_WRITE, \-1,
612 perror("fanotify_mark");
616 /* Prepare for polling */
622 fds[0].fd = STDIN_FILENO;
623 fds[0].events = POLLIN;
628 fds[1].events = POLLIN;
630 /* This is the loop to wait for incoming events */
632 printf("Listening for events.\\n");
634 poll_num = poll(fds, nfds, \-1);
635 if (poll_num == \-1) {
642 if (fds[0].revents & POLLIN) {
644 /* Console input is available: empty stdin and quit */
646 while (read(STDIN_FILENO, &buf, 1) > 0 && buf != '\\n')
650 if (fds[1].revents & POLLIN) {
652 /* Fanotify events are available */
659 printf("Listening for events stopped.\\n");
665 .BR fanotify_init (2),
666 .BR fanotify_mark (2),