VirtualFileSystem.cpp 46 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175
  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 = 0;
  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. Vector<NonnullLockRefPtr<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. Vector<NonnullLockRefPtr<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<NonnullRefPtr<OpenFileDescription>> VirtualFileSystem::open(Credentials const& credentials, StringView path, int options, mode_t mode, Custody& base, Optional<UidAndGid> owner)
  316. {
  317. return open(Process::current(), credentials, path, options, mode, base, owner);
  318. }
  319. ErrorOr<NonnullRefPtr<OpenFileDescription>> VirtualFileSystem::open(Process const& process, Credentials const& credentials, StringView path, int options, mode_t mode, Custody& base, Optional<UidAndGid> owner)
  320. {
  321. if ((options & O_CREAT) && (options & O_DIRECTORY))
  322. return EINVAL;
  323. RefPtr<Custody> parent_custody;
  324. auto custody_or_error = resolve_path(process, credentials, path, base, &parent_custody, options);
  325. if (custody_or_error.is_error()) {
  326. // NOTE: ENOENT with a non-null parent custody signals us that the immediate parent
  327. // of the file exists, but the file itself does not.
  328. if ((options & O_CREAT) && custody_or_error.error().code() == ENOENT && parent_custody)
  329. return create(process, credentials, path, options, mode, *parent_custody, move(owner));
  330. return custody_or_error.release_error();
  331. }
  332. if ((options & O_CREAT) && (options & O_EXCL))
  333. return EEXIST;
  334. auto& custody = *custody_or_error.value();
  335. auto& inode = custody.inode();
  336. auto metadata = inode.metadata();
  337. if (metadata.is_regular_file() && (custody.mount_flags() & MS_NOREGULAR))
  338. return EACCES;
  339. if ((options & O_DIRECTORY) && !metadata.is_directory())
  340. return ENOTDIR;
  341. bool should_truncate_file = false;
  342. if ((options & O_RDONLY) && !metadata.may_read(credentials))
  343. return EACCES;
  344. if (options & O_WRONLY) {
  345. if (!metadata.may_write(credentials))
  346. return EACCES;
  347. if (metadata.is_directory())
  348. return EISDIR;
  349. should_truncate_file = options & O_TRUNC;
  350. }
  351. if (options & O_EXEC) {
  352. if (!metadata.may_execute(credentials) || (custody.mount_flags() & MS_NOEXEC))
  353. return EACCES;
  354. }
  355. if (metadata.is_fifo()) {
  356. auto fifo = TRY(inode.fifo());
  357. if (options & O_WRONLY) {
  358. auto description = TRY(fifo->open_direction_blocking(FIFO::Direction::Writer));
  359. description->set_rw_mode(options);
  360. description->set_file_flags(options);
  361. description->set_original_inode({}, inode);
  362. return description;
  363. } else if (options & O_RDONLY) {
  364. auto description = TRY(fifo->open_direction_blocking(FIFO::Direction::Reader));
  365. description->set_rw_mode(options);
  366. description->set_file_flags(options);
  367. description->set_original_inode({}, inode);
  368. return description;
  369. }
  370. return EINVAL;
  371. }
  372. if (metadata.is_device()) {
  373. if (custody.mount_flags() & MS_NODEV)
  374. return EACCES;
  375. auto device = DeviceManagement::the().get_device(metadata.major_device, metadata.minor_device);
  376. if (device == nullptr) {
  377. return ENODEV;
  378. }
  379. auto description = TRY(device->open(options));
  380. description->set_original_inode({}, inode);
  381. description->set_original_custody({}, custody);
  382. return description;
  383. }
  384. // Check for read-only FS. Do this after handling devices, but before modifying the inode in any way.
  385. if ((options & O_WRONLY) && custody.is_readonly())
  386. return EROFS;
  387. if (should_truncate_file) {
  388. TRY(inode.truncate(0));
  389. TRY(inode.update_timestamps({}, {}, kgettimeofday()));
  390. }
  391. auto description = TRY(OpenFileDescription::try_create(custody));
  392. description->set_rw_mode(options);
  393. description->set_file_flags(options);
  394. return description;
  395. }
  396. ErrorOr<void> VirtualFileSystem::mknod(Credentials const& credentials, StringView path, mode_t mode, dev_t dev, Custody& base)
  397. {
  398. if (!is_regular_file(mode) && !is_block_device(mode) && !is_character_device(mode) && !is_fifo(mode) && !is_socket(mode))
  399. return EINVAL;
  400. RefPtr<Custody> parent_custody;
  401. auto existing_file_or_error = resolve_path(credentials, path, base, &parent_custody);
  402. if (!existing_file_or_error.is_error())
  403. return EEXIST;
  404. if (!parent_custody)
  405. return ENOENT;
  406. if (existing_file_or_error.error().code() != ENOENT)
  407. return existing_file_or_error.release_error();
  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. auto basename = KLexicalPath::basename(path);
  414. dbgln_if(VFS_DEBUG, "VirtualFileSystem::mknod: '{}' mode={} dev={} in {}", basename, mode, dev, parent_inode.identifier());
  415. (void)TRY(parent_inode.create_child(basename, mode, dev, credentials.euid(), credentials.egid()));
  416. return {};
  417. }
  418. ErrorOr<NonnullRefPtr<OpenFileDescription>> VirtualFileSystem::create(Credentials const& credentials, StringView path, int options, mode_t mode, Custody& parent_custody, Optional<UidAndGid> owner)
  419. {
  420. return create(Process::current(), credentials, path, options, mode, parent_custody, owner);
  421. }
  422. ErrorOr<NonnullRefPtr<OpenFileDescription>> VirtualFileSystem::create(Process const& process, Credentials const& credentials, StringView path, int options, mode_t mode, Custody& parent_custody, Optional<UidAndGid> owner)
  423. {
  424. auto basename = KLexicalPath::basename(path);
  425. auto parent_path = TRY(parent_custody.try_serialize_absolute_path());
  426. auto full_path = TRY(KLexicalPath::try_join(parent_path->view(), basename));
  427. TRY(validate_path_against_process_veil(process, full_path->view(), options));
  428. if (!is_socket(mode) && !is_fifo(mode) && !is_block_device(mode) && !is_character_device(mode)) {
  429. // Turn it into a regular file. (This feels rather hackish.)
  430. mode |= 0100000;
  431. }
  432. auto& parent_inode = parent_custody.inode();
  433. if (!parent_inode.metadata().may_write(credentials))
  434. return EACCES;
  435. if (parent_custody.is_readonly())
  436. return EROFS;
  437. if (is_regular_file(mode) && (parent_custody.mount_flags() & MS_NOREGULAR))
  438. return EACCES;
  439. dbgln_if(VFS_DEBUG, "VirtualFileSystem::create: '{}' in {}", basename, parent_inode.identifier());
  440. auto uid = owner.has_value() ? owner.value().uid : credentials.euid();
  441. auto gid = owner.has_value() ? owner.value().gid : credentials.egid();
  442. auto inode = TRY(parent_inode.create_child(basename, mode, 0, uid, gid));
  443. auto custody = TRY(Custody::try_create(&parent_custody, basename, inode, parent_custody.mount_flags()));
  444. auto description = TRY(OpenFileDescription::try_create(move(custody)));
  445. description->set_rw_mode(options);
  446. description->set_file_flags(options);
  447. return description;
  448. }
  449. ErrorOr<void> VirtualFileSystem::mkdir(Credentials const& credentials, StringView path, mode_t mode, Custody& base)
  450. {
  451. // Unlike in basically every other case, where it's only the last
  452. // path component (the one being created) that is allowed not to
  453. // exist, POSIX allows mkdir'ed path to have trailing slashes.
  454. // Let's handle that case by trimming any trailing slashes.
  455. path = path.trim("/"sv, TrimMode::Right);
  456. if (path.is_empty()) {
  457. // NOTE: This means the path was a series of slashes, which resolves to "/".
  458. path = "/"sv;
  459. }
  460. RefPtr<Custody> parent_custody;
  461. // FIXME: The errors returned by resolve_path_without_veil can leak information about paths that are not unveiled,
  462. // e.g. when the error is EACCESS or similar.
  463. auto result = resolve_path_without_veil(credentials, path, base, &parent_custody);
  464. if (!result.is_error())
  465. return EEXIST;
  466. else if (!parent_custody)
  467. return result.release_error();
  468. // NOTE: If resolve_path fails with a non-null parent custody, the error should be ENOENT.
  469. VERIFY(result.error().code() == ENOENT);
  470. TRY(validate_path_against_process_veil(*parent_custody, O_CREAT));
  471. auto& parent_inode = parent_custody->inode();
  472. if (!parent_inode.metadata().may_write(credentials))
  473. return EACCES;
  474. if (parent_custody->is_readonly())
  475. return EROFS;
  476. auto basename = KLexicalPath::basename(path);
  477. dbgln_if(VFS_DEBUG, "VirtualFileSystem::mkdir: '{}' in {}", basename, parent_inode.identifier());
  478. (void)TRY(parent_inode.create_child(basename, S_IFDIR | mode, 0, credentials.euid(), credentials.egid()));
  479. return {};
  480. }
  481. ErrorOr<void> VirtualFileSystem::access(Credentials const& credentials, StringView path, int mode, Custody& base, AccessFlags access_flags)
  482. {
  483. auto should_follow_symlinks = !has_flag(access_flags, AccessFlags::DoNotFollowSymlinks);
  484. auto custody = TRY(resolve_path(credentials, path, base, nullptr, should_follow_symlinks ? 0 : O_NOFOLLOW_NOERROR));
  485. auto& inode = custody->inode();
  486. auto metadata = inode.metadata();
  487. auto use_effective_ids = has_flag(access_flags, AccessFlags::EffectiveAccess) ? UseEffectiveIDs::Yes : UseEffectiveIDs::No;
  488. if (mode & R_OK) {
  489. if (!metadata.may_read(credentials, use_effective_ids))
  490. return EACCES;
  491. }
  492. if (mode & W_OK) {
  493. if (!metadata.may_write(credentials, use_effective_ids))
  494. return EACCES;
  495. if (custody->is_readonly())
  496. return EROFS;
  497. }
  498. if (mode & X_OK) {
  499. if (!metadata.may_execute(credentials, use_effective_ids))
  500. return EACCES;
  501. }
  502. return {};
  503. }
  504. ErrorOr<NonnullRefPtr<Custody>> VirtualFileSystem::open_directory(Credentials const& credentials, StringView path, Custody& base)
  505. {
  506. auto custody = TRY(resolve_path(credentials, path, base));
  507. auto& inode = custody->inode();
  508. if (!inode.is_directory())
  509. return ENOTDIR;
  510. if (!inode.metadata().may_execute(credentials))
  511. return EACCES;
  512. return custody;
  513. }
  514. ErrorOr<void> VirtualFileSystem::chmod(Credentials const& credentials, Custody& custody, mode_t mode)
  515. {
  516. auto& inode = custody.inode();
  517. if (credentials.euid() != inode.metadata().uid && !credentials.is_superuser())
  518. return EPERM;
  519. if (custody.is_readonly())
  520. return EROFS;
  521. // Only change the permission bits.
  522. mode = (inode.mode() & ~07777u) | (mode & 07777u);
  523. return inode.chmod(mode);
  524. }
  525. ErrorOr<void> VirtualFileSystem::chmod(Credentials const& credentials, StringView path, mode_t mode, Custody& base, int options)
  526. {
  527. auto custody = TRY(resolve_path(credentials, path, base, nullptr, options));
  528. return chmod(credentials, custody, mode);
  529. }
  530. ErrorOr<void> VirtualFileSystem::rename(Credentials const& credentials, Custody& old_base, StringView old_path, Custody& new_base, StringView new_path)
  531. {
  532. RefPtr<Custody> old_parent_custody;
  533. auto old_custody = TRY(resolve_path(credentials, old_path, old_base, &old_parent_custody, O_NOFOLLOW_NOERROR));
  534. auto& old_inode = old_custody->inode();
  535. RefPtr<Custody> new_parent_custody;
  536. auto new_custody_or_error = resolve_path(credentials, new_path, new_base, &new_parent_custody);
  537. if (new_custody_or_error.is_error()) {
  538. if (new_custody_or_error.error().code() != ENOENT || !new_parent_custody)
  539. return new_custody_or_error.release_error();
  540. }
  541. if (!old_parent_custody || !new_parent_custody) {
  542. return EPERM;
  543. }
  544. if (!new_custody_or_error.is_error()) {
  545. auto& new_inode = new_custody_or_error.value()->inode();
  546. if (old_inode.index() != new_inode.index() && old_inode.is_directory() && new_inode.is_directory()) {
  547. size_t child_count = 0;
  548. TRY(new_inode.traverse_as_directory([&child_count](auto&) -> ErrorOr<void> {
  549. ++child_count;
  550. return {};
  551. }));
  552. if (child_count > 2)
  553. return ENOTEMPTY;
  554. }
  555. }
  556. auto& old_parent_inode = old_parent_custody->inode();
  557. auto& new_parent_inode = new_parent_custody->inode();
  558. if (&old_parent_inode.fs() != &new_parent_inode.fs())
  559. return EXDEV;
  560. for (auto* new_ancestor = new_parent_custody.ptr(); new_ancestor; new_ancestor = new_ancestor->parent()) {
  561. if (&old_inode == &new_ancestor->inode())
  562. return EDIRINTOSELF;
  563. }
  564. if (!new_parent_inode.metadata().may_write(credentials))
  565. return EACCES;
  566. if (!old_parent_inode.metadata().may_write(credentials))
  567. return EACCES;
  568. if (old_parent_inode.metadata().is_sticky()) {
  569. if (!credentials.is_superuser() && old_parent_inode.metadata().uid != credentials.euid() && old_inode.metadata().uid != credentials.euid())
  570. return EACCES;
  571. }
  572. if (old_parent_custody->is_readonly() || new_parent_custody->is_readonly())
  573. return EROFS;
  574. auto old_basename = KLexicalPath::basename(old_path);
  575. if (old_basename.is_empty() || old_basename == "."sv || old_basename == ".."sv)
  576. return EINVAL;
  577. auto new_basename = KLexicalPath::basename(new_path);
  578. if (new_basename.is_empty() || new_basename == "."sv || new_basename == ".."sv)
  579. return EINVAL;
  580. if (old_basename == new_basename && old_parent_inode.index() == new_parent_inode.index())
  581. return {};
  582. if (!new_custody_or_error.is_error()) {
  583. auto& new_custody = *new_custody_or_error.value();
  584. auto& new_inode = new_custody.inode();
  585. // When the source/dest inodes are the same (in other words,
  586. // when `old_path` and `new_path` are the same), perform a no-op
  587. // and return success.
  588. // Linux (`vfs_rename()`) and OpenBSD (`dorenameat()`) appear to have
  589. // this same no-op behavior.
  590. if (&new_inode == &old_inode)
  591. return {};
  592. if (new_parent_inode.metadata().is_sticky()) {
  593. if (!credentials.is_superuser() && new_inode.metadata().uid != credentials.euid())
  594. return EACCES;
  595. }
  596. if (new_inode.is_directory() && !old_inode.is_directory())
  597. return EISDIR;
  598. TRY(new_parent_inode.remove_child(new_basename));
  599. }
  600. TRY(new_parent_inode.add_child(old_inode, new_basename, old_inode.mode()));
  601. TRY(old_parent_inode.remove_child(old_basename));
  602. // If the inode that we moved is a directory and we changed parent
  603. // directories, then we also have to make .. point to the new parent inode,
  604. // because .. is its own inode.
  605. if (old_inode.is_directory() && old_parent_inode.index() != new_parent_inode.index()) {
  606. TRY(old_inode.replace_child(".."sv, new_parent_inode));
  607. }
  608. return {};
  609. }
  610. ErrorOr<void> VirtualFileSystem::chown(Credentials const& credentials, Custody& custody, UserID a_uid, GroupID a_gid)
  611. {
  612. auto& inode = custody.inode();
  613. auto metadata = inode.metadata();
  614. if (credentials.euid() != metadata.uid && !credentials.is_superuser())
  615. return EPERM;
  616. UserID new_uid = metadata.uid;
  617. GroupID new_gid = metadata.gid;
  618. if (a_uid != (uid_t)-1) {
  619. if (credentials.euid() != a_uid && !credentials.is_superuser())
  620. return EPERM;
  621. new_uid = a_uid;
  622. }
  623. if (a_gid != (gid_t)-1) {
  624. if (!credentials.in_group(a_gid) && !credentials.is_superuser())
  625. return EPERM;
  626. new_gid = a_gid;
  627. }
  628. if (custody.is_readonly())
  629. return EROFS;
  630. dbgln_if(VFS_DEBUG, "VirtualFileSystem::chown(): inode {} <- uid={} gid={}", inode.identifier(), new_uid, new_gid);
  631. if (metadata.is_setuid() || metadata.is_setgid()) {
  632. dbgln_if(VFS_DEBUG, "VirtualFileSystem::chown(): Stripping SUID/SGID bits from {}", inode.identifier());
  633. TRY(inode.chmod(metadata.mode & ~(04000 | 02000)));
  634. }
  635. return inode.chown(new_uid, new_gid);
  636. }
  637. ErrorOr<void> VirtualFileSystem::chown(Credentials const& credentials, StringView path, UserID a_uid, GroupID a_gid, Custody& base, int options)
  638. {
  639. auto custody = TRY(resolve_path(credentials, path, base, nullptr, options));
  640. return chown(credentials, custody, a_uid, a_gid);
  641. }
  642. static bool hard_link_allowed(Credentials const& credentials, Inode const& inode)
  643. {
  644. auto metadata = inode.metadata();
  645. if (credentials.euid() == metadata.uid)
  646. return true;
  647. if (metadata.is_regular_file()
  648. && !metadata.is_setuid()
  649. && !(metadata.is_setgid() && metadata.mode & S_IXGRP)
  650. && metadata.may_write(credentials)) {
  651. return true;
  652. }
  653. return false;
  654. }
  655. ErrorOr<void> VirtualFileSystem::link(Credentials const& credentials, StringView old_path, StringView new_path, Custody& base)
  656. {
  657. // NOTE: To prevent unveil bypass by creating an hardlink after unveiling a path as read-only,
  658. // check that if write permission is allowed by the veil info on the old_path.
  659. auto old_custody = TRY(resolve_path(credentials, old_path, base, nullptr, O_RDWR));
  660. auto& old_inode = old_custody->inode();
  661. RefPtr<Custody> parent_custody;
  662. auto new_custody_or_error = resolve_path(credentials, new_path, base, &parent_custody);
  663. if (!new_custody_or_error.is_error())
  664. return EEXIST;
  665. if (!parent_custody)
  666. return ENOENT;
  667. auto& parent_inode = parent_custody->inode();
  668. if (parent_inode.fsid() != old_inode.fsid())
  669. return EXDEV;
  670. if (!parent_inode.metadata().may_write(credentials))
  671. return EACCES;
  672. if (old_inode.is_directory())
  673. return EPERM;
  674. if (parent_custody->is_readonly())
  675. return EROFS;
  676. if (!hard_link_allowed(credentials, old_inode))
  677. return EPERM;
  678. return parent_inode.add_child(old_inode, KLexicalPath::basename(new_path), old_inode.mode());
  679. }
  680. ErrorOr<void> VirtualFileSystem::unlink(Credentials const& credentials, StringView path, Custody& base)
  681. {
  682. RefPtr<Custody> parent_custody;
  683. auto custody = TRY(resolve_path(credentials, path, base, &parent_custody, O_NOFOLLOW_NOERROR | O_UNLINK_INTERNAL));
  684. auto& inode = custody->inode();
  685. if (inode.is_directory())
  686. return EISDIR;
  687. // We have just checked that the inode is not a directory, and thus it's not
  688. // the root. So it should have a parent. Note that this would be invalidated
  689. // if we were to support bind-mounting regular files on top of the root.
  690. VERIFY(parent_custody);
  691. auto& parent_inode = parent_custody->inode();
  692. if (!parent_inode.metadata().may_write(credentials))
  693. return EACCES;
  694. if (parent_inode.metadata().is_sticky()) {
  695. if (!credentials.is_superuser() && parent_inode.metadata().uid != credentials.euid() && inode.metadata().uid != credentials.euid())
  696. return EACCES;
  697. }
  698. if (parent_custody->is_readonly())
  699. return EROFS;
  700. return parent_inode.remove_child(KLexicalPath::basename(path));
  701. }
  702. ErrorOr<void> VirtualFileSystem::symlink(Credentials const& credentials, StringView target, StringView linkpath, Custody& base)
  703. {
  704. // NOTE: Check that the actual target (if it exists right now) is unveiled and prevent creating symlinks on veiled paths!
  705. if (auto target_custody_or_error = resolve_path_without_veil(credentials, target, base, nullptr, O_RDWR, 0); !target_custody_or_error.is_error()) {
  706. auto target_custody = target_custody_or_error.release_value();
  707. TRY(validate_path_against_process_veil(*target_custody, O_RDWR));
  708. }
  709. RefPtr<Custody> parent_custody;
  710. auto existing_custody_or_error = resolve_path(credentials, linkpath, base, &parent_custody, O_RDWR);
  711. if (!existing_custody_or_error.is_error())
  712. return EEXIST;
  713. if (!parent_custody)
  714. return ENOENT;
  715. // NOTE: VERY IMPORTANT! We prevent creating symlinks in case the program didn't unveil the parent_custody
  716. // path! For example, say the program wanted to create a symlink in /tmp/symlink to /tmp/test/pointee_symlink
  717. // and unveiled the /tmp/test/ directory path beforehand, but not the /tmp directory path - the symlink syscall will
  718. // fail here because we can't create the symlink in a parent directory path we didn't unveil beforehand.
  719. TRY(validate_path_against_process_veil(*parent_custody, O_RDWR));
  720. if (existing_custody_or_error.is_error() && existing_custody_or_error.error().code() != ENOENT)
  721. return existing_custody_or_error.release_error();
  722. auto& parent_inode = parent_custody->inode();
  723. if (!parent_inode.metadata().may_write(credentials))
  724. return EACCES;
  725. if (parent_custody->is_readonly())
  726. return EROFS;
  727. auto basename = KLexicalPath::basename(linkpath);
  728. dbgln_if(VFS_DEBUG, "VirtualFileSystem::symlink: '{}' (-> '{}') in {}", basename, target, parent_inode.identifier());
  729. auto inode = TRY(parent_inode.create_child(basename, S_IFLNK | 0644, 0, credentials.euid(), credentials.egid()));
  730. auto target_buffer = UserOrKernelBuffer::for_kernel_buffer(const_cast<u8*>((u8 const*)target.characters_without_null_termination()));
  731. TRY(inode->write_bytes(0, target.length(), target_buffer, nullptr));
  732. return {};
  733. }
  734. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/rmdir.html
  735. ErrorOr<void> VirtualFileSystem::rmdir(Credentials const& credentials, StringView path, Custody& base)
  736. {
  737. RefPtr<Custody> parent_custody;
  738. auto custody = TRY(resolve_path(credentials, path, base, &parent_custody));
  739. auto& inode = custody->inode();
  740. auto last_component = KLexicalPath::basename(path);
  741. // [EINVAL] The path argument contains a last component that is dot.
  742. if (last_component == "."sv)
  743. return EINVAL;
  744. // [ENOTDIR] A component of path names an existing file that is neither a directory
  745. // nor a symbolic link to a directory.
  746. if (!inode.is_directory())
  747. return ENOTDIR;
  748. // [EBUSY] The directory to be removed is currently in use by the system or some process
  749. // and the implementation considers this to be an error.
  750. // NOTE: If there is no parent, that means we're trying to rmdir the root directory!
  751. if (!parent_custody)
  752. return EBUSY;
  753. auto& parent_inode = parent_custody->inode();
  754. auto parent_metadata = parent_inode.metadata();
  755. // [EACCES] Search permission is denied on a component of the path prefix,
  756. // or write permission is denied on the parent directory of the directory to be removed.
  757. if (!parent_metadata.may_write(credentials))
  758. return EACCES;
  759. if (parent_metadata.is_sticky()) {
  760. // [EACCES] The S_ISVTX flag is set on the directory containing the file referred to by the path argument
  761. // and the process does not satisfy the criteria specified in XBD Directory Protection.
  762. if (!credentials.is_superuser()
  763. && inode.metadata().uid != credentials.euid()
  764. && parent_metadata.uid != credentials.euid()) {
  765. return EACCES;
  766. }
  767. }
  768. size_t child_count = 0;
  769. TRY(inode.traverse_as_directory([&child_count](auto&) -> ErrorOr<void> {
  770. ++child_count;
  771. return {};
  772. }));
  773. // [ENOTEMPTY] The path argument names a directory that is not an empty directory,
  774. // or there are hard links to the directory other than dot or a single entry in dot-dot.
  775. if (child_count != 2)
  776. return ENOTEMPTY;
  777. // [EROFS] The directory entry to be removed resides on a read-only file system.
  778. if (custody->is_readonly())
  779. return EROFS;
  780. TRY(inode.remove_child("."sv));
  781. TRY(inode.remove_child(".."sv));
  782. return parent_inode.remove_child(KLexicalPath::basename(path));
  783. }
  784. ErrorOr<void> VirtualFileSystem::for_each_mount(Function<ErrorOr<void>(Mount const&)> callback) const
  785. {
  786. return m_mounts.with([&](auto& mounts) -> ErrorOr<void> {
  787. for (auto& mount : mounts)
  788. TRY(callback(mount));
  789. return {};
  790. });
  791. }
  792. void VirtualFileSystem::sync()
  793. {
  794. FileSystem::sync();
  795. }
  796. NonnullRefPtr<Custody> VirtualFileSystem::root_custody()
  797. {
  798. return m_root_custody.with([](auto& root_custody) -> NonnullRefPtr<Custody> { return *root_custody; });
  799. }
  800. UnveilNode const& VirtualFileSystem::find_matching_unveiled_path(Process const& process, StringView path)
  801. {
  802. VERIFY(process.veil_state() != VeilState::None);
  803. return process.unveil_data().with([&](auto const& unveil_data) -> UnveilNode const& {
  804. auto path_parts = KLexicalPath::parts(path);
  805. return unveil_data.paths.traverse_until_last_accessible_node(path_parts.begin(), path_parts.end());
  806. });
  807. }
  808. ErrorOr<void> VirtualFileSystem::validate_path_against_process_veil(Custody const& custody, int options)
  809. {
  810. return validate_path_against_process_veil(Process::current(), custody, options);
  811. }
  812. ErrorOr<void> VirtualFileSystem::validate_path_against_process_veil(Process const& process, Custody const& custody, int options)
  813. {
  814. if (process.veil_state() == VeilState::None)
  815. return {};
  816. auto absolute_path = TRY(custody.try_serialize_absolute_path());
  817. return validate_path_against_process_veil(process, absolute_path->view(), options);
  818. }
  819. ErrorOr<void> VirtualFileSystem::validate_path_against_process_veil(Process const& process, StringView path, int options)
  820. {
  821. if (process.veil_state() == VeilState::None)
  822. return {};
  823. VERIFY(path.starts_with('/'));
  824. VERIFY(!path.contains("/../"sv) && !path.ends_with("/.."sv));
  825. VERIFY(!path.contains("/./"sv) && !path.ends_with("/."sv));
  826. #ifdef SKIP_PATH_VALIDATION_FOR_COVERAGE_INSTRUMENTATION
  827. // Skip veil validation against profile data when coverage is enabled for userspace
  828. // so that all processes can write out coverage data even with veils in place
  829. if (KLexicalPath::basename(path).ends_with(".profraw"sv))
  830. return {};
  831. #endif
  832. auto& unveiled_path = find_matching_unveiled_path(process, path);
  833. if (unveiled_path.permissions() == UnveilAccess::None) {
  834. dbgln("Rejecting path '{}' since it hasn't been unveiled.", path);
  835. dump_backtrace();
  836. return ENOENT;
  837. }
  838. if (options & O_CREAT) {
  839. if (!(unveiled_path.permissions() & UnveilAccess::CreateOrRemove)) {
  840. dbgln("Rejecting path '{}' since it hasn't been unveiled with 'c' permission.", path);
  841. dump_backtrace();
  842. return EACCES;
  843. }
  844. }
  845. if (options & O_UNLINK_INTERNAL) {
  846. if (!(unveiled_path.permissions() & UnveilAccess::CreateOrRemove)) {
  847. dbgln("Rejecting path '{}' for unlink since it hasn't been unveiled with 'c' permission.", path);
  848. dump_backtrace();
  849. return EACCES;
  850. }
  851. return {};
  852. }
  853. if (options & O_RDONLY) {
  854. if (options & O_DIRECTORY) {
  855. if (!(unveiled_path.permissions() & (UnveilAccess::Read | UnveilAccess::Browse))) {
  856. dbgln("Rejecting path '{}' since it hasn't been unveiled with 'r' or 'b' permissions.", path);
  857. dump_backtrace();
  858. return EACCES;
  859. }
  860. } else {
  861. if (!(unveiled_path.permissions() & UnveilAccess::Read)) {
  862. dbgln("Rejecting path '{}' since it hasn't been unveiled with 'r' permission.", path);
  863. dump_backtrace();
  864. return EACCES;
  865. }
  866. }
  867. }
  868. if (options & O_WRONLY) {
  869. if (!(unveiled_path.permissions() & UnveilAccess::Write)) {
  870. dbgln("Rejecting path '{}' since it hasn't been unveiled with 'w' permission.", path);
  871. dump_backtrace();
  872. return EACCES;
  873. }
  874. }
  875. if (options & O_EXEC) {
  876. if (!(unveiled_path.permissions() & UnveilAccess::Execute)) {
  877. dbgln("Rejecting path '{}' since it hasn't been unveiled with 'x' permission.", path);
  878. dump_backtrace();
  879. return EACCES;
  880. }
  881. }
  882. return {};
  883. }
  884. ErrorOr<void> VirtualFileSystem::validate_path_against_process_veil(StringView path, int options)
  885. {
  886. return validate_path_against_process_veil(Process::current(), path, options);
  887. }
  888. ErrorOr<NonnullRefPtr<Custody>> VirtualFileSystem::resolve_path(Credentials const& credentials, StringView path, NonnullRefPtr<Custody> base, RefPtr<Custody>* out_parent, int options, int symlink_recursion_level)
  889. {
  890. return resolve_path(Process::current(), credentials, path, base, out_parent, options, symlink_recursion_level);
  891. }
  892. ErrorOr<NonnullRefPtr<Custody>> VirtualFileSystem::resolve_path(Process const& process, Credentials const& credentials, StringView path, NonnullRefPtr<Custody> base, RefPtr<Custody>* out_parent, int options, int symlink_recursion_level)
  893. {
  894. // FIXME: The errors returned by resolve_path_without_veil can leak information about paths that are not unveiled,
  895. // e.g. when the error is EACCESS or similar.
  896. auto custody = TRY(resolve_path_without_veil(credentials, path, base, out_parent, options, symlink_recursion_level));
  897. if (auto result = validate_path_against_process_veil(process, *custody, options); result.is_error()) {
  898. if (out_parent)
  899. out_parent->clear();
  900. return result.release_error();
  901. }
  902. return custody;
  903. }
  904. static bool safe_to_follow_symlink(Credentials const& credentials, Inode const& inode, InodeMetadata const& parent_metadata)
  905. {
  906. auto metadata = inode.metadata();
  907. if (credentials.euid() == metadata.uid)
  908. return true;
  909. if (!(parent_metadata.is_sticky() && parent_metadata.mode & S_IWOTH))
  910. return true;
  911. if (metadata.uid == parent_metadata.uid)
  912. return true;
  913. return false;
  914. }
  915. 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)
  916. {
  917. if (symlink_recursion_level >= symlink_recursion_limit)
  918. return ELOOP;
  919. if (path.is_empty())
  920. return EINVAL;
  921. GenericLexer path_lexer(path);
  922. NonnullRefPtr<Custody> custody = path[0] == '/' ? root_custody() : base;
  923. bool extra_iteration = path[path.length() - 1] == '/';
  924. while (!path_lexer.is_eof() || extra_iteration) {
  925. if (path_lexer.is_eof())
  926. extra_iteration = false;
  927. auto part = path_lexer.consume_until('/');
  928. path_lexer.ignore();
  929. Custody& parent = custody;
  930. auto parent_metadata = parent.inode().metadata();
  931. if (!parent_metadata.is_directory())
  932. return ENOTDIR;
  933. // Ensure the current user is allowed to resolve paths inside this directory.
  934. if (!parent_metadata.may_execute(credentials))
  935. return EACCES;
  936. bool have_more_parts = !path_lexer.is_eof() || extra_iteration;
  937. if (part == "..") {
  938. // If we encounter a "..", take a step back, but don't go beyond the root.
  939. if (custody->parent())
  940. custody = *custody->parent();
  941. continue;
  942. } else if (part == "." || part.is_empty()) {
  943. continue;
  944. }
  945. // Okay, let's look up this part.
  946. auto child_or_error = parent.inode().lookup(part);
  947. if (child_or_error.is_error()) {
  948. if (out_parent) {
  949. // ENOENT with a non-null parent custody signals to caller that
  950. // we found the immediate parent of the file, but the file itself
  951. // does not exist yet.
  952. *out_parent = have_more_parts ? nullptr : &parent;
  953. }
  954. return child_or_error.release_error();
  955. }
  956. auto child_inode = child_or_error.release_value();
  957. int mount_flags_for_child = parent.mount_flags();
  958. // See if there's something mounted on the child; in that case
  959. // we would need to return the guest inode, not the host inode.
  960. if (auto mount = find_mount_for_host(child_inode->identifier())) {
  961. child_inode = mount->guest();
  962. mount_flags_for_child = mount->flags();
  963. }
  964. custody = TRY(Custody::try_create(&parent, part, *child_inode, mount_flags_for_child));
  965. if (child_inode->metadata().is_symlink()) {
  966. if (!have_more_parts) {
  967. if (options & O_NOFOLLOW)
  968. return ELOOP;
  969. if (options & O_NOFOLLOW_NOERROR)
  970. break;
  971. }
  972. if (!safe_to_follow_symlink(credentials, *child_inode, parent_metadata))
  973. return EACCES;
  974. TRY(validate_path_against_process_veil(*custody, options));
  975. auto symlink_target = TRY(child_inode->resolve_as_link(credentials, parent, out_parent, options, symlink_recursion_level + 1));
  976. if (!have_more_parts)
  977. return symlink_target;
  978. // Now, resolve the remaining path relative to the symlink target.
  979. // We prepend a "." to it to ensure that it's not empty and that
  980. // any initial slashes it might have get interpreted properly.
  981. StringBuilder remaining_path;
  982. TRY(remaining_path.try_append('.'));
  983. TRY(remaining_path.try_append(path.substring_view_starting_after_substring(part)));
  984. return resolve_path_without_veil(credentials, remaining_path.string_view(), symlink_target, out_parent, options, symlink_recursion_level + 1);
  985. }
  986. }
  987. if (out_parent)
  988. *out_parent = custody->parent();
  989. return custody;
  990. }
  991. }