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
30 API provides notification and interception of filesystem events.
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 are monitoring of complete mounts, access permission decisions, and the
41 possibility to read or modify files before access by other applications.
43 The following system calls are used with this API:
44 .BR fanotify_init (2),
45 .BR fanotify_mark (2),
54 creates and initializes an fanotify notification group and returns a file
55 descriptor referring to it.
57 An fanotify notification group is a kernel-internal object that holds
58 a list of files, directories, and mount points for which events shall be
61 For each entry in an fanotify notification group, two bit masks exist: the
66 The mark mask defines file activities for which an event shall be created.
67 The ignore mask defines activities for which no event shall be generated.
68 Having these two types of masks permits a mount point or directory to be
69 marked for receiving events, while at the same time ignoring events for
70 specific objects under that mount point or directory.
72 A possible usage of the ignore mask is for a file cache.
73 Events of interest for a file cache are modification of a file and closing
75 Hence, the cached directory or mount point is to be marked to receive these
77 After receiving the first event informing that a file has been modified, the
78 corresponding cache entry will be invalidated.
79 No further modification events for this file are of interest until the file is
81 Hence, the modify event can be added to the ignore mask.
82 Upon receiving the closed event, the modify event can be removed from the
83 ignore mask and the file cache entry can be updated.
85 The entries in the fanotify notification groups refer to files and directories
86 via their inode number and to mounts via their mount ID.
87 If files or directories are renamed or moved, the respective entries survive.
88 If files or directories are deleted or mounts are unmounted, the corresponding
91 Two types of events exist: notification events and permission events.
92 Notification events are only informative and require no action to be taken by
93 the receiving application except for closing the file descriptor passed in the
95 Permission events are requests to the receiving application to decide whether
96 permission for a file access shall be granted.
97 For these events, the recipient must write a response which decides whether
98 access is granted or not.
100 When all file descriptors referring to the fanotify notification group are
101 closed, the fanotify group is released and its resources are freed for reuse by
104 .BR fanotify_mark (2)
105 adds a file, directory, or mount to the group and specifies which events
106 shall be reported (or ignored), or removes or modifies such an entry.
108 When an fanotify event occurs, the fanotify file descriptor indicates as
109 readable when passed to
115 All events for an fanotify group are collected in a queue.
116 Consecutive events for the same filesystem object and originating from the
117 same process may be merged into a single event, with the exception that two
118 permission events are never merged into one queue entry.
119 Queue entries for notification events are removed when the event has been
121 Queue entries for permission events are removed when the permission
122 decision has been taken by writing to the fanotify file descriptor.
126 for the file descriptor returned by
127 .BR fanotify_init (2)
130 is not specified in the call to
131 .BR fanotify_init (2))
132 until either a file event occurs or the call is interrupted by a signal
138 is the length of the filled buffer, or \-1 in case of an error.
141 the read buffer contains one or more of the following structures:
145 struct fanotify_event_metadata {
159 This is the length of the data for the current event and the offset to the next
161 In the current implementation, the value of
164 .BR FAN_EVENT_METADATA_LEN .
165 In principle, the API design would allow to return variable-length structures.
166 Therefore, and for performance reasons, it is recommended to use a larger
167 buffer size when reading, for example 4096 bytes.
170 This field holds a version number for the structure.
171 It must be compared to
172 .B FANOTIFY_METADATA_VERSION
173 to verify that the structures returned at runtime match
174 the structures defined at compile time.
175 In case of a mismatch, the application should abandon trying to use the
176 fanotify file descriptor.
179 This field is not used.
182 This is the length of the structure.
183 The field was introduced to facilitate the implementation of optional headers
185 No such optional headers exist in the current implementation.
188 This is a bit mask describing the event.
191 This is an open file descriptor for the object being accessed, or
193 if a queue overflow occurred.
194 The file descriptor can be used to access the contents of the monitored file or
198 file status flag is set on the corresponding open file description.
199 This flag suppresses fanotify event generation.
200 Hence, when the receiver of the fanotify event accesses the notified file or
201 directory using this file descriptor, no additional events will be created.
202 The reading application is responsible for closing the file descriptor.
205 This is the ID of the process that caused the event.
206 A program listening to fanotify events can compare this PID to the PID returned
209 to determine whether the event is caused by the listener itself, or is due to a
210 file access by another program.
214 signals which events have occurred for a single filesystem object.
215 More than one of the following flags can be set at once in the bit mask.
218 A file or a directory (but see BUGS) was accessed (read).
221 A file or a directory was opened.
227 A file that was opened for writing
234 A file that was opened read-only
236 or a directory was closed.
239 The event queue exceeded the limit of 16384 entries.
240 This limit can be overridden in the call to
241 .BR fanotify_init (2)
243 .BR FAN_UNLIMITED_QUEUE .
246 An application wants to read a file or directory, for example using
250 The reader must write a response that determines whether the permission to
251 access the filesystem object shall be granted.
254 An application wants to open a file or directory.
255 The reader must write a response that determines whether the permission to
256 open the filesystem object shall be granted.
258 To check for any close event, the following bit mask may be used:
262 (FAN_CLOSE_WRITE | FAN_CLOSE_NOWRITE).
264 The following macros are provided to iterate over a buffer containing fanotify
265 event metadata returned by a
267 from an fanotify file descriptor.
269 .B FAN_EVENT_OK(meta, len)
270 This macro checks the remaining length
274 against the length of the metadata structure and the
276 field of the first metadata structure in the buffer.
278 .B FAN_EVENT_NEXT(meta, len)
279 This macro sets the pointer
281 to the next metadata structure using the length indicated in the
283 field of the metadata structure and reduces the remaining length of the
287 For permission events, the application must
289 a structure of the following form to the
295 struct fanotify_response {
304 This is the file descriptor from the structure
305 .IR fanotify_event_metadata .
308 This field indicates whether or not the permission is to be granted.
309 Its value must be either
311 to allow the file operation or
313 to deny the file operation.
315 If access has been denied, the requesting application call will receive an
319 To end listening, it is sufficient to
321 the fanotify file descriptor.
322 The outstanding permission events will be set to allowed, and all resources
323 will be returned to the kernel.
326 .I /proc/<pid>/fdinfo/<fd>
327 contains information about fanotify marks for file descriptor
332 .I Documentation/filesystems/proc.txt
335 In addition to the usual errors for
337 the following errors can occur when reading from the fanotify file descriptor:
340 The buffer is too short to hold the event.
343 The per-process limit on the number of open files has been reached.
344 See the description of
350 The system-wide limit on the number of open files has been reached.
352 .I /proc/sys/fs/file-max
357 A write enabled file descriptor shall be created for a file that is executing.
358 This error is returned by
366 argument when calling
367 .BR fanotify_init (2)
368 and the event occurred for a monitored file that is currently being execuded.
370 In addition to the usual errors for
372 the following errors can occur when writing to the fanotify file descriptor:
375 Fanotify access permissions are not enabled in the kernel configuration or the
378 in the response structure is not valid.
383 in the response structure is not valid.
384 This might occur because the file was already deleted by another thread or
387 The fanotify API was introduced in version 2.6.36 of the Linux kernel and
388 enabled in version 2.6.37.
389 Fdinfo support was added in version 3.8.
391 The fanotify API is Linux-specific.
393 The fanotify API is available only if the kernel was built with the
395 configuration option enabled.
396 In addition, fanotify permission handling is available only if the
397 .B CONFIG_FANOTIFY_ACCESS_PERMISSIONS
398 configuration option is enabled.
399 .SS Limitations and caveats
400 Fanotify reports only events that a user-space program triggers through the
402 As a result, it does not catch remote events that occur on network filesystems.
404 The fanotify API does not report file accesses and modifications that
411 Events for directories are created only if the directory itself is opened,
413 Adding, removing, or changing children of a marked directory does not create
414 events for the monitored directory itself.
416 Fanotify monitoring of directories is not recursive: to monitor subdirectories
417 under a directory, additional marks must be created.
418 (But note that the fanotify API provides no way of detecting when a
419 subdirectory has been created under a marked directory, which makes recursive
420 monitoring difficult.)
421 Monitoring mounts offers the capability to monitor a whole directory tree.
423 The event queue can overflow.
424 In this case, events are lost.
427 the following bugs exist:
429 .\" FIXME: Patch is in linux-next-20140424.
435 .\" FIXME: A patch was proposed.
436 When an event is generated, no check is made to see whether the user ID of the
437 receiving process has authorization to read or write the file before passing a
438 file descriptor for that file in
439 This poses a security risk, when the
441 capability is set for programs executed by unprivileged users.
443 The following program demonstrates the usage of the fanotify API.
444 It marks the mount point passed as command-line argument
445 and waits for events of type
448 .BR FAN_CLOSE_WRITE .
449 When a permission event occurs, a
453 The following output was recorded while editing the file
454 .IR /home/user/temp/notes .
455 Before the file was opened, a
458 After the file was closed, a
461 Execution of the program ends when the user presses the ENTER key.
465 # ./fanotify_example /home
466 Press enter key to terminate.
467 Listening for events.
468 FAN_OPEN_PERM: File /home/user/temp/notes
469 FAN_CLOSE_WRITE: File /home/user/temp/notes
471 Listening for events stopped.
476 #define _GNU_SOURCE /* Needed to get O_LARGEFILE defintion */
483 #include <sys/fanotify.h>
486 /* Read all available fanotify events from the file descriptor 'fd' */
489 handle_events(int fd)
491 const struct fanotify_event_metadata *metadata;
496 char procfd_path[PATH_MAX];
497 struct fanotify_response response;
499 /* Loop while events can be read from fanotify file descriptor */
503 /* Read some events */
505 len = read(fd, (void *) &buf, sizeof(buf));
506 if (len == \-1 && errno != EAGAIN) {
511 /* Check if end of available data reached */
516 /* Point to the first event in the buffer */
518 metadata = (struct fanotify_event_metadata *) buf;
520 /* Loop over all events in the buffer */
522 while (FAN_EVENT_OK(metadata, len)) {
524 /* Check that run\-time and compile\-time structures match */
526 if (metadata\->vers != FANOTIFY_METADATA_VERSION) {
528 "Mismatch of fanotify metadata version.\\n");
532 /* Check that the event contains a file descriptor */
534 if (metadata\->fd >= 0) {
536 /* Handle open permission event */
538 if (metadata\->mask & FAN_OPEN_PERM) {
539 printf("FAN_OPEN_PERM: ");
541 /* Allow file to be opened */
543 response.fd = metadata\->fd;
544 response.response = FAN_ALLOW;
546 sizeof(struct fanotify_response));
549 /* Handle closing of writable file event */
551 if (metadata\->mask & FAN_CLOSE_WRITE)
552 printf("FAN_CLOSE_WRITE: ");
554 /* Determine path of the file accessed */
556 snprintf(procfd_path, sizeof(procfd_path),
557 "/proc/self/fd/%d", metadata\->fd);
558 path_len = readlink(procfd_path, path,
560 if (path_len == \-1) {
565 path[path_len] = '\\0';
566 printf("File %s\\n", path);
568 /* Close the file descriptor of the event */
570 close(metadata\->fd);
573 /* Advance to next event */
575 metadata = FAN_EVENT_NEXT(metadata, len);
581 main(int argc, char *argv[])
586 struct pollfd fds[2];
588 /* Check mount point is supplied */
591 fprintf(stderr, "Usage: %s MOUNT\\n", argv[0]);
595 printf("Press enter key to terminate.\\n");
597 /* Create the file descriptor for accessing the fanotify API */
599 fd = fanotify_init(FAN_CLOEXEC | FAN_CLASS_CONTENT | FAN_NONBLOCK,
600 O_RDONLY | O_LARGEFILE);
602 perror("fanotify_init");
606 /* Mark the mount for:
607 \- permission events before opening files
608 \- notification events after closing a write\-enabled
611 if (fanotify_mark(fd, FAN_MARK_ADD | FAN_MARK_MOUNT,
612 FAN_OPEN_PERM | FAN_CLOSE_WRITE, \-1,
614 perror("fanotify_mark");
618 /* Prepare for polling */
624 fds[0].fd = STDIN_FILENO;
625 fds[0].events = POLLIN;
630 fds[1].events = POLLIN;
632 /* This is the loop to wait for incoming events */
634 printf("Listening for events.\\n");
636 poll_num = poll(fds, nfds, \-1);
637 if (poll_num == \-1) {
644 if (fds[0].revents & POLLIN) {
646 /* Console input is available: empty stdin and quit */
648 while (read(STDIN_FILENO, &buf, 1) > 0 && buf != '\\n')
652 if (fds[1].revents & POLLIN) {
654 /* Fanotify events are available */
661 printf("Listening for events stopped.\\n");
667 .BR fanotify_init (2),
668 .BR fanotify_mark (2),