#include #include #include #include #include #include #include #include #include #include #include #include #include #include #if defined(__linux__) #include #include #include #include #endif namespace Void::FileSystem { #if defined(__linux__) namespace { constexpr std::uint32_t kWatchMask = IN_CREATE | IN_DELETE | IN_MODIFY | IN_CLOSE_WRITE | IN_MOVED_FROM | IN_MOVED_TO | IN_ATTRIB | IN_DELETE_SELF | IN_MOVE_SELF | IN_EXCL_UNLINK | IN_ONLYDIR; [[nodiscard]] bool is_subpath_or_equal(const std::filesystem::path& candidate, const std::filesystem::path& prefix) { const std::string c = candidate.lexically_normal().generic_string(); const std::string p = prefix.lexically_normal().generic_string(); if (c == p) { return true; } if (p.empty()) { return false; } const std::size_t plen = p.size(); return c.size() > plen && c.compare(0, plen, p) == 0 && c[plen] == '/'; } [[nodiscard]] std::filesystem::path rebase_path(const std::filesystem::path& p, const std::filesystem::path& old_prefix, const std::filesystem::path& new_prefix) { const std::string ps = p.lexically_normal().generic_string(); const std::string os = old_prefix.lexically_normal().generic_string(); if (ps == os) { return new_prefix; } if (ps.size() > os.size() && ps.compare(0, os.size(), os) == 0 && ps[os.size()] == '/') { return new_prefix / std::filesystem::path{ps.substr(os.size() + 1U)}; } return p; } } // namespace struct DirectoryWatcher::Impl { struct PendingMove { std::filesystem::path path{}; bool is_directory{false}; std::chrono::steady_clock::time_point expires_at{}; }; Void::System::OwnedFd inotify_fd{}; Void::System::OwnedFd wake_fd{}; std::filesystem::path root{}; DirectoryWatcherOptions options{}; mutable std::mutex mutex{}; std::unordered_map wd_to_path{}; std::map path_to_wd{}; std::unordered_map pending_moves{}; std::deque queue{}; bool rescan_emitted{false}; ~Impl() noexcept { std::lock_guard lock{mutex}; for (const auto& [wd, _] : wd_to_path) { if (inotify_fd.valid()) { (void)::inotify_rm_watch(inotify_fd.get(), wd); } } wd_to_path.clear(); path_to_wd.clear(); } [[nodiscard]] bool should_ignore(const std::filesystem::path& p, bool is_dir) const { if (options.ignore) { return options.ignore(p, is_dir); } return false; } void push_event_locked(DirectoryEvent ev) { if (ev.kind == DirectoryEventKind::RescanRequired) { if (rescan_emitted) { return; } rescan_emitted = true; queue.push_back(std::move(ev)); return; } if (queue.size() >= options.max_queued_events) { if (!rescan_emitted) { rescan_emitted = true; queue.push_back(DirectoryEvent{ .kind = DirectoryEventKind::RescanRequired, .path = root, .old_path = {}, .is_directory = true, .detail = "DirectoryWatcher event queue full", }); } return; } queue.push_back(std::move(ev)); } void remove_watch_by_wd_locked(int wd, bool call_rm) { auto it = wd_to_path.find(wd); if (it == wd_to_path.end()) { return; } path_to_wd.erase(it->second); wd_to_path.erase(it); if (call_rm && inotify_fd.valid()) { (void)::inotify_rm_watch(inotify_fd.get(), wd); } } void remove_subtree_watches_locked(const std::filesystem::path& prefix) { std::vector wds; for (const auto& [wd, p] : wd_to_path) { if (is_subpath_or_equal(p, prefix)) { wds.push_back(wd); } } for (int wd : wds) { remove_watch_by_wd_locked(wd, true); } } void rewrite_subtree_watches_locked(const std::filesystem::path& old_prefix, const std::filesystem::path& new_prefix) { std::vector> updates; for (const auto& [wd, p] : wd_to_path) { if (is_subpath_or_equal(p, old_prefix)) { updates.emplace_back(wd, rebase_path(p, old_prefix, new_prefix)); } } for (const auto& [wd, new_p] : updates) { auto old_it = wd_to_path.find(wd); if (old_it != wd_to_path.end()) { path_to_wd.erase(old_it->second); old_it->second = new_p; path_to_wd[new_p] = wd; } } } void attach_single_dir_locked(const std::filesystem::path& dir_path) { const std::filesystem::path norm = dir_path.lexically_normal(); if (norm != root && should_ignore(norm, true)) { return; } if (path_to_wd.contains(norm)) { return; } if (wd_to_path.size() >= options.max_watches) { push_event_locked(DirectoryEvent{ .kind = DirectoryEventKind::RescanRequired, .path = norm, .old_path = {}, .is_directory = true, .detail = "DirectoryWatcher max_watches exceeded", }); return; } const int wd = ::inotify_add_watch(inotify_fd.get(), norm.c_str(), kWatchMask); if (wd < 0) { const int err = errno; if (err == ENOSPC || err == ENOMEM) { push_event_locked(DirectoryEvent{ .kind = DirectoryEventKind::RescanRequired, .path = norm, .old_path = {}, .is_directory = true, .detail = std::format( "inotify_add_watch exhausted watches (errno={})", err), }); } return; } // inotify_add_watch may return an existing wd if directory inode aliased. if (auto existing = wd_to_path.find(wd); existing != wd_to_path.end()) { if (existing->second != norm) { path_to_wd.erase(existing->second); existing->second = norm; } } else { wd_to_path.emplace(wd, norm); } path_to_wd[norm] = wd; } void attach_subtree_locked(const std::filesystem::path& dir_path, bool emit_existing_children) { const std::filesystem::path norm = dir_path.lexically_normal(); if (norm != root && should_ignore(norm, true)) { return; } std::error_code ec; const auto st = std::filesystem::symlink_status(norm, ec); if (ec || std::filesystem::is_symlink(st) || !std::filesystem::is_directory(st)) { return; } attach_single_dir_locked(norm); std::vector stack{norm}; while (!stack.empty()) { const std::filesystem::path cur = std::move(stack.back()); stack.pop_back(); ec.clear(); std::filesystem::directory_iterator it{ cur, std::filesystem::directory_options::skip_permission_denied, ec}; if (ec) { continue; } for (const auto& entry : it) { std::error_code st_ec; const auto est = entry.symlink_status(st_ec); if (st_ec || std::filesystem::is_symlink(est)) { continue; } const bool is_dir = std::filesystem::is_directory(est); const std::filesystem::path ep = entry.path().lexically_normal(); if (should_ignore(ep, is_dir)) { continue; } if (emit_existing_children) { push_event_locked(DirectoryEvent{ .kind = DirectoryEventKind::Created, .path = ep, .old_path = {}, .is_directory = is_dir, .detail = {}, }); } if (is_dir) { attach_single_dir_locked(ep); stack.push_back(ep); } } } } void flush_expired_moves_locked(std::chrono::steady_clock::time_point now, bool force_all) { for (auto it = pending_moves.begin(); it != pending_moves.end();) { if (force_all || now >= it->second.expires_at) { const auto p = it->second.path; const bool is_dir = it->second.is_directory; if (is_dir) { remove_subtree_watches_locked(p); } if (!should_ignore(p, is_dir)) { push_event_locked(DirectoryEvent{ .kind = DirectoryEventKind::Deleted, .path = p, .old_path = {}, .is_directory = is_dir, .detail = {}, }); } it = pending_moves.erase(it); } else { ++it; } } } void process_inotify_event_locked(const struct inotify_event* ev) { if ((ev->mask & IN_Q_OVERFLOW) != 0U) { push_event_locked(DirectoryEvent{ .kind = DirectoryEventKind::RescanRequired, .path = root, .old_path = {}, .is_directory = true, .detail = "inotify kernel event queue overflow (IN_Q_OVERFLOW)", }); return; } if ((ev->mask & IN_IGNORED) != 0U) { remove_watch_by_wd_locked(ev->wd, false); return; } const auto dir_it = wd_to_path.find(ev->wd); if (dir_it == wd_to_path.end()) { return; } const std::filesystem::path base = dir_it->second; const bool is_dir = (ev->mask & IN_ISDIR) != 0U; if ((ev->mask & (IN_DELETE_SELF | IN_MOVE_SELF)) != 0U && ev->len == 0U) { if (base == root) { push_event_locked(DirectoryEvent{ .kind = DirectoryEventKind::RescanRequired, .path = root, .old_path = {}, .is_directory = true, .detail = "watched root directory deleted or moved", }); remove_watch_by_wd_locked(ev->wd, false); } else if ((ev->mask & IN_DELETE_SELF) != 0U) { remove_watch_by_wd_locked(ev->wd, false); } return; } const std::string name = (ev->len > 0U && ev->name[0] != '\0') ? std::string{ev->name} : std::string{}; const std::filesystem::path full_path = name.empty() ? base : (base / name).lexically_normal(); if ((ev->mask & IN_MOVED_FROM) != 0U) { if (ev->cookie != 0U) { pending_moves.insert_or_assign( ev->cookie, PendingMove{ .path = full_path, .is_directory = is_dir, .expires_at = std::chrono::steady_clock::now() + options.rename_pair_window, }); } else { if (is_dir) { remove_subtree_watches_locked(full_path); } if (!should_ignore(full_path, is_dir)) { push_event_locked(DirectoryEvent{ .kind = DirectoryEventKind::Deleted, .path = full_path, .old_path = {}, .is_directory = is_dir, .detail = {}, }); } } return; } if ((ev->mask & IN_MOVED_TO) != 0U) { if (ev->cookie != 0U) { if (auto mit = pending_moves.find(ev->cookie); mit != pending_moves.end()) { const std::filesystem::path old_path = std::move(mit->second.path); pending_moves.erase(mit); const bool old_ignored = should_ignore(old_path, is_dir); const bool new_ignored = should_ignore(full_path, is_dir); if (is_dir) { if (new_ignored) { remove_subtree_watches_locked(old_path); } else { rewrite_subtree_watches_locked(old_path, full_path); attach_subtree_locked(full_path, false); } } if (!old_ignored && !new_ignored) { push_event_locked(DirectoryEvent{ .kind = DirectoryEventKind::Renamed, .path = full_path, .old_path = old_path, .is_directory = is_dir, .detail = {}, }); } else if (!old_ignored && new_ignored) { push_event_locked(DirectoryEvent{ .kind = DirectoryEventKind::Deleted, .path = old_path, .old_path = {}, .is_directory = is_dir, .detail = {}, }); } else if (old_ignored && !new_ignored) { push_event_locked(DirectoryEvent{ .kind = DirectoryEventKind::Created, .path = full_path, .old_path = {}, .is_directory = is_dir, .detail = {}, }); } return; } } if (should_ignore(full_path, is_dir)) { return; } push_event_locked(DirectoryEvent{ .kind = DirectoryEventKind::Created, .path = full_path, .old_path = {}, .is_directory = is_dir, .detail = {}, }); if (is_dir) { attach_subtree_locked(full_path, true); } return; } if (should_ignore(full_path, is_dir)) { return; } if ((ev->mask & IN_CREATE) != 0U) { push_event_locked(DirectoryEvent{ .kind = DirectoryEventKind::Created, .path = full_path, .old_path = {}, .is_directory = is_dir, .detail = {}, }); if (is_dir) { attach_subtree_locked(full_path, true); } } if ((ev->mask & IN_DELETE) != 0U) { if (is_dir) { remove_subtree_watches_locked(full_path); } push_event_locked(DirectoryEvent{ .kind = DirectoryEventKind::Deleted, .path = full_path, .old_path = {}, .is_directory = is_dir, .detail = {}, }); } if ((ev->mask & (IN_MODIFY | IN_CLOSE_WRITE)) != 0U) { push_event_locked(DirectoryEvent{ .kind = DirectoryEventKind::Modified, .path = full_path, .old_path = {}, .is_directory = is_dir, .detail = {}, }); } if ((ev->mask & IN_ATTRIB) != 0U) { push_event_locked(DirectoryEvent{ .kind = DirectoryEventKind::AttributeChanged, .path = full_path, .old_path = {}, .is_directory = is_dir, .detail = {}, }); } } [[nodiscard]] Void::Result::Result drain_inotify_locked() { alignas(struct inotify_event) std::array buf{}; for (;;) { const ssize_t n = ::read(inotify_fd.get(), buf.data(), buf.size()); if (n > 0) { ssize_t offset = 0; while (offset < n) { const auto* ev = reinterpret_cast( buf.data() + offset); process_inotify_event_locked(ev); offset += static_cast( sizeof(struct inotify_event) + ev->len); } continue; } if (n == 0) { break; } if (errno == EINTR) { continue; } if (errno == EAGAIN || errno == EWOULDBLOCK) { break; } const int err = errno; return std::unexpected{Void::System::make_system_error( Void::System::map_errno_to_system_code(err), "FileSystem::DirectoryWatcher: read(inotify) failed", err)}; } return {}; } void drain_wake_locked() noexcept { std::uint64_t val = 0; while (::read(wake_fd.get(), &val, sizeof(val)) > 0 || (errno == EINTR)) { } } }; DirectoryWatcher::DirectoryWatcher(std::unique_ptr impl) noexcept : impl_(std::move(impl)) { } DirectoryWatcher::~DirectoryWatcher() noexcept = default; DirectoryWatcher::DirectoryWatcher(DirectoryWatcher&&) noexcept = default; DirectoryWatcher& DirectoryWatcher::operator=(DirectoryWatcher&&) noexcept = default; Void::Result::Result DirectoryWatcher::create(const std::filesystem::path& root, DirectoryWatcherOptions options) { if (root.empty()) { return std::unexpected{Void::System::make_system_error( Void::System::SystemErrorCode::invalid_argument, "FileSystem::DirectoryWatcher::create: root cannot be empty")}; } std::error_code ec; const auto st = std::filesystem::status(root, ec); if (ec || !std::filesystem::is_directory(st)) { return std::unexpected{Void::System::make_system_error( Void::System::SystemErrorCode::not_found, std::format( "FileSystem::DirectoryWatcher::create: '{}' is not a directory", root.string()))}; } const int ifd = ::inotify_init1(IN_NONBLOCK | IN_CLOEXEC); if (ifd < 0) { const int err = errno; return std::unexpected{Void::System::make_system_error( Void::System::map_errno_to_system_code(err), "FileSystem::DirectoryWatcher::create: inotify_init1 failed", err)}; } Void::System::OwnedFd owned_ifd{ifd}; const int efd = ::eventfd(0, EFD_NONBLOCK | EFD_CLOEXEC); if (efd < 0) { const int err = errno; return std::unexpected{Void::System::make_system_error( Void::System::map_errno_to_system_code(err), "FileSystem::DirectoryWatcher::create: eventfd failed", err)}; } Void::System::OwnedFd owned_efd{efd}; auto impl = std::make_unique(); impl->inotify_fd = std::move(owned_ifd); impl->wake_fd = std::move(owned_efd); impl->root = std::filesystem::weakly_canonical(root, ec); if (ec || impl->root.empty()) { impl->root = root.lexically_normal(); } impl->options = std::move(options); { std::lock_guard lock{impl->mutex}; impl->attach_subtree_locked(impl->root, false); } return DirectoryWatcher{std::move(impl)}; } Void::Result::Result, Void::Result::Error> DirectoryWatcher::poll(std::chrono::milliseconds timeout) { if (!impl_) { return std::unexpected{Void::System::make_system_error( Void::System::SystemErrorCode::invalid_argument, "FileSystem::DirectoryWatcher::poll: moved-from watcher")}; } const auto start = std::chrono::steady_clock::now(); const auto end_time = start + std::max(std::chrono::milliseconds{0}, timeout); int ifd = -1; int efd = -1; { std::lock_guard lock{impl_->mutex}; if (auto dr = impl_->drain_inotify_locked(); !dr.has_value()) { return std::unexpected{std::move(dr.error())}; } impl_->flush_expired_moves_locked(std::chrono::steady_clock::now(), timeout.count() <= 0); if (!impl_->queue.empty() && impl_->pending_moves.empty()) { std::vector out; out.reserve(impl_->queue.size()); while (!impl_->queue.empty()) { out.push_back(std::move(impl_->queue.front())); impl_->queue.pop_front(); } return out; } ifd = impl_->inotify_fd.get(); efd = impl_->wake_fd.get(); } if (timeout.count() > 0) { for (;;) { const auto now = std::chrono::steady_clock::now(); std::chrono::steady_clock::time_point wait_until = end_time; { std::lock_guard lock{impl_->mutex}; for (const auto& [_, pm] : impl_->pending_moves) { wait_until = std::min(wait_until, pm.expires_at); } } if (now >= wait_until) { std::lock_guard lock{impl_->mutex}; impl_->flush_expired_moves_locked(now, false); if (now >= end_time || (!impl_->queue.empty() && impl_->pending_moves.empty())) { break; } continue; } const auto rem_ms = std::max( 1, std::chrono::duration_cast( wait_until - now) .count()); std::array pfds{{ {ifd, POLLIN, 0}, {efd, POLLIN, 0}, }}; const int rc = ::poll(pfds.data(), pfds.size(), static_cast(rem_ms)); if (rc < 0) { if (errno == EINTR) { continue; } const int err = errno; return std::unexpected{Void::System::make_system_error( Void::System::map_errno_to_system_code(err), "FileSystem::DirectoryWatcher::poll: poll failed", err)}; } std::lock_guard lock{impl_->mutex}; if (auto dr = impl_->drain_inotify_locked(); !dr.has_value()) { return std::unexpected{std::move(dr.error())}; } const bool woken = (pfds[1].revents & POLLIN) != 0; if (woken) { impl_->drain_wake_locked(); } impl_->flush_expired_moves_locked(std::chrono::steady_clock::now(), false); if (woken || (!impl_->queue.empty() && impl_->pending_moves.empty())) { break; } } } std::lock_guard lock{impl_->mutex}; std::vector out; out.reserve(impl_->queue.size()); while (!impl_->queue.empty()) { out.push_back(std::move(impl_->queue.front())); impl_->queue.pop_front(); } return out; } Void::Result::Result DirectoryWatcher::rescan() { if (!impl_) { return std::unexpected{Void::System::make_system_error( Void::System::SystemErrorCode::invalid_argument, "FileSystem::DirectoryWatcher::rescan: moved-from watcher")}; } std::lock_guard lock{impl_->mutex}; for (const auto& [wd, _] : impl_->wd_to_path) { (void)::inotify_rm_watch(impl_->inotify_fd.get(), wd); } impl_->wd_to_path.clear(); impl_->path_to_wd.clear(); impl_->pending_moves.clear(); impl_->queue.clear(); impl_->rescan_emitted = false; impl_->attach_subtree_locked(impl_->root, false); return {}; } void DirectoryWatcher::wake() noexcept { if (!impl_ || !impl_->wake_fd.valid()) { return; } const std::uint64_t one = 1; while (::write(impl_->wake_fd.get(), &one, sizeof(one)) < 0 && errno == EINTR) { } } void DirectoryWatcher::simulate_overflow_for_test() { if (!impl_) { return; } { std::lock_guard lock{impl_->mutex}; impl_->push_event_locked(DirectoryEvent{ .kind = DirectoryEventKind::RescanRequired, .path = impl_->root, .old_path = {}, .is_directory = true, .detail = "simulated IN_Q_OVERFLOW", }); } wake(); } const std::filesystem::path& DirectoryWatcher::root() const noexcept { static const std::filesystem::path kEmpty{}; return impl_ ? impl_->root : kEmpty; } std::size_t DirectoryWatcher::watch_count() const noexcept { if (!impl_) { return 0; } std::lock_guard lock{impl_->mutex}; return impl_->wd_to_path.size(); } int DirectoryWatcher::native_handle() const noexcept { return impl_ ? impl_->inotify_fd.get() : -1; } #else struct DirectoryWatcher::Impl { std::filesystem::path root{}; }; DirectoryWatcher::DirectoryWatcher(std::unique_ptr impl) noexcept : impl_(std::move(impl)) { } DirectoryWatcher::~DirectoryWatcher() noexcept = default; DirectoryWatcher::DirectoryWatcher(DirectoryWatcher&&) noexcept = default; DirectoryWatcher& DirectoryWatcher::operator=(DirectoryWatcher&&) noexcept = default; Void::Result::Result DirectoryWatcher::create(const std::filesystem::path&, DirectoryWatcherOptions) { return std::unexpected{Void::System::make_system_error( Void::System::SystemErrorCode::unsupported, "FileSystem::DirectoryWatcher: inotify watcher is Linux-only")}; } Void::Result::Result, Void::Result::Error> DirectoryWatcher::poll(std::chrono::milliseconds) { return std::unexpected{Void::System::make_system_error( Void::System::SystemErrorCode::unsupported, "FileSystem::DirectoryWatcher: unsupported platform")}; } Void::Result::Result DirectoryWatcher::rescan() { return std::unexpected{Void::System::make_system_error( Void::System::SystemErrorCode::unsupported, "FileSystem::DirectoryWatcher: unsupported platform")}; } void DirectoryWatcher::wake() noexcept {} void DirectoryWatcher::simulate_overflow_for_test() {} const std::filesystem::path& DirectoryWatcher::root() const noexcept { static const std::filesystem::path kEmpty{}; return impl_ ? impl_->root : kEmpty; } std::size_t DirectoryWatcher::watch_count() const noexcept { return 0; } int DirectoryWatcher::native_handle() const noexcept { return -1; } #endif } // namespace Void::FileSystem