Inode.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406
  1. /*
  2. * Copyright (c) 2018-2021, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2021, sin-ack <sin-ack@protonmail.com>
  4. * Copyright (c) 2022, Idan Horowitz <idan.horowitz@serenityos.org>
  5. *
  6. * SPDX-License-Identifier: BSD-2-Clause
  7. */
  8. #include <AK/NonnullRefPtrVector.h>
  9. #include <AK/Singleton.h>
  10. #include <AK/StringView.h>
  11. #include <Kernel/API/InodeWatcherEvent.h>
  12. #include <Kernel/FileSystem/Custody.h>
  13. #include <Kernel/FileSystem/Inode.h>
  14. #include <Kernel/FileSystem/InodeWatcher.h>
  15. #include <Kernel/FileSystem/OpenFileDescription.h>
  16. #include <Kernel/FileSystem/VirtualFileSystem.h>
  17. #include <Kernel/KBufferBuilder.h>
  18. #include <Kernel/Memory/SharedInodeVMObject.h>
  19. #include <Kernel/Net/LocalSocket.h>
  20. #include <Kernel/Process.h>
  21. namespace Kernel {
  22. static Singleton<SpinlockProtected<Inode::AllInstancesList>> s_all_instances;
  23. SpinlockProtected<Inode::AllInstancesList>& Inode::all_instances()
  24. {
  25. return s_all_instances;
  26. }
  27. void Inode::sync_all()
  28. {
  29. NonnullRefPtrVector<Inode, 32> inodes;
  30. Inode::all_instances().with([&](auto& all_inodes) {
  31. for (auto& inode : all_inodes) {
  32. if (inode.is_metadata_dirty())
  33. inodes.append(inode);
  34. }
  35. });
  36. for (auto& inode : inodes) {
  37. VERIFY(inode.is_metadata_dirty());
  38. (void)inode.flush_metadata();
  39. }
  40. }
  41. void Inode::sync()
  42. {
  43. if (is_metadata_dirty())
  44. (void)flush_metadata();
  45. fs().flush_writes();
  46. }
  47. ErrorOr<NonnullOwnPtr<KBuffer>> Inode::read_entire(OpenFileDescription* description) const
  48. {
  49. auto builder = TRY(KBufferBuilder::try_create());
  50. u8 buffer[4096];
  51. off_t offset = 0;
  52. for (;;) {
  53. auto buf = UserOrKernelBuffer::for_kernel_buffer(buffer);
  54. auto nread = TRY(read_bytes(offset, sizeof(buffer), buf, description));
  55. VERIFY(nread <= sizeof(buffer));
  56. if (nread == 0)
  57. break;
  58. TRY(builder.append((char const*)buffer, nread));
  59. offset += nread;
  60. if (nread < sizeof(buffer))
  61. break;
  62. }
  63. auto entire_file = builder.build();
  64. if (!entire_file)
  65. return ENOMEM;
  66. return entire_file.release_nonnull();
  67. }
  68. ErrorOr<NonnullRefPtr<Custody>> Inode::resolve_as_link(Custody& base, RefPtr<Custody>* out_parent, int options, int symlink_recursion_level) const
  69. {
  70. // The default implementation simply treats the stored
  71. // contents as a path and resolves that. That is, it
  72. // behaves exactly how you would expect a symlink to work.
  73. auto contents = TRY(read_entire());
  74. return VirtualFileSystem::the().resolve_path(StringView { contents->bytes() }, base, out_parent, options, symlink_recursion_level);
  75. }
  76. Inode::Inode(FileSystem& fs, InodeIndex index)
  77. : m_file_system(fs)
  78. , m_index(index)
  79. {
  80. Inode::all_instances().with([&](auto& all_inodes) { all_inodes.append(*this); });
  81. }
  82. Inode::~Inode()
  83. {
  84. m_watchers.for_each([&](auto& watcher) {
  85. watcher->unregister_by_inode({}, identifier());
  86. });
  87. }
  88. void Inode::will_be_destroyed()
  89. {
  90. MutexLocker locker(m_inode_lock);
  91. if (m_metadata_dirty)
  92. (void)flush_metadata();
  93. }
  94. ErrorOr<void> Inode::set_atime(time_t)
  95. {
  96. return ENOTIMPL;
  97. }
  98. ErrorOr<void> Inode::set_ctime(time_t)
  99. {
  100. return ENOTIMPL;
  101. }
  102. ErrorOr<void> Inode::set_mtime(time_t)
  103. {
  104. return ENOTIMPL;
  105. }
  106. ErrorOr<void> Inode::increment_link_count()
  107. {
  108. return ENOTIMPL;
  109. }
  110. ErrorOr<void> Inode::decrement_link_count()
  111. {
  112. return ENOTIMPL;
  113. }
  114. ErrorOr<void> Inode::set_shared_vmobject(Memory::SharedInodeVMObject& vmobject)
  115. {
  116. MutexLocker locker(m_inode_lock);
  117. m_shared_vmobject = TRY(vmobject.try_make_weak_ptr<Memory::SharedInodeVMObject>());
  118. return {};
  119. }
  120. RefPtr<LocalSocket> Inode::bound_socket() const
  121. {
  122. return m_bound_socket;
  123. }
  124. bool Inode::bind_socket(LocalSocket& socket)
  125. {
  126. MutexLocker locker(m_inode_lock);
  127. if (m_bound_socket)
  128. return false;
  129. m_bound_socket = socket;
  130. return true;
  131. }
  132. bool Inode::unbind_socket()
  133. {
  134. MutexLocker locker(m_inode_lock);
  135. if (!m_bound_socket)
  136. return false;
  137. m_bound_socket = nullptr;
  138. return true;
  139. }
  140. ErrorOr<void> Inode::register_watcher(Badge<InodeWatcher>, InodeWatcher& watcher)
  141. {
  142. return m_watchers.with([&](auto& watchers) -> ErrorOr<void> {
  143. VERIFY(!watchers.contains(&watcher));
  144. TRY(watchers.try_set(&watcher));
  145. return {};
  146. });
  147. }
  148. void Inode::unregister_watcher(Badge<InodeWatcher>, InodeWatcher& watcher)
  149. {
  150. m_watchers.with([&](auto& watchers) {
  151. VERIFY(watchers.contains(&watcher));
  152. watchers.remove(&watcher);
  153. });
  154. }
  155. ErrorOr<NonnullRefPtr<FIFO>> Inode::fifo()
  156. {
  157. MutexLocker locker(m_inode_lock);
  158. VERIFY(metadata().is_fifo());
  159. // FIXME: Release m_fifo when it is closed by all readers and writers
  160. if (!m_fifo)
  161. m_fifo = TRY(FIFO::try_create(metadata().uid));
  162. return NonnullRefPtr { *m_fifo };
  163. }
  164. void Inode::set_metadata_dirty(bool metadata_dirty)
  165. {
  166. MutexLocker locker(m_inode_lock);
  167. if (metadata_dirty) {
  168. // Sanity check.
  169. VERIFY(!fs().is_readonly());
  170. }
  171. if (m_metadata_dirty == metadata_dirty)
  172. return;
  173. m_metadata_dirty = metadata_dirty;
  174. if (m_metadata_dirty) {
  175. // FIXME: Maybe we should hook into modification events somewhere else, I'm not sure where.
  176. // We don't always end up on this particular code path, for instance when writing to an ext2fs file.
  177. m_watchers.for_each([&](auto& watcher) {
  178. watcher->notify_inode_event({}, identifier(), InodeWatcherEvent::Type::MetadataModified);
  179. });
  180. }
  181. }
  182. void Inode::did_add_child(InodeIdentifier, StringView name)
  183. {
  184. m_watchers.for_each([&](auto& watcher) {
  185. watcher->notify_inode_event({}, identifier(), InodeWatcherEvent::Type::ChildCreated, name);
  186. });
  187. }
  188. void Inode::did_remove_child(InodeIdentifier, StringView name)
  189. {
  190. if (name == "." || name == "..") {
  191. // These are just aliases and are not interesting to userspace.
  192. return;
  193. }
  194. m_watchers.for_each([&](auto& watcher) {
  195. watcher->notify_inode_event({}, identifier(), InodeWatcherEvent::Type::ChildDeleted, name);
  196. });
  197. }
  198. void Inode::did_modify_contents()
  199. {
  200. // FIXME: What happens if this fails?
  201. // ENOTIMPL would be a meaningless error to return here
  202. auto time = kgettimeofday().to_truncated_seconds();
  203. (void)set_mtime(time);
  204. (void)set_ctime(time);
  205. m_watchers.for_each([&](auto& watcher) {
  206. watcher->notify_inode_event({}, identifier(), InodeWatcherEvent::Type::ContentModified);
  207. });
  208. }
  209. void Inode::did_delete_self()
  210. {
  211. m_watchers.for_each([&](auto& watcher) {
  212. watcher->notify_inode_event({}, identifier(), InodeWatcherEvent::Type::Deleted);
  213. });
  214. }
  215. ErrorOr<void> Inode::prepare_to_write_data()
  216. {
  217. // FIXME: It's a poor design that filesystems are expected to call this before writing out data.
  218. // We should funnel everything through an interface at the VirtualFileSystem layer so this can happen from a single place.
  219. MutexLocker locker(m_inode_lock);
  220. if (fs().is_readonly())
  221. return EROFS;
  222. auto metadata = this->metadata();
  223. if (metadata.is_setuid() || metadata.is_setgid()) {
  224. dbgln("Inode::prepare_to_write_data(): Stripping SUID/SGID bits from {}", identifier());
  225. return chmod(metadata.mode & ~(04000 | 02000));
  226. }
  227. return {};
  228. }
  229. RefPtr<Memory::SharedInodeVMObject> Inode::shared_vmobject() const
  230. {
  231. MutexLocker locker(m_inode_lock);
  232. return m_shared_vmobject.strong_ref();
  233. }
  234. template<typename T>
  235. static inline bool range_overlap(T start1, T len1, T start2, T len2)
  236. {
  237. return ((start1 < start2 + len2) || len2 == 0) && ((start2 < start1 + len1) || len1 == 0);
  238. }
  239. static inline ErrorOr<void> normalize_flock(OpenFileDescription const& description, flock& lock)
  240. {
  241. off_t start;
  242. switch (lock.l_whence) {
  243. case SEEK_SET:
  244. start = lock.l_start;
  245. break;
  246. case SEEK_CUR:
  247. start = description.offset() + lock.l_start;
  248. break;
  249. case SEEK_END:
  250. // FIXME: Implement SEEK_END and negative lengths.
  251. return ENOTSUP;
  252. default:
  253. return EINVAL;
  254. }
  255. lock = { lock.l_type, SEEK_SET, start, lock.l_len, 0 };
  256. return {};
  257. }
  258. bool Inode::can_apply_flock(flock const& new_lock) const
  259. {
  260. VERIFY(new_lock.l_whence == SEEK_SET);
  261. if (new_lock.l_type == F_UNLCK)
  262. return true;
  263. return m_flocks.with([&](auto& flocks) {
  264. for (auto const& lock : flocks) {
  265. if (!range_overlap(lock.start, lock.len, new_lock.l_start, new_lock.l_len))
  266. continue;
  267. if (new_lock.l_type == F_RDLCK && lock.type == F_WRLCK)
  268. return false;
  269. if (new_lock.l_type == F_WRLCK)
  270. return false;
  271. }
  272. return true;
  273. });
  274. }
  275. ErrorOr<bool> Inode::try_apply_flock(Process const& process, OpenFileDescription const& description, flock const& lock)
  276. {
  277. return m_flocks.with([&](auto& flocks) -> ErrorOr<bool> {
  278. if (!can_apply_flock(lock))
  279. return false;
  280. if (lock.l_type == F_UNLCK) {
  281. bool any_locks_unlocked = false;
  282. for (size_t i = 0; i < flocks.size(); ++i) {
  283. if (&description == flocks[i].owner && flocks[i].start == lock.l_start && flocks[i].len == lock.l_len) {
  284. flocks.remove(i);
  285. any_locks_unlocked |= true;
  286. }
  287. }
  288. if (any_locks_unlocked)
  289. m_flock_blocker_set.unblock_all_blockers_whose_conditions_are_met();
  290. // Judging by the Linux implementation, unlocking a non-existent lock also works.
  291. return true;
  292. }
  293. TRY(flocks.try_append(Flock { lock.l_start, lock.l_len, &description, process.pid().value(), lock.l_type }));
  294. return true;
  295. });
  296. }
  297. ErrorOr<void> Inode::apply_flock(Process const& process, OpenFileDescription const& description, Userspace<flock const*> input_lock, ShouldBlock should_block)
  298. {
  299. auto new_lock = TRY(copy_typed_from_user(input_lock));
  300. TRY(normalize_flock(description, new_lock));
  301. while (true) {
  302. auto success = TRY(try_apply_flock(process, description, new_lock));
  303. if (success)
  304. return {};
  305. if (should_block == ShouldBlock::No)
  306. return EAGAIN;
  307. if (Thread::current()->block<Thread::FlockBlocker>({}, *this, new_lock).was_interrupted())
  308. return EINTR;
  309. }
  310. }
  311. ErrorOr<void> Inode::get_flock(OpenFileDescription const& description, Userspace<flock*> reference_lock) const
  312. {
  313. flock lookup = {};
  314. TRY(copy_from_user(&lookup, reference_lock));
  315. TRY(normalize_flock(description, lookup));
  316. return m_flocks.with([&](auto& flocks) {
  317. for (auto const& lock : flocks) {
  318. if (!range_overlap(lock.start, lock.len, lookup.l_start, lookup.l_len))
  319. continue;
  320. // Locks with the same owner can't conflict with each other.
  321. if (lock.pid == Process::current().pid())
  322. continue;
  323. if ((lookup.l_type == F_RDLCK && lock.type == F_WRLCK) || lookup.l_type == F_WRLCK) {
  324. lookup = { lock.type, SEEK_SET, lock.start, lock.len, lock.pid };
  325. return copy_to_user(reference_lock, &lookup);
  326. }
  327. }
  328. lookup.l_type = F_UNLCK;
  329. return copy_to_user(reference_lock, &lookup);
  330. });
  331. }
  332. void Inode::remove_flocks_for_description(OpenFileDescription const& description)
  333. {
  334. m_flocks.with([&](auto& flocks) {
  335. flocks.remove_all_matching([&](auto& entry) { return entry.owner == &description; });
  336. });
  337. }
  338. bool Inode::has_watchers() const
  339. {
  340. return !m_watchers.with([&](auto& watchers) { return watchers.is_empty(); });
  341. }
  342. }