FileSystem.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457
  1. /*
  2. * Copyright (c) 2018-2021, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2023, Cameron Youell <cameronyouell@gmail.com>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include <AK/LexicalPath.h>
  8. #include <AK/ScopeGuard.h>
  9. #include <LibCore/DirIterator.h>
  10. #include <LibCore/System.h>
  11. #include <LibFileSystem/FileSystem.h>
  12. #include <limits.h>
  13. #if defined(AK_OS_SERENITY)
  14. # include <serenity.h>
  15. #elif !defined(AK_OS_IOS) && defined(AK_OS_BSD_GENERIC)
  16. # include <sys/disk.h>
  17. #elif defined(AK_OS_LINUX)
  18. # include <linux/fs.h>
  19. #endif
  20. // On Linux distros that use glibc `basename` is defined as a macro that expands to `__xpg_basename`, so we undefine it
  21. #if defined(AK_OS_LINUX) && defined(basename)
  22. # undef basename
  23. #endif
  24. namespace FileSystem {
  25. ErrorOr<ByteString> current_working_directory()
  26. {
  27. return Core::System::getcwd();
  28. }
  29. ErrorOr<ByteString> absolute_path(StringView path)
  30. {
  31. if (exists(path))
  32. return real_path(path);
  33. if (path.starts_with("/"sv))
  34. return LexicalPath::canonicalized_path(path);
  35. auto working_directory = TRY(current_working_directory());
  36. return LexicalPath::absolute_path(working_directory, path);
  37. }
  38. ErrorOr<ByteString> real_path(StringView path)
  39. {
  40. if (path.is_null())
  41. return Error::from_errno(ENOENT);
  42. ByteString dep_path = path;
  43. char* real_path = realpath(dep_path.characters(), nullptr);
  44. ScopeGuard free_path = [real_path]() { free(real_path); };
  45. if (!real_path)
  46. return Error::from_syscall("realpath"sv, -errno);
  47. return ByteString { real_path, strlen(real_path) };
  48. }
  49. bool exists(StringView path)
  50. {
  51. return !Core::System::stat(path).is_error();
  52. }
  53. bool exists(int fd)
  54. {
  55. return !Core::System::fstat(fd).is_error();
  56. }
  57. bool is_device(StringView path)
  58. {
  59. auto st_or_error = Core::System::stat(path);
  60. if (st_or_error.is_error())
  61. return false;
  62. auto st = st_or_error.release_value();
  63. return S_ISBLK(st.st_mode) || S_ISCHR(st.st_mode);
  64. }
  65. bool is_device(int fd)
  66. {
  67. auto st_or_error = Core::System::fstat(fd);
  68. if (st_or_error.is_error())
  69. return false;
  70. auto st = st_or_error.release_value();
  71. return S_ISBLK(st.st_mode) || S_ISCHR(st.st_mode);
  72. }
  73. bool is_block_device(StringView path)
  74. {
  75. auto st_or_error = Core::System::stat(path);
  76. if (st_or_error.is_error())
  77. return false;
  78. auto st = st_or_error.release_value();
  79. return S_ISBLK(st.st_mode);
  80. }
  81. bool is_block_device(int fd)
  82. {
  83. auto st_or_error = Core::System::fstat(fd);
  84. if (st_or_error.is_error())
  85. return false;
  86. auto st = st_or_error.release_value();
  87. return S_ISBLK(st.st_mode);
  88. }
  89. bool is_char_device(StringView path)
  90. {
  91. auto st_or_error = Core::System::stat(path);
  92. if (st_or_error.is_error())
  93. return false;
  94. auto st = st_or_error.release_value();
  95. return S_ISCHR(st.st_mode);
  96. }
  97. bool is_char_device(int fd)
  98. {
  99. auto st_or_error = Core::System::fstat(fd);
  100. if (st_or_error.is_error())
  101. return false;
  102. auto st = st_or_error.release_value();
  103. return S_ISCHR(st.st_mode);
  104. }
  105. bool is_regular_file(StringView path)
  106. {
  107. auto st_or_error = Core::System::stat(path);
  108. if (st_or_error.is_error())
  109. return false;
  110. auto st = st_or_error.release_value();
  111. return S_ISREG(st.st_mode);
  112. }
  113. bool is_regular_file(int fd)
  114. {
  115. auto st_or_error = Core::System::fstat(fd);
  116. if (st_or_error.is_error())
  117. return false;
  118. auto st = st_or_error.release_value();
  119. return S_ISREG(st.st_mode);
  120. }
  121. bool is_directory(StringView path)
  122. {
  123. auto st_or_error = Core::System::stat(path);
  124. if (st_or_error.is_error())
  125. return false;
  126. auto st = st_or_error.release_value();
  127. return S_ISDIR(st.st_mode);
  128. }
  129. bool is_directory(int fd)
  130. {
  131. auto st_or_error = Core::System::fstat(fd);
  132. if (st_or_error.is_error())
  133. return false;
  134. auto st = st_or_error.release_value();
  135. return S_ISDIR(st.st_mode);
  136. }
  137. bool is_link(StringView path)
  138. {
  139. auto st_or_error = Core::System::lstat(path);
  140. if (st_or_error.is_error())
  141. return false;
  142. auto st = st_or_error.release_value();
  143. return S_ISLNK(st.st_mode);
  144. }
  145. bool is_link(int fd)
  146. {
  147. auto st_or_error = Core::System::fstat(fd);
  148. if (st_or_error.is_error())
  149. return false;
  150. auto st = st_or_error.release_value();
  151. return S_ISLNK(st.st_mode);
  152. }
  153. static ErrorOr<ByteString> get_duplicate_file_name(StringView path)
  154. {
  155. int duplicate_count = 0;
  156. LexicalPath lexical_path(path);
  157. auto parent_path = LexicalPath::canonicalized_path(lexical_path.dirname());
  158. auto basename = lexical_path.basename();
  159. auto current_name = LexicalPath::join(parent_path, basename).string();
  160. while (exists(current_name)) {
  161. ++duplicate_count;
  162. current_name = LexicalPath::join(parent_path, ByteString::formatted("{} ({})", basename, duplicate_count)).string();
  163. }
  164. return current_name;
  165. }
  166. ErrorOr<void> copy_file(StringView destination_path, StringView source_path, struct stat const& source_stat, Core::File& source, PreserveMode preserve_mode)
  167. {
  168. auto destination_or_error = Core::File::open(destination_path, Core::File::OpenMode::Write, 0666);
  169. if (destination_or_error.is_error()) {
  170. if (destination_or_error.error().code() != EISDIR)
  171. return destination_or_error.release_error();
  172. auto destination_dir_path = ByteString::formatted("{}/{}", destination_path, LexicalPath::basename(source_path));
  173. destination_or_error = TRY(Core::File::open(destination_dir_path, Core::File::OpenMode::Write, 0666));
  174. }
  175. auto destination = destination_or_error.release_value();
  176. if (source_stat.st_size > 0)
  177. TRY(destination->truncate(source_stat.st_size));
  178. while (true) {
  179. auto bytes_read = TRY(source.read_until_eof());
  180. if (bytes_read.is_empty())
  181. break;
  182. TRY(destination->write_until_depleted(bytes_read));
  183. }
  184. auto my_umask = umask(0);
  185. umask(my_umask);
  186. // NOTE: We don't copy the set-uid and set-gid bits unless requested.
  187. if (!has_flag(preserve_mode, PreserveMode::Permissions))
  188. my_umask |= 06000;
  189. TRY(Core::System::fchmod(destination->fd(), source_stat.st_mode & ~my_umask));
  190. if (has_flag(preserve_mode, PreserveMode::Ownership))
  191. TRY(Core::System::fchown(destination->fd(), source_stat.st_uid, source_stat.st_gid));
  192. if (has_flag(preserve_mode, PreserveMode::Timestamps)) {
  193. struct timespec times[2] = {
  194. #if defined(AK_OS_MACOS) || defined(AK_OS_IOS)
  195. source_stat.st_atimespec,
  196. source_stat.st_mtimespec,
  197. #else
  198. source_stat.st_atim,
  199. source_stat.st_mtim,
  200. #endif
  201. };
  202. TRY(Core::System::utimensat(AT_FDCWD, destination_path, times, 0));
  203. }
  204. return {};
  205. }
  206. ErrorOr<void> copy_directory(StringView destination_path, StringView source_path, struct stat const& source_stat, LinkMode link, PreserveMode preserve_mode)
  207. {
  208. TRY(Core::System::mkdir(destination_path, 0755));
  209. auto source_rp = TRY(real_path(source_path));
  210. source_rp = ByteString::formatted("{}/", source_rp);
  211. auto destination_rp = TRY(real_path(destination_path));
  212. destination_rp = ByteString::formatted("{}/", destination_rp);
  213. if (!destination_rp.is_empty() && destination_rp.starts_with(source_rp))
  214. return Error::from_errno(EINVAL);
  215. Core::DirIterator di(source_path, Core::DirIterator::SkipParentAndBaseDir);
  216. if (di.has_error())
  217. return di.error();
  218. while (di.has_next()) {
  219. auto filename = di.next_path();
  220. TRY(copy_file_or_directory(
  221. ByteString::formatted("{}/{}", destination_path, filename),
  222. ByteString::formatted("{}/{}", source_path, filename),
  223. RecursionMode::Allowed, link, AddDuplicateFileMarker::Yes, preserve_mode));
  224. }
  225. auto my_umask = umask(0);
  226. umask(my_umask);
  227. TRY(Core::System::chmod(destination_path, source_stat.st_mode & ~my_umask));
  228. if (has_flag(preserve_mode, PreserveMode::Ownership))
  229. TRY(Core::System::chown(destination_path, source_stat.st_uid, source_stat.st_gid));
  230. if (has_flag(preserve_mode, PreserveMode::Timestamps)) {
  231. struct timespec times[2] = {
  232. #if defined(AK_OS_MACOS) || defined(AK_OS_IOS)
  233. source_stat.st_atimespec,
  234. source_stat.st_mtimespec,
  235. #else
  236. source_stat.st_atim,
  237. source_stat.st_mtim,
  238. #endif
  239. };
  240. TRY(Core::System::utimensat(AT_FDCWD, destination_path, times, 0));
  241. }
  242. return {};
  243. }
  244. ErrorOr<void> copy_file_or_directory(StringView destination_path, StringView source_path, RecursionMode recursion_mode, LinkMode link_mode, AddDuplicateFileMarker add_duplicate_file_marker, PreserveMode preserve_mode)
  245. {
  246. ByteString final_destination_path;
  247. if (add_duplicate_file_marker == AddDuplicateFileMarker::Yes)
  248. final_destination_path = TRY(get_duplicate_file_name(destination_path));
  249. else
  250. final_destination_path = destination_path;
  251. auto source = TRY(Core::File::open(source_path, Core::File::OpenMode::Read));
  252. auto source_stat = TRY(Core::System::fstat(source->fd()));
  253. if (is_directory(source_path)) {
  254. if (recursion_mode == RecursionMode::Disallowed) {
  255. return Error::from_errno(EISDIR);
  256. }
  257. return copy_directory(final_destination_path, source_path, source_stat);
  258. }
  259. if (link_mode == LinkMode::Allowed)
  260. return TRY(Core::System::link(source_path, final_destination_path));
  261. return copy_file(final_destination_path, source_path, source_stat, *source, preserve_mode);
  262. }
  263. ErrorOr<void> move_file(StringView destination_path, StringView source_path, PreserveMode preserve_mode)
  264. {
  265. auto maybe_error = Core::System::rename(source_path, destination_path);
  266. if (!maybe_error.is_error())
  267. return {};
  268. if (!maybe_error.error().is_errno() || maybe_error.error().code() != EXDEV)
  269. return maybe_error;
  270. auto source = TRY(Core::File::open(source_path, Core::File::OpenMode::Read));
  271. auto source_stat = TRY(Core::System::fstat(source->fd()));
  272. TRY(copy_file(destination_path, source_path, source_stat, *source, preserve_mode));
  273. return Core::System::unlink(source_path);
  274. }
  275. ErrorOr<void> remove(StringView path, RecursionMode mode)
  276. {
  277. if (is_directory(path) && mode == RecursionMode::Allowed) {
  278. auto di = Core::DirIterator(path, Core::DirIterator::SkipParentAndBaseDir);
  279. if (di.has_error())
  280. return di.error();
  281. while (di.has_next())
  282. TRY(remove(di.next_full_path(), RecursionMode::Allowed));
  283. TRY(Core::System::rmdir(path));
  284. } else {
  285. TRY(Core::System::unlink(path));
  286. }
  287. return {};
  288. }
  289. ErrorOr<off_t> size_from_stat(StringView path)
  290. {
  291. auto st = TRY(Core::System::stat(path));
  292. return st.st_size;
  293. }
  294. ErrorOr<off_t> size_from_fstat(int fd)
  295. {
  296. auto st = TRY(Core::System::fstat(fd));
  297. return st.st_size;
  298. }
  299. ErrorOr<off_t> block_device_size_from_ioctl(StringView path)
  300. {
  301. if (!path.characters_without_null_termination())
  302. return Error::from_syscall("ioctl"sv, -EFAULT);
  303. ByteString path_string = path;
  304. int fd = open(path_string.characters(), O_RDONLY);
  305. if (fd < 0)
  306. return Error::from_errno(errno);
  307. off_t size = TRY(block_device_size_from_ioctl(fd));
  308. if (close(fd) != 0)
  309. return Error::from_errno(errno);
  310. return size;
  311. }
  312. ErrorOr<off_t> block_device_size_from_ioctl(int fd)
  313. {
  314. #if defined(AK_OS_SERENITY)
  315. u64 size = 0;
  316. TRY(Core::System::ioctl(fd, STORAGE_DEVICE_GET_SIZE, &size));
  317. return static_cast<off_t>(size);
  318. #elif defined(AK_OS_MACOS)
  319. u64 block_count = 0;
  320. u32 block_size = 0;
  321. TRY(Core::System::ioctl(fd, DKIOCGETBLOCKCOUNT, &block_count));
  322. TRY(Core::System::ioctl(fd, DKIOCGETBLOCKSIZE, &block_size));
  323. return static_cast<off_t>(block_count * block_size);
  324. #elif defined(AK_OS_FREEBSD) || defined(AK_OS_NETBSD)
  325. off_t size = 0;
  326. TRY(Core::System::ioctl(fd, DIOCGMEDIASIZE, &size));
  327. return size;
  328. #elif defined(AK_OS_LINUX)
  329. u64 size = 0;
  330. TRY(Core::System::ioctl(fd, BLKGETSIZE64, &size));
  331. return static_cast<off_t>(size);
  332. #else
  333. // FIXME: Add support for more platforms.
  334. (void)fd;
  335. return Error::from_string_literal("Platform does not support getting block device size");
  336. #endif
  337. }
  338. bool can_delete_or_move(StringView path)
  339. {
  340. VERIFY(!path.is_empty());
  341. auto directory = LexicalPath::dirname(path);
  342. auto directory_has_write_access = !Core::System::access(directory, W_OK).is_error();
  343. if (!directory_has_write_access)
  344. return false;
  345. auto stat_or_empty = [](StringView path) {
  346. auto stat_or_error = Core::System::stat(path);
  347. if (stat_or_error.is_error()) {
  348. struct stat stat { };
  349. return stat;
  350. }
  351. return stat_or_error.release_value();
  352. };
  353. auto directory_stat = stat_or_empty(directory);
  354. bool is_directory_sticky = (directory_stat.st_mode & S_ISVTX) != 0;
  355. if (!is_directory_sticky)
  356. return true;
  357. // Directory is sticky, only the file owner, directory owner, and root can modify (rename, remove) it.
  358. auto user_id = geteuid();
  359. return user_id == 0 || directory_stat.st_uid == user_id || stat_or_empty(path).st_uid == user_id;
  360. }
  361. ErrorOr<ByteString> read_link(StringView link_path)
  362. {
  363. return Core::System::readlink(link_path);
  364. }
  365. ErrorOr<void> link_file(StringView destination_path, StringView source_path)
  366. {
  367. return TRY(Core::System::symlink(source_path, TRY(get_duplicate_file_name(destination_path))));
  368. }
  369. bool looks_like_shared_library(StringView path)
  370. {
  371. return path.ends_with(".so"sv) || path.contains(".so."sv);
  372. }
  373. }