VirtualFileSystem.cpp 35 KB

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