FileWatcherLinux.cpp 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178
  1. /*
  2. * Copyright (c) 2023, Tim Flynn <trflynn89@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include "FileWatcher.h"
  7. #include <AK/ByteString.h>
  8. #include <AK/Debug.h>
  9. #include <AK/LexicalPath.h>
  10. #include <LibCore/Notifier.h>
  11. #include <errno.h>
  12. #include <limits.h>
  13. #include <string.h>
  14. #include <sys/inotify.h>
  15. #include <sys/ioctl.h>
  16. #include <unistd.h>
  17. #if !defined(AK_OS_LINUX)
  18. static_assert(false, "This file must only be used for Linux");
  19. #endif
  20. namespace Core {
  21. static constexpr unsigned file_watcher_flags_to_inotify_flags(FileWatcherFlags flags)
  22. {
  23. unsigned result = 0;
  24. if (has_flag(flags, FileWatcherFlags::Nonblock))
  25. result |= IN_NONBLOCK;
  26. if (has_flag(flags, FileWatcherFlags::CloseOnExec))
  27. result |= IN_CLOEXEC;
  28. return result;
  29. }
  30. static Optional<FileWatcherEvent> get_event_from_fd(int fd, HashMap<unsigned, ByteString> const& wd_to_path)
  31. {
  32. static constexpr auto max_event_size = sizeof(inotify_event) + NAME_MAX + 1;
  33. // Note from INOTIFY(7) man page:
  34. //
  35. // Some systems cannot read integer variables if they are not properly aligned. On other
  36. // systems, incorrect alignment may decrease performance. Hence, the buffer used for reading
  37. // from the inotify file descriptor should have the same alignment as inotify_event.
  38. alignas(alignof(inotify_event)) Array<u8, max_event_size> buffer;
  39. ssize_t rc = ::read(fd, buffer.data(), buffer.size());
  40. if (rc == 0) {
  41. return {};
  42. } else if (rc < 0) {
  43. dbgln_if(FILE_WATCHER_DEBUG, "get_event_from_fd: Reading from wd {} failed: {}", fd, strerror(errno));
  44. return {};
  45. }
  46. auto const* event = reinterpret_cast<inotify_event const*>(buffer.data());
  47. FileWatcherEvent result;
  48. auto it = wd_to_path.find(event->wd);
  49. if (it == wd_to_path.end()) {
  50. dbgln_if(FILE_WATCHER_DEBUG, "get_event_from_fd: Got an event for a non-existent wd {}?!", event->wd);
  51. return {};
  52. }
  53. auto const& path = it->value;
  54. if ((event->mask & IN_CREATE) != 0)
  55. result.type |= FileWatcherEvent::Type::ChildCreated;
  56. if ((event->mask & IN_DELETE) != 0)
  57. result.type |= FileWatcherEvent::Type::ChildDeleted;
  58. if ((event->mask & IN_DELETE_SELF) != 0)
  59. result.type |= FileWatcherEvent::Type::Deleted;
  60. if ((event->mask & IN_MODIFY) != 0)
  61. result.type |= FileWatcherEvent::Type::ContentModified;
  62. if ((event->mask & IN_ATTRIB) != 0)
  63. result.type |= FileWatcherEvent::Type::MetadataModified;
  64. if ((event->mask & IN_IGNORED) != 0)
  65. return {};
  66. if (result.type == FileWatcherEvent::Type::Invalid) {
  67. warnln("Unknown event type {:x} returned by the watch_file descriptor for {}", event->mask, path);
  68. return {};
  69. }
  70. if (event->len > 0) {
  71. StringView child_name { event->name, strlen(event->name) };
  72. result.event_path = LexicalPath::join(path, child_name).string();
  73. } else {
  74. result.event_path = path;
  75. }
  76. dbgln_if(FILE_WATCHER_DEBUG, "get_event_from_fd: got event from wd {} on '{}' type {}", fd, result.event_path, result.type);
  77. return result;
  78. }
  79. ErrorOr<NonnullRefPtr<FileWatcher>> FileWatcher::create(FileWatcherFlags flags)
  80. {
  81. auto watcher_fd = ::inotify_init1(file_watcher_flags_to_inotify_flags(flags | FileWatcherFlags::CloseOnExec));
  82. if (watcher_fd < 0)
  83. return Error::from_errno(errno);
  84. auto notifier = TRY(Notifier::try_create(watcher_fd, Notifier::Type::Read));
  85. return adopt_nonnull_ref_or_enomem(new (nothrow) FileWatcher(watcher_fd, move(notifier)));
  86. }
  87. FileWatcher::FileWatcher(int watcher_fd, NonnullRefPtr<Notifier> notifier)
  88. : FileWatcherBase(watcher_fd)
  89. , m_notifier(move(notifier))
  90. {
  91. m_notifier->on_activation = [this] {
  92. auto maybe_event = get_event_from_fd(m_notifier->fd(), m_wd_to_path);
  93. if (maybe_event.has_value()) {
  94. auto event = maybe_event.value();
  95. if (has_flag(event.type, FileWatcherEvent::Type::Deleted)) {
  96. auto result = remove_watch(event.event_path);
  97. if (result.is_error()) {
  98. dbgln_if(FILE_WATCHER_DEBUG, "on_ready_to_read: {}", result.error());
  99. }
  100. }
  101. on_change(event);
  102. }
  103. };
  104. }
  105. FileWatcher::~FileWatcher() = default;
  106. ErrorOr<bool> FileWatcherBase::add_watch(ByteString path, FileWatcherEvent::Type event_mask)
  107. {
  108. if (m_path_to_wd.find(path) != m_path_to_wd.end()) {
  109. dbgln_if(FILE_WATCHER_DEBUG, "add_watch: path '{}' is already being watched", path);
  110. return false;
  111. }
  112. unsigned inotify_mask = 0;
  113. if (has_flag(event_mask, FileWatcherEvent::Type::ChildCreated))
  114. inotify_mask |= IN_CREATE;
  115. if (has_flag(event_mask, FileWatcherEvent::Type::ChildDeleted))
  116. inotify_mask |= IN_DELETE;
  117. if (has_flag(event_mask, FileWatcherEvent::Type::Deleted))
  118. inotify_mask |= IN_DELETE_SELF;
  119. if (has_flag(event_mask, FileWatcherEvent::Type::ContentModified))
  120. inotify_mask |= IN_MODIFY;
  121. if (has_flag(event_mask, FileWatcherEvent::Type::MetadataModified))
  122. inotify_mask |= IN_ATTRIB;
  123. int watch_descriptor = ::inotify_add_watch(m_watcher_fd, path.characters(), inotify_mask);
  124. if (watch_descriptor < 0)
  125. return Error::from_errno(errno);
  126. m_path_to_wd.set(path, watch_descriptor);
  127. m_wd_to_path.set(watch_descriptor, path);
  128. dbgln_if(FILE_WATCHER_DEBUG, "add_watch: watching path '{}' on InodeWatcher {} wd {}", path, m_watcher_fd, watch_descriptor);
  129. return true;
  130. }
  131. ErrorOr<bool> FileWatcherBase::remove_watch(ByteString path)
  132. {
  133. auto it = m_path_to_wd.find(path);
  134. if (it == m_path_to_wd.end()) {
  135. dbgln_if(FILE_WATCHER_DEBUG, "remove_watch: path '{}' is not being watched", path);
  136. return false;
  137. }
  138. m_path_to_wd.remove(it);
  139. m_wd_to_path.remove(it->value);
  140. if (::inotify_rm_watch(m_watcher_fd, it->value) < 0)
  141. return Error::from_errno(errno);
  142. dbgln_if(FILE_WATCHER_DEBUG, "remove_watch: stopped watching path '{}' on InodeWatcher {}", path, m_watcher_fd);
  143. return true;
  144. }
  145. }