VirtualFileSystem.cpp 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059
  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/Devices/BlockDevice.h>
  30. #include <Kernel/FileSystem/Custody.h>
  31. #include <Kernel/FileSystem/FileBackedFileSystem.h>
  32. #include <Kernel/FileSystem/FileDescription.h>
  33. #include <Kernel/FileSystem/FileSystem.h>
  34. #include <Kernel/FileSystem/VirtualFileSystem.h>
  35. #include <Kernel/KSyms.h>
  36. #include <Kernel/Process.h>
  37. #include <LibC/errno_numbers.h>
  38. //#define VFS_DEBUG
  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. #ifdef 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. dbg() << "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. #ifdef VFS_DEBUG
  351. dbg() << "VFS::create: '" << p.basename() << "' in " << parent_inode.identifier();
  352. #endif
  353. uid_t uid = owner.has_value() ? owner.value().uid : current_process->euid();
  354. gid_t gid = owner.has_value() ? owner.value().gid : current_process->egid();
  355. auto inode_or_error = parent_inode.create_child(p.basename(), mode, 0, uid, gid);
  356. if (inode_or_error.is_error())
  357. return inode_or_error.error();
  358. auto new_custody = Custody::create(&parent_custody, p.basename(), inode_or_error.value(), parent_custody.mount_flags());
  359. auto description = FileDescription::create(*new_custody);
  360. if (!description.is_error()) {
  361. description.value()->set_rw_mode(options);
  362. description.value()->set_file_flags(options);
  363. }
  364. return description;
  365. }
  366. KResult VFS::mkdir(StringView path, mode_t mode, Custody& base)
  367. {
  368. // Unlike in basically every other case, where it's only the last
  369. // path component (the one being created) that is allowed not to
  370. // exist, POSIX allows mkdir'ed path to have trailing slashes.
  371. // Let's handle that case by trimming any trailing slashes.
  372. while (path.length() > 1 && path.ends_with("/"))
  373. path = path.substring_view(0, path.length() - 1);
  374. RefPtr<Custody> parent_custody;
  375. auto result = resolve_path(path, base, &parent_custody);
  376. if (!result.is_error())
  377. return EEXIST;
  378. if (!parent_custody)
  379. return ENOENT;
  380. if (result.error() != -ENOENT)
  381. return result.error();
  382. auto& parent_inode = parent_custody->inode();
  383. auto current_process = Process::current();
  384. if (!parent_inode.metadata().may_write(*current_process))
  385. return EACCES;
  386. if (parent_custody->is_readonly())
  387. return EROFS;
  388. LexicalPath p(path);
  389. #ifdef VFS_DEBUG
  390. dbg() << "VFS::mkdir: '" << p.basename() << "' in " << parent_inode.identifier();
  391. #endif
  392. return parent_inode.create_child(p.basename(), S_IFDIR | mode, 0, current_process->euid(), current_process->egid()).result();
  393. }
  394. KResult VFS::access(StringView path, int mode, Custody& base)
  395. {
  396. auto custody_or_error = resolve_path(path, base);
  397. if (custody_or_error.is_error())
  398. return custody_or_error.error();
  399. auto& custody = *custody_or_error.value();
  400. auto& inode = custody.inode();
  401. auto metadata = inode.metadata();
  402. auto current_process = Process::current();
  403. if (mode & R_OK) {
  404. if (!metadata.may_read(*current_process))
  405. return EACCES;
  406. }
  407. if (mode & W_OK) {
  408. if (!metadata.may_write(*current_process))
  409. return EACCES;
  410. if (custody.is_readonly())
  411. return EROFS;
  412. }
  413. if (mode & X_OK) {
  414. if (!metadata.may_execute(*current_process))
  415. return EACCES;
  416. }
  417. return KSuccess;
  418. }
  419. KResultOr<NonnullRefPtr<Custody>> VFS::open_directory(StringView path, Custody& base)
  420. {
  421. auto inode_or_error = resolve_path(path, base);
  422. if (inode_or_error.is_error())
  423. return inode_or_error.error();
  424. auto& custody = *inode_or_error.value();
  425. auto& inode = custody.inode();
  426. if (!inode.is_directory())
  427. return ENOTDIR;
  428. if (!inode.metadata().may_execute(*Process::current()))
  429. return EACCES;
  430. return custody;
  431. }
  432. KResult VFS::chmod(Custody& custody, mode_t mode)
  433. {
  434. auto& inode = custody.inode();
  435. auto current_process = Process::current();
  436. if (current_process->euid() != inode.metadata().uid && !current_process->is_superuser())
  437. return EPERM;
  438. if (custody.is_readonly())
  439. return EROFS;
  440. // Only change the permission bits.
  441. mode = (inode.mode() & ~07777u) | (mode & 07777u);
  442. return inode.chmod(mode);
  443. }
  444. KResult VFS::chmod(StringView path, mode_t mode, Custody& base)
  445. {
  446. auto custody_or_error = resolve_path(path, base);
  447. if (custody_or_error.is_error())
  448. return custody_or_error.error();
  449. auto& custody = *custody_or_error.value();
  450. return chmod(custody, mode);
  451. }
  452. KResult VFS::rename(StringView old_path, StringView new_path, Custody& base)
  453. {
  454. RefPtr<Custody> old_parent_custody;
  455. auto old_custody_or_error = resolve_path(old_path, base, &old_parent_custody, O_NOFOLLOW_NOERROR);
  456. if (old_custody_or_error.is_error())
  457. return old_custody_or_error.error();
  458. auto& old_custody = *old_custody_or_error.value();
  459. auto& old_inode = old_custody.inode();
  460. RefPtr<Custody> new_parent_custody;
  461. auto new_custody_or_error = resolve_path(new_path, base, &new_parent_custody);
  462. if (new_custody_or_error.is_error()) {
  463. if (new_custody_or_error.error() != -ENOENT || !new_parent_custody)
  464. return new_custody_or_error.error();
  465. }
  466. auto& old_parent_inode = old_parent_custody->inode();
  467. auto& new_parent_inode = new_parent_custody->inode();
  468. if (&old_parent_inode.fs() != &new_parent_inode.fs())
  469. return EXDEV;
  470. for (auto* new_ancestor = new_parent_custody.ptr(); new_ancestor; new_ancestor = new_ancestor->parent()) {
  471. if (&old_inode == &new_ancestor->inode())
  472. return EDIRINTOSELF;
  473. }
  474. auto current_process = Process::current();
  475. if (!new_parent_inode.metadata().may_write(*current_process))
  476. return EACCES;
  477. if (!old_parent_inode.metadata().may_write(*current_process))
  478. return EACCES;
  479. if (old_parent_inode.metadata().is_sticky()) {
  480. if (!current_process->is_superuser() && old_inode.metadata().uid != current_process->euid())
  481. return EACCES;
  482. }
  483. if (old_parent_custody->is_readonly() || new_parent_custody->is_readonly())
  484. return EROFS;
  485. auto new_basename = LexicalPath(new_path).basename();
  486. if (!new_custody_or_error.is_error()) {
  487. auto& new_custody = *new_custody_or_error.value();
  488. auto& new_inode = new_custody.inode();
  489. // FIXME: Is this really correct? Check what other systems do.
  490. if (&new_inode == &old_inode)
  491. return KSuccess;
  492. if (new_parent_inode.metadata().is_sticky()) {
  493. if (!current_process->is_superuser() && new_inode.metadata().uid != current_process->euid())
  494. return EACCES;
  495. }
  496. if (new_inode.is_directory() && !old_inode.is_directory())
  497. return EISDIR;
  498. auto result = new_parent_inode.remove_child(new_basename);
  499. if (result.is_error())
  500. return result;
  501. }
  502. auto result = new_parent_inode.add_child(old_inode, new_basename, old_inode.mode());
  503. if (result.is_error())
  504. return result;
  505. result = old_parent_inode.remove_child(LexicalPath(old_path).basename());
  506. if (result.is_error())
  507. return result;
  508. return KSuccess;
  509. }
  510. KResult VFS::chown(Custody& custody, uid_t a_uid, gid_t a_gid)
  511. {
  512. auto& inode = custody.inode();
  513. auto metadata = inode.metadata();
  514. auto current_process = Process::current();
  515. if (current_process->euid() != metadata.uid && !current_process->is_superuser())
  516. return EPERM;
  517. uid_t new_uid = metadata.uid;
  518. gid_t new_gid = metadata.gid;
  519. if (a_uid != (uid_t)-1) {
  520. if (current_process->euid() != a_uid && !current_process->is_superuser())
  521. return EPERM;
  522. new_uid = a_uid;
  523. }
  524. if (a_gid != (gid_t)-1) {
  525. if (!current_process->in_group(a_gid) && !current_process->is_superuser())
  526. return EPERM;
  527. new_gid = a_gid;
  528. }
  529. if (custody.is_readonly())
  530. return EROFS;
  531. dbgln("VFS::chown(): inode {} <- uid={} gid={}", inode.identifier(), new_uid, new_gid);
  532. if (metadata.is_setuid() || metadata.is_setgid()) {
  533. dbgln("VFS::chown(): Stripping SUID/SGID bits from {}", inode.identifier());
  534. auto result = inode.chmod(metadata.mode & ~(04000 | 02000));
  535. if (result.is_error())
  536. return result;
  537. }
  538. return inode.chown(new_uid, new_gid);
  539. }
  540. KResult VFS::chown(StringView path, uid_t a_uid, gid_t a_gid, Custody& base)
  541. {
  542. auto custody_or_error = resolve_path(path, base);
  543. if (custody_or_error.is_error())
  544. return custody_or_error.error();
  545. auto& custody = *custody_or_error.value();
  546. return chown(custody, a_uid, a_gid);
  547. }
  548. static bool hard_link_allowed(const Inode& inode)
  549. {
  550. auto metadata = inode.metadata();
  551. if (Process::current()->euid() == metadata.uid)
  552. return true;
  553. if (metadata.is_regular_file()
  554. && !metadata.is_setuid()
  555. && !(metadata.is_setgid() && metadata.mode & S_IXGRP)
  556. && metadata.may_write(*Process::current())) {
  557. return true;
  558. }
  559. return false;
  560. }
  561. KResult VFS::link(StringView old_path, StringView new_path, Custody& base)
  562. {
  563. auto old_custody_or_error = resolve_path(old_path, base);
  564. if (old_custody_or_error.is_error())
  565. return old_custody_or_error.error();
  566. auto& old_custody = *old_custody_or_error.value();
  567. auto& old_inode = old_custody.inode();
  568. RefPtr<Custody> parent_custody;
  569. auto new_custody_or_error = resolve_path(new_path, base, &parent_custody);
  570. if (!new_custody_or_error.is_error())
  571. return EEXIST;
  572. if (!parent_custody)
  573. return ENOENT;
  574. auto& parent_inode = parent_custody->inode();
  575. if (parent_inode.fsid() != old_inode.fsid())
  576. return EXDEV;
  577. if (!parent_inode.metadata().may_write(*Process::current()))
  578. return EACCES;
  579. if (old_inode.is_directory())
  580. return EPERM;
  581. if (parent_custody->is_readonly())
  582. return EROFS;
  583. if (!hard_link_allowed(old_inode))
  584. return EPERM;
  585. return parent_inode.add_child(old_inode, LexicalPath(new_path).basename(), old_inode.mode());
  586. }
  587. KResult VFS::unlink(StringView path, Custody& base)
  588. {
  589. RefPtr<Custody> parent_custody;
  590. auto custody_or_error = resolve_path(path, base, &parent_custody, O_NOFOLLOW_NOERROR | O_UNLINK_INTERNAL);
  591. if (custody_or_error.is_error())
  592. return custody_or_error.error();
  593. auto& custody = *custody_or_error.value();
  594. auto& inode = custody.inode();
  595. if (inode.is_directory())
  596. return EISDIR;
  597. // We have just checked that the inode is not a directory, and thus it's not
  598. // the root. So it should have a parent. Note that this would be invalidated
  599. // if we were to support bind-mounting regular files on top of the root.
  600. ASSERT(parent_custody);
  601. auto& parent_inode = parent_custody->inode();
  602. auto current_process = Process::current();
  603. if (!parent_inode.metadata().may_write(*current_process))
  604. return EACCES;
  605. if (parent_inode.metadata().is_sticky()) {
  606. if (!current_process->is_superuser() && inode.metadata().uid != current_process->euid())
  607. return EACCES;
  608. }
  609. if (parent_custody->is_readonly())
  610. return EROFS;
  611. auto result = parent_inode.remove_child(LexicalPath(path).basename());
  612. if (result.is_error())
  613. return result;
  614. return KSuccess;
  615. }
  616. KResult VFS::symlink(StringView target, StringView linkpath, Custody& base)
  617. {
  618. RefPtr<Custody> parent_custody;
  619. auto existing_custody_or_error = resolve_path(linkpath, base, &parent_custody);
  620. if (!existing_custody_or_error.is_error())
  621. return EEXIST;
  622. if (!parent_custody)
  623. return ENOENT;
  624. if (existing_custody_or_error.error() != -ENOENT)
  625. return existing_custody_or_error.error();
  626. auto& parent_inode = parent_custody->inode();
  627. auto current_process = Process::current();
  628. if (!parent_inode.metadata().may_write(*current_process))
  629. return EACCES;
  630. if (parent_custody->is_readonly())
  631. return EROFS;
  632. LexicalPath p(linkpath);
  633. dbgln("VFS::symlink: '{}' (-> '{}') in {}", p.basename(), target, parent_inode.identifier());
  634. auto inode_or_error = parent_inode.create_child(p.basename(), S_IFLNK | 0644, 0, current_process->euid(), current_process->egid());
  635. if (inode_or_error.is_error())
  636. return inode_or_error.error();
  637. auto& inode = inode_or_error.value();
  638. auto target_buffer = UserOrKernelBuffer::for_kernel_buffer(const_cast<u8*>((const u8*)target.characters_without_null_termination()));
  639. ssize_t nwritten = inode->write_bytes(0, target.length(), target_buffer, nullptr);
  640. if (nwritten < 0)
  641. return KResult((ErrnoCode)-nwritten);
  642. return KSuccess;
  643. }
  644. KResult VFS::rmdir(StringView path, Custody& base)
  645. {
  646. RefPtr<Custody> parent_custody;
  647. auto custody_or_error = resolve_path(path, base, &parent_custody);
  648. if (custody_or_error.is_error())
  649. return KResult(custody_or_error.error());
  650. auto& custody = *custody_or_error.value();
  651. auto& inode = custody.inode();
  652. // FIXME: We should return EINVAL if the last component of the path is "."
  653. // FIXME: We should return ENOTEMPTY if the last component of the path is ".."
  654. if (!inode.is_directory())
  655. return ENOTDIR;
  656. if (!parent_custody)
  657. return EBUSY;
  658. auto& parent_inode = parent_custody->inode();
  659. auto parent_metadata = parent_inode.metadata();
  660. if (!parent_metadata.may_write(*Process::current()))
  661. return EACCES;
  662. if (parent_metadata.is_sticky()) {
  663. if (!Process::current()->is_superuser() && inode.metadata().uid != Process::current()->euid())
  664. return EACCES;
  665. }
  666. KResultOr<size_t> dir_count_result = inode.directory_entry_count();
  667. if (dir_count_result.is_error())
  668. return dir_count_result.result();
  669. if (dir_count_result.value() != 2)
  670. return ENOTEMPTY;
  671. if (custody.is_readonly())
  672. return EROFS;
  673. auto result = inode.remove_child(".");
  674. if (result.is_error())
  675. return result;
  676. result = inode.remove_child("..");
  677. if (result.is_error())
  678. return result;
  679. return parent_inode.remove_child(LexicalPath(path).basename());
  680. }
  681. VFS::Mount::Mount(FS& guest_fs, Custody* host_custody, int flags)
  682. : m_guest(guest_fs.root_inode())
  683. , m_guest_fs(guest_fs)
  684. , m_host_custody(host_custody)
  685. , m_flags(flags)
  686. {
  687. }
  688. VFS::Mount::Mount(Inode& source, Custody& host_custody, int flags)
  689. : m_guest(source)
  690. , m_guest_fs(source.fs())
  691. , m_host_custody(host_custody)
  692. , m_flags(flags)
  693. {
  694. }
  695. String VFS::Mount::absolute_path() const
  696. {
  697. if (!m_host_custody)
  698. return "/";
  699. return m_host_custody->absolute_path();
  700. }
  701. Inode* VFS::Mount::host()
  702. {
  703. if (!m_host_custody)
  704. return nullptr;
  705. return &m_host_custody->inode();
  706. }
  707. const Inode* VFS::Mount::host() const
  708. {
  709. if (!m_host_custody)
  710. return nullptr;
  711. return &m_host_custody->inode();
  712. }
  713. void VFS::for_each_mount(Function<void(const Mount&)> callback) const
  714. {
  715. for (auto& mount : m_mounts) {
  716. callback(mount);
  717. }
  718. }
  719. void VFS::sync()
  720. {
  721. FS::sync();
  722. }
  723. Custody& VFS::root_custody()
  724. {
  725. if (!m_root_custody)
  726. m_root_custody = Custody::create(nullptr, "", *m_root_inode, root_mount_flags);
  727. return *m_root_custody;
  728. }
  729. const UnveilNode* VFS::find_matching_unveiled_path(StringView path)
  730. {
  731. auto& unveil_root = Process::current()->unveiled_paths();
  732. if (unveil_root.is_empty())
  733. return nullptr;
  734. LexicalPath lexical_path { path };
  735. auto& path_parts = lexical_path.parts();
  736. auto& last_matching_node = unveil_root.traverse_until_last_accessible_node(path_parts.begin(), path_parts.end());
  737. return &last_matching_node;
  738. }
  739. KResult VFS::validate_path_against_process_veil(StringView path, int options)
  740. {
  741. if (Process::current()->veil_state() == VeilState::None)
  742. return KSuccess;
  743. if (path == "/usr/lib/Loader.so")
  744. return KSuccess;
  745. // FIXME: Figure out a nicer way to do this.
  746. if (String(path).contains("/.."))
  747. return EINVAL;
  748. auto* unveiled_path = find_matching_unveiled_path(path);
  749. if (!unveiled_path) {
  750. dbgln("Rejecting path '{}' since it hasn't been unveiled.", path);
  751. dump_backtrace();
  752. return ENOENT;
  753. }
  754. if (options & O_CREAT) {
  755. if (!(unveiled_path->permissions() & UnveilAccess::CreateOrRemove)) {
  756. dbgln("Rejecting path '{}' since it hasn't been unveiled with 'c' permission.", path);
  757. dump_backtrace();
  758. return EACCES;
  759. }
  760. }
  761. if (options & O_UNLINK_INTERNAL) {
  762. if (!(unveiled_path->permissions() & UnveilAccess::CreateOrRemove)) {
  763. dbgln("Rejecting path '{}' for unlink since it hasn't been unveiled with 'c' permission.", path);
  764. dump_backtrace();
  765. return EACCES;
  766. }
  767. return KSuccess;
  768. }
  769. if (options & O_RDONLY) {
  770. if (options & O_DIRECTORY) {
  771. if (!(unveiled_path->permissions() & (UnveilAccess::Read | UnveilAccess::Browse))) {
  772. dbgln("Rejecting path '{}' since it hasn't been unveiled with 'r' or 'b' permissions.", path);
  773. dump_backtrace();
  774. return EACCES;
  775. }
  776. } else {
  777. if (!(unveiled_path->permissions() & UnveilAccess::Read)) {
  778. dbgln("Rejecting path '{}' since it hasn't been unveiled with 'r' permission.", path);
  779. dump_backtrace();
  780. return EACCES;
  781. }
  782. }
  783. }
  784. if (options & O_WRONLY) {
  785. if (!(unveiled_path->permissions() & UnveilAccess::Write)) {
  786. dbgln("Rejecting path '{}' since it hasn't been unveiled with 'w' permission.", path);
  787. dump_backtrace();
  788. return EACCES;
  789. }
  790. }
  791. if (options & O_EXEC) {
  792. if (!(unveiled_path->permissions() & UnveilAccess::Execute)) {
  793. dbgln("Rejecting path '{}' since it hasn't been unveiled with 'x' permission.", path);
  794. dump_backtrace();
  795. return EACCES;
  796. }
  797. }
  798. return KSuccess;
  799. }
  800. KResultOr<NonnullRefPtr<Custody>> VFS::resolve_path(StringView path, Custody& base, RefPtr<Custody>* out_parent, int options, int symlink_recursion_level)
  801. {
  802. auto custody_or_error = resolve_path_without_veil(path, base, out_parent, options, symlink_recursion_level);
  803. if (custody_or_error.is_error())
  804. return custody_or_error.error();
  805. auto& custody = custody_or_error.value();
  806. auto result = validate_path_against_process_veil(custody->absolute_path(), options);
  807. if (result.is_error())
  808. return result;
  809. return custody;
  810. }
  811. static bool safe_to_follow_symlink(const Inode& inode, const InodeMetadata& parent_metadata)
  812. {
  813. auto metadata = inode.metadata();
  814. if (Process::current()->euid() == metadata.uid)
  815. return true;
  816. if (!(parent_metadata.is_sticky() && parent_metadata.mode & S_IWOTH))
  817. return true;
  818. if (metadata.uid == parent_metadata.uid)
  819. return true;
  820. return false;
  821. }
  822. KResultOr<NonnullRefPtr<Custody>> VFS::resolve_path_without_veil(StringView path, Custody& base, RefPtr<Custody>* out_parent, int options, int symlink_recursion_level)
  823. {
  824. if (symlink_recursion_level >= symlink_recursion_limit)
  825. return ELOOP;
  826. if (path.is_empty())
  827. return EINVAL;
  828. auto parts = path.split_view('/', true);
  829. auto current_process = Process::current();
  830. auto& current_root = current_process->root_directory();
  831. NonnullRefPtr<Custody> custody = path[0] == '/' ? current_root : base;
  832. for (size_t i = 0; i < parts.size(); ++i) {
  833. Custody& parent = custody;
  834. auto parent_metadata = parent.inode().metadata();
  835. if (!parent_metadata.is_directory())
  836. return ENOTDIR;
  837. // Ensure the current user is allowed to resolve paths inside this directory.
  838. if (!parent_metadata.may_execute(*current_process))
  839. return EACCES;
  840. auto& part = parts[i];
  841. bool have_more_parts = i + 1 < parts.size();
  842. if (part == "..") {
  843. // If we encounter a "..", take a step back, but don't go beyond the root.
  844. if (custody->parent())
  845. custody = *custody->parent();
  846. continue;
  847. } else if (part == "." || part.is_empty()) {
  848. continue;
  849. }
  850. // Okay, let's look up this part.
  851. auto child_inode = parent.inode().lookup(part);
  852. if (!child_inode) {
  853. if (out_parent) {
  854. // ENOENT with a non-null parent custody signals to caller that
  855. // we found the immediate parent of the file, but the file itself
  856. // does not exist yet.
  857. *out_parent = have_more_parts ? nullptr : &parent;
  858. }
  859. return ENOENT;
  860. }
  861. int mount_flags_for_child = parent.mount_flags();
  862. // See if there's something mounted on the child; in that case
  863. // we would need to return the guest inode, not the host inode.
  864. if (auto mount = find_mount_for_host(*child_inode)) {
  865. child_inode = mount->guest();
  866. mount_flags_for_child = mount->flags();
  867. }
  868. custody = Custody::create(&parent, part, *child_inode, mount_flags_for_child);
  869. if (child_inode->metadata().is_symlink()) {
  870. if (!have_more_parts) {
  871. if (options & O_NOFOLLOW)
  872. return ELOOP;
  873. if (options & O_NOFOLLOW_NOERROR)
  874. break;
  875. }
  876. if (!safe_to_follow_symlink(*child_inode, parent_metadata))
  877. return EACCES;
  878. auto symlink_target = child_inode->resolve_as_link(parent, out_parent, options, symlink_recursion_level + 1);
  879. if (symlink_target.is_error() || !have_more_parts)
  880. return symlink_target;
  881. // Now, resolve the remaining path relative to the symlink target.
  882. // We prepend a "." to it to ensure that it's not empty and that
  883. // any initial slashes it might have get interpreted properly.
  884. StringBuilder remaining_path;
  885. remaining_path.append('.');
  886. remaining_path.append(path.substring_view_starting_after_substring(part));
  887. return resolve_path_without_veil(remaining_path.to_string(), *symlink_target.value(), out_parent, options, symlink_recursion_level + 1);
  888. }
  889. }
  890. if (out_parent)
  891. *out_parent = custody->parent();
  892. return custody;
  893. }
  894. }