VirtualFileSystem.cpp 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/AnyOf.h>
  7. #include <AK/GenericLexer.h>
  8. #include <AK/RefPtr.h>
  9. #include <AK/Singleton.h>
  10. #include <AK/StringBuilder.h>
  11. #include <Kernel/API/POSIX/errno.h>
  12. #include <Kernel/Debug.h>
  13. #include <Kernel/Devices/BlockDevice.h>
  14. #include <Kernel/Devices/DeviceManagement.h>
  15. #include <Kernel/FileSystem/Custody.h>
  16. #include <Kernel/FileSystem/FileBackedFileSystem.h>
  17. #include <Kernel/FileSystem/FileSystem.h>
  18. #include <Kernel/FileSystem/OpenFileDescription.h>
  19. #include <Kernel/FileSystem/VirtualFileSystem.h>
  20. #include <Kernel/KLexicalPath.h>
  21. #include <Kernel/KSyms.h>
  22. #include <Kernel/Process.h>
  23. #include <Kernel/Sections.h>
  24. namespace Kernel {
  25. static Singleton<VirtualFileSystem> s_the;
  26. static constexpr int root_mount_flags = MS_NODEV | MS_NOSUID | MS_RDONLY;
  27. UNMAP_AFTER_INIT void VirtualFileSystem::initialize()
  28. {
  29. s_the.ensure_instance();
  30. }
  31. VirtualFileSystem& VirtualFileSystem::the()
  32. {
  33. return *s_the;
  34. }
  35. UNMAP_AFTER_INIT VirtualFileSystem::VirtualFileSystem()
  36. : m_root_custody(LockRank::None)
  37. {
  38. }
  39. UNMAP_AFTER_INIT VirtualFileSystem::~VirtualFileSystem() = default;
  40. InodeIdentifier VirtualFileSystem::root_inode_id() const
  41. {
  42. VERIFY(m_root_inode);
  43. return m_root_inode->identifier();
  44. }
  45. bool VirtualFileSystem::mount_point_exists_at_inode(InodeIdentifier inode_identifier)
  46. {
  47. return m_mounts.with([&](auto& mounts) -> bool {
  48. return any_of(mounts, [&inode_identifier](auto const& existing_mount) {
  49. return existing_mount->host() && existing_mount->host()->identifier() == inode_identifier;
  50. });
  51. });
  52. }
  53. ErrorOr<void> VirtualFileSystem::mount(FileSystem& fs, Custody& mount_point, int flags)
  54. {
  55. auto new_mount = TRY(adopt_nonnull_own_or_enomem(new (nothrow) Mount(fs, &mount_point, flags)));
  56. return m_mounts.with([&](auto& mounts) -> ErrorOr<void> {
  57. auto& inode = mount_point.inode();
  58. dbgln("VirtualFileSystem: FileSystemID {}, Mounting {} at inode {} with flags {}",
  59. fs.fsid(),
  60. fs.class_name(),
  61. inode.identifier(),
  62. flags);
  63. if (mount_point_exists_at_inode(inode.identifier())) {
  64. dbgln("VirtualFileSystem: Mounting unsuccessful - inode {} is already a mount-point.", inode.identifier());
  65. return EBUSY;
  66. }
  67. // Note: Actually add a mount for the filesystem and increment the filesystem mounted count
  68. new_mount->guest_fs().mounted_count({}).with([&](auto& mounted_count) {
  69. mounted_count++;
  70. });
  71. mounts.append(move(new_mount));
  72. return {};
  73. });
  74. }
  75. ErrorOr<void> VirtualFileSystem::bind_mount(Custody& source, Custody& mount_point, int flags)
  76. {
  77. auto new_mount = TRY(adopt_nonnull_own_or_enomem(new (nothrow) Mount(source.inode(), mount_point, flags)));
  78. return m_mounts.with([&](auto& mounts) -> ErrorOr<void> {
  79. auto& inode = mount_point.inode();
  80. dbgln("VirtualFileSystem: Bind-mounting inode {} at inode {}", source.inode().identifier(), inode.identifier());
  81. if (mount_point_exists_at_inode(inode.identifier())) {
  82. dbgln("VirtualFileSystem: Bind-mounting unsuccessful - inode {} is already a mount-point.",
  83. mount_point.inode().identifier());
  84. return EBUSY;
  85. }
  86. mounts.append(move(new_mount));
  87. return {};
  88. });
  89. }
  90. ErrorOr<void> VirtualFileSystem::remount(Custody& mount_point, int new_flags)
  91. {
  92. dbgln("VirtualFileSystem: Remounting inode {}", mount_point.inode().identifier());
  93. auto* mount = find_mount_for_guest(mount_point.inode().identifier());
  94. if (!mount)
  95. return ENODEV;
  96. mount->set_flags(new_flags);
  97. return {};
  98. }
  99. void VirtualFileSystem::sync_filesystems()
  100. {
  101. NonnullLockRefPtrVector<FileSystem, 32> file_systems;
  102. m_file_systems_list.with([&](auto const& list) {
  103. for (auto& fs : list)
  104. file_systems.append(fs);
  105. });
  106. for (auto& fs : file_systems)
  107. fs.flush_writes();
  108. }
  109. void VirtualFileSystem::lock_all_filesystems()
  110. {
  111. NonnullLockRefPtrVector<FileSystem, 32> file_systems;
  112. m_file_systems_list.with([&](auto const& list) {
  113. for (auto& fs : list)
  114. file_systems.append(fs);
  115. });
  116. for (auto& fs : file_systems)
  117. fs.m_lock.lock();
  118. }
  119. ErrorOr<void> VirtualFileSystem::unmount(Custody& mountpoint_custody)
  120. {
  121. auto& guest_inode = mountpoint_custody.inode();
  122. auto custody_path = TRY(mountpoint_custody.try_serialize_absolute_path());
  123. dbgln("VirtualFileSystem: unmount called with inode {} on mountpoint {}", guest_inode.identifier(), custody_path->view());
  124. return m_mounts.with([&](auto& mounts) -> ErrorOr<void> {
  125. for (size_t i = 0; i < mounts.size(); ++i) {
  126. auto& mount = mounts[i];
  127. if (&mount->guest() != &guest_inode)
  128. continue;
  129. auto mountpoint_path = TRY(mount->absolute_path());
  130. if (custody_path->view() != mountpoint_path->view())
  131. continue;
  132. NonnullRefPtr<FileSystem> fs = mount->guest_fs();
  133. TRY(fs->prepare_to_unmount());
  134. fs->mounted_count({}).with([&](auto& mounted_count) {
  135. VERIFY(mounted_count > 0);
  136. if (mounted_count == 1) {
  137. dbgln("VirtualFileSystem: Unmounting file system {} for the last time...", fs->fsid());
  138. m_file_systems_list.with([&](auto& list) {
  139. list.remove(*fs);
  140. });
  141. if (fs->is_file_backed()) {
  142. dbgln("VirtualFileSystem: Unmounting file backed file system {} for the last time...", fs->fsid());
  143. auto& file_backed_fs = static_cast<FileBackedFileSystem&>(*fs);
  144. m_file_backed_file_systems_list.with([&](auto& list) {
  145. list.remove(file_backed_fs);
  146. });
  147. }
  148. } else {
  149. mounted_count--;
  150. }
  151. });
  152. dbgln("VirtualFileSystem: Unmounting file system {}...", fs->fsid());
  153. (void)mounts.unstable_take(i);
  154. return {};
  155. }
  156. dbgln("VirtualFileSystem: Nothing mounted on inode {}", guest_inode.identifier());
  157. return ENODEV;
  158. });
  159. }
  160. ErrorOr<void> VirtualFileSystem::mount_root(FileSystem& fs)
  161. {
  162. if (m_root_inode) {
  163. dmesgln("VirtualFileSystem: mount_root can't mount another root");
  164. return EEXIST;
  165. }
  166. auto new_mount = TRY(adopt_nonnull_own_or_enomem(new (nothrow) Mount(fs, nullptr, root_mount_flags)));
  167. auto& root_inode = fs.root_inode();
  168. if (!root_inode.is_directory()) {
  169. dmesgln("VirtualFileSystem: root inode ({}) for / is not a directory :(", root_inode.identifier());
  170. return ENOTDIR;
  171. }
  172. m_root_inode = root_inode;
  173. if (fs.is_file_backed()) {
  174. auto pseudo_path = TRY(static_cast<FileBackedFileSystem&>(fs).file_description().pseudo_path());
  175. dmesgln("VirtualFileSystem: mounted root({}) from {} ({})", fs.fsid(), fs.class_name(), pseudo_path);
  176. m_file_backed_file_systems_list.with([&](auto& list) {
  177. list.append(static_cast<FileBackedFileSystem&>(fs));
  178. });
  179. } else {
  180. dmesgln("VirtualFileSystem: mounted root({}) from {}", fs.fsid(), fs.class_name());
  181. }
  182. m_file_systems_list.with([&](auto& fs_list) {
  183. fs_list.append(fs);
  184. });
  185. // Note: Actually add a mount for the filesystem and increment the filesystem mounted count
  186. m_mounts.with([&](auto& mounts) {
  187. new_mount->guest_fs().mounted_count({}).with([&](auto& mounted_count) {
  188. mounted_count++;
  189. });
  190. mounts.append(move(new_mount));
  191. });
  192. RefPtr<Custody> new_root_custody = TRY(Custody::try_create(nullptr, ""sv, *m_root_inode, root_mount_flags));
  193. m_root_custody.with([&](auto& root_custody) {
  194. swap(root_custody, new_root_custody);
  195. });
  196. return {};
  197. }
  198. auto VirtualFileSystem::find_mount_for_host(InodeIdentifier id) -> Mount*
  199. {
  200. return m_mounts.with([&](auto& mounts) -> Mount* {
  201. for (auto& mount : mounts) {
  202. if (mount->host() && mount->host()->identifier() == id)
  203. return mount.ptr();
  204. }
  205. return nullptr;
  206. });
  207. }
  208. auto VirtualFileSystem::find_mount_for_guest(InodeIdentifier id) -> Mount*
  209. {
  210. return m_mounts.with([&](auto& mounts) -> Mount* {
  211. for (auto& mount : mounts) {
  212. if (mount->guest().identifier() == id)
  213. return mount.ptr();
  214. }
  215. return nullptr;
  216. });
  217. }
  218. bool VirtualFileSystem::is_vfs_root(InodeIdentifier inode) const
  219. {
  220. return inode == root_inode_id();
  221. }
  222. ErrorOr<void> VirtualFileSystem::traverse_directory_inode(Inode& dir_inode, Function<ErrorOr<void>(FileSystem::DirectoryEntryView const&)> callback)
  223. {
  224. return dir_inode.traverse_as_directory([&](auto& entry) -> ErrorOr<void> {
  225. InodeIdentifier resolved_inode;
  226. if (auto mount = find_mount_for_host(entry.inode))
  227. resolved_inode = mount->guest().identifier();
  228. else
  229. resolved_inode = entry.inode;
  230. // FIXME: This is now broken considering chroot and bind mounts.
  231. bool is_root_inode = dir_inode.identifier() == dir_inode.fs().root_inode().identifier();
  232. if (is_root_inode && !is_vfs_root(dir_inode.identifier()) && entry.name == "..") {
  233. auto mount = find_mount_for_guest(dir_inode.identifier());
  234. VERIFY(mount);
  235. VERIFY(mount->host());
  236. resolved_inode = mount->host()->identifier();
  237. }
  238. TRY(callback({ entry.name, resolved_inode, entry.file_type }));
  239. return {};
  240. });
  241. }
  242. ErrorOr<void> VirtualFileSystem::utime(Credentials const& credentials, StringView path, Custody& base, time_t atime, time_t mtime)
  243. {
  244. auto custody = TRY(resolve_path(credentials, path, base));
  245. auto& inode = custody->inode();
  246. if (!credentials.is_superuser() && inode.metadata().uid != credentials.euid())
  247. return EACCES;
  248. if (custody->is_readonly())
  249. return EROFS;
  250. TRY(inode.update_timestamps(Time::from_timespec({ atime, 0 }), {}, Time::from_timespec({ mtime, 0 })));
  251. return {};
  252. }
  253. ErrorOr<void> VirtualFileSystem::utimensat(Credentials const& credentials, StringView path, Custody& base, timespec const& atime, timespec const& mtime, int options)
  254. {
  255. auto custody = TRY(resolve_path(credentials, path, base, nullptr, options));
  256. auto& inode = custody->inode();
  257. if (!credentials.is_superuser() && inode.metadata().uid != credentials.euid())
  258. return EACCES;
  259. if (custody->is_readonly())
  260. return EROFS;
  261. // NOTE: A standard ext2 inode cannot store nanosecond timestamps.
  262. TRY(inode.update_timestamps(
  263. (atime.tv_nsec != UTIME_OMIT) ? Time::from_timespec(atime) : Optional<Time> {},
  264. {},
  265. (mtime.tv_nsec != UTIME_OMIT) ? Time::from_timespec(mtime) : Optional<Time> {}));
  266. return {};
  267. }
  268. ErrorOr<InodeMetadata> VirtualFileSystem::lookup_metadata(Credentials const& credentials, StringView path, Custody& base, int options)
  269. {
  270. auto custody = TRY(resolve_path(credentials, path, base, nullptr, options));
  271. return custody->inode().metadata();
  272. }
  273. ErrorOr<NonnullLockRefPtr<FileBackedFileSystem>> VirtualFileSystem::find_already_existing_or_create_file_backed_file_system(OpenFileDescription& description, Function<ErrorOr<NonnullLockRefPtr<FileSystem>>(OpenFileDescription&)> callback)
  274. {
  275. return TRY(m_file_backed_file_systems_list.with([&](auto& list) -> ErrorOr<NonnullLockRefPtr<FileBackedFileSystem>> {
  276. for (auto& node : list) {
  277. if (&node.file_description() == &description) {
  278. return node;
  279. }
  280. if (&node.file() == &description.file()) {
  281. return node;
  282. }
  283. }
  284. auto fs = TRY(callback(description));
  285. VERIFY(fs->is_file_backed());
  286. list.append(static_cast<FileBackedFileSystem&>(*fs));
  287. m_file_systems_list.with([&](auto& fs_list) {
  288. fs_list.append(*fs);
  289. });
  290. return static_ptr_cast<FileBackedFileSystem>(fs);
  291. }));
  292. }
  293. ErrorOr<NonnullLockRefPtr<OpenFileDescription>> VirtualFileSystem::open(Credentials const& credentials, StringView path, int options, mode_t mode, Custody& base, Optional<UidAndGid> owner)
  294. {
  295. if ((options & O_CREAT) && (options & O_DIRECTORY))
  296. return EINVAL;
  297. RefPtr<Custody> parent_custody;
  298. auto custody_or_error = resolve_path(credentials, path, base, &parent_custody, options);
  299. if (custody_or_error.is_error()) {
  300. // NOTE: ENOENT with a non-null parent custody signals us that the immediate parent
  301. // of the file exists, but the file itself does not.
  302. if ((options & O_CREAT) && custody_or_error.error().code() == ENOENT && parent_custody)
  303. return create(credentials, path, options, mode, *parent_custody, move(owner));
  304. return custody_or_error.release_error();
  305. }
  306. if ((options & O_CREAT) && (options & O_EXCL))
  307. return EEXIST;
  308. auto& custody = *custody_or_error.value();
  309. auto& inode = custody.inode();
  310. auto metadata = inode.metadata();
  311. if (metadata.is_regular_file() && (custody.mount_flags() & MS_NOREGULAR))
  312. return EACCES;
  313. if ((options & O_DIRECTORY) && !metadata.is_directory())
  314. return ENOTDIR;
  315. bool should_truncate_file = false;
  316. if ((options & O_RDONLY) && !metadata.may_read(credentials))
  317. return EACCES;
  318. if (options & O_WRONLY) {
  319. if (!metadata.may_write(credentials))
  320. return EACCES;
  321. if (metadata.is_directory())
  322. return EISDIR;
  323. should_truncate_file = options & O_TRUNC;
  324. }
  325. if (options & O_EXEC) {
  326. if (!metadata.may_execute(credentials) || (custody.mount_flags() & MS_NOEXEC))
  327. return EACCES;
  328. }
  329. if (metadata.is_fifo()) {
  330. auto fifo = TRY(inode.fifo());
  331. if (options & O_WRONLY) {
  332. auto description = TRY(fifo->open_direction_blocking(FIFO::Direction::Writer));
  333. description->set_rw_mode(options);
  334. description->set_file_flags(options);
  335. description->set_original_inode({}, inode);
  336. return description;
  337. } else if (options & O_RDONLY) {
  338. auto description = TRY(fifo->open_direction_blocking(FIFO::Direction::Reader));
  339. description->set_rw_mode(options);
  340. description->set_file_flags(options);
  341. description->set_original_inode({}, inode);
  342. return description;
  343. }
  344. return EINVAL;
  345. }
  346. if (metadata.is_device()) {
  347. if (custody.mount_flags() & MS_NODEV)
  348. return EACCES;
  349. auto device = DeviceManagement::the().get_device(metadata.major_device, metadata.minor_device);
  350. if (device == nullptr) {
  351. return ENODEV;
  352. }
  353. auto description = TRY(device->open(options));
  354. description->set_original_inode({}, inode);
  355. description->set_original_custody({}, custody);
  356. return description;
  357. }
  358. // Check for read-only FS. Do this after handling devices, but before modifying the inode in any way.
  359. if ((options & O_WRONLY) && custody.is_readonly())
  360. return EROFS;
  361. if (should_truncate_file) {
  362. TRY(inode.truncate(0));
  363. TRY(inode.update_timestamps({}, {}, kgettimeofday()));
  364. }
  365. auto description = TRY(OpenFileDescription::try_create(custody));
  366. description->set_rw_mode(options);
  367. description->set_file_flags(options);
  368. return description;
  369. }
  370. ErrorOr<void> VirtualFileSystem::mknod(Credentials const& credentials, StringView path, mode_t mode, dev_t dev, Custody& base)
  371. {
  372. if (!is_regular_file(mode) && !is_block_device(mode) && !is_character_device(mode) && !is_fifo(mode) && !is_socket(mode))
  373. return EINVAL;
  374. RefPtr<Custody> parent_custody;
  375. auto existing_file_or_error = resolve_path(credentials, path, base, &parent_custody);
  376. if (!existing_file_or_error.is_error())
  377. return EEXIST;
  378. if (!parent_custody)
  379. return ENOENT;
  380. if (existing_file_or_error.error().code() != ENOENT)
  381. return existing_file_or_error.release_error();
  382. auto& parent_inode = parent_custody->inode();
  383. if (!parent_inode.metadata().may_write(credentials))
  384. return EACCES;
  385. if (parent_custody->is_readonly())
  386. return EROFS;
  387. auto basename = KLexicalPath::basename(path);
  388. dbgln_if(VFS_DEBUG, "VirtualFileSystem::mknod: '{}' mode={} dev={} in {}", basename, mode, dev, parent_inode.identifier());
  389. (void)TRY(parent_inode.create_child(basename, mode, dev, credentials.euid(), credentials.egid()));
  390. return {};
  391. }
  392. ErrorOr<NonnullLockRefPtr<OpenFileDescription>> VirtualFileSystem::create(Credentials const& credentials, StringView path, int options, mode_t mode, Custody& parent_custody, Optional<UidAndGid> owner)
  393. {
  394. auto basename = KLexicalPath::basename(path);
  395. auto parent_path = TRY(parent_custody.try_serialize_absolute_path());
  396. auto full_path = TRY(KLexicalPath::try_join(parent_path->view(), basename));
  397. TRY(validate_path_against_process_veil(full_path->view(), options));
  398. if (!is_socket(mode) && !is_fifo(mode) && !is_block_device(mode) && !is_character_device(mode)) {
  399. // Turn it into a regular file. (This feels rather hackish.)
  400. mode |= 0100000;
  401. }
  402. auto& parent_inode = parent_custody.inode();
  403. if (!parent_inode.metadata().may_write(credentials))
  404. return EACCES;
  405. if (parent_custody.is_readonly())
  406. return EROFS;
  407. if (is_regular_file(mode) && (parent_custody.mount_flags() & MS_NOREGULAR))
  408. return EACCES;
  409. dbgln_if(VFS_DEBUG, "VirtualFileSystem::create: '{}' in {}", basename, parent_inode.identifier());
  410. auto uid = owner.has_value() ? owner.value().uid : credentials.euid();
  411. auto gid = owner.has_value() ? owner.value().gid : credentials.egid();
  412. auto inode = TRY(parent_inode.create_child(basename, mode, 0, uid, gid));
  413. auto custody = TRY(Custody::try_create(&parent_custody, basename, inode, parent_custody.mount_flags()));
  414. auto description = TRY(OpenFileDescription::try_create(move(custody)));
  415. description->set_rw_mode(options);
  416. description->set_file_flags(options);
  417. return description;
  418. }
  419. ErrorOr<void> VirtualFileSystem::mkdir(Credentials const& credentials, StringView path, mode_t mode, Custody& base)
  420. {
  421. // Unlike in basically every other case, where it's only the last
  422. // path component (the one being created) that is allowed not to
  423. // exist, POSIX allows mkdir'ed path to have trailing slashes.
  424. // Let's handle that case by trimming any trailing slashes.
  425. path = path.trim("/"sv, TrimMode::Right);
  426. if (path.is_empty()) {
  427. // NOTE: This means the path was a series of slashes, which resolves to "/".
  428. path = "/"sv;
  429. }
  430. RefPtr<Custody> parent_custody;
  431. // FIXME: The errors returned by resolve_path_without_veil can leak information about paths that are not unveiled,
  432. // e.g. when the error is EACCESS or similar.
  433. auto result = resolve_path_without_veil(credentials, path, base, &parent_custody);
  434. if (!result.is_error())
  435. return EEXIST;
  436. else if (!parent_custody)
  437. return result.release_error();
  438. // NOTE: If resolve_path fails with a non-null parent custody, the error should be ENOENT.
  439. VERIFY(result.error().code() == ENOENT);
  440. TRY(validate_path_against_process_veil(*parent_custody, O_CREAT));
  441. auto& parent_inode = parent_custody->inode();
  442. if (!parent_inode.metadata().may_write(credentials))
  443. return EACCES;
  444. if (parent_custody->is_readonly())
  445. return EROFS;
  446. auto basename = KLexicalPath::basename(path);
  447. dbgln_if(VFS_DEBUG, "VirtualFileSystem::mkdir: '{}' in {}", basename, parent_inode.identifier());
  448. (void)TRY(parent_inode.create_child(basename, S_IFDIR | mode, 0, credentials.euid(), credentials.egid()));
  449. return {};
  450. }
  451. ErrorOr<void> VirtualFileSystem::access(Credentials const& credentials, StringView path, int mode, Custody& base)
  452. {
  453. auto custody = TRY(resolve_path(credentials, path, base));
  454. auto& inode = custody->inode();
  455. auto metadata = inode.metadata();
  456. if (mode & R_OK) {
  457. if (!metadata.may_read(credentials))
  458. return EACCES;
  459. }
  460. if (mode & W_OK) {
  461. if (!metadata.may_write(credentials))
  462. return EACCES;
  463. if (custody->is_readonly())
  464. return EROFS;
  465. }
  466. if (mode & X_OK) {
  467. if (!metadata.may_execute(credentials))
  468. return EACCES;
  469. }
  470. return {};
  471. }
  472. ErrorOr<NonnullRefPtr<Custody>> VirtualFileSystem::open_directory(Credentials const& credentials, StringView path, Custody& base)
  473. {
  474. auto custody = TRY(resolve_path(credentials, path, base));
  475. auto& inode = custody->inode();
  476. if (!inode.is_directory())
  477. return ENOTDIR;
  478. if (!inode.metadata().may_execute(credentials))
  479. return EACCES;
  480. return custody;
  481. }
  482. ErrorOr<void> VirtualFileSystem::chmod(Credentials const& credentials, Custody& custody, mode_t mode)
  483. {
  484. auto& inode = custody.inode();
  485. if (credentials.euid() != inode.metadata().uid && !credentials.is_superuser())
  486. return EPERM;
  487. if (custody.is_readonly())
  488. return EROFS;
  489. // Only change the permission bits.
  490. mode = (inode.mode() & ~07777u) | (mode & 07777u);
  491. return inode.chmod(mode);
  492. }
  493. ErrorOr<void> VirtualFileSystem::chmod(Credentials const& credentials, StringView path, mode_t mode, Custody& base, int options)
  494. {
  495. auto custody = TRY(resolve_path(credentials, path, base, nullptr, options));
  496. return chmod(credentials, custody, mode);
  497. }
  498. ErrorOr<void> VirtualFileSystem::rename(Credentials const& credentials, StringView old_path, StringView new_path, Custody& base)
  499. {
  500. RefPtr<Custody> old_parent_custody;
  501. auto old_custody = TRY(resolve_path(credentials, old_path, base, &old_parent_custody, O_NOFOLLOW_NOERROR));
  502. auto& old_inode = old_custody->inode();
  503. RefPtr<Custody> new_parent_custody;
  504. auto new_custody_or_error = resolve_path(credentials, new_path, base, &new_parent_custody);
  505. if (new_custody_or_error.is_error()) {
  506. if (new_custody_or_error.error().code() != ENOENT || !new_parent_custody)
  507. return new_custody_or_error.release_error();
  508. }
  509. if (!old_parent_custody || !new_parent_custody) {
  510. return EPERM;
  511. }
  512. if (!new_custody_or_error.is_error()) {
  513. auto& new_inode = new_custody_or_error.value()->inode();
  514. if (old_inode.index() != new_inode.index() && old_inode.is_directory() && new_inode.is_directory()) {
  515. size_t child_count = 0;
  516. TRY(new_inode.traverse_as_directory([&child_count](auto&) -> ErrorOr<void> {
  517. ++child_count;
  518. return {};
  519. }));
  520. if (child_count > 2)
  521. return ENOTEMPTY;
  522. }
  523. }
  524. auto& old_parent_inode = old_parent_custody->inode();
  525. auto& new_parent_inode = new_parent_custody->inode();
  526. if (&old_parent_inode.fs() != &new_parent_inode.fs())
  527. return EXDEV;
  528. for (auto* new_ancestor = new_parent_custody.ptr(); new_ancestor; new_ancestor = new_ancestor->parent()) {
  529. if (&old_inode == &new_ancestor->inode())
  530. return EDIRINTOSELF;
  531. }
  532. if (!new_parent_inode.metadata().may_write(credentials))
  533. return EACCES;
  534. if (!old_parent_inode.metadata().may_write(credentials))
  535. return EACCES;
  536. if (old_parent_inode.metadata().is_sticky()) {
  537. if (!credentials.is_superuser() && old_inode.metadata().uid != credentials.euid())
  538. return EACCES;
  539. }
  540. if (old_parent_custody->is_readonly() || new_parent_custody->is_readonly())
  541. return EROFS;
  542. auto old_basename = KLexicalPath::basename(old_path);
  543. if (old_basename.is_empty() || old_basename == "."sv || old_basename == ".."sv)
  544. return EINVAL;
  545. auto new_basename = KLexicalPath::basename(new_path);
  546. if (new_basename.is_empty() || new_basename == "."sv || new_basename == ".."sv)
  547. return EINVAL;
  548. if (old_basename == new_basename && old_parent_inode.index() == new_parent_inode.index())
  549. return {};
  550. if (!new_custody_or_error.is_error()) {
  551. auto& new_custody = *new_custody_or_error.value();
  552. auto& new_inode = new_custody.inode();
  553. // FIXME: Is this really correct? Check what other systems do.
  554. if (&new_inode == &old_inode)
  555. return {};
  556. if (new_parent_inode.metadata().is_sticky()) {
  557. if (!credentials.is_superuser() && new_inode.metadata().uid != credentials.euid())
  558. return EACCES;
  559. }
  560. if (new_inode.is_directory() && !old_inode.is_directory())
  561. return EISDIR;
  562. TRY(new_parent_inode.remove_child(new_basename));
  563. }
  564. TRY(new_parent_inode.add_child(old_inode, new_basename, old_inode.mode()));
  565. TRY(old_parent_inode.remove_child(old_basename));
  566. // If the inode that we moved is a directory and we changed parent
  567. // directories, then we also have to make .. point to the new parent inode,
  568. // because .. is its own inode.
  569. if (old_inode.is_directory() && old_parent_inode.index() != new_parent_inode.index()) {
  570. TRY(old_inode.replace_child(".."sv, new_parent_inode));
  571. }
  572. return {};
  573. }
  574. ErrorOr<void> VirtualFileSystem::chown(Credentials const& credentials, Custody& custody, UserID a_uid, GroupID a_gid)
  575. {
  576. auto& inode = custody.inode();
  577. auto metadata = inode.metadata();
  578. if (credentials.euid() != metadata.uid && !credentials.is_superuser())
  579. return EPERM;
  580. UserID new_uid = metadata.uid;
  581. GroupID new_gid = metadata.gid;
  582. if (a_uid != (uid_t)-1) {
  583. if (credentials.euid() != a_uid && !credentials.is_superuser())
  584. return EPERM;
  585. new_uid = a_uid;
  586. }
  587. if (a_gid != (gid_t)-1) {
  588. if (!credentials.in_group(a_gid) && !credentials.is_superuser())
  589. return EPERM;
  590. new_gid = a_gid;
  591. }
  592. if (custody.is_readonly())
  593. return EROFS;
  594. dbgln_if(VFS_DEBUG, "VirtualFileSystem::chown(): inode {} <- uid={} gid={}", inode.identifier(), new_uid, new_gid);
  595. if (metadata.is_setuid() || metadata.is_setgid()) {
  596. dbgln_if(VFS_DEBUG, "VirtualFileSystem::chown(): Stripping SUID/SGID bits from {}", inode.identifier());
  597. TRY(inode.chmod(metadata.mode & ~(04000 | 02000)));
  598. }
  599. return inode.chown(new_uid, new_gid);
  600. }
  601. ErrorOr<void> VirtualFileSystem::chown(Credentials const& credentials, StringView path, UserID a_uid, GroupID a_gid, Custody& base, int options)
  602. {
  603. auto custody = TRY(resolve_path(credentials, path, base, nullptr, options));
  604. return chown(credentials, custody, a_uid, a_gid);
  605. }
  606. static bool hard_link_allowed(Credentials const& credentials, Inode const& inode)
  607. {
  608. auto metadata = inode.metadata();
  609. if (credentials.euid() == metadata.uid)
  610. return true;
  611. if (metadata.is_regular_file()
  612. && !metadata.is_setuid()
  613. && !(metadata.is_setgid() && metadata.mode & S_IXGRP)
  614. && metadata.may_write(credentials)) {
  615. return true;
  616. }
  617. return false;
  618. }
  619. ErrorOr<void> VirtualFileSystem::link(Credentials const& credentials, StringView old_path, StringView new_path, Custody& base)
  620. {
  621. auto old_custody = TRY(resolve_path(credentials, old_path, base));
  622. auto& old_inode = old_custody->inode();
  623. RefPtr<Custody> parent_custody;
  624. auto new_custody_or_error = resolve_path(credentials, new_path, base, &parent_custody);
  625. if (!new_custody_or_error.is_error())
  626. return EEXIST;
  627. if (!parent_custody)
  628. return ENOENT;
  629. auto& parent_inode = parent_custody->inode();
  630. if (parent_inode.fsid() != old_inode.fsid())
  631. return EXDEV;
  632. if (!parent_inode.metadata().may_write(credentials))
  633. return EACCES;
  634. if (old_inode.is_directory())
  635. return EPERM;
  636. if (parent_custody->is_readonly())
  637. return EROFS;
  638. if (!hard_link_allowed(credentials, old_inode))
  639. return EPERM;
  640. return parent_inode.add_child(old_inode, KLexicalPath::basename(new_path), old_inode.mode());
  641. }
  642. ErrorOr<void> VirtualFileSystem::unlink(Credentials const& credentials, StringView path, Custody& base)
  643. {
  644. RefPtr<Custody> parent_custody;
  645. auto custody = TRY(resolve_path(credentials, path, base, &parent_custody, O_NOFOLLOW_NOERROR | O_UNLINK_INTERNAL));
  646. auto& inode = custody->inode();
  647. if (inode.is_directory())
  648. return EISDIR;
  649. // We have just checked that the inode is not a directory, and thus it's not
  650. // the root. So it should have a parent. Note that this would be invalidated
  651. // if we were to support bind-mounting regular files on top of the root.
  652. VERIFY(parent_custody);
  653. auto& parent_inode = parent_custody->inode();
  654. if (!parent_inode.metadata().may_write(credentials))
  655. return EACCES;
  656. if (parent_inode.metadata().is_sticky()) {
  657. if (!credentials.is_superuser() && inode.metadata().uid != credentials.euid())
  658. return EACCES;
  659. }
  660. if (parent_custody->is_readonly())
  661. return EROFS;
  662. return parent_inode.remove_child(KLexicalPath::basename(path));
  663. }
  664. ErrorOr<void> VirtualFileSystem::symlink(Credentials const& credentials, StringView target, StringView linkpath, Custody& base)
  665. {
  666. RefPtr<Custody> parent_custody;
  667. auto existing_custody_or_error = resolve_path(credentials, linkpath, base, &parent_custody);
  668. if (!existing_custody_or_error.is_error())
  669. return EEXIST;
  670. if (!parent_custody)
  671. return ENOENT;
  672. if (existing_custody_or_error.is_error() && existing_custody_or_error.error().code() != ENOENT)
  673. return existing_custody_or_error.release_error();
  674. auto& parent_inode = parent_custody->inode();
  675. if (!parent_inode.metadata().may_write(credentials))
  676. return EACCES;
  677. if (parent_custody->is_readonly())
  678. return EROFS;
  679. auto basename = KLexicalPath::basename(linkpath);
  680. dbgln_if(VFS_DEBUG, "VirtualFileSystem::symlink: '{}' (-> '{}') in {}", basename, target, parent_inode.identifier());
  681. auto inode = TRY(parent_inode.create_child(basename, S_IFLNK | 0644, 0, credentials.euid(), credentials.egid()));
  682. auto target_buffer = UserOrKernelBuffer::for_kernel_buffer(const_cast<u8*>((u8 const*)target.characters_without_null_termination()));
  683. TRY(inode->write_bytes(0, target.length(), target_buffer, nullptr));
  684. return {};
  685. }
  686. ErrorOr<void> VirtualFileSystem::rmdir(Credentials const& credentials, StringView path, Custody& base)
  687. {
  688. RefPtr<Custody> parent_custody;
  689. auto custody = TRY(resolve_path(credentials, path, base, &parent_custody));
  690. auto& inode = custody->inode();
  691. // FIXME: We should return EINVAL if the last component of the path is "."
  692. // FIXME: We should return ENOTEMPTY if the last component of the path is ".."
  693. if (!inode.is_directory())
  694. return ENOTDIR;
  695. if (!parent_custody)
  696. return EBUSY;
  697. auto& parent_inode = parent_custody->inode();
  698. auto parent_metadata = parent_inode.metadata();
  699. if (!parent_metadata.may_write(credentials))
  700. return EACCES;
  701. if (parent_metadata.is_sticky()) {
  702. if (!credentials.is_superuser() && inode.metadata().uid != credentials.euid())
  703. return EACCES;
  704. }
  705. size_t child_count = 0;
  706. TRY(inode.traverse_as_directory([&child_count](auto&) -> ErrorOr<void> {
  707. ++child_count;
  708. return {};
  709. }));
  710. if (child_count != 2)
  711. return ENOTEMPTY;
  712. if (custody->is_readonly())
  713. return EROFS;
  714. TRY(inode.remove_child("."sv));
  715. TRY(inode.remove_child(".."sv));
  716. return parent_inode.remove_child(KLexicalPath::basename(path));
  717. }
  718. ErrorOr<void> VirtualFileSystem::for_each_mount(Function<ErrorOr<void>(Mount const&)> callback) const
  719. {
  720. return m_mounts.with([&](auto& mounts) -> ErrorOr<void> {
  721. for (auto& mount : mounts)
  722. TRY(callback(*mount));
  723. return {};
  724. });
  725. }
  726. void VirtualFileSystem::sync()
  727. {
  728. FileSystem::sync();
  729. }
  730. NonnullRefPtr<Custody> VirtualFileSystem::root_custody()
  731. {
  732. return m_root_custody.with([](auto& root_custody) -> NonnullRefPtr<Custody> { return *root_custody; });
  733. }
  734. UnveilNode const& VirtualFileSystem::find_matching_unveiled_path(StringView path)
  735. {
  736. auto& current_process = Process::current();
  737. VERIFY(current_process.veil_state() != VeilState::None);
  738. return current_process.unveil_data().with([&](auto const& unveil_data) -> UnveilNode const& {
  739. auto path_parts = KLexicalPath::parts(path);
  740. return unveil_data.paths.traverse_until_last_accessible_node(path_parts.begin(), path_parts.end());
  741. });
  742. }
  743. ErrorOr<void> VirtualFileSystem::validate_path_against_process_veil(Custody const& custody, int options)
  744. {
  745. if (Process::current().veil_state() == VeilState::None)
  746. return {};
  747. auto absolute_path = TRY(custody.try_serialize_absolute_path());
  748. return validate_path_against_process_veil(absolute_path->view(), options);
  749. }
  750. ErrorOr<void> VirtualFileSystem::validate_path_against_process_veil(StringView path, int options)
  751. {
  752. if (Process::current().veil_state() == VeilState::None)
  753. return {};
  754. VERIFY(path.starts_with('/'));
  755. VERIFY(!path.contains("/../"sv) && !path.ends_with("/.."sv));
  756. VERIFY(!path.contains("/./"sv) && !path.ends_with("/."sv));
  757. #ifdef SKIP_PATH_VALIDATION_FOR_COVERAGE_INSTRUMENTATION
  758. // Skip veil validation against profile data when coverage is enabled for userspace
  759. // so that all processes can write out coverage data even with veils in place
  760. if (KLexicalPath::basename(path).ends_with(".profraw"sv))
  761. return {};
  762. #endif
  763. auto& unveiled_path = find_matching_unveiled_path(path);
  764. if (unveiled_path.permissions() == UnveilAccess::None) {
  765. dbgln("Rejecting path '{}' since it hasn't been unveiled.", path);
  766. dump_backtrace();
  767. return ENOENT;
  768. }
  769. if (options & O_CREAT) {
  770. if (!(unveiled_path.permissions() & UnveilAccess::CreateOrRemove)) {
  771. dbgln("Rejecting path '{}' since it hasn't been unveiled with 'c' permission.", path);
  772. dump_backtrace();
  773. return EACCES;
  774. }
  775. }
  776. if (options & O_UNLINK_INTERNAL) {
  777. if (!(unveiled_path.permissions() & UnveilAccess::CreateOrRemove)) {
  778. dbgln("Rejecting path '{}' for unlink since it hasn't been unveiled with 'c' permission.", path);
  779. dump_backtrace();
  780. return EACCES;
  781. }
  782. return {};
  783. }
  784. if (options & O_RDONLY) {
  785. if (options & O_DIRECTORY) {
  786. if (!(unveiled_path.permissions() & (UnveilAccess::Read | UnveilAccess::Browse))) {
  787. dbgln("Rejecting path '{}' since it hasn't been unveiled with 'r' or 'b' permissions.", path);
  788. dump_backtrace();
  789. return EACCES;
  790. }
  791. } else {
  792. if (!(unveiled_path.permissions() & UnveilAccess::Read)) {
  793. dbgln("Rejecting path '{}' since it hasn't been unveiled with 'r' permission.", path);
  794. dump_backtrace();
  795. return EACCES;
  796. }
  797. }
  798. }
  799. if (options & O_WRONLY) {
  800. if (!(unveiled_path.permissions() & UnveilAccess::Write)) {
  801. dbgln("Rejecting path '{}' since it hasn't been unveiled with 'w' permission.", path);
  802. dump_backtrace();
  803. return EACCES;
  804. }
  805. }
  806. if (options & O_EXEC) {
  807. if (!(unveiled_path.permissions() & UnveilAccess::Execute)) {
  808. dbgln("Rejecting path '{}' since it hasn't been unveiled with 'x' permission.", path);
  809. dump_backtrace();
  810. return EACCES;
  811. }
  812. }
  813. return {};
  814. }
  815. ErrorOr<NonnullRefPtr<Custody>> VirtualFileSystem::resolve_path(Credentials const& credentials, StringView path, NonnullRefPtr<Custody> base, RefPtr<Custody>* out_parent, int options, int symlink_recursion_level)
  816. {
  817. // FIXME: The errors returned by resolve_path_without_veil can leak information about paths that are not unveiled,
  818. // e.g. when the error is EACCESS or similar.
  819. auto custody = TRY(resolve_path_without_veil(credentials, path, base, out_parent, options, symlink_recursion_level));
  820. if (auto result = validate_path_against_process_veil(*custody, options); result.is_error()) {
  821. if (out_parent)
  822. out_parent->clear();
  823. return result.release_error();
  824. }
  825. return custody;
  826. }
  827. static bool safe_to_follow_symlink(Credentials const& credentials, Inode const& inode, InodeMetadata const& parent_metadata)
  828. {
  829. auto metadata = inode.metadata();
  830. if (credentials.euid() == metadata.uid)
  831. return true;
  832. if (!(parent_metadata.is_sticky() && parent_metadata.mode & S_IWOTH))
  833. return true;
  834. if (metadata.uid == parent_metadata.uid)
  835. return true;
  836. return false;
  837. }
  838. ErrorOr<NonnullRefPtr<Custody>> VirtualFileSystem::resolve_path_without_veil(Credentials const& credentials, StringView path, NonnullRefPtr<Custody> base, RefPtr<Custody>* out_parent, int options, int symlink_recursion_level)
  839. {
  840. if (symlink_recursion_level >= symlink_recursion_limit)
  841. return ELOOP;
  842. if (path.is_empty())
  843. return EINVAL;
  844. GenericLexer path_lexer(path);
  845. NonnullRefPtr<Custody> custody = path[0] == '/' ? root_custody() : base;
  846. bool extra_iteration = path[path.length() - 1] == '/';
  847. while (!path_lexer.is_eof() || extra_iteration) {
  848. if (path_lexer.is_eof())
  849. extra_iteration = false;
  850. auto part = path_lexer.consume_until('/');
  851. path_lexer.ignore();
  852. Custody& parent = custody;
  853. auto parent_metadata = parent.inode().metadata();
  854. if (!parent_metadata.is_directory())
  855. return ENOTDIR;
  856. // Ensure the current user is allowed to resolve paths inside this directory.
  857. if (!parent_metadata.may_execute(credentials))
  858. return EACCES;
  859. bool have_more_parts = !path_lexer.is_eof() || extra_iteration;
  860. if (part == "..") {
  861. // If we encounter a "..", take a step back, but don't go beyond the root.
  862. if (custody->parent())
  863. custody = *custody->parent();
  864. continue;
  865. } else if (part == "." || part.is_empty()) {
  866. continue;
  867. }
  868. // Okay, let's look up this part.
  869. auto child_or_error = parent.inode().lookup(part);
  870. if (child_or_error.is_error()) {
  871. if (out_parent) {
  872. // ENOENT with a non-null parent custody signals to caller that
  873. // we found the immediate parent of the file, but the file itself
  874. // does not exist yet.
  875. *out_parent = have_more_parts ? nullptr : &parent;
  876. }
  877. return child_or_error.release_error();
  878. }
  879. auto child_inode = child_or_error.release_value();
  880. int mount_flags_for_child = parent.mount_flags();
  881. // See if there's something mounted on the child; in that case
  882. // we would need to return the guest inode, not the host inode.
  883. if (auto mount = find_mount_for_host(child_inode->identifier())) {
  884. child_inode = mount->guest();
  885. mount_flags_for_child = mount->flags();
  886. }
  887. custody = TRY(Custody::try_create(&parent, part, *child_inode, mount_flags_for_child));
  888. if (child_inode->metadata().is_symlink()) {
  889. if (!have_more_parts) {
  890. if (options & O_NOFOLLOW)
  891. return ELOOP;
  892. if (options & O_NOFOLLOW_NOERROR)
  893. break;
  894. }
  895. if (!safe_to_follow_symlink(credentials, *child_inode, parent_metadata))
  896. return EACCES;
  897. TRY(validate_path_against_process_veil(*custody, options));
  898. auto symlink_target = TRY(child_inode->resolve_as_link(credentials, parent, out_parent, options, symlink_recursion_level + 1));
  899. if (!have_more_parts)
  900. return symlink_target;
  901. // Now, resolve the remaining path relative to the symlink target.
  902. // We prepend a "." to it to ensure that it's not empty and that
  903. // any initial slashes it might have get interpreted properly.
  904. StringBuilder remaining_path;
  905. TRY(remaining_path.try_append('.'));
  906. TRY(remaining_path.try_append(path.substring_view_starting_after_substring(part)));
  907. return resolve_path_without_veil(credentials, remaining_path.string_view(), symlink_target, out_parent, options, symlink_recursion_level + 1);
  908. }
  909. }
  910. if (out_parent)
  911. *out_parent = custody->parent();
  912. return custody;
  913. }
  914. }