Debian Codegraph @

upstream/fedora-44/man7/fanotify.7

raw
1 .\" Copyright (C) 2013, Heinrich Schuchardt <[email protected]>
2 .\" and Copyright (C) 2014, Michael Kerrisk <[email protected]>
3 .\"
4 .\" SPDX-License-Identifier: Linux-man-pages-copyleft
5 .TH fanotify 7 2024-11-17 "Linux man-pages 6.13"
6 .SH NAME
7 fanotify \- monitoring filesystem events
8 .SH DESCRIPTION
9 The fanotify API provides notification and interception of
10 filesystem events.
11 Use cases include virus scanning and hierarchical storage management.
12 In the original fanotify API, only a limited set of events was supported.
13 In particular, there was no support for create, delete, and move events.
14 The support for those events was added in Linux 5.1.
15 (See
16 .BR inotify (7)
17 for details of an API that did notify those events pre Linux 5.1.)
18 .P
19 Additional capabilities compared to the
20 .BR inotify (7)
21 API include the ability to monitor all of the objects
22 in a mounted filesystem,
23 the ability to make access permission decisions, and the
24 possibility to read or modify files before access by other applications.
25 .P
26 The following system calls are used with this API:
27 .BR fanotify_init (2),
28 .BR fanotify_mark (2),
29 .BR read (2),
30 .BR write (2),
31 and
32 .BR close (2).
33 .SS fanotify_init(), fanotify_mark(), and notification groups
34 The
35 .BR fanotify_init (2)
36 system call creates and initializes an fanotify notification group
37 and returns a file descriptor referring to it.
38 .P
39 An fanotify notification group is a kernel-internal object that holds
40 a list of files, directories, filesystems, and mounts for which
41 events shall be created.
42 .P
43 For each entry in an fanotify notification group, two bit masks exist: the
44 .I mark
45 mask and the
46 .I ignore
47 mask.
48 The mark mask defines file activities for which an event shall be created.
49 The ignore mask defines activities for which no event shall be generated.
50 Having these two types of masks permits a filesystem, mount, or
51 directory to be marked for receiving events, while at the same time
52 ignoring events for specific objects under a mount or directory.
53 .P
54 The
55 .BR fanotify_mark (2)
56 system call adds a file, directory, filesystem, or mount to a
57 notification group and specifies which events
58 shall be reported (or ignored), or removes or modifies such an entry.
59 .P
60 A possible usage of the ignore mask is for a file cache.
61 Events of interest for a file cache are modification of a file and closing
62 of the same.
63 Hence, the cached directory or mount is to be marked to receive these
64 events.
65 After receiving the first event informing that a file has been modified,
66 the corresponding cache entry will be invalidated.
67 No further modification events for this file are of interest until the file
68 is closed.
69 Hence, the modify event can be added to the ignore mask.
70 Upon receiving the close event, the modify event can be removed from the
71 ignore mask and the file cache entry can be updated.
72 .P
73 The entries in the fanotify notification groups refer to files and
74 directories via their inode number and to mounts via their mount ID.
75 If files or directories are renamed or moved within the same mount,
76 the respective entries survive.
77 If files or directories are deleted or moved to another mount or if
78 filesystems or mounts are unmounted, the corresponding entries are deleted.
79 .SS The event queue
80 As events occur on the filesystem objects monitored by a notification group,
81 the fanotify system generates events that are collected in a queue.
82 These events can then be read (using
83 .BR read (2)
84 or similar)
85 from the fanotify file descriptor
86 returned by
87 .BR fanotify_init (2).
88 .P
89 Two types of events are generated:
90 .I notification
91 events and
92 .I permission
93 events.
94 Notification events are merely informative and require no action to be taken
95 by the receiving application with one exception: if a valid file descriptor
96 is provided within a generic event, the file descriptor must be closed.
97 Permission events are requests to the receiving application to decide
98 whether permission for a file access shall be granted.
99 For these events, the recipient must write a response which decides whether
100 access is granted or not.
101 .P
102 An event is removed from the event queue of the fanotify group
103 when it has been read.
104 Permission events that have been read are kept in an internal list of the
105 fanotify group until either a permission decision has been taken by
106 writing to the fanotify file descriptor or the fanotify file descriptor
107 is closed.
108 .SS Reading fanotify events
109 Calling
110 .BR read (2)
111 for the file descriptor returned by
112 .BR fanotify_init (2)
113 blocks (if the flag
114 .B FAN_NONBLOCK
115 is not specified in the call to
116 .BR fanotify_init (2))
117 until either a file event occurs or the call is interrupted by a signal
118 (see
119 .BR signal (7)).
120 .P
121 After a successful
122 .BR read (2),
123 the read buffer contains one or more of the following structures:
124 .P
125 .in +4n
126 .EX
127 struct fanotify_event_metadata {
128 __u32 event_len;
129 __u8 vers;
130 __u8 reserved;
131 __u16 metadata_len;
132 __aligned_u64 mask;
133 __s32 fd;
134 __s32 pid;
135 };
136 .EE
137 .in
138 .P
139 Information records are
140 supplemental pieces of information that
141 may be provided alongside the generic
142 .I fanotify_event_metadata
143 structure.
144 The
145 .I flags
146 passed to
147 .BR fanotify_init (2)
148 have influence over the type of information records that
149 may be returned for an event.
150 For example,
151 if a notification group is initialized with
152 .B FAN_REPORT_FID
153 or
154 .BR FAN_REPORT_DIR_FID ,
155 then event listeners should also expect to receive a
156 .I fanotify_event_info_fid
157 structure alongside the
158 .I fanotify_event_metadata
159 structure,
160 whereby file handles are used to
161 identify filesystem objects
162 rather than file descriptors.
163 Information records may also be stacked,
164 meaning that using the various
165 .B FAN_REPORT_*
166 flags in conjunction with one another is supported.
167 In such cases,
168 multiple information records can be returned for an event
169 alongside the generic
170 .I fanotify_event_metadata
171 structure.
172 For example,
173 if a notification group is initialized with
174 .B FAN_REPORT_TARGET_FID
175 and
176 .BR FAN_REPORT_PIDFD ,
177 then an event listener should expect to receive up to two
178 .I fanotify_event_info_fid
179 information records and one
180 .I fanotify_event_info_pidfd
181 information record alongside the generic
182 .I fanotify_event_metadata
183 structure.
184 Importantly,
185 fanotify provides no guarantee around
186 the ordering of information records
187 when a notification group is initialized with a
188 stacked based configuration.
189 Each information record has a nested structure of type
190 .IR fanotify_event_info_header .
191 It is imperative for event listeners to inspect the
192 .I info_type
193 field of this structure in order to
194 determine the type of information record that
195 had been received for a given event.
196 .P
197 In cases where an fanotify group
198 identifies filesystem objects by file handles,
199 event listeners should also expect to
200 receive one or more of the below
201 information record objects alongside the generic
202 .I fanotify_event_metadata
203 structure within the read buffer:
204 .P
205 .in +4n
206 .EX
207 struct fanotify_event_info_fid {
208 struct fanotify_event_info_header hdr;
209 __kernel_fsid_t fsid;
210 unsigned char handle[];
211 };
212 .EE
213 .in
214 .P
215 In cases where an fanotify group is initialized with
216 .BR FAN_REPORT_PIDFD ,
217 event listeners should expect to receive the below
218 information record object alongside the generic
219 .I fanotify_event_metadata
220 structure within the read buffer:
221 .P
222 .in +4n
223 .EX
224 struct fanotify_event_info_pidfd {
225 struct fanotify_event_info_header hdr;
226 __s32 pidfd;
227 };
228 .EE
229 .in
230 .P
231 In case of a
232 .B FAN_FS_ERROR
233 event,
234 an additional information record describing the error that occurred
235 is returned alongside the generic
236 .I fanotify_event_metadata
237 structure within the read buffer.
238 This structure is defined as follows:
239 .P
240 .in +4n
241 .EX
242 struct fanotify_event_info_error {
243 struct fanotify_event_info_header hdr;
244 __s32 error;
245 __u32 error_count;
246 };
247 .EE
248 .in
249 .P
250 All information records contain a nested structure of type
251 .IR fanotify_event_info_header .
252 This structure holds meta-information about the information record
253 that may have been returned alongside the generic
254 .I fanotify_event_metadata
255 structure.
256 This structure is defined as follows:
257 .P
258 .in +4n
259 .EX
260 struct fanotify_event_info_header {
261 __u8 info_type;
262 __u8 pad;
263 __u16 len;
264 };
265 .EE
266 .in
267 .P
268 For performance reasons, it is recommended to use a large
269 buffer size (for example, 4096 bytes),
270 so that multiple events can be retrieved by a single
271 .BR read (2).
272 .P
273 The return value of
274 .BR read (2)
275 is the number of bytes placed in the buffer,
276 or \-1 in case of an error (but see BUGS).
277 .P
278 The fields of the
279 .I fanotify_event_metadata
280 structure are as follows:
281 .TP
282 .I event_len
283 This is the size of the data for the current event and the offset
284 to the next event in the buffer.
285 Unless the group identifies filesystem objects by file handles, the value of
286 .I event_len
287 is always
288 .BR FAN_EVENT_METADATA_LEN .
289 For a group that identifies filesystem objects by file handles,
290 .I event_len
291 also includes the variable size file identifier records.
292 .TP
293 .I vers
294 This field holds a version number for the structure.
295 It must be compared to
296 .B FANOTIFY_METADATA_VERSION
297 to verify that the structures returned at run time match
298 the structures defined at compile time.
299 In case of a mismatch, the application should abandon trying to use the
300 fanotify file descriptor.
301 .TP
302 .I reserved
303 This field is not used.
304 .TP
305 .I metadata_len
306 This is the size of the structure.
307 The field was introduced to facilitate the implementation of
308 optional headers per event type.
309 No such optional headers exist in the current implementation.
310 .TP
311 .I mask
312 This is a bit mask describing the event (see below).
313 .TP
314 .I fd
315 This is an open file descriptor for the object being accessed, or
316 .B FAN_NOFD
317 if a queue overflow occurred.
318 With an fanotify group that identifies filesystem objects by file handles,
319 applications should expect this value to be set to
320 .B FAN_NOFD
321 for each event that is received.
322 The file descriptor can be used to access the contents
323 of the monitored file or directory.
324 The reading application is responsible for closing this file descriptor.
325 .IP
326 When calling
327 .BR fanotify_init (2),
328 the caller may specify (via the
329 .I event_f_flags
330 argument) various file status flags that are to be set
331 on the open file description that corresponds to this file descriptor.
332 In addition, the (kernel-internal)
333 .B FMODE_NONOTIFY
334 file status flag is set on the open file description.
335 This flag suppresses fanotify event generation.
336 Hence, when the receiver of the fanotify event accesses the notified file or
337 directory using this file descriptor, no additional events will be created.
338 .TP
339 .I pid
340 If flag
341 .B FAN_REPORT_TID
342 was set in
343 .BR fanotify_init (2),
344 this is the TID of the thread that caused the event.
345 Otherwise, this the PID of the process that caused the event.
346 .P
347 A program listening to fanotify events can compare this PID
348 to the PID returned by
349 .BR getpid (2),
350 to determine whether the event is caused by the listener itself,
351 or is due to a file access by another process.
352 .P
353 The bit mask in
354 .I mask
355 indicates which events have occurred for a single filesystem object.
356 Multiple bits may be set in this mask,
357 if more than one event occurred for the monitored filesystem object.
358 In particular,
359 consecutive events for the same filesystem object and originating from the
360 same process may be merged into a single event, with the exception that two
361 permission events are never merged into one queue entry.
362 .P
363 The bits that may appear in
364 .I mask
365 are as follows:
366 .TP
367 .B FAN_ACCESS
368 A file or a directory (but see BUGS) was accessed (read).
369 .TP
370 .B FAN_OPEN
371 A file or a directory was opened.
372 .TP
373 .B FAN_OPEN_EXEC
374 A file was opened with the intent to be executed.
375 See NOTES in
376 .BR fanotify_mark (2)
377 for additional details.
378 .TP
379 .B FAN_ATTRIB
380 A file or directory metadata was changed.
381 .TP
382 .B FAN_CREATE
383 A child file or directory was created in a watched parent.
384 .TP
385 .B FAN_DELETE
386 A child file or directory was deleted in a watched parent.
387 .TP
388 .B FAN_DELETE_SELF
389 A watched file or directory was deleted.
390 .TP
391 .B FAN_FS_ERROR
392 A filesystem error was detected.
393 .TP
394 .B FAN_RENAME
395 A file or directory has been moved to or from a watched parent directory.
396 .TP
397 .B FAN_MOVED_FROM
398 A file or directory has been moved from a watched parent directory.
399 .TP
400 .B FAN_MOVED_TO
401 A file or directory has been moved to a watched parent directory.
402 .TP
403 .B FAN_MOVE_SELF
404 A watched file or directory was moved.
405 .TP
406 .B FAN_MODIFY
407 A file was modified.
408 .TP
409 .B FAN_CLOSE_WRITE
410 A file that was opened for writing
411 .RB ( O_WRONLY
412 or
413 .BR O_RDWR )
414 was closed.
415 .TP
416 .B FAN_CLOSE_NOWRITE
417 A file or directory that was opened read-only
418 .RB ( O_RDONLY )
419 was closed.
420 .TP
421 .B FAN_Q_OVERFLOW
422 The event queue exceeded the limit on number of events.
423 This limit can be overridden by specifying the
424 .B FAN_UNLIMITED_QUEUE
425 flag when calling
426 .BR fanotify_init (2).
427 .TP
428 .B FAN_ACCESS_PERM
429 An application wants to read a file or directory, for example using
430 .BR read (2)
431 or
432 .BR readdir (2).
433 The reader must write a response (as described below)
434 that determines whether the permission to
435 access the filesystem object shall be granted.
436 .TP
437 .B FAN_OPEN_PERM
438 An application wants to open a file or directory.
439 The reader must write a response that determines whether the permission to
440 open the filesystem object shall be granted.
441 .TP
442 .B FAN_OPEN_EXEC_PERM
443 An application wants to open a file for execution.
444 The reader must write a response that determines whether the permission to
445 open the filesystem object for execution shall be granted.
446 See NOTES in
447 .BR fanotify_mark (2)
448 for additional details.
449 .P
450 To check for any close event, the following bit mask may be used:
451 .TP
452 .B FAN_CLOSE
453 A file was closed.
454 This is a synonym for:
455 .IP
456 .in +4n
457 .EX
458 FAN_CLOSE_WRITE | FAN_CLOSE_NOWRITE
459 .EE
460 .in
461 .P
462 To check for any move event, the following bit mask may be used:
463 .TP
464 .B FAN_MOVE
465 A file or directory was moved.
466 This is a synonym for:
467 .IP
468 .in +4n
469 .EX
470 FAN_MOVED_FROM | FAN_MOVED_TO
471 .EE
472 .in
473 .P
474 The following bits may appear in
475 .I mask
476 only in conjunction with other event type bits:
477 .TP
478 .B FAN_ONDIR
479 The events described in the
480 .I mask
481 have occurred on a directory object.
482 Reporting events on directories requires setting this flag in the mark mask.
483 See
484 .BR fanotify_mark (2)
485 for additional details.
486 The
487 .B FAN_ONDIR
488 flag is reported in an event mask only if the fanotify group identifies
489 filesystem objects by file handles.
490 .P
491 Information records that are supplied alongside the generic
492 .I fanotify_event_metadata
493 structure will always contain a nested structure of type
494 .IR fanotify_event_info_header .
495 The fields of the
496 .I fanotify_event_info_header
497 are as follows:
498 .TP
499 .I info_type
500 A unique integer value representing
501 the type of information record object received for an event.
502 The value of this field can be set to one of the following:
503 .BR FAN_EVENT_INFO_TYPE_FID ,
504 .BR FAN_EVENT_INFO_TYPE_DFID ,
505 .BR FAN_EVENT_INFO_TYPE_DFID_NAME ,
506 or
507 .BR FAN_EVENT_INFO_TYPE_PIDFD .
508 The value set for this field
509 is dependent on the flags that have been supplied to
510 .BR fanotify_init (2).
511 Refer to the field details of each information record object type below
512 to understand the different cases in which the
513 .I info_type
514 values can be set.
515 .TP
516 .I pad
517 This field is currently not used by any information record object type
518 and therefore is set to zero.
519 .TP
520 .I len
521 The value of
522 .I len
523 is set to the size of the information record object,
524 including the
525 .IR fanotify_event_info_header .
526 The total size of all additional information records
527 is not expected to be larger than
528 .RI ( event_len
529 \-
530 .IR metadata_len ).
531 .P
532 The fields of the
533 .I fanotify_event_info_fid
534 structure are as follows:
535 .TP
536 .I hdr
537 This is a structure of type
538 .IR fanotify_event_info_header .
539 For example, when an fanotify file descriptor is created using
540 .BR FAN_REPORT_FID ,
541 a single information record is expected to be attached to the event with
542 .I info_type
543 field value of
544 .BR FAN_EVENT_INFO_TYPE_FID .
545 When an fanotify file descriptor is created using the combination of
546 .B FAN_REPORT_FID
547 and
548 .BR FAN_REPORT_DIR_FID ,
549 there may be two information records attached to the event:
550 one with
551 .I info_type
552 field value of
553 .BR FAN_EVENT_INFO_TYPE_DFID ,
554 identifying a parent directory object, and one with
555 .I info_type
556 field value of
557 .BR FAN_EVENT_INFO_TYPE_FID ,
558 identifying a child object.
559 Note that for the directory entry modification events
560 .BR FAN_CREATE ,
561 .BR FAN_DELETE ,
562 .BR FAN_MOVE ,
563 and
564 .BR FAN_RENAME ,
565 an information record identifying the created/deleted/moved child object
566 is reported only if an fanotify group was initialized with the flag
567 .BR FAN_REPORT_TARGET_FID .
568 .TP
569 .I fsid
570 This is a unique identifier of the filesystem containing the object
571 associated with the event.
572 It is a structure of type
573 .I __kernel_fsid_t
574 and contains the same value as
575 .I f_fsid
576 when calling
577 .BR statfs (2).
578 Note that some filesystems (e.g.,
579 .BR fuse (4))
580 report zero
581 .IR fsid .
582 In these cases,
583 it is not possible to use
584 .I fsid
585 to associate the event with a specific filesystem instance,
586 so monitoring different filesystem instances that report zero
587 .I fsid
588 with the same fanotify group is not supported.
589 .TP
590 .I handle
591 This field contains a variable-size structure of type
592 .IR "struct file_handle" .
593 It is an opaque handle that corresponds to a specified object on a
594 filesystem as returned by
595 .BR name_to_handle_at (2).
596 It can be used to uniquely identify a file on a filesystem and can be
597 passed as an argument to
598 .BR open_by_handle_at (2).
599 If the value of
600 .I info_type
601 field is
602 .BR FAN_EVENT_INFO_TYPE_DFID_NAME ,
603 the file handle is followed by a null terminated string that identifies the
604 created/deleted/moved directory entry name.
605 For other events such as
606 .BR FAN_OPEN ,
607 .BR FAN_ATTRIB ,
608 .BR FAN_DELETE_SELF ,
609 and
610 .BR FAN_MOVE_SELF ,
611 if the value of
612 .I info_type
613 field is
614 .BR FAN_EVENT_INFO_TYPE_FID ,
615 the
616 .I handle
617 identifies the object correlated to the event.
618 If the value of
619 .I info_type
620 field is
621 .BR FAN_EVENT_INFO_TYPE_DFID ,
622 the
623 .I handle
624 identifies the directory object correlated to the event or the parent directory
625 of a non-directory object correlated to the event.
626 If the value of
627 .I info_type
628 field is
629 .BR FAN_EVENT_INFO_TYPE_DFID_NAME ,
630 the
631 .I handle
632 identifies the same directory object that would be reported with
633 .B FAN_EVENT_INFO_TYPE_DFID
634 and the file handle is followed by a null terminated string that identifies the
635 name of a directory entry in that directory, or '.' to identify the directory
636 object itself.
637 .P
638 The fields of the
639 .I fanotify_event_info_pidfd
640 structure are as follows:
641 .TP
642 .I hdr
643 This is a structure of type
644 .IR fanotify_event_info_header .
645 When an fanotify group is initialized using
646 .BR FAN_REPORT_PIDFD ,
647 the
648 .I info_type
649 field value of the
650 .I fanotify_event_info_header
651 is set to
652 .BR FAN_EVENT_INFO_TYPE_PIDFD .
653 .TP
654 .I pidfd
655 This is a process file descriptor that refers to
656 the process responsible for generating the event.
657 The returned process file descriptor is no different from
658 one which could be obtained manually if
659 .BR pidfd_open (2)
660 were to be called on
661 .IR fanotify_event_metadata.pid .
662 In the instance that an error is encountered during pidfd creation,
663 one of two possible error types represented by
664 a negative integer value may be returned in this
665 .I pidfd
666 field.
667 In cases where
668 the process responsible for generating the event
669 has terminated prior to
670 the event listener being able to
671 read events from the notification queue,
672 .B FAN_NOPIDFD
673 is returned.
674 The pidfd creation for an event is only performed at the time the
675 events are read from the notification queue.
676 All other possible pidfd creation failures are represented by
677 .BR FAN_EPIDFD .
678 Once the event listener has dealt with an event
679 and the pidfd is no longer required,
680 the pidfd should be closed via
681 .BR close (2).
682 .P
683 The fields of the
684 .I fanotify_event_info_error
685 structure are as follows:
686 .TP
687 .I hdr
688 This is a structure of type
689 .IR fanotify_event_info_header .
690 The
691 .I info_type
692 field is set to
693 .BR FAN_EVENT_INFO_TYPE_ERROR .
694 .TP
695 .I error
696 Identifies the type of error that occurred.
697 .TP
698 .I error_count
699 This is a counter of the number of errors suppressed
700 since the last error was read.
701 .P
702 The following macros are provided to iterate over a buffer containing
703 fanotify event metadata returned by a
704 .BR read (2)
705 from an fanotify file descriptor:
706 .TP
707 .B FAN_EVENT_OK(meta, size)
708 This macro checks the remaining size
709 .I size
710 of the buffer
711 .I meta
712 against the size of the metadata structure and the
713 .I event_len
714 field of the first metadata structure in the buffer.
715 .TP
716 .B FAN_EVENT_NEXT(meta, size)
717 This macro uses the size indicated in the
718 .I event_len
719 field of the metadata structure pointed to by
720 .I meta
721 to calculate the address of the next metadata structure that follows
722 .IR meta .
723 .I size
724 is the number of bytes of metadata that currently remain in the buffer.
725 The macro returns a pointer to the next metadata structure that follows
726 .IR meta ,
727 and reduces
728 .I size
729 by the number of bytes in the metadata structure that
730 has been skipped over (i.e., it subtracts
731 .I meta\->event_len
732 from
733 .IR size ).
734 .P
735 In addition, there is:
736 .TP
737 .B FAN_EVENT_METADATA_LEN
738 This macro returns the size (in bytes) of the structure
739 .IR fanotify_event_metadata .
740 This is the minimum size (and currently the only size) of any event metadata.
741 .\"
742 .SS Monitoring an fanotify file descriptor for events
743 When an fanotify event occurs, the fanotify file descriptor indicates as
744 readable when passed to
745 .BR epoll (7),
746 .BR poll (2),
747 or
748 .BR select (2).
749 .SS Dealing with permission events
750 For permission events, the application must
751 .BR write (2)
752 a structure of the following form to the
753 fanotify file descriptor:
754 .P
755 .in +4n
756 .EX
757 struct fanotify_response {
758 __s32 fd;
759 __u32 response;
760 };
761 .EE
762 .in
763 .P
764 The fields of this structure are as follows:
765 .TP
766 .I fd
767 This is the file descriptor from the structure
768 .IR fanotify_event_metadata .
769 .TP
770 .I response
771 This field indicates whether or not the permission is to be granted.
772 Its value must be either
773 .B FAN_ALLOW
774 to allow the file operation or
775 .B FAN_DENY
776 to deny the file operation.
777 .P
778 If access is denied, the requesting application call will receive an
779 .B EPERM
780 error.
781 Additionally, if the notification group has been created with the
782 .B FAN_ENABLE_AUDIT
783 flag, then the
784 .B FAN_AUDIT
785 flag can be set in the
786 .I response
787 field.
788 In that case, the audit subsystem will log information about the access
789 decision to the audit logs.
790 .\"
791 .SS Monitoring filesystems for errors
792 A single
793 .B FAN_FS_ERROR
794 event is stored per filesystem at once.
795 Extra error messages are suppressed and accounted for in the
796 .I error_count
797 field of the existing
798 .B FAN_FS_ERROR
799 event record,
800 but details about the errors are lost.
801 .P
802 Errors reported by
803 .B FAN_FS_ERROR
804 are generic
805 .I errno
806 values,
807 but not all kinds of error types are reported by all filesystems.
808 .P
809 Errors not directly related to a file (i.e. super block corruption)
810 are reported with an invalid
811 .IR handle .
812 For these errors, the
813 .I handle
814 will have the field
815 .I handle_type
816 set to
817 .BR FILEID_INVALID ,
818 and the handle buffer size set to
819 .BR 0 .
820 .\"
821 .SS Closing the fanotify file descriptor
822 When all file descriptors referring to the fanotify notification group are
823 closed, the fanotify group is released and its resources
824 are freed for reuse by the kernel.
825 Upon
826 .BR close (2),
827 outstanding permission events will be set to allowed.
828 .SS /proc interfaces
829 The file
830 .IR /proc/ pid /fdinfo/ fd
831 contains information about fanotify marks for file descriptor
832 .I fd
833 of process
834 .IR pid .
835 See
836 .BR proc (5)
837 for details.
838 .P
839 Since Linux 5.13 (and 5.10.220),
840 .\" commit 5b8fea65d197f408bb00b251c70d842826d6b70b
841 the following interfaces can be used to control the amount of
842 kernel resources consumed by fanotify:
843 .TP
844 .I /proc/sys/fs/fanotify/max_queued_events
845 The value in this file is used when an application calls
846 .BR fanotify_init (2)
847 to set an upper limit on the number of events that can be
848 queued to the corresponding fanotify group.
849 Events in excess of this limit are dropped, but an
850 .B FAN_Q_OVERFLOW
851 event is always generated.
852 Prior to Linux kernel 5.13,
853 .\" commit 5b8fea65d197f408bb00b251c70d842826d6b70b
854 the hardcoded limit was 16384 events.
855 .TP
856 .I /proc/sys/fs/fanotify/max_user_group
857 This specifies an upper limit on the number of fanotify groups
858 that can be created per real user ID.
859 Prior to Linux kernel 5.13,
860 .\" commit 5b8fea65d197f408bb00b251c70d842826d6b70b
861 the hardcoded limit was 128 groups per user.
862 .TP
863 .I /proc/sys/fs/fanotify/max_user_marks
864 This specifies an upper limit on the number of fanotify marks
865 that can be created per real user ID.
866 Prior to Linux kernel 5.13,
867 .\" commit 5b8fea65d197f408bb00b251c70d842826d6b70b
868 the hardcoded limit was 8192 marks per group (not per user).
869 .SH ERRORS
870 In addition to the usual errors for
871 .BR read (2),
872 the following errors can occur when reading from the
873 fanotify file descriptor:
874 .TP
875 .B EINVAL
876 The buffer is too small to hold the event.
877 .TP
878 .B EMFILE
879 The per-process limit on the number of open files has been reached.
880 See the description of
881 .B RLIMIT_NOFILE
882 in
883 .BR getrlimit (2).
884 .TP
885 .B ENFILE
886 The system-wide limit on the total number of open files has been reached.
887 See
888 .I /proc/sys/fs/file\-max
889 in
890 .BR proc (5).
891 .TP
892 .B ETXTBSY
893 This error is returned by
894 .BR read (2)
895 if
896 .B O_RDWR
897 or
898 .B O_WRONLY
899 was specified in the
900 .I event_f_flags
901 argument when calling
902 .BR fanotify_init (2)
903 and an event occurred for a monitored file that is currently being executed.
904 .P
905 In addition to the usual errors for
906 .BR write (2),
907 the following errors can occur when writing to the fanotify file descriptor:
908 .TP
909 .B EINVAL
910 Fanotify access permissions are not enabled in the kernel configuration
911 or the value of
912 .I response
913 in the response structure is not valid.
914 .TP
915 .B ENOENT
916 The file descriptor
917 .I fd
918 in the response structure is not valid.
919 This may occur when a response for the permission event has already been
920 written.
921 .SH STANDARDS
922 Linux.
923 .SH HISTORY
924 The fanotify API was introduced in Linux 2.6.36 and
925 enabled in Linux 2.6.37.
926 fdinfo support was added in Linux 3.8.
927 .SH NOTES
928 The fanotify API is available only if the kernel was built with the
929 .B CONFIG_FANOTIFY
930 configuration option enabled.
931 In addition, fanotify permission handling is available only if the
932 .B CONFIG_FANOTIFY_ACCESS_PERMISSIONS
933 configuration option is enabled.
934 .SS Limitations and caveats
935 Fanotify reports only events that a user-space program triggers through the
936 filesystem API.
937 As a result,
938 it does not catch remote events that occur on network filesystems.
939 .P
940 The fanotify API does not report file accesses and modifications that
941 may occur because of
942 .BR mmap (2),
943 .BR msync (2),
944 and
945 .BR munmap (2).
946 .P
947 Events for directories are created only if the directory itself is opened,
948 read, and closed.
949 Adding, removing, or changing children of a marked directory does not create
950 events for the monitored directory itself.
951 .P
952 Fanotify monitoring of directories is not recursive:
953 to monitor subdirectories under a directory,
954 additional marks must be created.
955 The
956 .B FAN_CREATE
957 event can be used for detecting when a subdirectory has been created under
958 a marked directory.
959 An additional mark must then be set on the newly created subdirectory.
960 This approach is racy, because it can lose events that occurred inside the
961 newly created subdirectory, before a mark is added on that subdirectory.
962 Monitoring mounts offers the capability to monitor a whole directory tree
963 in a race-free manner.
964 Monitoring filesystems offers the capability to monitor changes made from
965 any mount of a filesystem instance in a race-free manner.
966 .P
967 The event queue can overflow.
968 In this case, events are lost.
969 .SH BUGS
970 Before Linux 3.19,
971 .BR fallocate (2)
972 did not generate fanotify events.
973 Since Linux 3.19,
974 .\" commit 820c12d5d6c0890bc93dd63893924a13041fdc35
975 calls to
976 .BR fallocate (2)
977 generate
978 .B FAN_MODIFY
979 events.
980 .P
981 As of Linux 3.17,
982 the following bugs exist:
983 .IP \[bu] 3
984 On Linux, a filesystem object may be accessible through multiple paths,
985 for example, a part of a filesystem may be remounted using the
986 .I \-\-bind
987 option of
988 .BR mount (8).
989 A listener that marked a mount will be notified only of events that were
990 triggered for a filesystem object using the same mount.
991 Any other event will pass unnoticed.
992 .IP \[bu]
993 .\" FIXME . A patch was proposed.
994 When an event is generated,
995 no check is made to see whether the user ID of the
996 receiving process has authorization to read or write the file
997 before passing a file descriptor for that file.
998 This poses a security risk, when the
999 .B CAP_SYS_ADMIN
1000 capability is set for programs executed by unprivileged users.
1001 .IP \[bu]
1002 If a call to
1003 .BR read (2)
1004 processes multiple events from the fanotify queue and an error occurs,
1005 the return value will be the total size of the events successfully
1006 copied to the user-space buffer before the error occurred.
1007 The return value will not be \-1, and
1008 .I errno
1009 will not be set.
1010 Thus, the reading application has no way to detect the error.
1011 .SH EXAMPLES
1012 The two example programs below demonstrate the usage of the fanotify API.
1013 .SS Example program: fanotify_example.c
1014 The first program is an example of fanotify being
1015 used with its event object information passed in the form of a file
1016 descriptor.
1017 The program marks the mount passed as a command-line argument and
1018 waits for events of type
1019 .B FAN_OPEN_PERM
1020 and
1021 .BR FAN_CLOSE_WRITE .
1022 When a permission event occurs, a
1023 .B FAN_ALLOW
1024 response is given.
1025 .P
1026 The following shell session shows an example of
1027 running this program.
1028 This session involved editing the file
1029 .IR /home/user/temp/notes .
1030 Before the file was opened, a
1031 .B FAN_OPEN_PERM
1032 event occurred.
1033 After the file was closed, a
1034 .B FAN_CLOSE_WRITE
1035 event occurred.
1036 Execution of the program ends when the user presses the ENTER key.
1037 .P
1038 .in +4n
1039 .EX
1040 # \fB./fanotify_example /home\fP
1041 Press enter key to terminate.
1042 Listening for events.
1043 FAN_OPEN_PERM: File /home/user/temp/notes
1044 FAN_CLOSE_WRITE: File /home/user/temp/notes
1045 \&
1046 Listening for events stopped.
1047 .EE
1048 .in
1049 .SS Program source: fanotify_example.c
1050 \&
1051 .EX
1052 #define _GNU_SOURCE /* Needed to get O_LARGEFILE definition */
1053 #include <errno.h>
1054 #include <fcntl.h>
1055 #include <limits.h>
1056 #include <poll.h>
1057 #include <stdio.h>
1058 #include <stdlib.h>
1059 #include <sys/fanotify.h>
1060 #include <unistd.h>
1061 \&
1062 /* Read all available fanotify events from the file descriptor \[aq]fd\[aq]. */
1063 \&
1064 static void
1065 handle_events(int fd)
1066 {
1067 const struct fanotify_event_metadata *metadata;
1068 struct fanotify_event_metadata buf[200];
1069 ssize_t size;
1070 char path[PATH_MAX];
1071 ssize_t path_len;
1072 char procfd_path[PATH_MAX];
1073 struct fanotify_response response;
1074 \&
1075 /* Loop while events can be read from fanotify file descriptor. */
1076 \&
1077 for (;;) {
1078 \&
1079 /* Read some events. */
1080 \&
1081 size = read(fd, buf, sizeof(buf));
1082 if (size == \-1 && errno != EAGAIN) {
1083 perror("read");
1084 exit(EXIT_FAILURE);
1085 }
1086 \&
1087 /* Check if end of available data reached. */
1088 \&
1089 if (size <= 0)
1090 break;
1091 \&
1092 /* Point to the first event in the buffer. */
1093 \&
1094 metadata = buf;
1095 \&
1096 /* Loop over all events in the buffer. */
1097 \&
1098 while (FAN_EVENT_OK(metadata, size)) {
1099 \&
1100 /* Check that run\-time and compile\-time structures match. */
1101 \&
1102 if (metadata\->vers != FANOTIFY_METADATA_VERSION) {
1103 fprintf(stderr,
1104 "Mismatch of fanotify metadata version.\[rs]n");
1105 exit(EXIT_FAILURE);
1106 }
1107 \&
1108 /* metadata\->fd contains either FAN_NOFD, indicating a
1109 queue overflow, or a file descriptor (a nonnegative
1110 integer). Here, we simply ignore queue overflow. */
1111 \&
1112 if (metadata\->fd >= 0) {
1113 \&
1114 /* Handle open permission event. */
1115 \&
1116 if (metadata\->mask & FAN_OPEN_PERM) {
1117 printf("FAN_OPEN_PERM: ");
1118 \&
1119 /* Allow file to be opened. */
1120 \&
1121 response.fd = metadata\->fd;
1122 response.response = FAN_ALLOW;
1123 write(fd, &response, sizeof(response));
1124 }
1125 \&
1126 /* Handle closing of writable file event. */
1127 \&
1128 if (metadata\->mask & FAN_CLOSE_WRITE)
1129 printf("FAN_CLOSE_WRITE: ");
1130 \&
1131 /* Retrieve and print pathname of the accessed file. */
1132 \&
1133 snprintf(procfd_path, sizeof(procfd_path),
1134 "/proc/self/fd/%d", metadata\->fd);
1135 path_len = readlink(procfd_path, path,
1136 sizeof(path) \- 1);
1137 if (path_len == \-1) {
1138 perror("readlink");
1139 exit(EXIT_FAILURE);
1140 }
1141 \&
1142 path[path_len] = \[aq]\[rs]0\[aq];
1143 printf("File %s\[rs]n", path);
1144 \&
1145 /* Close the file descriptor of the event. */
1146 \&
1147 close(metadata\->fd);
1148 }
1149 \&
1150 /* Advance to next event. */
1151 \&
1152 metadata = FAN_EVENT_NEXT(metadata, size);
1153 }
1154 }
1155 }
1156 \&
1157 int
1158 main(int argc, char *argv[])
1159 {
1160 char buf;
1161 int fd, poll_num;
1162 nfds_t nfds;
1163 struct pollfd fds[2];
1164 \&
1165 /* Check mount point is supplied. */
1166 \&
1167 if (argc != 2) {
1168 fprintf(stderr, "Usage: %s MOUNT\[rs]n", argv[0]);
1169 exit(EXIT_FAILURE);
1170 }
1171 \&
1172 printf("Press enter key to terminate.\[rs]n");
1173 \&
1174 /* Create the file descriptor for accessing the fanotify API. */
1175 \&
1176 fd = fanotify_init(FAN_CLOEXEC | FAN_CLASS_CONTENT | FAN_NONBLOCK,
1177 O_RDONLY | O_LARGEFILE);
1178 if (fd == \-1) {
1179 perror("fanotify_init");
1180 exit(EXIT_FAILURE);
1181 }
1182 \&
1183 /* Mark the mount for:
1184 \- permission events before opening files
1185 \- notification events after closing a write\-enabled
1186 file descriptor. */
1187 \&
1188 if (fanotify_mark(fd, FAN_MARK_ADD | FAN_MARK_MOUNT,
1189 FAN_OPEN_PERM | FAN_CLOSE_WRITE, AT_FDCWD,
1190 argv[1]) == \-1) {
1191 perror("fanotify_mark");
1192 exit(EXIT_FAILURE);
1193 }
1194 \&
1195 /* Prepare for polling. */
1196 \&
1197 nfds = 2;
1198 \&
1199 fds[0].fd = STDIN_FILENO; /* Console input */
1200 fds[0].events = POLLIN;
1201 \&
1202 fds[1].fd = fd; /* Fanotify input */
1203 fds[1].events = POLLIN;
1204 \&
1205 /* This is the loop to wait for incoming events. */
1206 \&
1207 printf("Listening for events.\[rs]n");
1208 \&
1209 while (1) {
1210 poll_num = poll(fds, nfds, \-1);
1211 if (poll_num == \-1) {
1212 if (errno == EINTR) /* Interrupted by a signal */
1213 continue; /* Restart poll() */
1214 \&
1215 perror("poll"); /* Unexpected error */
1216 exit(EXIT_FAILURE);
1217 }
1218 \&
1219 if (poll_num > 0) {
1220 if (fds[0].revents & POLLIN) {
1221 \&
1222 /* Console input is available: empty stdin and quit. */
1223 \&
1224 while (read(STDIN_FILENO, &buf, 1) > 0 && buf != \[aq]\[rs]n\[aq])
1225 continue;
1226 break;
1227 }
1228 \&
1229 if (fds[1].revents & POLLIN) {
1230 \&
1231 /* Fanotify events are available. */
1232 \&
1233 handle_events(fd);
1234 }
1235 }
1236 }
1237 \&
1238 printf("Listening for events stopped.\[rs]n");
1239 exit(EXIT_SUCCESS);
1240 }
1241 .EE
1242 .\"
1243 .SS Example program: fanotify_fid.c
1244 The second program is an example of fanotify being used with a group that
1245 identifies objects by file handles.
1246 The program marks the filesystem object that is passed as
1247 a command-line argument
1248 and waits until an event of type
1249 .B FAN_CREATE
1250 has occurred.
1251 The event mask indicates which type of filesystem object\[em]either
1252 a file or a directory\[em]was created.
1253 Once all events have been read from the buffer and processed accordingly,
1254 the program simply terminates.
1255 .P
1256 The following shell sessions show two different invocations of
1257 this program, with different actions performed on a watched object.
1258 .P
1259 The first session shows a mark being placed on
1260 .IR /home/user .
1261 This is followed by the creation of a regular file,
1262 .IR /home/user/testfile.txt .
1263 This results in a
1264 .B FAN_CREATE
1265 event being generated and reported against the file's parent watched
1266 directory object and with the created file name.
1267 Program execution ends once all events captured within the buffer have
1268 been processed.
1269 .P
1270 .in +4n
1271 .EX
1272 # \fB./fanotify_fid /home/user\fP
1273 Listening for events.
1274 FAN_CREATE (file created):
1275 Directory /home/user has been modified.
1276 Entry \[aq]testfile.txt\[aq] is not a subdirectory.
1277 All events processed successfully. Program exiting.
1278 \&
1279 $ \fBtouch /home/user/testfile.txt\fP # In another terminal
1280 .EE
1281 .in
1282 .P
1283 The second session shows a mark being placed on
1284 .IR /home/user .
1285 This is followed by the creation of a directory,
1286 .IR /home/user/testdir .
1287 This specific action results in a
1288 .B FAN_CREATE
1289 event being generated and is reported with the
1290 .B FAN_ONDIR
1291 flag set and with the created directory name.
1292 .P
1293 .in +4n
1294 .EX
1295 # \fB./fanotify_fid /home/user\fP
1296 Listening for events.
1297 FAN_CREATE | FAN_ONDIR (subdirectory created):
1298 Directory /home/user has been modified.
1299 Entry \[aq]testdir\[aq] is a subdirectory.
1300 All events processed successfully. Program exiting.
1301 \&
1302 $ \fBmkdir \-p /home/user/testdir\fP # In another terminal
1303 .EE
1304 .in
1305 .SS Program source: fanotify_fid.c
1306 \&
1307 .EX
1308 #define _GNU_SOURCE
1309 #include <errno.h>
1310 #include <fcntl.h>
1311 #include <limits.h>
1312 #include <stdio.h>
1313 #include <stdlib.h>
1314 #include <sys/types.h>
1315 #include <sys/stat.h>
1316 #include <sys/fanotify.h>
1317 #include <unistd.h>
1318 \&
1319 #define BUF_SIZE 256
1320 \&
1321 int
1322 main(int argc, char *argv[])
1323 {
1324 int fd, ret, event_fd, mount_fd;
1325 ssize_t size, path_len;
1326 char path[PATH_MAX];
1327 char procfd_path[PATH_MAX];
1328 char events_buf[BUF_SIZE];
1329 struct file_handle *file_handle;
1330 struct fanotify_event_metadata *metadata;
1331 struct fanotify_event_info_fid *fid;
1332 const char *file_name;
1333 struct stat sb;
1334 \&
1335 if (argc != 2) {
1336 fprintf(stderr, "Invalid number of command line arguments.\[rs]n");
1337 exit(EXIT_FAILURE);
1338 }
1339 \&
1340 mount_fd = open(argv[1], O_DIRECTORY | O_RDONLY);
1341 if (mount_fd == \-1) {
1342 perror(argv[1]);
1343 exit(EXIT_FAILURE);
1344 }
1345 \&
1346 /* Create an fanotify file descriptor with FAN_REPORT_DFID_NAME as
1347 a flag so that program can receive fid events with directory
1348 entry name. */
1349 \&
1350 fd = fanotify_init(FAN_CLASS_NOTIF | FAN_REPORT_DFID_NAME, 0);
1351 if (fd == \-1) {
1352 perror("fanotify_init");
1353 exit(EXIT_FAILURE);
1354 }
1355 \&
1356 /* Place a mark on the filesystem object supplied in argv[1]. */
1357 \&
1358 ret = fanotify_mark(fd, FAN_MARK_ADD | FAN_MARK_ONLYDIR,
1359 FAN_CREATE | FAN_ONDIR,
1360 AT_FDCWD, argv[1]);
1361 if (ret == \-1) {
1362 perror("fanotify_mark");
1363 exit(EXIT_FAILURE);
1364 }
1365 \&
1366 printf("Listening for events.\[rs]n");
1367 \&
1368 /* Read events from the event queue into a buffer. */
1369 \&
1370 size = read(fd, events_buf, sizeof(events_buf));
1371 if (size == \-1 && errno != EAGAIN) {
1372 perror("read");
1373 exit(EXIT_FAILURE);
1374 }
1375 \&
1376 /* Process all events within the buffer. */
1377 \&
1378 for (metadata = (struct fanotify_event_metadata *) events_buf;
1379 FAN_EVENT_OK(metadata, size);
1380 metadata = FAN_EVENT_NEXT(metadata, size)) {
1381 fid = (struct fanotify_event_info_fid *) (metadata + 1);
1382 file_handle = (struct file_handle *) fid\->handle;
1383 \&
1384 /* Ensure that the event info is of the correct type. */
1385 \&
1386 if (fid\->hdr.info_type == FAN_EVENT_INFO_TYPE_FID ||
1387 fid\->hdr.info_type == FAN_EVENT_INFO_TYPE_DFID) {
1388 file_name = NULL;
1389 } else if (fid\->hdr.info_type == FAN_EVENT_INFO_TYPE_DFID_NAME) {
1390 file_name = file_handle\->f_handle +
1391 file_handle\->handle_bytes;
1392 } else {
1393 fprintf(stderr, "Received unexpected event info type.\[rs]n");
1394 exit(EXIT_FAILURE);
1395 }
1396 \&
1397 if (metadata\->mask == FAN_CREATE)
1398 printf("FAN_CREATE (file created):\[rs]n");
1399 \&
1400 if (metadata\->mask == (FAN_CREATE | FAN_ONDIR))
1401 printf("FAN_CREATE | FAN_ONDIR (subdirectory created):\[rs]n");
1402 \&
1403 /* metadata\->fd is set to FAN_NOFD when the group identifies
1404 objects by file handles. To obtain a file descriptor for
1405 the file object corresponding to an event you can use the
1406 struct file_handle that\[aq]s provided within the
1407 fanotify_event_info_fid in conjunction with the
1408 open_by_handle_at(2) system call. A check for ESTALE is
1409 done to accommodate for the situation where the file handle
1410 for the object was deleted prior to this system call. */
1411 \&
1412 event_fd = open_by_handle_at(mount_fd, file_handle, O_RDONLY);
1413 if (event_fd == \-1) {
1414 if (errno == ESTALE) {
1415 printf("File handle is no longer valid. "
1416 "File has been deleted\[rs]n");
1417 continue;
1418 } else {
1419 perror("open_by_handle_at");
1420 exit(EXIT_FAILURE);
1421 }
1422 }
1423 \&
1424 snprintf(procfd_path, sizeof(procfd_path), "/proc/self/fd/%d",
1425 event_fd);
1426 \&
1427 /* Retrieve and print the path of the modified dentry. */
1428 \&
1429 path_len = readlink(procfd_path, path, sizeof(path) \- 1);
1430 if (path_len == \-1) {
1431 perror("readlink");
1432 exit(EXIT_FAILURE);
1433 }
1434 \&
1435 path[path_len] = \[aq]\[rs]0\[aq];
1436 printf("\[rs]tDirectory \[aq]%s\[aq] has been modified.\[rs]n", path);
1437 \&
1438 if (file_name) {
1439 ret = fstatat(event_fd, file_name, &sb, 0);
1440 if (ret == \-1) {
1441 if (errno != ENOENT) {
1442 perror("fstatat");
1443 exit(EXIT_FAILURE);
1444 }
1445 printf("\[rs]tEntry \[aq]%s\[aq] does not exist.\[rs]n", file_name);
1446 } else if ((sb.st_mode & S_IFMT) == S_IFDIR) {
1447 printf("\[rs]tEntry \[aq]%s\[aq] is a subdirectory.\[rs]n", file_name);
1448 } else {
1449 printf("\[rs]tEntry \[aq]%s\[aq] is not a subdirectory.\[rs]n",
1450 file_name);
1451 }
1452 }
1453 \&
1454 /* Close associated file descriptor for this event. */
1455 \&
1456 close(event_fd);
1457 }
1458 \&
1459 printf("All events processed successfully. Program exiting.\[rs]n");
1460 exit(EXIT_SUCCESS);
1461 }
1462 .EE
1463 .SH SEE ALSO
1464 .ad l
1465 .BR fanotify_init (2),
1466 .BR fanotify_mark (2),
1467 .BR inotify (7)