VirtualFileSystem.cpp 35 KB

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