OpenFileDescription.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537
  1. /*
  2. * Copyright (c) 2018-2022, 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/MemoryStream.h>
  8. #include <Kernel/API/POSIX/errno.h>
  9. #include <Kernel/Devices/BlockDevice.h>
  10. #include <Kernel/FileSystem/Custody.h>
  11. #include <Kernel/FileSystem/FIFO.h>
  12. #include <Kernel/FileSystem/InodeFile.h>
  13. #include <Kernel/FileSystem/InodeWatcher.h>
  14. #include <Kernel/FileSystem/OpenFileDescription.h>
  15. #include <Kernel/FileSystem/VirtualFileSystem.h>
  16. #include <Kernel/Memory/MemoryManager.h>
  17. #include <Kernel/Net/Socket.h>
  18. #include <Kernel/TTY/MasterPTY.h>
  19. #include <Kernel/TTY/TTY.h>
  20. #include <Kernel/Tasks/Process.h>
  21. #include <Kernel/UnixTypes.h>
  22. namespace Kernel {
  23. ErrorOr<NonnullRefPtr<OpenFileDescription>> OpenFileDescription::try_create(Custody& custody)
  24. {
  25. auto inode_file = TRY(InodeFile::create(custody.inode()));
  26. auto description = TRY(adopt_nonnull_ref_or_enomem(new (nothrow) OpenFileDescription(move(inode_file))));
  27. description->m_state.with([&](auto& state) { state.custody = custody; });
  28. TRY(description->attach());
  29. return description;
  30. }
  31. ErrorOr<NonnullRefPtr<OpenFileDescription>> OpenFileDescription::try_create(File& file)
  32. {
  33. auto description = TRY(adopt_nonnull_ref_or_enomem(new (nothrow) OpenFileDescription(file)));
  34. TRY(description->attach());
  35. return description;
  36. }
  37. OpenFileDescription::OpenFileDescription(File& file)
  38. : m_file(file)
  39. {
  40. if (file.is_inode())
  41. m_inode = static_cast<InodeFile&>(file).inode();
  42. auto metadata = this->metadata();
  43. m_state.with([&](auto& state) { state.is_directory = metadata.is_directory(); });
  44. }
  45. OpenFileDescription::~OpenFileDescription()
  46. {
  47. m_file->detach(*this);
  48. // FIXME: Should this error path be observed somehow?
  49. (void)m_file->close();
  50. if (m_inode)
  51. m_inode->detach(*this);
  52. if (m_inode)
  53. m_inode->remove_flocks_for_description(*this);
  54. }
  55. ErrorOr<void> OpenFileDescription::attach()
  56. {
  57. if (m_inode)
  58. TRY(m_inode->attach(*this));
  59. return m_file->attach(*this);
  60. }
  61. void OpenFileDescription::set_original_custody(Badge<VirtualFileSystem>, Custody& custody)
  62. {
  63. m_state.with([&](auto& state) { state.custody = custody; });
  64. }
  65. Thread::FileBlocker::BlockFlags OpenFileDescription::should_unblock(Thread::FileBlocker::BlockFlags block_flags) const
  66. {
  67. using BlockFlags = Thread::FileBlocker::BlockFlags;
  68. BlockFlags unblock_flags = BlockFlags::None;
  69. if (has_flag(block_flags, BlockFlags::Read) && can_read())
  70. unblock_flags |= BlockFlags::Read;
  71. if (has_flag(block_flags, BlockFlags::Write) && can_write())
  72. unblock_flags |= BlockFlags::Write;
  73. // TODO: Implement Thread::FileBlocker::BlockFlags::Exception
  74. if (has_any_flag(block_flags, BlockFlags::SocketFlags)) {
  75. auto const* sock = socket();
  76. VERIFY(sock);
  77. if (has_flag(block_flags, BlockFlags::Accept) && sock->can_accept())
  78. unblock_flags |= BlockFlags::Accept;
  79. if (has_flag(block_flags, BlockFlags::Connect) && sock->setup_state() == Socket::SetupState::Completed)
  80. unblock_flags |= BlockFlags::Connect;
  81. }
  82. return unblock_flags;
  83. }
  84. ErrorOr<struct stat> OpenFileDescription::stat()
  85. {
  86. // FIXME: This is due to the Device class not overriding File::stat().
  87. if (m_inode)
  88. return m_inode->metadata().stat();
  89. return m_file->stat();
  90. }
  91. ErrorOr<off_t> OpenFileDescription::seek(off_t offset, int whence)
  92. {
  93. if (!m_file->is_seekable())
  94. return ESPIPE;
  95. auto metadata = this->metadata();
  96. auto new_offset = TRY(m_state.with([&](auto& state) -> ErrorOr<off_t> {
  97. off_t new_offset;
  98. switch (whence) {
  99. case SEEK_SET:
  100. new_offset = offset;
  101. break;
  102. case SEEK_CUR:
  103. if (Checked<off_t>::addition_would_overflow(state.current_offset, offset))
  104. return EOVERFLOW;
  105. new_offset = state.current_offset + offset;
  106. break;
  107. case SEEK_END:
  108. if (!metadata.is_valid())
  109. return EIO;
  110. if (Checked<off_t>::addition_would_overflow(metadata.size, offset))
  111. return EOVERFLOW;
  112. new_offset = metadata.size + offset;
  113. break;
  114. default:
  115. return EINVAL;
  116. }
  117. if (new_offset < 0)
  118. return EINVAL;
  119. state.current_offset = new_offset;
  120. return new_offset;
  121. }));
  122. // FIXME: Return EINVAL if attempting to seek past the end of a seekable device.
  123. m_file->did_seek(*this, new_offset);
  124. if (m_inode)
  125. m_inode->did_seek(*this, new_offset);
  126. evaluate_block_conditions();
  127. return new_offset;
  128. }
  129. ErrorOr<size_t> OpenFileDescription::read(UserOrKernelBuffer& buffer, u64 offset, size_t count)
  130. {
  131. if (Checked<u64>::addition_would_overflow(offset, count))
  132. return EOVERFLOW;
  133. return m_file->read(*this, offset, buffer, count);
  134. }
  135. ErrorOr<size_t> OpenFileDescription::write(u64 offset, UserOrKernelBuffer const& data, size_t data_size)
  136. {
  137. if (Checked<u64>::addition_would_overflow(offset, data_size))
  138. return EOVERFLOW;
  139. return m_file->write(*this, offset, data, data_size);
  140. }
  141. ErrorOr<size_t> OpenFileDescription::read(UserOrKernelBuffer& buffer, size_t count)
  142. {
  143. auto offset = TRY(m_state.with([&](auto& state) -> ErrorOr<off_t> {
  144. if (Checked<off_t>::addition_would_overflow(state.current_offset, count))
  145. return EOVERFLOW;
  146. return state.current_offset;
  147. }));
  148. auto nread = TRY(m_file->read(*this, offset, buffer, count));
  149. if (m_file->is_seekable())
  150. m_state.with([&](auto& state) { state.current_offset = offset + nread; });
  151. evaluate_block_conditions();
  152. return nread;
  153. }
  154. ErrorOr<size_t> OpenFileDescription::write(UserOrKernelBuffer const& data, size_t size)
  155. {
  156. auto offset = TRY(m_state.with([&](auto& state) -> ErrorOr<off_t> {
  157. if (Checked<off_t>::addition_would_overflow(state.current_offset, size))
  158. return EOVERFLOW;
  159. return state.current_offset;
  160. }));
  161. auto nwritten = TRY(m_file->write(*this, offset, data, size));
  162. if (m_file->is_seekable())
  163. m_state.with([&](auto& state) { state.current_offset = offset + nwritten; });
  164. evaluate_block_conditions();
  165. return nwritten;
  166. }
  167. bool OpenFileDescription::can_write() const
  168. {
  169. return m_file->can_write(*this, offset());
  170. }
  171. bool OpenFileDescription::can_read() const
  172. {
  173. return m_file->can_read(*this, offset());
  174. }
  175. ErrorOr<size_t> OpenFileDescription::get_dir_entries(UserOrKernelBuffer& output_buffer, size_t size)
  176. {
  177. if (!is_directory())
  178. return ENOTDIR;
  179. auto metadata = this->metadata();
  180. if (!metadata.is_valid())
  181. return EIO;
  182. size_t remaining = size;
  183. u8 stack_buffer[PAGE_SIZE];
  184. Bytes temp_buffer(stack_buffer, sizeof(stack_buffer));
  185. FixedMemoryStream stream { temp_buffer };
  186. auto flush_stream_to_output_buffer = [&stream, &remaining, &temp_buffer, &output_buffer]() -> ErrorOr<void> {
  187. auto buffered_size = TRY(stream.tell());
  188. if (buffered_size == 0)
  189. return {};
  190. if (remaining < buffered_size)
  191. return Error::from_errno(EINVAL);
  192. TRY(output_buffer.write(temp_buffer.trim(buffered_size)));
  193. output_buffer = output_buffer.offset(buffered_size);
  194. remaining -= buffered_size;
  195. TRY(stream.seek(0));
  196. return {};
  197. };
  198. ErrorOr<void> result = VirtualFileSystem::the().traverse_directory_inode(*m_inode, [&flush_stream_to_output_buffer, &stream, this](auto& entry) -> ErrorOr<void> {
  199. // FIXME: Double check the calculation, at least the type for the name length mismatches.
  200. size_t serialized_size = sizeof(ino_t) + sizeof(u8) + sizeof(size_t) + sizeof(char) * entry.name.length();
  201. if (serialized_size > TRY(stream.size()) - TRY(stream.tell()))
  202. TRY(flush_stream_to_output_buffer());
  203. MUST(stream.write_value<u64>(entry.inode.index().value()));
  204. MUST(stream.write_value(m_inode->fs().internal_file_type_to_directory_entry_type(entry)));
  205. MUST(stream.write_value<u32>(entry.name.length()));
  206. MUST(stream.write_until_depleted(entry.name.bytes()));
  207. return {};
  208. });
  209. if (result.is_error()) {
  210. // We should only return EFAULT when the userspace buffer is too small,
  211. // so that userspace can reliably use it as a signal to increase its
  212. // buffer size.
  213. VERIFY(result.error().code() != EFAULT);
  214. return result.release_error();
  215. }
  216. TRY(flush_stream_to_output_buffer());
  217. return size - remaining;
  218. }
  219. bool OpenFileDescription::is_device() const
  220. {
  221. return m_file->is_device();
  222. }
  223. Device const* OpenFileDescription::device() const
  224. {
  225. if (!is_device())
  226. return nullptr;
  227. return static_cast<Device const*>(m_file.ptr());
  228. }
  229. Device* OpenFileDescription::device()
  230. {
  231. if (!is_device())
  232. return nullptr;
  233. return static_cast<Device*>(m_file.ptr());
  234. }
  235. bool OpenFileDescription::is_tty() const
  236. {
  237. return m_file->is_tty();
  238. }
  239. const TTY* OpenFileDescription::tty() const
  240. {
  241. if (!is_tty())
  242. return nullptr;
  243. return static_cast<const TTY*>(m_file.ptr());
  244. }
  245. TTY* OpenFileDescription::tty()
  246. {
  247. if (!is_tty())
  248. return nullptr;
  249. return static_cast<TTY*>(m_file.ptr());
  250. }
  251. bool OpenFileDescription::is_inode_watcher() const
  252. {
  253. return m_file->is_inode_watcher();
  254. }
  255. InodeWatcher const* OpenFileDescription::inode_watcher() const
  256. {
  257. if (!is_inode_watcher())
  258. return nullptr;
  259. return static_cast<InodeWatcher const*>(m_file.ptr());
  260. }
  261. InodeWatcher* OpenFileDescription::inode_watcher()
  262. {
  263. if (!is_inode_watcher())
  264. return nullptr;
  265. return static_cast<InodeWatcher*>(m_file.ptr());
  266. }
  267. bool OpenFileDescription::is_master_pty() const
  268. {
  269. return m_file->is_master_pty();
  270. }
  271. MasterPTY const* OpenFileDescription::master_pty() const
  272. {
  273. if (!is_master_pty())
  274. return nullptr;
  275. return static_cast<MasterPTY const*>(m_file.ptr());
  276. }
  277. MasterPTY* OpenFileDescription::master_pty()
  278. {
  279. if (!is_master_pty())
  280. return nullptr;
  281. return static_cast<MasterPTY*>(m_file.ptr());
  282. }
  283. ErrorOr<void> OpenFileDescription::close()
  284. {
  285. if (m_file->attach_count() > 0)
  286. return {};
  287. return m_file->close();
  288. }
  289. ErrorOr<NonnullOwnPtr<KString>> OpenFileDescription::original_absolute_path() const
  290. {
  291. if (auto custody = this->custody())
  292. return custody->try_serialize_absolute_path();
  293. return ENOENT;
  294. }
  295. ErrorOr<NonnullOwnPtr<KString>> OpenFileDescription::pseudo_path() const
  296. {
  297. if (auto custody = this->custody())
  298. return custody->try_serialize_absolute_path();
  299. return m_file->pseudo_path(*this);
  300. }
  301. InodeMetadata OpenFileDescription::metadata() const
  302. {
  303. if (m_inode)
  304. return m_inode->metadata();
  305. return {};
  306. }
  307. ErrorOr<NonnullLockRefPtr<Memory::VMObject>> OpenFileDescription::vmobject_for_mmap(Process& process, Memory::VirtualRange const& range, u64& offset, bool shared)
  308. {
  309. return m_file->vmobject_for_mmap(process, range, offset, shared);
  310. }
  311. ErrorOr<void> OpenFileDescription::truncate(u64 length)
  312. {
  313. return m_file->truncate(length);
  314. }
  315. ErrorOr<void> OpenFileDescription::sync()
  316. {
  317. return m_file->sync();
  318. }
  319. bool OpenFileDescription::is_fifo() const
  320. {
  321. return m_file->is_fifo();
  322. }
  323. FIFO* OpenFileDescription::fifo()
  324. {
  325. if (!is_fifo())
  326. return nullptr;
  327. return static_cast<FIFO*>(m_file.ptr());
  328. }
  329. bool OpenFileDescription::is_socket() const
  330. {
  331. return m_file->is_socket();
  332. }
  333. Socket* OpenFileDescription::socket()
  334. {
  335. if (!is_socket())
  336. return nullptr;
  337. return static_cast<Socket*>(m_file.ptr());
  338. }
  339. Socket const* OpenFileDescription::socket() const
  340. {
  341. if (!is_socket())
  342. return nullptr;
  343. return static_cast<Socket const*>(m_file.ptr());
  344. }
  345. void OpenFileDescription::set_file_flags(u32 flags)
  346. {
  347. m_state.with([&](auto& state) {
  348. state.is_blocking = !(flags & O_NONBLOCK);
  349. state.should_append = flags & O_APPEND;
  350. state.direct = flags & O_DIRECT;
  351. state.file_flags = flags;
  352. });
  353. }
  354. ErrorOr<void> OpenFileDescription::chmod(Credentials const& credentials, mode_t mode)
  355. {
  356. return m_file->chmod(credentials, *this, mode);
  357. }
  358. ErrorOr<void> OpenFileDescription::chown(Credentials const& credentials, UserID uid, GroupID gid)
  359. {
  360. return m_file->chown(credentials, *this, uid, gid);
  361. }
  362. FileBlockerSet& OpenFileDescription::blocker_set()
  363. {
  364. return m_file->blocker_set();
  365. }
  366. ErrorOr<void> OpenFileDescription::apply_flock(Process const& process, Userspace<flock const*> lock, ShouldBlock should_block)
  367. {
  368. if (!m_inode)
  369. return EBADF;
  370. return m_inode->apply_flock(process, *this, lock, should_block);
  371. }
  372. ErrorOr<void> OpenFileDescription::get_flock(Userspace<flock*> lock) const
  373. {
  374. if (!m_inode)
  375. return EBADF;
  376. return m_inode->get_flock(*this, lock);
  377. }
  378. bool OpenFileDescription::is_readable() const
  379. {
  380. return m_state.with([](auto& state) { return state.readable; });
  381. }
  382. bool OpenFileDescription::is_writable() const
  383. {
  384. return m_state.with([](auto& state) { return state.writable; });
  385. }
  386. void OpenFileDescription::set_readable(bool b)
  387. {
  388. m_state.with([&](auto& state) { state.readable = b; });
  389. }
  390. void OpenFileDescription::set_writable(bool b)
  391. {
  392. m_state.with([&](auto& state) { state.writable = b; });
  393. }
  394. void OpenFileDescription::set_rw_mode(int options)
  395. {
  396. m_state.with([&](auto& state) {
  397. state.readable = (options & O_RDONLY) == O_RDONLY;
  398. state.writable = (options & O_WRONLY) == O_WRONLY;
  399. });
  400. }
  401. bool OpenFileDescription::is_direct() const
  402. {
  403. return m_state.with([](auto& state) { return state.direct; });
  404. }
  405. bool OpenFileDescription::is_directory() const
  406. {
  407. return m_state.with([](auto& state) { return state.is_directory; });
  408. }
  409. bool OpenFileDescription::is_blocking() const
  410. {
  411. return m_state.with([](auto& state) { return state.is_blocking; });
  412. }
  413. void OpenFileDescription::set_blocking(bool b)
  414. {
  415. m_state.with([&](auto& state) { state.is_blocking = b; });
  416. }
  417. bool OpenFileDescription::should_append() const
  418. {
  419. return m_state.with([](auto& state) { return state.should_append; });
  420. }
  421. u32 OpenFileDescription::file_flags() const
  422. {
  423. return m_state.with([](auto& state) { return state.file_flags; });
  424. }
  425. FIFO::Direction OpenFileDescription::fifo_direction() const
  426. {
  427. return m_state.with([](auto& state) { return state.fifo_direction; });
  428. }
  429. void OpenFileDescription::set_fifo_direction(Badge<FIFO>, FIFO::Direction direction)
  430. {
  431. m_state.with([&](auto& state) { state.fifo_direction = direction; });
  432. }
  433. OwnPtr<OpenFileDescriptionData>& OpenFileDescription::data()
  434. {
  435. return m_state.with([](auto& state) -> OwnPtr<OpenFileDescriptionData>& { return state.data; });
  436. }
  437. off_t OpenFileDescription::offset() const
  438. {
  439. return m_state.with([](auto& state) { return state.current_offset; });
  440. }
  441. RefPtr<Custody const> OpenFileDescription::custody() const
  442. {
  443. return m_state.with([](auto& state) { return state.custody; });
  444. }
  445. RefPtr<Custody> OpenFileDescription::custody()
  446. {
  447. return m_state.with([](auto& state) { return state.custody; });
  448. }
  449. }