VirtualFileSystem.cpp 35 KB

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