OpenFileDescription.cpp 15 KB

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