VirtualFileSystem.cpp 41 KB

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