OpenFileDescription.cpp 15 KB

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