OpenFileDescription.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547
  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<NonnullOwnPtr<KBuffer>> OpenFileDescription::read_entire_file()
  178. {
  179. // HACK ALERT: (This entire function)
  180. VERIFY(m_file->is_inode());
  181. VERIFY(m_inode);
  182. return m_inode->read_entire(this);
  183. }
  184. ErrorOr<size_t> OpenFileDescription::get_dir_entries(UserOrKernelBuffer& output_buffer, size_t size)
  185. {
  186. if (!is_directory())
  187. return ENOTDIR;
  188. auto metadata = this->metadata();
  189. if (!metadata.is_valid())
  190. return EIO;
  191. size_t remaining = size;
  192. u8 stack_buffer[PAGE_SIZE];
  193. Bytes temp_buffer(stack_buffer, sizeof(stack_buffer));
  194. FixedMemoryStream stream { temp_buffer };
  195. auto flush_stream_to_output_buffer = [&stream, &remaining, &temp_buffer, &output_buffer]() -> ErrorOr<void> {
  196. auto buffered_size = TRY(stream.tell());
  197. if (buffered_size == 0)
  198. return {};
  199. if (remaining < buffered_size)
  200. return Error::from_errno(EINVAL);
  201. TRY(output_buffer.write(temp_buffer.trim(buffered_size)));
  202. output_buffer = output_buffer.offset(buffered_size);
  203. remaining -= buffered_size;
  204. TRY(stream.seek(0));
  205. return {};
  206. };
  207. ErrorOr<void> result = VirtualFileSystem::the().traverse_directory_inode(*m_inode, [&flush_stream_to_output_buffer, &stream, this](auto& entry) -> ErrorOr<void> {
  208. // FIXME: Double check the calculation, at least the type for the name length mismatches.
  209. size_t serialized_size = sizeof(ino_t) + sizeof(u8) + sizeof(size_t) + sizeof(char) * entry.name.length();
  210. if (serialized_size > TRY(stream.size()) - TRY(stream.tell()))
  211. TRY(flush_stream_to_output_buffer());
  212. MUST(stream.write_value<u64>(entry.inode.index().value()));
  213. MUST(stream.write_value(m_inode->fs().internal_file_type_to_directory_entry_type(entry)));
  214. MUST(stream.write_value<u32>(entry.name.length()));
  215. MUST(stream.write_entire_buffer(entry.name.bytes()));
  216. return {};
  217. });
  218. if (result.is_error()) {
  219. // We should only return EFAULT when the userspace buffer is too small,
  220. // so that userspace can reliably use it as a signal to increase its
  221. // buffer size.
  222. VERIFY(result.error().code() != EFAULT);
  223. return result.release_error();
  224. }
  225. TRY(flush_stream_to_output_buffer());
  226. return size - remaining;
  227. }
  228. bool OpenFileDescription::is_device() const
  229. {
  230. return m_file->is_device();
  231. }
  232. Device const* OpenFileDescription::device() const
  233. {
  234. if (!is_device())
  235. return nullptr;
  236. return static_cast<Device const*>(m_file.ptr());
  237. }
  238. Device* OpenFileDescription::device()
  239. {
  240. if (!is_device())
  241. return nullptr;
  242. return static_cast<Device*>(m_file.ptr());
  243. }
  244. bool OpenFileDescription::is_tty() const
  245. {
  246. return m_file->is_tty();
  247. }
  248. const TTY* OpenFileDescription::tty() const
  249. {
  250. if (!is_tty())
  251. return nullptr;
  252. return static_cast<const TTY*>(m_file.ptr());
  253. }
  254. TTY* OpenFileDescription::tty()
  255. {
  256. if (!is_tty())
  257. return nullptr;
  258. return static_cast<TTY*>(m_file.ptr());
  259. }
  260. bool OpenFileDescription::is_inode_watcher() const
  261. {
  262. return m_file->is_inode_watcher();
  263. }
  264. InodeWatcher const* OpenFileDescription::inode_watcher() const
  265. {
  266. if (!is_inode_watcher())
  267. return nullptr;
  268. return static_cast<InodeWatcher const*>(m_file.ptr());
  269. }
  270. InodeWatcher* OpenFileDescription::inode_watcher()
  271. {
  272. if (!is_inode_watcher())
  273. return nullptr;
  274. return static_cast<InodeWatcher*>(m_file.ptr());
  275. }
  276. bool OpenFileDescription::is_master_pty() const
  277. {
  278. return m_file->is_master_pty();
  279. }
  280. MasterPTY const* OpenFileDescription::master_pty() const
  281. {
  282. if (!is_master_pty())
  283. return nullptr;
  284. return static_cast<MasterPTY const*>(m_file.ptr());
  285. }
  286. MasterPTY* OpenFileDescription::master_pty()
  287. {
  288. if (!is_master_pty())
  289. return nullptr;
  290. return static_cast<MasterPTY*>(m_file.ptr());
  291. }
  292. ErrorOr<void> OpenFileDescription::close()
  293. {
  294. if (m_file->attach_count() > 0)
  295. return {};
  296. return m_file->close();
  297. }
  298. ErrorOr<NonnullOwnPtr<KString>> OpenFileDescription::original_absolute_path() const
  299. {
  300. if (auto custody = this->custody())
  301. return custody->try_serialize_absolute_path();
  302. return ENOENT;
  303. }
  304. ErrorOr<NonnullOwnPtr<KString>> OpenFileDescription::pseudo_path() const
  305. {
  306. if (auto custody = this->custody())
  307. return custody->try_serialize_absolute_path();
  308. return m_file->pseudo_path(*this);
  309. }
  310. InodeMetadata OpenFileDescription::metadata() const
  311. {
  312. if (m_inode)
  313. return m_inode->metadata();
  314. return {};
  315. }
  316. ErrorOr<NonnullLockRefPtr<Memory::VMObject>> OpenFileDescription::vmobject_for_mmap(Process& process, Memory::VirtualRange const& range, u64& offset, bool shared)
  317. {
  318. return m_file->vmobject_for_mmap(process, range, offset, shared);
  319. }
  320. ErrorOr<void> OpenFileDescription::truncate(u64 length)
  321. {
  322. return m_file->truncate(length);
  323. }
  324. ErrorOr<void> OpenFileDescription::sync()
  325. {
  326. return m_file->sync();
  327. }
  328. bool OpenFileDescription::is_fifo() const
  329. {
  330. return m_file->is_fifo();
  331. }
  332. FIFO* OpenFileDescription::fifo()
  333. {
  334. if (!is_fifo())
  335. return nullptr;
  336. return static_cast<FIFO*>(m_file.ptr());
  337. }
  338. bool OpenFileDescription::is_socket() const
  339. {
  340. return m_file->is_socket();
  341. }
  342. Socket* OpenFileDescription::socket()
  343. {
  344. if (!is_socket())
  345. return nullptr;
  346. return static_cast<Socket*>(m_file.ptr());
  347. }
  348. Socket const* OpenFileDescription::socket() const
  349. {
  350. if (!is_socket())
  351. return nullptr;
  352. return static_cast<Socket const*>(m_file.ptr());
  353. }
  354. void OpenFileDescription::set_file_flags(u32 flags)
  355. {
  356. m_state.with([&](auto& state) {
  357. state.is_blocking = !(flags & O_NONBLOCK);
  358. state.should_append = flags & O_APPEND;
  359. state.direct = flags & O_DIRECT;
  360. state.file_flags = flags;
  361. });
  362. }
  363. ErrorOr<void> OpenFileDescription::chmod(Credentials const& credentials, mode_t mode)
  364. {
  365. return m_file->chmod(credentials, *this, mode);
  366. }
  367. ErrorOr<void> OpenFileDescription::chown(Credentials const& credentials, UserID uid, GroupID gid)
  368. {
  369. return m_file->chown(credentials, *this, uid, gid);
  370. }
  371. FileBlockerSet& OpenFileDescription::blocker_set()
  372. {
  373. return m_file->blocker_set();
  374. }
  375. ErrorOr<void> OpenFileDescription::apply_flock(Process const& process, Userspace<flock const*> lock, ShouldBlock should_block)
  376. {
  377. if (!m_inode)
  378. return EBADF;
  379. return m_inode->apply_flock(process, *this, lock, should_block);
  380. }
  381. ErrorOr<void> OpenFileDescription::get_flock(Userspace<flock*> lock) const
  382. {
  383. if (!m_inode)
  384. return EBADF;
  385. return m_inode->get_flock(*this, lock);
  386. }
  387. bool OpenFileDescription::is_readable() const
  388. {
  389. return m_state.with([](auto& state) { return state.readable; });
  390. }
  391. bool OpenFileDescription::is_writable() const
  392. {
  393. return m_state.with([](auto& state) { return state.writable; });
  394. }
  395. void OpenFileDescription::set_readable(bool b)
  396. {
  397. m_state.with([&](auto& state) { state.readable = b; });
  398. }
  399. void OpenFileDescription::set_writable(bool b)
  400. {
  401. m_state.with([&](auto& state) { state.writable = b; });
  402. }
  403. void OpenFileDescription::set_rw_mode(int options)
  404. {
  405. m_state.with([&](auto& state) {
  406. state.readable = (options & O_RDONLY) == O_RDONLY;
  407. state.writable = (options & O_WRONLY) == O_WRONLY;
  408. });
  409. }
  410. bool OpenFileDescription::is_direct() const
  411. {
  412. return m_state.with([](auto& state) { return state.direct; });
  413. }
  414. bool OpenFileDescription::is_directory() const
  415. {
  416. return m_state.with([](auto& state) { return state.is_directory; });
  417. }
  418. bool OpenFileDescription::is_blocking() const
  419. {
  420. return m_state.with([](auto& state) { return state.is_blocking; });
  421. }
  422. void OpenFileDescription::set_blocking(bool b)
  423. {
  424. m_state.with([&](auto& state) { state.is_blocking = b; });
  425. }
  426. bool OpenFileDescription::should_append() const
  427. {
  428. return m_state.with([](auto& state) { return state.should_append; });
  429. }
  430. u32 OpenFileDescription::file_flags() const
  431. {
  432. return m_state.with([](auto& state) { return state.file_flags; });
  433. }
  434. FIFO::Direction OpenFileDescription::fifo_direction() const
  435. {
  436. return m_state.with([](auto& state) { return state.fifo_direction; });
  437. }
  438. void OpenFileDescription::set_fifo_direction(Badge<FIFO>, FIFO::Direction direction)
  439. {
  440. m_state.with([&](auto& state) { state.fifo_direction = direction; });
  441. }
  442. OwnPtr<OpenFileDescriptionData>& OpenFileDescription::data()
  443. {
  444. return m_state.with([](auto& state) -> OwnPtr<OpenFileDescriptionData>& { return state.data; });
  445. }
  446. off_t OpenFileDescription::offset() const
  447. {
  448. return m_state.with([](auto& state) { return state.current_offset; });
  449. }
  450. RefPtr<Custody const> OpenFileDescription::custody() const
  451. {
  452. return m_state.with([](auto& state) { return state.custody; });
  453. }
  454. RefPtr<Custody> OpenFileDescription::custody()
  455. {
  456. return m_state.with([](auto& state) { return state.custody; });
  457. }
  458. }