VirtualFileSystem.cpp 43 KB

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