VirtualFileSystem.cpp 38 KB

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