OpenFileDescription.cpp 15 KB

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