VirtualFileSystem.cpp 35 KB

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