VirtualFileSystem.cpp 51 KB

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