fanotify(7) | Miscellaneous Information Manual | fanotify(7) |
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(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 не будет закрыт.
Вызов 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:
Программа, слушающая события fanotify, может сравнить этот PID с PID, возвращаемым getpid(2), для проверки, что событие не возникло из-за самого слушающего, а из-за доступа к файлу другого процесса.
В битовой маске mask указывают события, произошедшие с одиночным объектом файловой системы. В маске может быть установлено несколько бит, если было более одного события с отслеживаемым объектом файловой системы. В частности, возникшие друг за другом события с одним объектом файловой системы и произошедшие из-за одного процесса могут быть объединены в одно событие, за исключением того, что два события доступа никогда не объединяются в одном элементе очереди.
Биты маски mask:
Для проверки любого события закрытия может использоваться следующая битовая маска:
FAN_CLOSE_WRITE | FAN_CLOSE_NOWRITE
Для проверки любого события перемещения может использоваться следующая битовая маска:
FAN_MOVED_FROM | FAN_MOVED_TO
The following bits may appear in mask only in conjunction with other event type bits:
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:
Поля структуры fanotify_event_info_fid:
Поля структуры fanotify_event_info_pidfd:
Поля структуры fanotify_event_info_error:
Следующие макросы позволяют обходить буфер с метаданными событий fanotify, возвращаемый read(2) из файлового дескриптора fanotify:
Дополнительно есть:
Когда возникает событие fanotify файловый дескриптор fanotify помечается как доступный для чтения при его передаче в epoll(7), poll(2) или select(2).
Для событий доступа приложение должно записать (write(2)) в файловый дескриптор fanotify следующую структуру:
struct fanotify_response { __s32 fd; __u32 response; };
Поля этой структуры имеют следующее назначение:
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.
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 освобождается и её ресурсы становятся доступны ядру для повторного использования. После close(2) все оставшиеся непросмотренные события доступа будут разрешены.
Файл /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:
Кроме обычных ошибок read(2) при чтении из файлового дескриптора fanotify могут возникать следующие ошибки:
Кроме обычных ошибок write(2) при записи в файловый дескриптор fanotify могут возникать следующие ошибки:
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 существуют следующие дефекты:
Далее показано два примера программы, в которых продемонстрированоиспользование программного интерфейса fanotify.
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 Ожидание событий прекращено.
#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); }
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 # в другом терминале
#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.
5 февраля 2023 г. | Linux man-pages 6.03 |