VirtualFileSystem.cpp 35 KB

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