OpenFileDescription.cpp 15 KB

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