FileDescription.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467
  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::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::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 != 0)
  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) {
  247. return error;
  248. }
  249. return size - remaining;
  250. }
  251. bool FileDescription::is_device() const
  252. {
  253. return m_file->is_device();
  254. }
  255. const Device* FileDescription::device() const
  256. {
  257. if (!is_device())
  258. return nullptr;
  259. return static_cast<const Device*>(m_file.ptr());
  260. }
  261. Device* FileDescription::device()
  262. {
  263. if (!is_device())
  264. return nullptr;
  265. return static_cast<Device*>(m_file.ptr());
  266. }
  267. bool FileDescription::is_tty() const
  268. {
  269. return m_file->is_tty();
  270. }
  271. const TTY* FileDescription::tty() const
  272. {
  273. if (!is_tty())
  274. return nullptr;
  275. return static_cast<const TTY*>(m_file.ptr());
  276. }
  277. TTY* FileDescription::tty()
  278. {
  279. if (!is_tty())
  280. return nullptr;
  281. return static_cast<TTY*>(m_file.ptr());
  282. }
  283. bool FileDescription::is_inode_watcher() const
  284. {
  285. return m_file->is_inode_watcher();
  286. }
  287. const InodeWatcher* FileDescription::inode_watcher() const
  288. {
  289. if (!is_inode_watcher())
  290. return nullptr;
  291. return static_cast<const InodeWatcher*>(m_file.ptr());
  292. }
  293. InodeWatcher* FileDescription::inode_watcher()
  294. {
  295. if (!is_inode_watcher())
  296. return nullptr;
  297. return static_cast<InodeWatcher*>(m_file.ptr());
  298. }
  299. bool FileDescription::is_master_pty() const
  300. {
  301. return m_file->is_master_pty();
  302. }
  303. const MasterPTY* FileDescription::master_pty() const
  304. {
  305. if (!is_master_pty())
  306. return nullptr;
  307. return static_cast<const MasterPTY*>(m_file.ptr());
  308. }
  309. MasterPTY* FileDescription::master_pty()
  310. {
  311. if (!is_master_pty())
  312. return nullptr;
  313. return static_cast<MasterPTY*>(m_file.ptr());
  314. }
  315. KResult FileDescription::close()
  316. {
  317. if (m_file->attach_count() > 0)
  318. return KSuccess;
  319. return m_file->close();
  320. }
  321. String FileDescription::absolute_path() const
  322. {
  323. if (m_custody)
  324. return m_custody->absolute_path();
  325. return m_file->absolute_path(*this);
  326. }
  327. InodeMetadata FileDescription::metadata() const
  328. {
  329. if (m_inode)
  330. return m_inode->metadata();
  331. return {};
  332. }
  333. KResultOr<Memory::Region*> FileDescription::mmap(Process& process, Memory::VirtualRange const& range, u64 offset, int prot, bool shared)
  334. {
  335. MutexLocker locker(m_lock);
  336. return m_file->mmap(process, *this, range, offset, prot, shared);
  337. }
  338. KResult FileDescription::truncate(u64 length)
  339. {
  340. MutexLocker locker(m_lock);
  341. return m_file->truncate(length);
  342. }
  343. bool FileDescription::is_fifo() const
  344. {
  345. return m_file->is_fifo();
  346. }
  347. FIFO* FileDescription::fifo()
  348. {
  349. if (!is_fifo())
  350. return nullptr;
  351. return static_cast<FIFO*>(m_file.ptr());
  352. }
  353. bool FileDescription::is_socket() const
  354. {
  355. return m_file->is_socket();
  356. }
  357. Socket* FileDescription::socket()
  358. {
  359. if (!is_socket())
  360. return nullptr;
  361. return static_cast<Socket*>(m_file.ptr());
  362. }
  363. const Socket* FileDescription::socket() const
  364. {
  365. if (!is_socket())
  366. return nullptr;
  367. return static_cast<const Socket*>(m_file.ptr());
  368. }
  369. void FileDescription::set_file_flags(u32 flags)
  370. {
  371. MutexLocker locker(m_lock);
  372. m_is_blocking = !(flags & O_NONBLOCK);
  373. m_should_append = flags & O_APPEND;
  374. m_direct = flags & O_DIRECT;
  375. m_file_flags = flags;
  376. }
  377. KResult FileDescription::chmod(mode_t mode)
  378. {
  379. MutexLocker locker(m_lock);
  380. return m_file->chmod(*this, mode);
  381. }
  382. KResult FileDescription::chown(uid_t uid, gid_t gid)
  383. {
  384. MutexLocker locker(m_lock);
  385. return m_file->chown(*this, uid, gid);
  386. }
  387. FileBlockCondition& FileDescription::block_condition()
  388. {
  389. return m_file->block_condition();
  390. }
  391. KResult FileDescription::apply_flock(Process const& process, Userspace<flock const*> lock)
  392. {
  393. if (!m_inode)
  394. return EBADF;
  395. return m_inode->apply_flock(process, *this, lock);
  396. }
  397. KResult FileDescription::get_flock(Userspace<flock*> lock) const
  398. {
  399. if (!m_inode)
  400. return EBADF;
  401. return m_inode->get_flock(*this, lock);
  402. }
  403. }