FileSystem.cpp 11 KB

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