VirtualFileSystem.cpp 33 KB

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