VirtualFileSystem.cpp 36 KB

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