VirtualFileSystem.cpp 36 KB

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