Provided by: manpages-ru_4.21.0-2_all bug

ИМЯ

       fanotify - отслеживание событий в файловой системе

ОПИСАНИЕ

       The  fanotify  API  provides notification and interception of filesystem events.  Use cases include virus
       scanning and hierarchical storage management.  In the original fanotify API, only a limited set of events
       was supported.  In particular, there was no support for create, delete, and move events.  The support for
       those events was added in Linux 5.1.  (See inotify(7)  for details of an API that did notify those events
       pre Linux 5.1.)

       Дополнительные возможности по сравнению с программным интерфейсом inotify(7): способность отслеживать все
       объекты в смонтированной файловой системе, давать права на доступ и читать или изменять файлы  перед  тем
       как доступ получат другие приложения.

       В  программный  интерфейс входят следующие системные вызовы: fanotify_init(2), fanotify_mark(2), read(2),
       write(2) и close(2).

   Вызовы fanotify_init(), fanotify_mark() и группы уведомлений
       Системный вызов fanotify_init(2) создаёт  и  инициализирует  группу  уведомления  fanotify  и  возвращает
       указывающий на неё файловый дескриптор.

       An  fanotify  notification  group  is  a  kernel-internal object that holds a list of files, directories,
       filesystems, and mounts for which events shall be created.

       For each entry in an fanotify notification group, two bit masks exist: the mark mask and the ignore mask.
       The mark mask defines file activities for which an event shall  be  created.   The  ignore  mask  defines
       activities  for which no event shall be generated.  Having these two types of masks permits a filesystem,
       mount, or directory to be marked for receiving events,  while  at  the  same  time  ignoring  events  for
       specific objects under a mount or directory.

       The  fanotify_mark(2)   system  call adds a file, directory, filesystem, or mount to a notification group
       and specifies which events shall be reported (or ignored), or removes or modifies such an entry.

       A possible usage of the ignore mask is for a file cache.   Events  of  interest  for  a  file  cache  are
       modification  of a file and closing of the same.  Hence, the cached directory or mount is to be marked to
       receive these events.  After receiving the first event informing that  a  file  has  been  modified,  the
       corresponding  cache  entry  will  be  invalidated.   No further modification events for this file are of
       interest until the file is closed.  Hence, the modify event can  be  added  to  the  ignore  mask.   Upon
       receiving  the close event, the modify event can be removed from the ignore mask and the file cache entry
       can be updated.

       Записи в группе уведомления fanotify ссылаются на файл и каталог по номеру  иноды  (inode),  а  на  точку
       монтирования — через ID монтирования. При переименовании или перемещении файла или каталога внутри той же
       точки  монтирования  соответствующая  запись остаётся. Если файл или каталог удаляется или перемещается в
       другую  точку  монтирования,  или  если  файловая  система  или  точка  монтирования  размонтируется,  то
       соответствующая запись удаляется.

   Очередь событий
       Для  возникающих событий с объектами файловой системы, которые отслеживаются группой уведомления, система
       fanotify генерирует события и помещает их в очередь. После  этого  события  можно  прочитать  (с  помощью
       read(2) и подобных) из файлового дескриптора fanotify, возвращённого fanotify_init(2).

       Two  types  of  events are generated: notification events and permission events.  Notification events are
       merely informative and require no action to be taken by the receiving application with one exception:  if
       a  valid  file  descriptor  is  provided  within  a  generic  event,  the file descriptor must be closed.
       Permission events are requests to the receiving application to  decide  whether  permission  for  a  file
       access  shall  be  granted.   For these events, the recipient must write a response which decides whether
       access is granted or not.

       Событие удаляется из очереди событий группы fanotify  после  прочтения.  События  доступа,  которые  были
       прочитаны,  остаются  во  внутреннем  списке  группы fanotify до тех пор, пока решение о доступе не будет
       записано в файловый дескриптор fanotify, или файловый дескриптор fanotify не будет закрыт.

   Чтение событий fanotify
       Вызов read(2) с файловым дескриптором, полученным от  fanotify_init(2),  блокирует  выполнение  (если  не
       указан  флаг  FAN_NONBLOCK в вызове fanotify_init(2)) до тех пор, пока не произойдёт файловое событие или
       вызов не будет прерван сигналом (смотрите signal(7)).

       After a successful read(2), the read buffer contains one or more of the following structures:

           struct fanotify_event_metadata {
               __u32 event_len;
               __u8 vers;
               __u8 reserved;
               __u16 metadata_len;
               __aligned_u64 mask;
               __s32 fd;
               __s32 pid;
           };

       Information records are supplemental pieces of information that may be  provided  alongside  the  generic
       fanotify_event_metadata structure.  The flags passed to fanotify_init(2)  have influence over the type of
       information  records  that  may  be  returned  for  an  event.   For  example, if a notification group is
       initialized with FAN_REPORT_FID or FAN_REPORT_DIR_FID, then event listeners should also expect to receive
       a fanotify_event_info_fid structure alongside the fanotify_event_metadata structure, whereby file handles
       are used to identify filesystem objects rather than file descriptors.  Information records  may  also  be
       stacked,  meaning that using the various FAN_REPORT_* flags in conjunction with one another is supported.
       In such cases, multiple  information  records  can  be  returned  for  an  event  alongside  the  generic
       fanotify_event_metadata   structure.    For   example,  if  a  notification  group  is  initialized  with
       FAN_REPORT_TARGET_FID and FAN_REPORT_PIDFD, then an event listener should expect to  receive  up  to  two
       fanotify_event_info_fid   information   records  and  one  fanotify_event_info_pidfd  information  record
       alongside the generic fanotify_event_metadata structure.  Importantly,  fanotify  provides  no  guarantee
       around  the ordering of information records when a notification group is initialized with a stacked based
       configuration.  Each information record has a nested structure of type fanotify_event_info_header.  It is
       imperative for event listeners to inspect the info_type field of this structure in order to determine the
       type of information record that had been received for a given event.

       In cases where an fanotify group identifies filesystem objects by file handles,  event  listeners  should
       also  expect  to  receive  one  or  more  of  the  below information record objects alongside the generic
       fanotify_event_metadata structure within the read buffer:

           struct fanotify_event_info_fid {
               struct fanotify_event_info_header hdr;
               __kernel_fsid_t fsid;
               unsigned char file_handle[0];
           };

       In cases where an fanotify group is initialized with FAN_REPORT_PIDFD, event listeners should  expect  to
       receive  the  below  information  record  object  alongside the generic fanotify_event_metadata structure
       within the read buffer:

           struct fanotify_event_info_pidfd {
                   struct fanotify_event_info_header hdr;
                   __s32 pidfd;
           };

       In case of a FAN_FS_ERROR event, an additional information record describing the error that  occurred  is
       returned  alongside the generic fanotify_event_metadata structure within the read buffer.  This structure
       is defined as follows:

           struct fanotify_event_info_error {
               struct fanotify_event_info_header hdr;
               __s32 error;
               __u32 error_count;
           };

       All information records contain a nested structure of type  fanotify_event_info_header.   This  structure
       holds  meta-information  about  the  information record that may have been returned alongside the generic
       fanotify_event_metadata structure.  This structure is defined as follows:

           struct fanotify_event_info_header {
                __u8 info_type;
                __u8 pad;
                __u16 len;
           };

       Для увеличения производительности рекомендуется использовать буфер большого размера (например, 4096 байт)
       для того, чтобы получить несколько событий за один вызов read(2).

       Возвращаемое read(2) значение — количество байт помещённых в буфер, или -1 в случае ошибки  (но  смотрите
       ДЕФЕКТЫ).

       Поля структуры fanotify_event_metadata:

       event_len
              This  is  the  length  of  the  data for the current event and the offset to the next event in the
              buffer.  Unless the group identifies filesystem objects by file handles, the value of event_len is
              always FAN_EVENT_METADATA_LEN.  For a group that identifies filesystem objects  by  file  handles,
              event_len also includes the variable length file identifier records.

       vers   Номер  версии структуры. Он должен сравниваться с FANOTIFY_METADATA_VERSION для проверки того, что
              структуры, возвращаемые во время  выполнения,  соответствуют  структурам,  определённым  во  время
              компиляция.  В  случае  несоответствия  приложение должно прекратить попытки использовать файловый
              дескриптор fanotify.

       reserved
              Не используется.

       metadata_len
              Длина структуры. Это поле было  добавлено  для  облегчения  реализации  необязательных  заголовков
              разных типов событий. В текущей реализации такие необязательные заголовки отсутствуют.

       mask   Битовая маска, описывающая событие (смотрите далее).

       fd     This  is  an  open  file descriptor for the object being accessed, or FAN_NOFD if a queue overflow
              occurred.  With an fanotify group that identifies filesystem objects by file handles, applications
              should expect this value to be set to  FAN_NOFD  for  each  event  that  is  received.   The  file
              descriptor  can  be  used  to access the contents of the monitored file or directory.  The reading
              application is responsible for closing this file descriptor.

              Когда вызывается fanotify_init(2) вызывающий может указать (в аргументе  event_f_flags)  различные
              флаги состояния файла, которые будут установлены на открытом файловом дескрипторе, соответствующем
              этому  файловому  дескриптору.  Также,  на отрываемом файловом дескрипторе устанавливается (внутри
              ядра) флаг состояния файла FMODE_NONOTIFY. Этот флаг подавляет генерацию событий  fanotify.  Таким
              образом,  когда  получатель  события  fanotify обратится к отслеживаемому файлу или каталогу через
              этот файловый дескриптор, дополнительных событий создано не будет.

       pid    Если в fanotify_init(2) установлен флаг FAN_REPORT_TID, то это TID нити,  из-за  которой  возникло
              событие. В противном случае это PID процесса, из-за которой возникло событие.

       Программа,  слушающая  события  fanotify,  может  сравнить  этот  PID  с PID, возвращаемым getpid(2), для
       проверки, что событие не возникло из-за самого слушающего, а из-за доступа к файлу другого процесса.

       В битовой маске mask указывают события, произошедшие с одиночным объектом файловой системы. В маске может
       быть установлено несколько бит, если было более одного события с отслеживаемым объектом файловой системы.
       В частности, возникшие друг за другом события с одним объектом  файловой  системы  и  произошедшие  из-за
       одного  процесса  могут  быть  объединены  в  одно  событие, за исключением того, что два события доступа
       никогда не объединяются в одном элементе очереди.

       Биты маски mask:

       FAN_ACCESS
              Доступ (на чтение) к файлу или каталогу (но смотрите ДЕФЕКТЫ).

       FAN_OPEN
              Файл или каталог открыт.

       FAN_OPEN_EXEC
              Файл открыт для выполнения. Смотрите ЗАМЕЧАНИЯ в fanotify_mark(2).

       FAN_ATTRIB
              Метаданные файла или каталога изменены.

       FAN_CREATE
              Создан дочерний файл или каталог в отслеживаемом родителе.

       FAN_DELETE
              Удалён дочерний файл или каталог в отслеживаемом родителе.

       FAN_DELETE_SELF
              Отслеживаемый файл или каталог был удалён.

       FAN_FS_ERROR
              A filesystem error was detected.

       FAN_RENAME
              A file or directory has been moved to or from a watched parent directory.

       FAN_MOVED_FROM
              Дочерний файл или каталог был перемещён из отслеживаемого родительского каталога.

       FAN_MOVED_TO
              Дочерний файл или каталог был помещён в отслеживаемый родительский каталог.

       FAN_MOVE_SELF
              Отслеживаемый файл или каталог был перемещён.

       FAN_MODIFY
              Файл изменён.

       FAN_CLOSE_WRITE
              Файл, открытый на запись (O_WRONLY или O_RDWR), закрыт.

       FAN_CLOSE_NOWRITE
              Файл или каталог, открытый только для чтения (O_RDONLY), закрыт.

       FAN_Q_OVERFLOW
              The event queue exceeded the limit  on  number  of  events.   This  limit  can  be  overridden  by
              specifying the FAN_UNLIMITED_QUEUE flag when calling fanotify_init(2).

       FAN_ACCESS_PERM
              Приложение  хочет прочитать файл или каталог, например, с помощью read(2) или readdir(2). Читатель
              события должен написать ответ (описано далее) о разрешении доступа к объекту файловой системы.

       FAN_OPEN_PERM
              Приложение хочет открыть файл или каталог. Читатель события должен  написать  ответ  о  разрешении
              открытия объекта файловой системы.

       FAN_OPEN_EXEC_PERM
              Приложение хочет открыть файл для выполнения. Читатель должен написать ответ о разрешении открытия
              объекта файловой системы для выполнения. Смотрите ЗАМЕЧАНИЯ в fanotify_mark(2).

       Для проверки любого события закрытия может использоваться следующая битовая маска:

       FAN_CLOSE
              Файл закрыт. Это синоним:

                  FAN_CLOSE_WRITE | FAN_CLOSE_NOWRITE

       Для проверки любого события перемещения может использоваться следующая битовая маска:

       FAN_MOVE
              Файл или каталог был перемещён. Это синоним для:

                  FAN_MOVED_FROM | FAN_MOVED_TO

       The following bits may appear in mask only in conjunction with other event type bits:

       FAN_ONDIR
              The  events  described  in  the  mask  have  occurred  on a directory object.  Reporting events on
              directories requires setting this flag in the mark mask.   See  fanotify_mark(2)   for  additional
              details.   The  FAN_ONDIR  flag is reported in an event mask only if the fanotify group identifies
              filesystem objects by file handles.

       Information records that are supplied alongside the generic fanotify_event_metadata structure will always
       contain   a   nested   structure   of   type   fanotify_event_info_header.     The    fields    of    the
       fanotify_event_info_header are as follows:

       info_type
              A  unique  integer value representing the type of information record object received for an event.
              The  value  of  this  field  can  be  set  to  one  of  the  following:   FAN_EVENT_INFO_TYPE_FID,
              FAN_EVENT_INFO_TYPE_DFID,  FAN_EVENT_INFO_TYPE_DFID_NAME, or FAN_EVENT_INFO_TYPE_PIDFD.  The value
              set for this field is dependent on the flags that have been supplied to  fanotify_init(2).   Refer
              to  the  field  details  of  each information record object type below to understand the different
              cases in which the info_type values can be set.

       pad    This field is currently not used by any information record object type and  therefore  is  set  to
              zero.

       len    The  value  of  len  is  set  to  the  size  of  the  information  record  object,  including  the
              fanotify_event_info_header.  The total size of all additional information records is not  expected
              to be larger than (event_len - metadata_len).

       Поля структуры fanotify_event_info_fid:

       hdr    This  is  a  structure  of  type  fanotify_event_info_header.   For example, when an fanotify file
              descriptor is created using FAN_REPORT_FID, a single information record is expected to be attached
              to the event with info_type  field  value  of  FAN_EVENT_INFO_TYPE_FID.   When  an  fanotify  file
              descriptor is created using the combination of FAN_REPORT_FID and FAN_REPORT_DIR_FID, there may be
              two   information   records   attached   to   the   event:  one  with  info_type  field  value  of
              FAN_EVENT_INFO_TYPE_DFID, identifying a parent directory object,  and  one  with  info_type  field
              value  of  FAN_EVENT_INFO_TYPE_FID, identifying a child object.  Note that for the directory entry
              modification events FAN_CREATE,  FAN_DELETE,  FAN_MOVE,  and  FAN_RENAME,  an  information  record
              identifying  the  created/deleted/moved  child  object  is  reported only if an fanotify group was
              initialized with the flag FAN_REPORT_TARGET_FID.

       fsid   Уникальный идентификатор файловой системы, содержащей объект, связанный с событием. Это  структура
              имеет тип __kernel_fsid_t и содержит те же значения что и f_fsid при вызове statfs(2).

       file_handle
              This  is  a  variable  length  structure  of type struct file_handle.  It is an opaque handle that
              corresponds to a specified object on a filesystem as returned by name_to_handle_at(2).  It can  be
              used  to  uniquely  identify  a  file  on  a  filesystem  and  can  be  passed  as  an argument to
              open_by_handle_at(2).  If the value of info_type field is FAN_EVENT_INFO_TYPE_DFID_NAME, the  file
              handle is followed by a null terminated string that identifies the created/deleted/moved directory
              entry name.  For other events such as FAN_OPEN, FAN_ATTRIB, FAN_DELETE_SELF, and FAN_MOVE_SELF, if
              the  value  of  info_type  field is FAN_EVENT_INFO_TYPE_FID, the file_handle identifies the object
              correlated to the event.  If  the  value  of  info_type  field  is  FAN_EVENT_INFO_TYPE_DFID,  the
              file_handle  identifies  the directory object correlated to the event or the parent directory of a
              non-directory  object  correlated  to  the  event.   If  the   value   of   info_type   field   is
              FAN_EVENT_INFO_TYPE_DFID_NAME,  the file_handle identifies the same directory object that would be
              reported with FAN_EVENT_INFO_TYPE_DFID and the file handle is followed by a null terminated string
              that identifies the name of a directory entry in that directory, or '.' to identify the  directory
              object itself.

       Поля структуры fanotify_event_info_pidfd:

       hdr    This  is  a  structure  of type fanotify_event_info_header.  When an fanotify group is initialized
              using FAN_REPORT_PIDFD, the info_type field value of  the  fanotify_event_info_header  is  set  to
              FAN_EVENT_INFO_TYPE_PIDFD.

       pidfd  This is a process file descriptor that refers to the process responsible for generating the event.
              The  returned process file descriptor is no different from one which could be obtained manually if
              pidfd_open(2)  were to be called on fanotify_event_metadata.pid.  In the instance that an error is
              encountered during pidfd creation, one of two possible  error  types  represented  by  a  negative
              integer  value  may  be  returned in this pidfd field.  In cases where the process responsible for
              generating the event has terminated prior to the event listener being able to read events from the
              notification queue, FAN_NOPIDFD is returned.  The pidfd creation for an event is only performed at
              the time the events are read from the notification  queue.   All  other  possible  pidfd  creation
              failures  are  represented by FAN_EPIDFD.  Once the event listener has dealt with an event and the
              pidfd is no longer required, the pidfd should be closed via close(2).

       Поля структуры fanotify_event_info_error:

       hdr    This  is  a  structure  of  type  fanotify_event_info_header.   The  info_type  field  is  set  to
              FAN_EVENT_INFO_TYPE_ERROR.

       error  Identifies the type of error that occurred.

       error_count
              This is a counter of the number of errors suppressed since the last error was read.

       Следующие  макросы  позволяют  обходить  буфер  с  метаданными  событий fanotify, возвращаемый read(2) из
       файлового дескриптора fanotify:

       FAN_EVENT_OK(meta, len)
              Этот макрос сверяет оставшуюся длину len  буфера  meta  с  длиной  структуры  метаданных  и  полем
              event_len из первой структуры метаданных в буфере.

       FAN_EVENT_NEXT(meta, len)
              Этот  макрос  использует  длину из поля event_len структуры метаданных, на которую указывает meta,
              для вычисления адреса следующей структуры метаданных, которая находится после  meta.  В  поле  len
              указано  количество байт метаданных, оставшихся в буфере. Макрос возвращает указатель на следующую
              структуру метаданных после meta и уменьшает len на количество байт в структуре метаданных, которая
              была пропущена (т. е., вычитает meta->event_len из len).

       Дополнительно есть:

       FAN_EVENT_METADATA_LEN
              Этот макрос возвращает размер (в байтах) структуры fanotify_event_metadata. Это минимальный размер
              (и, в настоящее время, единственный) метаданных любого события.

   Отслеживание событий через файловый дескриптор fanotify
       Когда возникает событие fanotify файловый дескриптор fanotify помечается как доступный для чтения при его
       передаче в epoll(7), poll(2) или select(2).

   Работа с событиями доступа
       Для событий доступа приложение должно  записать  (write(2))  в  файловый  дескриптор  fanotify  следующую
       структуру:

           struct fanotify_response {
               __s32 fd;
               __u32 response;
           };

       Поля этой структуры имеют следующее назначение:

       fd     Файловый дескриптор из структуры fanotify_event_metadata.

       response
              В  этом  поле  указывает  о  разрешении  доступа или запрещении. Данное значение должно быть равно
              FAN_ALLOW, чтобы разрешить операцию с файлом, или FAN_DENY для запрета.

       If access is denied, the requesting application call will receive an EPERM error.  Additionally,  if  the
       notification group has been created with the FAN_ENABLE_AUDIT flag, then the FAN_AUDIT flag can be set in
       the  response field.  In that case, the audit subsystem will log information about the access decision to
       the audit logs.

   Monitoring filesystems for errors
       A single FAN_FS_ERROR event is stored per filesystem at once.  Extra error messages  are  suppressed  and
       accounted  for  in the error_count field of the existing FAN_FS_ERROR event record, but details about the
       errors are lost.

       Errors reported by FAN_FS_ERROR are generic errno values, but not all kinds of error types  are  reported
       by all filesystems.

       Errors  not  directly  related  to  a  file  (i.e.  super block corruption)  are reported with an invalid
       file_handle.  For these errors, the file_handle will have the field handle_type  set  to  FILEID_INVALID,
       and the handle buffer size set to 0.

   Закрытие файлового дескриптора fanotify
       Когда  все  файловые  дескрипторы,  указывающие  на группу уведомления fanotify, закрыты, группа fanotify
       освобождается и её ресурсы становятся доступны ядру для  повторного  использования.  После  close(2)  все
       оставшиеся непросмотренные события доступа будут разрешены.

   Интерфейс /proc
       Файл  /proc/[pid]/fdinfo/[fd] содержит информацию о метках fanotify для файлового дескриптора fd процесса
       pid Подробности смотрите в proc(5).

       Since Linux 5.13, the following interfaces can be used to control the amount of kernel resources consumed
       by fanotify:

       /proc/sys/fs/fanotify/max_queued_events
              The value in this file is used when an application calls fanotify_init(2) to set an upper limit on
              the number of events that can be queued to the corresponding fanotify group.  Events in excess  of
              this  limit  are  dropped, but an FAN_Q_OVERFLOW event is always generated.  Prior to Linux kernel
              5.13, the hardcoded limit was 16384 events.

       /proc/sys/fs/fanotify/max_user_group
              This specifies an upper limit on the number of fanotify groups that can be created per  real  user
              ID.  Prior to Linux kernel 5.13, the hardcoded limit was 128 groups per user.

       /proc/sys/fs/fanotify/max_user_marks
              This  specifies  an  upper limit on the number of fanotify marks that can be created per real user
              ID.  Prior to Linux kernel 5.13, the hardcoded limit was 8192 marks per group (not per user).

ОШИБКИ

       Кроме обычных ошибок read(2) при чтении из  файлового  дескриптора  fanotify  могут  возникать  следующие
       ошибки:

       EINVAL Буфер слишком мал для хранения события.

       EMFILE Достигнуто максимальное попроцессное количество открытых файлов. Смотрите описание RLIMIT_NOFILE в
              getrlimit(2).

       ENFILE Достигнут  предел  на общее количество открытых файлов в системе. Смотрите /proc/sys/fs/file-max в
              proc(5).

       ETXTBSY
              Эта ошибка возвращается read(2), если при вызове fanotify_init(2) в  аргументе  event_f_flags  был
              указан  O_RDWR  или  O_WRONLY  и произошло событие с отслеживаемым файлом, который в данный момент
              выполняется.

       Кроме обычных ошибок write(2) при записи в файловый дескриптор fanotify могут возникать следующие ошибки:

       EINVAL Свойство для проверки прав доступа  fanotify  не  включено  в  настройках  ядра  или  некорректное
              значение response в структуре ответа.

       ENOENT Некорректный  файловый  дескриптор  fd  в  структуре ответа. Это может происходить, когда ответ на
              право доступа уже был записан.

ВЕРСИИ

       The fanotify API was introduced in Linux 2.6.36 and enabled in Linux 2.6.37.  Fdinfo support was added in
       Linux 3.8.

СТАНДАРТЫ

       Программный интерфейс fanotify есть только в Linux.

ЗАМЕЧАНИЯ

       Программный интерфейс fanotify доступен только, если  ядро  собрано  с  включённым  параметром  настройки
       CONFIG_FANOTIFY.  Также,  работа  с  доступом в fanotify доступна только, если включён параметр настройки
       CONFIG_FANOTIFY_ACCESS_PERMISSIONS.

   Ограничения и подводные камни
       Fanotify сообщает только о событиях, которые возникли  при  использовании  пользовательскими  программами
       программного  интерфейса  файловой  системы.  Поэтому  события  об  обращении к файлам в сетевых файловых
       системах не отлавливаются.

       Программный интерфейс fanotify не сообщает о доступе и изменениях, которые могут произойти из-за mmap(2),
       msync(2) и munmap(2).

       События для каталогов создаются только, если сам каталог открывается, читается и закрывается. Добавление,
       удаление и изменение потомков отслеживаемого каталога не приводит к возникновению событий.

       Fanotify monitoring of directories is  not  recursive:  to  monitor  subdirectories  under  a  directory,
       additional marks must be created.  The FAN_CREATE event can be used for detecting when a subdirectory has
       been  created  under  a  marked  directory.   An  additional  mark  must then be set on the newly created
       subdirectory.  This approach is racy, because it can lose events that occurred inside the  newly  created
       subdirectory,  before  a  mark is added on that subdirectory.  Monitoring mounts offers the capability to
       monitor a whole directory tree in a race-free manner.  Monitoring filesystems offers  the  capability  to
       monitor changes made from any mount of a filesystem instance in a race-free manner.

       Очередь событий может переполниться. В этом случае события теряются.

ДЕФЕКТЫ

       До  Linux  3.19,  fallocate(2) не генерировал событий fanotify. Начиная с Linux 3.19, вызовы fallocate(2)
       генерируют событие FAN_MODIFY.

       В Linux 3.17 существуют следующие дефекты:

       •  В Linux объект файловой системы может быть доступен через несколько путей,  например,  часть  файловой
          системы  может  быть  перемонтирована  mount(8) с использованием параметра --bind. Ожидающий слушатель
          получит уведомления об объекте файловой системы только из запрошенной точки монтирования.  О  событиях
          из других точек уведомлений не поступит.

       •  При  генерации  события  не делается проверка, что пользовательскому ID получающего процесса разрешено
          читать или писать в файл  перед  передачей  файлового  дескриптора  на  этот  файл.  Это  представляет
          некоторый риск безопасности, когда у программ, выполняющихся непривилегированными пользователями, есть
          мандат CAP_SYS_ADMIN.

       •  Если вызов read(2) получает несколько событий из очереди fanotify и возникает ошибка, будет возвращена
          полная  длина  событий,  которые  были  успешно  скопированы в буфер пользовательского пространства до
          ошибки. Возвращаемое значение не будет равно -1, и  в  errno  не  записывается  код  ошибки.  То  есть
          читающее приложение не может обнаружить ошибку.

ПРИМЕРЫ

       Далее  показано  два примера программы, в которых продемонстрированоиспользование программного интерфейса
       fanotify.

   Программа-пример: fanotify_example.c
       The first program is an example of fanotify being used with its event object information  passed  in  the
       form  of  a file descriptor.  The program marks the mount passed as a command-line argument and waits for
       events of type FAN_OPEN_PERM and FAN_CLOSE_WRITE.  When a permission event occurs, a  FAN_ALLOW  response
       is given.

       В  сеансе  оболочки  далее  показан  пример  запуска программы. В сеансе выполняется редактирование файла
       /home/user/temp/notes. Перед открытием  файла  возникает  событие  FAN_OPEN_PERM.  После  закрытия  файла
       возникает событие FAN_CLOSE_WRITE. Выполнение программы заканчивается после нажатия пользователем клавиши
       ENTER.

           # ./fanotify_example /home
           Нажмите enter для завершения работы.
           Ожидание событий.
           FAN_OPEN_PERM: Файл /home/user/temp/notes
           FAN_CLOSE_WRITE: Файл /home/user/temp/notes

           Ожидание событий прекращено.

   Исходный код программы: fanotify_example.c

       #define _GNU_SOURCE     /* для получения определения O_LARGEFILE */
       #include <errno.h>
       #include <fcntl.h>
       #include <limits.h>
       #include <poll.h>
       #include <stdio.h>
       #include <stdlib.h>
       #include <sys/fanotify.h>
       #include <unistd.h>

       /* Read all available fanotify events from the file descriptor 'fd'. */

       static void
       handle_events(int fd)
       {
           const struct fanotify_event_metadata *metadata;
           struct fanotify_event_metadata buf[200];
           ssize_t len;
           char path[PATH_MAX];
           ssize_t path_len;
           char procfd_path[PATH_MAX];
           struct fanotify_response response;

           /* Проходим по всем событиям, которые можем прочитать
              из файлового дескриптора fanotify. */

           for (;;) {

               /* читаем несколько событий */

               len = read(fd, buf, sizeof(buf));
               if (len == -1 && errno != EAGAIN) {
                   perror("read");
                   exit(EXIT_FAILURE);
               }

               /* Проверяем, достигнут ли конец доступных данных. */

               if (len <= 0)
                   break;

               /* Выбираем первое событие в буфере. */

               metadata = buf;

               /* Проходим по всем событиям в буфере. */

               while (FAN_EVENT_OK(metadata, len)) {

                   /* Проверяем, что структуры, использовавшиеся при сборке,
                      идентичны структурам при выполнении. */

                   if (metadata->vers != FANOTIFY_METADATA_VERSION) {
                       fprintf(stderr,
                               "Версия метаданных fanotify не совпадает.\n");
                       exit(EXIT_FAILURE);
                   }

                   /* metadata->fd содержит или FAN_NOFD, указывающее
                      на переполнение очереди, или файловый дескриптор
                      (неотрицательное целое). Здесь мы просто игнорируем
                      переполнение очереди. */

                   if (metadata->fd >= 0) {

                       /* Обрабатываем событие на право открытия. */

                       if (metadata->mask & FAN_OPEN_PERM) {
                           printf("FAN_OPEN_PERM: ");

                           /* Разрешаем открыть файл. */

                           response.fd = metadata->fd;
                           response.response = FAN_ALLOW;
                           write(fd, &response, sizeof(response));
                       }

                       /* Обрабатываем событие закрытия записываемого файла. */

                       if (metadata->mask & FAN_CLOSE_WRITE)
                           printf("FAN_CLOSE_WRITE: ");

                       /* Получаем и выводим имя файла, к которому
                          отслеживается доступ. */

                       snprintf(procfd_path, sizeof(procfd_path),
                                "/proc/self/fd/%d", metadata->fd);
                       path_len = readlink(procfd_path, path,
                                           sizeof(path) - 1);
                       if (path_len == -1) {
                           perror("readlink");
                           exit(EXIT_FAILURE);
                       }

                       path[path_len] = '\0';
                       printf("File %s\n", path);

                       /* Закрываем файловый дескриптор из события. */

                       close(metadata->fd);
                   }

                   /* Переходим на следующее событие. */

                   metadata = FAN_EVENT_NEXT(metadata, len);
               }
           }
       }

       int
       main(int argc, char *argv[])
       {
           char buf;
           int fd, poll_num;
           nfds_t nfds;
           struct pollfd fds[2];

           /* Проверяем заданную точку монтирования. */

           if (argc != 2) {
               fprintf(stderr, "Использование: %s ТОЧКА_МОНТИРОВАНИЯ\n",
                                               argv[0]);
               exit(EXIT_FAILURE);
           }

           printf("Нажмите enter для завершения работы.\n");

           /* Создаём файловый дескриптор для доступа к fanotify API. */

           fd = fanotify_init(FAN_CLOEXEC | FAN_CLASS_CONTENT | FAN_NONBLOCK,
                              O_RDONLY | O_LARGEFILE);
           if (fd == -1) {
               perror("fanotify_init");
               exit(EXIT_FAILURE);
           }

           /* Помечаем точку монтирования для:
              - событий доступа перед открытием файлов
              - событий уведомления после закрытия файлового дескриптора
                для файла открытого для записи. */

           if (fanotify_mark(fd, FAN_MARK_ADD | FAN_MARK_MOUNT,
                             FAN_OPEN_PERM | FAN_CLOSE_WRITE, AT_FDCWD,
                             argv[1]) == -1) {
               perror("fanotify_mark");
               exit(EXIT_FAILURE);
           }

           /* Подготовка к опросу. */

           nfds = 2;

           fds[0].fd = STDIN_FILENO;       /* Console input */
           fds[0].events = POLLIN;

           fds[1].fd = fd;                 /* Fanotify input */
           fds[1].events = POLLIN;

           /* Цикл ожидания входящих событий. */

           printf("Ожидание событий.\n");

           while (1) {
               poll_num = poll(fds, nfds, -1);
               if (poll_num == -1) {
                   if (errno == EINTR)     /* прервано сигналом */
                       continue;           /* перезапуск poll() */

                   perror("poll");         /* неожиданная ошибка */
                   exit(EXIT_FAILURE);
               }

               if (poll_num > 0) {
                   if (fds[0].revents & POLLIN) {

                       /* Доступен ввод с консоли: опустошаем stdin и выходим. */

                       while (read(STDIN_FILENO, &buf, 1) > 0 && buf != '\n')
                           continue;
                       break;
                   }

                   if (fds[1].revents & POLLIN) {

                       /* Доступны события fanotify. */

                       handle_events(fd);
                   }
               }
           }

           printf("Ожидание событий прекращено.\n");
           exit(EXIT_SUCCESS);
       }

   Программа-пример: fanotify_fid.c
       The  second  program  is  an  example of fanotify being used with a group that identifies objects by file
       handles.  The program marks the filesystem object that is passed as a  command-line  argument  and  waits
       until  an  event  of  type  FAN_CREATE  has  occurred.  The event mask indicates which type of filesystem
       object—either a file or a directory—was created.  Once all events have been  read  from  the  buffer  and
       processed accordingly, the program simply terminates.

       В  следующих  сеансах  показано  два  разных  запуска  программы  с  разными  выполняемыми действиями над
       наблюдаемым объектом.

       The first session shows a mark being placed on /home/user.  This is followed by the creation of a regular
       file, /home/user/testfile.txt.  This results in a FAN_CREATE event being generated and  reported  against
       the  file's  parent watched directory object and with the created file name.  Program execution ends once
       all events captured within the buffer have been processed.

           # ./fanotify_fid /home/user
           Listening for events.
           FAN_CREATE (file created):
                   Directory /home/user has been modified.
                   Entry 'testfile.txt' is not a subdirectory.
           All events processed successfully. Program exiting.

           $ touch /home/user/testfile.txt              # в другом терминале

       The second session shows a mark being placed on /home/user.  This  is  followed  by  the  creation  of  a
       directory, /home/user/testdir.  This specific action results in a FAN_CREATE event being generated and is
       reported with the FAN_ONDIR flag set and with the created directory name.

           # ./fanotify_fid /home/user
           Listening for events.
           FAN_CREATE | FAN_ONDIR (subdirectory created):
                   Directory /home/user has been modified.
                   Entry 'testdir' is a subdirectory.
           All events processed successfully. Program exiting.

           $ mkdir -p /home/user/testdir          # в другом терминале

   Исходный код программы: fanotify_fid.c

       #define _GNU_SOURCE
       #include <errno.h>
       #include <fcntl.h>
       #include <limits.h>
       #include <stdio.h>
       #include <stdlib.h>
       #include <sys/types.h>
       #include <sys/stat.h>
       #include <sys/fanotify.h>
       #include <unistd.h>

       #define BUF_SIZE 256

       int
       main(int argc, char *argv[])
       {
           int fd, ret, event_fd, mount_fd;
           ssize_t len, path_len;
           char path[PATH_MAX];
           char procfd_path[PATH_MAX];
           char events_buf[BUF_SIZE];
           struct file_handle *file_handle;
           struct fanotify_event_metadata *metadata;
           struct fanotify_event_info_fid *fid;
           const char *file_name;
           struct stat sb;

           if (argc != 2) {
               fprintf(stderr, "Некорректное количество аргументов в командной строке.\n");
               exit(EXIT_FAILURE);
           }

           mount_fd = open(argv[1], O_DIRECTORY | O_RDONLY);
           if (mount_fd == -1) {
               perror(argv[1]);
               exit(EXIT_FAILURE);
           }

           /* Create an fanotify file descriptor with FAN_REPORT_DFID_NAME as
              a flag so that program can receive fid events with directory
              entry name. */

           fd = fanotify_init(FAN_CLASS_NOTIF | FAN_REPORT_DFID_NAME, 0);
           if (fd == -1) {
               perror("fanotify_init");
               exit(EXIT_FAILURE);
           }

           /* ставим метку на объект файловой системы, заданный в argv[1]. */

           ret = fanotify_mark(fd, FAN_MARK_ADD | FAN_MARK_ONLYDIR,
                               FAN_CREATE | FAN_ONDIR,
                               AT_FDCWD, argv[1]);
           if (ret == -1) {
               perror("fanotify_mark");
               exit(EXIT_FAILURE);
           }

           printf("Ожидание событий.\n");

           /* Читаем события из очереди событий в буфер. */

           len = read(fd, events_buf, sizeof(events_buf));
           if (len == -1 && errno != EAGAIN) {
               perror("read");
               exit(EXIT_FAILURE);
           }

           /* Обрабатываем все события в буфере. */

           for (metadata = (struct fanotify_event_metadata *) events_buf;
                   FAN_EVENT_OK(metadata, len);
                   metadata = FAN_EVENT_NEXT(metadata, len)) {
               fid = (struct fanotify_event_info_fid *) (metadata + 1);
               file_handle = (struct file_handle *) fid->handle;

               /* Проверим, что информация о событии правильного типа. */

               if (fid->hdr.info_type == FAN_EVENT_INFO_TYPE_FID ||
                   fid->hdr.info_type == FAN_EVENT_INFO_TYPE_DFID) {
                   file_name = NULL;
               } else if (fid->hdr.info_type == FAN_EVENT_INFO_TYPE_DFID_NAME) {
                   file_name = file_handle->f_handle +
                               file_handle->handle_bytes;
               } else {
                   fprintf(stderr, "Received unexpected event info type.\n");
                   exit(EXIT_FAILURE);
               }

               if (metadata->mask == FAN_CREATE)
                   printf("FAN_CREATE (создан файл):\n");

               if (metadata->mask == (FAN_CREATE | FAN_ONDIR))
                   printf("FAN_CREATE | FAN_ONDIR (создан подкаталог):\n");

            /* metadata->fd is set to FAN_NOFD when the group identifies
               objects by file handles.  To obtain a file descriptor for
               the file object corresponding to an event you can use the
               struct file_handle that's provided within the
               fanotify_event_info_fid in conjunction with the
               open_by_handle_at(2) system call.  A check for ESTALE is
               done to accommodate for the situation where the file handle
               for the object was deleted prior to this system call. */

               event_fd = open_by_handle_at(mount_fd, file_handle, O_RDONLY);
               if (event_fd == -1) {
                   if (errno == ESTALE) {
                       printf("Обработчик файл более недействителен. "
                               "Файл был удалён\n");
                       continue;
                   } else {
                       perror("open_by_handle_at");
                       exit(EXIT_FAILURE);
                   }
               }

               snprintf(procfd_path, sizeof(procfd_path), "/proc/self/fd/%d",
                       event_fd);

               /* Получаем и выводим путь изменённой dentry. */

               path_len = readlink(procfd_path, path, sizeof(path) - 1);
               if (path_len == -1) {
                   perror("readlink");
                   exit(EXIT_FAILURE);
               }

               path[path_len] = '\0';
               printf("\tDirectory '%s' has been modified.\n", path);

               if (file_name) {
                   ret = fstatat(event_fd, file_name, &sb, 0);
                   if (ret == -1) {
                       if (errno != ENOENT) {
                           perror("fstatat");
                           exit(EXIT_FAILURE);
                       }
                       printf("\tEntry '%s' does not exist.\n", file_name);
                   } else if ((sb.st_mode & S_IFMT) == S_IFDIR) {
                       printf("\tEntry '%s' is a subdirectory.\n", file_name);
                   } else {
                       printf("\tEntry '%s' is not a subdirectory.\n",
                               file_name);
                   }
               }

               /* Закрываем связанный файловый дескриптор этого события. */

               close(event_fd);
           }

           printf("Все события успешно обработаны. Завершение программы.\n");
           exit(EXIT_SUCCESS);
       }

СМ. ТАКЖЕ

       fanotify_init(2), fanotify_mark(2), inotify(7)

ПЕРЕВОД

       Русский перевод этой страницы руководства был сделан Azamat Hackimov <azamat.hackimov@gmail.com>, Dmitry
       Bolkhovskikh <d20052005@yandex.ru>, Yuri Kozlov <yuray@komyakino.ru> и Иван Павлов <pavia00@gmail.com>

       Этот перевод является бесплатной документацией; прочитайте Стандартную общественную лицензию GNU версии 3
       или более позднюю, чтобы узнать об условиях авторского права. Мы не несем НИКАКОЙ ОТВЕТСТВЕННОСТИ.

       Если вы обнаружите ошибки в переводе этой страницы руководства, пожалуйста, отправьте электронное письмо
       на man-pages-ru-talks@lists.sourceforge.net.

Linux man-pages 6.03                            5 февраля 2023 г.                                    fanotify(7)