VirtualFileSystem.cpp 43 KB

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