VirtualFileSystem.cpp 33 KB

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