FileSystem.cpp 11 KB

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