Inode.cpp 11 KB

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