FileDescription.cpp 12 KB

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