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