FileSystem.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395
  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 <LibCore/DirIterator.h>
  9. #include <LibCore/System.h>
  10. #include <LibFileSystem/FileSystem.h>
  11. #ifdef AK_OS_SERENITY
  12. # include <serenity.h>
  13. #endif
  14. // On Linux distros that use glibc `basename` is defined as a macro that expands to `__xpg_basename`, so we undefine it
  15. #if defined(AK_OS_LINUX) && defined(basename)
  16. # undef basename
  17. #endif
  18. namespace FileSystem {
  19. ErrorOr<String> current_working_directory()
  20. {
  21. auto cwd = TRY(Core::System::getcwd());
  22. return TRY(String::from_deprecated_string({ cwd }));
  23. }
  24. ErrorOr<String> absolute_path(StringView path)
  25. {
  26. if (exists(path))
  27. return TRY(real_path(path));
  28. if (path.starts_with("/"sv))
  29. return TRY(String::from_deprecated_string(LexicalPath::canonicalized_path(path)));
  30. auto working_directory = TRY(current_working_directory());
  31. auto full_path = LexicalPath::join(working_directory, path).string();
  32. return TRY(String::from_deprecated_string(LexicalPath::canonicalized_path(full_path)));
  33. }
  34. ErrorOr<String> real_path(StringView path)
  35. {
  36. if (path.is_null())
  37. return Error::from_errno(ENOENT);
  38. DeprecatedString dep_path = path;
  39. auto* real_path = realpath(dep_path.characters(), nullptr);
  40. if (!real_path)
  41. return Error::from_syscall("realpath"sv, -errno);
  42. return TRY(String::from_deprecated_string({ real_path }));
  43. }
  44. bool exists(StringView path)
  45. {
  46. return !Core::System::stat(path).is_error();
  47. }
  48. bool exists(int fd)
  49. {
  50. return !Core::System::fstat(fd).is_error();
  51. }
  52. bool is_device(StringView path)
  53. {
  54. auto st_or_error = Core::System::stat(path);
  55. if (st_or_error.is_error())
  56. return false;
  57. auto st = st_or_error.release_value();
  58. return S_ISBLK(st.st_mode) || S_ISCHR(st.st_mode);
  59. }
  60. bool is_device(int fd)
  61. {
  62. auto st_or_error = Core::System::fstat(fd);
  63. if (st_or_error.is_error())
  64. return false;
  65. auto st = st_or_error.release_value();
  66. return S_ISBLK(st.st_mode) || S_ISCHR(st.st_mode);
  67. }
  68. bool is_block_device(StringView path)
  69. {
  70. auto st_or_error = Core::System::stat(path);
  71. if (st_or_error.is_error())
  72. return false;
  73. auto st = st_or_error.release_value();
  74. return S_ISBLK(st.st_mode);
  75. }
  76. bool is_block_device(int fd)
  77. {
  78. auto st_or_error = Core::System::fstat(fd);
  79. if (st_or_error.is_error())
  80. return false;
  81. auto st = st_or_error.release_value();
  82. return S_ISBLK(st.st_mode);
  83. }
  84. bool is_char_device(StringView path)
  85. {
  86. auto st_or_error = Core::System::stat(path);
  87. if (st_or_error.is_error())
  88. return false;
  89. auto st = st_or_error.release_value();
  90. return S_ISCHR(st.st_mode);
  91. }
  92. bool is_char_device(int fd)
  93. {
  94. auto st_or_error = Core::System::fstat(fd);
  95. if (st_or_error.is_error())
  96. return false;
  97. auto st = st_or_error.release_value();
  98. return S_ISCHR(st.st_mode);
  99. }
  100. bool is_directory(StringView path)
  101. {
  102. auto st_or_error = Core::System::stat(path);
  103. if (st_or_error.is_error())
  104. return false;
  105. auto st = st_or_error.release_value();
  106. return S_ISDIR(st.st_mode);
  107. }
  108. bool is_directory(int fd)
  109. {
  110. auto st_or_error = Core::System::fstat(fd);
  111. if (st_or_error.is_error())
  112. return false;
  113. auto st = st_or_error.release_value();
  114. return S_ISDIR(st.st_mode);
  115. }
  116. bool is_link(StringView path)
  117. {
  118. auto st_or_error = Core::System::lstat(path);
  119. if (st_or_error.is_error())
  120. return false;
  121. auto st = st_or_error.release_value();
  122. return S_ISLNK(st.st_mode);
  123. }
  124. bool is_link(int fd)
  125. {
  126. auto st_or_error = Core::System::fstat(fd);
  127. if (st_or_error.is_error())
  128. return false;
  129. auto st = st_or_error.release_value();
  130. return S_ISLNK(st.st_mode);
  131. }
  132. static ErrorOr<String> get_duplicate_file_name(StringView path)
  133. {
  134. int duplicate_count = 0;
  135. LexicalPath lexical_path(path);
  136. auto parent_path = LexicalPath::canonicalized_path(lexical_path.dirname());
  137. auto basename = lexical_path.basename();
  138. auto current_name = TRY(String::from_deprecated_string(LexicalPath::join(parent_path, basename).string()));
  139. while (exists(current_name)) {
  140. ++duplicate_count;
  141. current_name = TRY(String::from_deprecated_string(LexicalPath::join(parent_path, TRY(String::formatted("{} ({})", basename, duplicate_count))).string()));
  142. }
  143. return current_name;
  144. }
  145. ErrorOr<void> copy_file(StringView destination_path, StringView source_path, struct stat const& source_stat, Core::File& source, PreserveMode preserve_mode)
  146. {
  147. auto destination_or_error = Core::File::open(destination_path, Core::File::OpenMode::Write, 0666);
  148. if (destination_or_error.is_error()) {
  149. if (destination_or_error.error().code() != EISDIR)
  150. return destination_or_error.release_error();
  151. auto destination_dir_path = TRY(String::formatted("{}/{}", destination_path, LexicalPath::basename(source_path)));
  152. destination_or_error = TRY(Core::File::open(destination_dir_path, Core::File::OpenMode::Write, 0666));
  153. }
  154. auto destination = destination_or_error.release_value();
  155. if (source_stat.st_size > 0)
  156. TRY(destination->truncate(source_stat.st_size));
  157. while (true) {
  158. auto bytes_read = TRY(source.read_until_eof());
  159. if (bytes_read.is_empty())
  160. break;
  161. TRY(destination->write_until_depleted(bytes_read));
  162. }
  163. auto my_umask = umask(0);
  164. umask(my_umask);
  165. // NOTE: We don't copy the set-uid and set-gid bits unless requested.
  166. if (!has_flag(preserve_mode, PreserveMode::Permissions))
  167. my_umask |= 06000;
  168. TRY(Core::System::fchmod(destination->fd(), source_stat.st_mode & ~my_umask));
  169. if (has_flag(preserve_mode, PreserveMode::Ownership))
  170. TRY(Core::System::fchown(destination->fd(), source_stat.st_uid, source_stat.st_gid));
  171. if (has_flag(preserve_mode, PreserveMode::Timestamps)) {
  172. struct timespec times[2] = {
  173. #ifdef AK_OS_MACOS
  174. source_stat.st_atimespec,
  175. source_stat.st_mtimespec,
  176. #else
  177. source_stat.st_atim,
  178. source_stat.st_mtim,
  179. #endif
  180. };
  181. TRY(Core::System::utimensat(AT_FDCWD, destination_path, times, 0));
  182. }
  183. return {};
  184. }
  185. ErrorOr<void> copy_directory(StringView destination_path, StringView source_path, struct stat const& source_stat, LinkMode link, PreserveMode preserve_mode)
  186. {
  187. TRY(Core::System::mkdir(destination_path, 0755));
  188. auto source_rp = TRY(real_path(source_path));
  189. source_rp = TRY(String::formatted("{}/", source_rp));
  190. auto destination_rp = TRY(real_path(destination_path));
  191. destination_rp = TRY(String::formatted("{}/", destination_rp));
  192. if (!destination_rp.is_empty() && destination_rp.starts_with_bytes(source_rp))
  193. return Error::from_errno(EINVAL);
  194. Core::DirIterator di(source_path, Core::DirIterator::SkipParentAndBaseDir);
  195. if (di.has_error())
  196. return di.error();
  197. while (di.has_next()) {
  198. auto filename = TRY(String::from_deprecated_string(di.next_path()));
  199. TRY(copy_file_or_directory(
  200. TRY(String::formatted("{}/{}", destination_path, filename)),
  201. TRY(String::formatted("{}/{}", source_path, filename)),
  202. RecursionMode::Allowed, link, AddDuplicateFileMarker::Yes, preserve_mode));
  203. }
  204. auto my_umask = umask(0);
  205. umask(my_umask);
  206. TRY(Core::System::chmod(destination_path, source_stat.st_mode & ~my_umask));
  207. if (has_flag(preserve_mode, PreserveMode::Ownership))
  208. TRY(Core::System::chown(destination_path, source_stat.st_uid, source_stat.st_gid));
  209. if (has_flag(preserve_mode, PreserveMode::Timestamps)) {
  210. struct timespec times[2] = {
  211. #ifdef AK_OS_MACOS
  212. source_stat.st_atimespec,
  213. source_stat.st_mtimespec,
  214. #else
  215. source_stat.st_atim,
  216. source_stat.st_mtim,
  217. #endif
  218. };
  219. TRY(Core::System::utimensat(AT_FDCWD, destination_path, times, 0));
  220. }
  221. return {};
  222. }
  223. 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)
  224. {
  225. String final_destination_path;
  226. if (add_duplicate_file_marker == AddDuplicateFileMarker::Yes)
  227. final_destination_path = TRY(get_duplicate_file_name(destination_path));
  228. else
  229. final_destination_path = TRY(String::from_utf8(destination_path));
  230. auto source = TRY(Core::File::open(source_path, Core::File::OpenMode::Read));
  231. auto source_stat = TRY(Core::System::fstat(source->fd()));
  232. if (is_directory(source_path)) {
  233. if (recursion_mode == RecursionMode::Disallowed) {
  234. return Error::from_errno(EISDIR);
  235. }
  236. return copy_directory(final_destination_path, source_path, source_stat);
  237. }
  238. if (link_mode == LinkMode::Allowed)
  239. return TRY(Core::System::link(source_path, final_destination_path));
  240. return copy_file(final_destination_path, source_path, source_stat, *source, preserve_mode);
  241. }
  242. ErrorOr<void> remove(StringView path, RecursionMode mode)
  243. {
  244. if (is_directory(path) && mode == RecursionMode::Allowed) {
  245. auto di = Core::DirIterator(path, Core::DirIterator::SkipParentAndBaseDir);
  246. if (di.has_error())
  247. return di.error();
  248. while (di.has_next())
  249. TRY(remove(di.next_full_path(), RecursionMode::Allowed));
  250. TRY(Core::System::rmdir(path));
  251. } else {
  252. TRY(Core::System::unlink(path));
  253. }
  254. return {};
  255. }
  256. ErrorOr<size_t> size(StringView path)
  257. {
  258. auto st = TRY(Core::System::stat(path));
  259. return st.st_size;
  260. }
  261. bool can_delete_or_move(StringView path)
  262. {
  263. VERIFY(!path.is_empty());
  264. auto directory = LexicalPath::dirname(path);
  265. auto directory_has_write_access = !Core::System::access(directory, W_OK).is_error();
  266. if (!directory_has_write_access)
  267. return false;
  268. auto stat_or_empty = [](StringView path) {
  269. auto stat_or_error = Core::System::stat(path);
  270. if (stat_or_error.is_error()) {
  271. struct stat stat { };
  272. return stat;
  273. }
  274. return stat_or_error.release_value();
  275. };
  276. auto directory_stat = stat_or_empty(directory);
  277. bool is_directory_sticky = (directory_stat.st_mode & S_ISVTX) != 0;
  278. if (!is_directory_sticky)
  279. return true;
  280. // Directory is sticky, only the file owner, directory owner, and root can modify (rename, remove) it.
  281. auto user_id = geteuid();
  282. return user_id == 0 || directory_stat.st_uid == user_id || stat_or_empty(path).st_uid == user_id;
  283. }
  284. ErrorOr<String> read_link(StringView link_path)
  285. {
  286. return TRY(String::from_deprecated_string(TRY(Core::System::readlink(link_path))));
  287. }
  288. ErrorOr<void> link_file(StringView destination_path, StringView source_path)
  289. {
  290. return TRY(Core::System::symlink(source_path, TRY(get_duplicate_file_name(destination_path))));
  291. }
  292. ErrorOr<String> resolve_executable_from_environment(StringView filename)
  293. {
  294. if (filename.is_empty())
  295. return Error::from_errno(ENOENT);
  296. // Paths that aren't just a file name generally count as already resolved.
  297. if (filename.contains('/')) {
  298. TRY(Core::System::access(filename, X_OK));
  299. return TRY(String::from_utf8(filename));
  300. }
  301. auto const* path_str = ::getenv("PATH");
  302. StringView path;
  303. if (path_str)
  304. path = { path_str, strlen(path_str) };
  305. if (path.is_empty())
  306. path = DEFAULT_PATH_SV;
  307. auto directories = path.split_view(':');
  308. for (auto directory : directories) {
  309. auto file = TRY(String::formatted("{}/{}", directory, filename));
  310. if (!Core::System::access(file, X_OK).is_error())
  311. return file;
  312. }
  313. return Error::from_errno(ENOENT);
  314. }
  315. bool looks_like_shared_library(StringView path)
  316. {
  317. return path.ends_with(".so"sv) || path.contains(".so."sv);
  318. }
  319. }