FileDescription.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466
  1. /*
  2. * Copyright (c) 2018-2020, 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/Debug.h>
  9. #include <Kernel/Devices/BlockDevice.h>
  10. #include <Kernel/FileSystem/Custody.h>
  11. #include <Kernel/FileSystem/FIFO.h>
  12. #include <Kernel/FileSystem/FileDescription.h>
  13. #include <Kernel/FileSystem/FileSystem.h>
  14. #include <Kernel/FileSystem/InodeFile.h>
  15. #include <Kernel/FileSystem/InodeWatcher.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. #include <LibC/errno_numbers.h>
  23. namespace Kernel {
  24. KResultOr<NonnullRefPtr<FileDescription>> FileDescription::try_create(Custody& custody)
  25. {
  26. auto inode_file = InodeFile::create(custody.inode());
  27. if (inode_file.is_error())
  28. return inode_file.error();
  29. auto description = adopt_ref_if_nonnull(new (nothrow) FileDescription(*inode_file.release_value()));
  30. if (!description)
  31. return ENOMEM;
  32. description->m_custody = custody;
  33. auto result = description->attach();
  34. if (result.is_error()) {
  35. dbgln_if(FILEDESCRIPTION_DEBUG, "Failed to create file description for custody: {}", result);
  36. return result;
  37. }
  38. return description.release_nonnull();
  39. }
  40. KResultOr<NonnullRefPtr<FileDescription>> FileDescription::try_create(File& file)
  41. {
  42. auto description = adopt_ref_if_nonnull(new (nothrow) FileDescription(file));
  43. if (!description)
  44. return ENOMEM;
  45. auto result = description->attach();
  46. if (result.is_error()) {
  47. dbgln_if(FILEDESCRIPTION_DEBUG, "Failed to create file description for file: {}", result);
  48. return result;
  49. }
  50. return description.release_nonnull();
  51. }
  52. FileDescription::FileDescription(File& file)
  53. : m_file(file)
  54. {
  55. if (file.is_inode())
  56. m_inode = static_cast<InodeFile&>(file).inode();
  57. m_is_directory = metadata().is_directory();
  58. }
  59. FileDescription::~FileDescription()
  60. {
  61. m_file->detach(*this);
  62. if (is_fifo())
  63. static_cast<FIFO*>(m_file.ptr())->detach(m_fifo_direction);
  64. // FIXME: Should this error path be observed somehow?
  65. (void)m_file->close();
  66. if (m_inode)
  67. m_inode->detach(*this);
  68. if (m_inode)
  69. m_inode->remove_flocks_for_description(*this);
  70. }
  71. KResult FileDescription::attach()
  72. {
  73. if (m_inode) {
  74. auto result = m_inode->attach(*this);
  75. if (result.is_error())
  76. return result;
  77. }
  78. return m_file->attach(*this);
  79. }
  80. Thread::FileBlocker::BlockFlags FileDescription::should_unblock(Thread::FileBlocker::BlockFlags block_flags) const
  81. {
  82. using BlockFlags = Thread::FileBlocker::BlockFlags;
  83. BlockFlags unblock_flags = BlockFlags::None;
  84. if (has_flag(block_flags, BlockFlags::Read) && can_read())
  85. unblock_flags |= BlockFlags::Read;
  86. if (has_flag(block_flags, BlockFlags::Write) && can_write())
  87. unblock_flags |= BlockFlags::Write;
  88. // TODO: Implement Thread::FileBlocker::BlockFlags::Exception
  89. if (has_any_flag(block_flags, BlockFlags::SocketFlags)) {
  90. auto* sock = socket();
  91. VERIFY(sock);
  92. if (has_flag(block_flags, BlockFlags::Accept) && sock->can_accept())
  93. unblock_flags |= BlockFlags::Accept;
  94. if (has_flag(block_flags, BlockFlags::Connect) && sock->setup_state() == Socket::SetupState::Completed)
  95. unblock_flags |= BlockFlags::Connect;
  96. }
  97. return unblock_flags;
  98. }
  99. KResult FileDescription::stat(::stat& buffer)
  100. {
  101. MutexLocker locker(m_lock);
  102. // FIXME: This is due to the Device class not overriding File::stat().
  103. if (m_inode)
  104. return m_inode->metadata().stat(buffer);
  105. return m_file->stat(buffer);
  106. }
  107. KResultOr<off_t> FileDescription::seek(off_t offset, int whence)
  108. {
  109. MutexLocker locker(m_lock);
  110. if (!m_file->is_seekable())
  111. return ESPIPE;
  112. off_t new_offset;
  113. switch (whence) {
  114. case SEEK_SET:
  115. new_offset = offset;
  116. break;
  117. case SEEK_CUR:
  118. if (Checked<off_t>::addition_would_overflow(m_current_offset, offset))
  119. return EOVERFLOW;
  120. new_offset = m_current_offset + offset;
  121. break;
  122. case SEEK_END:
  123. if (!metadata().is_valid())
  124. return EIO;
  125. if (Checked<off_t>::addition_would_overflow(metadata().size, offset))
  126. return EOVERFLOW;
  127. new_offset = metadata().size + offset;
  128. break;
  129. default:
  130. return EINVAL;
  131. }
  132. if (new_offset < 0)
  133. return EINVAL;
  134. // FIXME: Return EINVAL if attempting to seek past the end of a seekable device.
  135. m_current_offset = new_offset;
  136. m_file->did_seek(*this, new_offset);
  137. if (m_inode)
  138. m_inode->did_seek(*this, new_offset);
  139. evaluate_block_conditions();
  140. return m_current_offset;
  141. }
  142. KResultOr<size_t> FileDescription::read(UserOrKernelBuffer& buffer, u64 offset, size_t count)
  143. {
  144. if (Checked<u64>::addition_would_overflow(offset, count))
  145. return EOVERFLOW;
  146. return m_file->read(*this, offset, buffer, count);
  147. }
  148. KResultOr<size_t> FileDescription::write(u64 offset, UserOrKernelBuffer const& data, size_t data_size)
  149. {
  150. if (Checked<u64>::addition_would_overflow(offset, data_size))
  151. return EOVERFLOW;
  152. return m_file->write(*this, offset, data, data_size);
  153. }
  154. KResultOr<size_t> FileDescription::read(UserOrKernelBuffer& buffer, size_t count)
  155. {
  156. MutexLocker locker(m_lock);
  157. if (Checked<off_t>::addition_would_overflow(m_current_offset, count))
  158. return EOVERFLOW;
  159. auto nread_or_error = m_file->read(*this, offset(), buffer, count);
  160. if (!nread_or_error.is_error()) {
  161. if (m_file->is_seekable())
  162. m_current_offset += nread_or_error.value();
  163. evaluate_block_conditions();
  164. }
  165. return nread_or_error;
  166. }
  167. KResultOr<size_t> FileDescription::write(const UserOrKernelBuffer& data, size_t size)
  168. {
  169. MutexLocker locker(m_lock);
  170. if (Checked<off_t>::addition_would_overflow(m_current_offset, size))
  171. return EOVERFLOW;
  172. auto nwritten_or_error = m_file->write(*this, offset(), data, size);
  173. if (!nwritten_or_error.is_error()) {
  174. if (m_file->is_seekable())
  175. m_current_offset += nwritten_or_error.value();
  176. evaluate_block_conditions();
  177. }
  178. return nwritten_or_error;
  179. }
  180. bool FileDescription::can_write() const
  181. {
  182. return m_file->can_write(*this, offset());
  183. }
  184. bool FileDescription::can_read() const
  185. {
  186. return m_file->can_read(*this, offset());
  187. }
  188. KResultOr<NonnullOwnPtr<KBuffer>> FileDescription::read_entire_file()
  189. {
  190. // HACK ALERT: (This entire function)
  191. VERIFY(m_file->is_inode());
  192. VERIFY(m_inode);
  193. return m_inode->read_entire(this);
  194. }
  195. KResultOr<size_t> FileDescription::get_dir_entries(UserOrKernelBuffer& output_buffer, size_t size)
  196. {
  197. MutexLocker locker(m_lock, Mutex::Mode::Shared);
  198. if (!is_directory())
  199. return ENOTDIR;
  200. auto metadata = this->metadata();
  201. if (!metadata.is_valid())
  202. return EIO;
  203. size_t remaining = size;
  204. KResult error = KSuccess;
  205. u8 stack_buffer[PAGE_SIZE];
  206. Bytes temp_buffer(stack_buffer, sizeof(stack_buffer));
  207. OutputMemoryStream stream { temp_buffer };
  208. auto flush_stream_to_output_buffer = [&error, &stream, &remaining, &output_buffer]() -> bool {
  209. if (error.is_error())
  210. return false;
  211. if (stream.size() == 0)
  212. return true;
  213. if (remaining < stream.size()) {
  214. error = EINVAL;
  215. return false;
  216. } else if (!output_buffer.write(stream.bytes())) {
  217. error = EFAULT;
  218. return false;
  219. }
  220. output_buffer = output_buffer.offset(stream.size());
  221. remaining -= stream.size();
  222. stream.reset();
  223. return true;
  224. };
  225. KResult result = VirtualFileSystem::the().traverse_directory_inode(*m_inode, [&flush_stream_to_output_buffer, &stream, this](auto& entry) {
  226. size_t serialized_size = sizeof(ino_t) + sizeof(u8) + sizeof(size_t) + sizeof(char) * entry.name.length();
  227. if (serialized_size > stream.remaining()) {
  228. if (!flush_stream_to_output_buffer()) {
  229. return false;
  230. }
  231. }
  232. stream << (u64)entry.inode.index().value();
  233. stream << m_inode->fs().internal_file_type_to_directory_entry_type(entry);
  234. stream << (u32)entry.name.length();
  235. stream << entry.name.bytes();
  236. return true;
  237. });
  238. flush_stream_to_output_buffer();
  239. if (result.is_error()) {
  240. // We should only return EFAULT when the userspace buffer is too small,
  241. // so that userspace can reliably use it as a signal to increase its
  242. // buffer size.
  243. VERIFY(result != EFAULT);
  244. return result;
  245. }
  246. if (error.is_error())
  247. return error;
  248. return size - remaining;
  249. }
  250. bool FileDescription::is_device() const
  251. {
  252. return m_file->is_device();
  253. }
  254. const Device* FileDescription::device() const
  255. {
  256. if (!is_device())
  257. return nullptr;
  258. return static_cast<const Device*>(m_file.ptr());
  259. }
  260. Device* FileDescription::device()
  261. {
  262. if (!is_device())
  263. return nullptr;
  264. return static_cast<Device*>(m_file.ptr());
  265. }
  266. bool FileDescription::is_tty() const
  267. {
  268. return m_file->is_tty();
  269. }
  270. const TTY* FileDescription::tty() const
  271. {
  272. if (!is_tty())
  273. return nullptr;
  274. return static_cast<const TTY*>(m_file.ptr());
  275. }
  276. TTY* FileDescription::tty()
  277. {
  278. if (!is_tty())
  279. return nullptr;
  280. return static_cast<TTY*>(m_file.ptr());
  281. }
  282. bool FileDescription::is_inode_watcher() const
  283. {
  284. return m_file->is_inode_watcher();
  285. }
  286. const InodeWatcher* FileDescription::inode_watcher() const
  287. {
  288. if (!is_inode_watcher())
  289. return nullptr;
  290. return static_cast<const InodeWatcher*>(m_file.ptr());
  291. }
  292. InodeWatcher* FileDescription::inode_watcher()
  293. {
  294. if (!is_inode_watcher())
  295. return nullptr;
  296. return static_cast<InodeWatcher*>(m_file.ptr());
  297. }
  298. bool FileDescription::is_master_pty() const
  299. {
  300. return m_file->is_master_pty();
  301. }
  302. const MasterPTY* FileDescription::master_pty() const
  303. {
  304. if (!is_master_pty())
  305. return nullptr;
  306. return static_cast<const MasterPTY*>(m_file.ptr());
  307. }
  308. MasterPTY* FileDescription::master_pty()
  309. {
  310. if (!is_master_pty())
  311. return nullptr;
  312. return static_cast<MasterPTY*>(m_file.ptr());
  313. }
  314. KResult FileDescription::close()
  315. {
  316. if (m_file->attach_count() > 0)
  317. return KSuccess;
  318. return m_file->close();
  319. }
  320. String FileDescription::absolute_path() const
  321. {
  322. if (m_custody)
  323. return m_custody->absolute_path();
  324. return m_file->absolute_path(*this);
  325. }
  326. InodeMetadata FileDescription::metadata() const
  327. {
  328. if (m_inode)
  329. return m_inode->metadata();
  330. return {};
  331. }
  332. KResultOr<Memory::Region*> FileDescription::mmap(Process& process, Memory::VirtualRange const& range, u64 offset, int prot, bool shared)
  333. {
  334. MutexLocker locker(m_lock);
  335. return m_file->mmap(process, *this, range, offset, prot, shared);
  336. }
  337. KResult FileDescription::truncate(u64 length)
  338. {
  339. MutexLocker locker(m_lock);
  340. return m_file->truncate(length);
  341. }
  342. bool FileDescription::is_fifo() const
  343. {
  344. return m_file->is_fifo();
  345. }
  346. FIFO* FileDescription::fifo()
  347. {
  348. if (!is_fifo())
  349. return nullptr;
  350. return static_cast<FIFO*>(m_file.ptr());
  351. }
  352. bool FileDescription::is_socket() const
  353. {
  354. return m_file->is_socket();
  355. }
  356. Socket* FileDescription::socket()
  357. {
  358. if (!is_socket())
  359. return nullptr;
  360. return static_cast<Socket*>(m_file.ptr());
  361. }
  362. const Socket* FileDescription::socket() const
  363. {
  364. if (!is_socket())
  365. return nullptr;
  366. return static_cast<const Socket*>(m_file.ptr());
  367. }
  368. void FileDescription::set_file_flags(u32 flags)
  369. {
  370. MutexLocker locker(m_lock);
  371. m_is_blocking = !(flags & O_NONBLOCK);
  372. m_should_append = flags & O_APPEND;
  373. m_direct = flags & O_DIRECT;
  374. m_file_flags = flags;
  375. }
  376. KResult FileDescription::chmod(mode_t mode)
  377. {
  378. MutexLocker locker(m_lock);
  379. return m_file->chmod(*this, mode);
  380. }
  381. KResult FileDescription::chown(UserID uid, GroupID gid)
  382. {
  383. MutexLocker locker(m_lock);
  384. return m_file->chown(*this, uid, gid);
  385. }
  386. FileBlockerSet& FileDescription::blocker_set()
  387. {
  388. return m_file->blocker_set();
  389. }
  390. KResult FileDescription::apply_flock(Process const& process, Userspace<flock const*> lock)
  391. {
  392. if (!m_inode)
  393. return EBADF;
  394. return m_inode->apply_flock(process, *this, lock);
  395. }
  396. KResult FileDescription::get_flock(Userspace<flock*> lock) const
  397. {
  398. if (!m_inode)
  399. return EBADF;
  400. return m_inode->get_flock(*this, lock);
  401. }
  402. }