VirtualFileSystem.cpp 38 KB

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