VirtualFileSystem.cpp 46 KB

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