VirtualFileSystem.cpp 40 KB

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