VirtualFileSystem.cpp 35 KB

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