FileSystem.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  1. /*
  2. * Copyright (c) 2018-2021, Andreas Kling <andreas@ladybird.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_IOS) && defined(AK_OS_BSD_GENERIC)
  14. # include <sys/disk.h>
  15. #elif defined(AK_OS_LINUX)
  16. # include <linux/fs.h>
  17. #endif
  18. // On Linux distros that use glibc `basename` is defined as a macro that expands to `__xpg_basename`, so we undefine it
  19. #if defined(AK_OS_LINUX) && defined(basename)
  20. # undef basename
  21. #endif
  22. namespace FileSystem {
  23. ErrorOr<ByteString> current_working_directory()
  24. {
  25. return Core::System::getcwd();
  26. }
  27. ErrorOr<ByteString> absolute_path(StringView path)
  28. {
  29. if (exists(path))
  30. return real_path(path);
  31. if (path.starts_with("/"sv))
  32. return LexicalPath::canonicalized_path(path);
  33. auto working_directory = TRY(current_working_directory());
  34. return LexicalPath::absolute_path(working_directory, path);
  35. }
  36. ErrorOr<ByteString> real_path(StringView path)
  37. {
  38. if (path.is_null())
  39. return Error::from_errno(ENOENT);
  40. ByteString dep_path = path;
  41. char* real_path = realpath(dep_path.characters(), nullptr);
  42. ScopeGuard free_path = [real_path]() { free(real_path); };
  43. if (!real_path)
  44. return Error::from_syscall("realpath"sv, -errno);
  45. return ByteString { real_path, strlen(real_path) };
  46. }
  47. bool exists(StringView path)
  48. {
  49. return !Core::System::stat(path).is_error();
  50. }
  51. bool exists(int fd)
  52. {
  53. return !Core::System::fstat(fd).is_error();
  54. }
  55. bool is_regular_file(StringView path)
  56. {
  57. auto st_or_error = Core::System::stat(path);
  58. if (st_or_error.is_error())
  59. return false;
  60. auto st = st_or_error.release_value();
  61. return S_ISREG(st.st_mode);
  62. }
  63. bool is_regular_file(int fd)
  64. {
  65. auto st_or_error = Core::System::fstat(fd);
  66. if (st_or_error.is_error())
  67. return false;
  68. auto st = st_or_error.release_value();
  69. return S_ISREG(st.st_mode);
  70. }
  71. bool is_directory(StringView path)
  72. {
  73. auto st_or_error = Core::System::stat(path);
  74. if (st_or_error.is_error())
  75. return false;
  76. auto st = st_or_error.release_value();
  77. return S_ISDIR(st.st_mode);
  78. }
  79. bool is_directory(int fd)
  80. {
  81. auto st_or_error = Core::System::fstat(fd);
  82. if (st_or_error.is_error())
  83. return false;
  84. auto st = st_or_error.release_value();
  85. return S_ISDIR(st.st_mode);
  86. }
  87. bool is_link(StringView path)
  88. {
  89. auto st_or_error = Core::System::lstat(path);
  90. if (st_or_error.is_error())
  91. return false;
  92. auto st = st_or_error.release_value();
  93. return S_ISLNK(st.st_mode);
  94. }
  95. bool is_link(int fd)
  96. {
  97. auto st_or_error = Core::System::fstat(fd);
  98. if (st_or_error.is_error())
  99. return false;
  100. auto st = st_or_error.release_value();
  101. return S_ISLNK(st.st_mode);
  102. }
  103. static ErrorOr<ByteString> get_duplicate_file_name(StringView path)
  104. {
  105. int duplicate_count = 0;
  106. LexicalPath lexical_path(path);
  107. auto parent_path = LexicalPath::canonicalized_path(lexical_path.dirname());
  108. auto basename = lexical_path.basename();
  109. auto current_name = LexicalPath::join(parent_path, basename).string();
  110. while (exists(current_name)) {
  111. ++duplicate_count;
  112. current_name = LexicalPath::join(parent_path, ByteString::formatted("{} ({})", basename, duplicate_count)).string();
  113. }
  114. return current_name;
  115. }
  116. ErrorOr<void> copy_file(StringView destination_path, StringView source_path, struct stat const& source_stat, Core::File& source, PreserveMode preserve_mode)
  117. {
  118. auto destination_or_error = Core::File::open(destination_path, Core::File::OpenMode::Write, 0666);
  119. if (destination_or_error.is_error()) {
  120. if (destination_or_error.error().code() != EISDIR)
  121. return destination_or_error.release_error();
  122. auto destination_dir_path = ByteString::formatted("{}/{}", destination_path, LexicalPath::basename(source_path));
  123. destination_or_error = TRY(Core::File::open(destination_dir_path, Core::File::OpenMode::Write, 0666));
  124. }
  125. auto destination = destination_or_error.release_value();
  126. if (source_stat.st_size > 0)
  127. TRY(destination->truncate(source_stat.st_size));
  128. while (true) {
  129. auto bytes_read = TRY(source.read_until_eof());
  130. if (bytes_read.is_empty())
  131. break;
  132. TRY(destination->write_until_depleted(bytes_read));
  133. }
  134. auto my_umask = umask(0);
  135. umask(my_umask);
  136. // NOTE: We don't copy the set-uid and set-gid bits unless requested.
  137. if (!has_flag(preserve_mode, PreserveMode::Permissions))
  138. my_umask |= 06000;
  139. if (auto result = Core::System::fchmod(destination->fd(), source_stat.st_mode & ~my_umask); result.is_error())
  140. if (result.error().is_errno() && result.error().code() != ENOTSUP)
  141. return result.release_error();
  142. if (has_flag(preserve_mode, PreserveMode::Ownership))
  143. if (auto result = Core::System::fchown(destination->fd(), source_stat.st_uid, source_stat.st_gid); result.is_error())
  144. if (result.error().is_errno() && result.error().code() != ENOTSUP)
  145. return result.release_error();
  146. if (has_flag(preserve_mode, PreserveMode::Timestamps)) {
  147. struct timespec times[2] = {
  148. #if defined(AK_OS_MACOS) || defined(AK_OS_IOS)
  149. source_stat.st_atimespec,
  150. source_stat.st_mtimespec,
  151. #else
  152. source_stat.st_atim,
  153. source_stat.st_mtim,
  154. #endif
  155. };
  156. TRY(Core::System::utimensat(AT_FDCWD, destination_path, times, 0));
  157. }
  158. return {};
  159. }
  160. ErrorOr<void> copy_directory(StringView destination_path, StringView source_path, struct stat const& source_stat, LinkMode link, PreserveMode preserve_mode)
  161. {
  162. TRY(Core::System::mkdir(destination_path, 0755));
  163. auto source_rp = TRY(real_path(source_path));
  164. source_rp = ByteString::formatted("{}/", source_rp);
  165. auto destination_rp = TRY(real_path(destination_path));
  166. destination_rp = ByteString::formatted("{}/", destination_rp);
  167. if (!destination_rp.is_empty() && destination_rp.starts_with(source_rp))
  168. return Error::from_errno(EINVAL);
  169. Core::DirIterator di(source_path, Core::DirIterator::SkipParentAndBaseDir);
  170. if (di.has_error())
  171. return di.error();
  172. while (di.has_next()) {
  173. auto filename = di.next_path();
  174. TRY(copy_file_or_directory(
  175. ByteString::formatted("{}/{}", destination_path, filename),
  176. ByteString::formatted("{}/{}", source_path, filename),
  177. RecursionMode::Allowed, link, AddDuplicateFileMarker::Yes, preserve_mode));
  178. }
  179. auto my_umask = umask(0);
  180. umask(my_umask);
  181. TRY(Core::System::chmod(destination_path, source_stat.st_mode & ~my_umask));
  182. if (has_flag(preserve_mode, PreserveMode::Ownership))
  183. TRY(Core::System::chown(destination_path, source_stat.st_uid, source_stat.st_gid));
  184. if (has_flag(preserve_mode, PreserveMode::Timestamps)) {
  185. struct timespec times[2] = {
  186. #if defined(AK_OS_MACOS) || defined(AK_OS_IOS)
  187. source_stat.st_atimespec,
  188. source_stat.st_mtimespec,
  189. #else
  190. source_stat.st_atim,
  191. source_stat.st_mtim,
  192. #endif
  193. };
  194. TRY(Core::System::utimensat(AT_FDCWD, destination_path, times, 0));
  195. }
  196. return {};
  197. }
  198. 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)
  199. {
  200. ByteString final_destination_path;
  201. if (add_duplicate_file_marker == AddDuplicateFileMarker::Yes)
  202. final_destination_path = TRY(get_duplicate_file_name(destination_path));
  203. else
  204. final_destination_path = destination_path;
  205. auto source = TRY(Core::File::open(source_path, Core::File::OpenMode::Read));
  206. auto source_stat = TRY(Core::System::fstat(source->fd()));
  207. if (is_directory(source_path)) {
  208. if (recursion_mode == RecursionMode::Disallowed) {
  209. return Error::from_errno(EISDIR);
  210. }
  211. return copy_directory(final_destination_path, source_path, source_stat);
  212. }
  213. if (link_mode == LinkMode::Allowed)
  214. return TRY(Core::System::link(source_path, final_destination_path));
  215. return copy_file(final_destination_path, source_path, source_stat, *source, preserve_mode);
  216. }
  217. ErrorOr<void> move_file(StringView destination_path, StringView source_path, PreserveMode preserve_mode)
  218. {
  219. auto maybe_error = Core::System::rename(source_path, destination_path);
  220. if (!maybe_error.is_error())
  221. return {};
  222. if (!maybe_error.error().is_errno() || maybe_error.error().code() != EXDEV)
  223. return maybe_error;
  224. auto source = TRY(Core::File::open(source_path, Core::File::OpenMode::Read));
  225. auto source_stat = TRY(Core::System::fstat(source->fd()));
  226. TRY(copy_file(destination_path, source_path, source_stat, *source, preserve_mode));
  227. return Core::System::unlink(source_path);
  228. }
  229. ErrorOr<void> remove(StringView path, RecursionMode mode)
  230. {
  231. if (is_directory(path) && mode == RecursionMode::Allowed) {
  232. auto di = Core::DirIterator(path, Core::DirIterator::SkipParentAndBaseDir);
  233. if (di.has_error())
  234. return di.error();
  235. while (di.has_next())
  236. TRY(remove(di.next_full_path(), RecursionMode::Allowed));
  237. TRY(Core::System::rmdir(path));
  238. } else {
  239. TRY(Core::System::unlink(path));
  240. }
  241. return {};
  242. }
  243. ErrorOr<off_t> size_from_stat(StringView path)
  244. {
  245. auto st = TRY(Core::System::stat(path));
  246. return st.st_size;
  247. }
  248. ErrorOr<off_t> size_from_fstat(int fd)
  249. {
  250. auto st = TRY(Core::System::fstat(fd));
  251. return st.st_size;
  252. }
  253. bool can_delete_or_move(StringView path)
  254. {
  255. VERIFY(!path.is_empty());
  256. auto directory = LexicalPath::dirname(path);
  257. auto directory_has_write_access = !Core::System::access(directory, W_OK).is_error();
  258. if (!directory_has_write_access)
  259. return false;
  260. auto stat_or_empty = [](StringView path) {
  261. auto stat_or_error = Core::System::stat(path);
  262. if (stat_or_error.is_error()) {
  263. struct stat stat { };
  264. return stat;
  265. }
  266. return stat_or_error.release_value();
  267. };
  268. auto directory_stat = stat_or_empty(directory);
  269. bool is_directory_sticky = (directory_stat.st_mode & S_ISVTX) != 0;
  270. if (!is_directory_sticky)
  271. return true;
  272. // Directory is sticky, only the file owner, directory owner, and root can modify (rename, remove) it.
  273. auto user_id = geteuid();
  274. return user_id == 0 || directory_stat.st_uid == user_id || stat_or_empty(path).st_uid == user_id;
  275. }
  276. }