Inode.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404
  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/Singleton.h>
  9. #include <AK/StringView.h>
  10. #include <Kernel/API/InodeWatcherEvent.h>
  11. #include <Kernel/FileSystem/Custody.h>
  12. #include <Kernel/FileSystem/Inode.h>
  13. #include <Kernel/FileSystem/InodeWatcher.h>
  14. #include <Kernel/FileSystem/OpenFileDescription.h>
  15. #include <Kernel/FileSystem/VirtualFileSystem.h>
  16. #include <Kernel/KBufferBuilder.h>
  17. #include <Kernel/Library/NonnullLockRefPtrVector.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. NonnullLockRefPtrVector<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(Process::current().credentials(), 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. LockRefPtr<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<NonnullLockRefPtr<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 NonnullLockRefPtr { *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. VERIFY(m_inode_lock.is_locked());
  218. if (fs().is_readonly())
  219. return EROFS;
  220. auto metadata = this->metadata();
  221. if (metadata.is_setuid() || metadata.is_setgid()) {
  222. dbgln("Inode::prepare_to_write_data(): Stripping SUID/SGID bits from {}", identifier());
  223. return chmod(metadata.mode & ~(04000 | 02000));
  224. }
  225. return {};
  226. }
  227. LockRefPtr<Memory::SharedInodeVMObject> Inode::shared_vmobject() const
  228. {
  229. MutexLocker locker(m_inode_lock);
  230. return m_shared_vmobject.strong_ref();
  231. }
  232. template<typename T>
  233. static inline bool range_overlap(T start1, T len1, T start2, T len2)
  234. {
  235. return ((start1 < start2 + len2) || len2 == 0) && ((start2 < start1 + len1) || len1 == 0);
  236. }
  237. static inline ErrorOr<void> normalize_flock(OpenFileDescription const& description, flock& lock)
  238. {
  239. off_t start;
  240. switch (lock.l_whence) {
  241. case SEEK_SET:
  242. start = lock.l_start;
  243. break;
  244. case SEEK_CUR:
  245. start = description.offset() + lock.l_start;
  246. break;
  247. case SEEK_END:
  248. // FIXME: Implement SEEK_END and negative lengths.
  249. return ENOTSUP;
  250. default:
  251. return EINVAL;
  252. }
  253. lock = { lock.l_type, SEEK_SET, start, lock.l_len, 0 };
  254. return {};
  255. }
  256. bool Inode::can_apply_flock(flock const& new_lock) const
  257. {
  258. VERIFY(new_lock.l_whence == SEEK_SET);
  259. if (new_lock.l_type == F_UNLCK)
  260. return true;
  261. return m_flocks.with([&](auto& flocks) {
  262. for (auto const& lock : flocks) {
  263. if (!range_overlap(lock.start, lock.len, new_lock.l_start, new_lock.l_len))
  264. continue;
  265. if (new_lock.l_type == F_RDLCK && lock.type == F_WRLCK)
  266. return false;
  267. if (new_lock.l_type == F_WRLCK)
  268. return false;
  269. }
  270. return true;
  271. });
  272. }
  273. ErrorOr<bool> Inode::try_apply_flock(Process const& process, OpenFileDescription const& description, flock const& lock)
  274. {
  275. return m_flocks.with([&](auto& flocks) -> ErrorOr<bool> {
  276. if (!can_apply_flock(lock))
  277. return false;
  278. if (lock.l_type == F_UNLCK) {
  279. bool any_locks_unlocked = false;
  280. for (size_t i = 0; i < flocks.size(); ++i) {
  281. if (&description == flocks[i].owner && flocks[i].start == lock.l_start && flocks[i].len == lock.l_len) {
  282. flocks.remove(i);
  283. any_locks_unlocked |= true;
  284. }
  285. }
  286. if (any_locks_unlocked)
  287. m_flock_blocker_set.unblock_all_blockers_whose_conditions_are_met();
  288. // Judging by the Linux implementation, unlocking a non-existent lock also works.
  289. return true;
  290. }
  291. TRY(flocks.try_append(Flock { lock.l_start, lock.l_len, &description, process.pid().value(), lock.l_type }));
  292. return true;
  293. });
  294. }
  295. ErrorOr<void> Inode::apply_flock(Process const& process, OpenFileDescription const& description, Userspace<flock const*> input_lock, ShouldBlock should_block)
  296. {
  297. auto new_lock = TRY(copy_typed_from_user(input_lock));
  298. TRY(normalize_flock(description, new_lock));
  299. while (true) {
  300. auto success = TRY(try_apply_flock(process, description, new_lock));
  301. if (success)
  302. return {};
  303. if (should_block == ShouldBlock::No)
  304. return EAGAIN;
  305. if (Thread::current()->block<Thread::FlockBlocker>({}, *this, new_lock).was_interrupted())
  306. return EINTR;
  307. }
  308. }
  309. ErrorOr<void> Inode::get_flock(OpenFileDescription const& description, Userspace<flock*> reference_lock) const
  310. {
  311. flock lookup = {};
  312. TRY(copy_from_user(&lookup, reference_lock));
  313. TRY(normalize_flock(description, lookup));
  314. return m_flocks.with([&](auto& flocks) {
  315. for (auto const& lock : flocks) {
  316. if (!range_overlap(lock.start, lock.len, lookup.l_start, lookup.l_len))
  317. continue;
  318. // Locks with the same owner can't conflict with each other.
  319. if (lock.pid == Process::current().pid())
  320. continue;
  321. if ((lookup.l_type == F_RDLCK && lock.type == F_WRLCK) || lookup.l_type == F_WRLCK) {
  322. lookup = { lock.type, SEEK_SET, lock.start, lock.len, lock.pid };
  323. return copy_to_user(reference_lock, &lookup);
  324. }
  325. }
  326. lookup.l_type = F_UNLCK;
  327. return copy_to_user(reference_lock, &lookup);
  328. });
  329. }
  330. void Inode::remove_flocks_for_description(OpenFileDescription const& description)
  331. {
  332. m_flocks.with([&](auto& flocks) {
  333. flocks.remove_all_matching([&](auto& entry) { return entry.owner == &description; });
  334. });
  335. }
  336. bool Inode::has_watchers() const
  337. {
  338. return !m_watchers.with([&](auto& watchers) { return watchers.is_empty(); });
  339. }
  340. }