Serenity Operating System
1/*
2 * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
3 * Copyright (c) 2021, sin-ack <sin-ack@protonmail.com>
4 *
5 * SPDX-License-Identifier: BSD-2-Clause
6 */
7
8#include <Kernel/API/InodeWatcherFlags.h>
9#include <Kernel/FileSystem/Custody.h>
10#include <Kernel/FileSystem/InodeWatcher.h>
11#include <Kernel/FileSystem/OpenFileDescription.h>
12#include <Kernel/FileSystem/VirtualFileSystem.h>
13#include <Kernel/Process.h>
14
15namespace Kernel {
16
17ErrorOr<FlatPtr> Process::sys$create_inode_watcher(u32 flags)
18{
19 VERIFY_NO_PROCESS_BIG_LOCK(this);
20 TRY(require_promise(Pledge::rpath));
21
22 auto watcher = TRY(InodeWatcher::try_create());
23 auto description = TRY(OpenFileDescription::try_create(move(watcher)));
24
25 description->set_readable(true);
26 if (flags & static_cast<unsigned>(InodeWatcherFlags::Nonblock))
27 description->set_blocking(false);
28
29 return m_fds.with_exclusive([&](auto& fds) -> ErrorOr<FlatPtr> {
30 auto fd_allocation = TRY(fds.allocate());
31 fds[fd_allocation.fd].set(move(description));
32
33 if (flags & static_cast<unsigned>(InodeWatcherFlags::CloseOnExec))
34 fds[fd_allocation.fd].set_flags(fds[fd_allocation.fd].flags() | FD_CLOEXEC);
35
36 return fd_allocation.fd;
37 });
38}
39
40ErrorOr<FlatPtr> Process::sys$inode_watcher_add_watch(Userspace<Syscall::SC_inode_watcher_add_watch_params const*> user_params)
41{
42 VERIFY_PROCESS_BIG_LOCK_ACQUIRED(this);
43 TRY(require_promise(Pledge::rpath));
44 auto params = TRY(copy_typed_from_user(user_params));
45
46 auto description = TRY(open_file_description(params.fd));
47 if (!description->is_inode_watcher())
48 return EBADF;
49 auto* inode_watcher = description->inode_watcher();
50 auto path = TRY(get_syscall_path_argument(params.user_path));
51 auto custody = TRY(VirtualFileSystem::the().resolve_path(credentials(), path->view(), current_directory()));
52 if (!custody->inode().fs().supports_watchers())
53 return ENOTSUP;
54
55 return TRY(inode_watcher->register_inode(custody->inode(), params.event_mask));
56}
57
58ErrorOr<FlatPtr> Process::sys$inode_watcher_remove_watch(int fd, int wd)
59{
60 VERIFY_PROCESS_BIG_LOCK_ACQUIRED(this);
61 auto description = TRY(open_file_description(fd));
62 if (!description->is_inode_watcher())
63 return EBADF;
64 TRY(description->inode_watcher()->unregister_by_wd(wd));
65 return 0;
66}
67
68}