VirtualFileSystem.cpp 34 KB

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