VirtualFileSystem.cpp 44 KB

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