DeprecatedFile.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467
  1. /*
  2. * Copyright (c) 2018-2022, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/LexicalPath.h>
  7. #include <AK/Platform.h>
  8. #include <AK/ScopeGuard.h>
  9. #include <LibCore/DeprecatedFile.h>
  10. #include <LibCore/DirIterator.h>
  11. #include <LibCore/System.h>
  12. #include <LibFileSystem/FileSystem.h>
  13. #include <errno.h>
  14. #include <fcntl.h>
  15. #include <libgen.h>
  16. #include <stdio.h>
  17. #include <string.h>
  18. #include <sys/stat.h>
  19. #include <unistd.h>
  20. #include <utime.h>
  21. #ifdef AK_OS_SERENITY
  22. # include <serenity.h>
  23. #endif
  24. // On Linux distros that use glibc `basename` is defined as a macro that expands to `__xpg_basename`, so we undefine it
  25. #if defined(AK_OS_LINUX) && defined(basename)
  26. # undef basename
  27. #endif
  28. namespace Core {
  29. ErrorOr<NonnullRefPtr<DeprecatedFile>> DeprecatedFile::open(DeprecatedString filename, OpenMode mode, mode_t permissions)
  30. {
  31. auto file = DeprecatedFile::construct(move(filename));
  32. if (!file->open_impl(mode, permissions))
  33. return Error::from_errno(file->error());
  34. return file;
  35. }
  36. DeprecatedFile::DeprecatedFile(DeprecatedString filename, Object* parent)
  37. : IODevice(parent)
  38. , m_filename(move(filename))
  39. {
  40. }
  41. DeprecatedFile::~DeprecatedFile()
  42. {
  43. if (m_should_close_file_descriptor == ShouldCloseFileDescriptor::Yes && mode() != OpenMode::NotOpen)
  44. close();
  45. }
  46. bool DeprecatedFile::open(int fd, OpenMode mode, ShouldCloseFileDescriptor should_close)
  47. {
  48. set_fd(fd);
  49. set_mode(mode);
  50. m_should_close_file_descriptor = should_close;
  51. return true;
  52. }
  53. bool DeprecatedFile::open(OpenMode mode)
  54. {
  55. return open_impl(mode, 0666);
  56. }
  57. bool DeprecatedFile::open_impl(OpenMode mode, mode_t permissions)
  58. {
  59. VERIFY(!m_filename.is_null());
  60. int flags = 0;
  61. if (has_flag(mode, OpenMode::ReadOnly) && has_flag(mode, OpenMode::WriteOnly)) {
  62. flags |= O_RDWR | O_CREAT;
  63. } else if (has_flag(mode, OpenMode::ReadOnly)) {
  64. flags |= O_RDONLY;
  65. } else if (has_flag(mode, OpenMode::WriteOnly)) {
  66. flags |= O_WRONLY | O_CREAT;
  67. bool should_truncate = !(has_flag(mode, OpenMode::Append) || has_flag(mode, OpenMode::MustBeNew));
  68. if (should_truncate)
  69. flags |= O_TRUNC;
  70. }
  71. if (has_flag(mode, OpenMode::Append))
  72. flags |= O_APPEND;
  73. if (has_flag(mode, OpenMode::Truncate))
  74. flags |= O_TRUNC;
  75. if (has_flag(mode, OpenMode::MustBeNew))
  76. flags |= O_EXCL;
  77. if (!has_flag(mode, OpenMode::KeepOnExec))
  78. flags |= O_CLOEXEC;
  79. int fd = ::open(m_filename.characters(), flags, permissions);
  80. if (fd < 0) {
  81. set_error(errno);
  82. return false;
  83. }
  84. set_fd(fd);
  85. set_mode(mode);
  86. return true;
  87. }
  88. int DeprecatedFile::leak_fd()
  89. {
  90. m_should_close_file_descriptor = ShouldCloseFileDescriptor::No;
  91. return fd();
  92. }
  93. bool DeprecatedFile::is_device() const
  94. {
  95. struct stat st;
  96. if (fstat(fd(), &st) < 0)
  97. return false;
  98. return S_ISBLK(st.st_mode) || S_ISCHR(st.st_mode);
  99. }
  100. bool DeprecatedFile::is_block_device() const
  101. {
  102. struct stat stat;
  103. if (fstat(fd(), &stat) < 0)
  104. return false;
  105. return S_ISBLK(stat.st_mode);
  106. }
  107. bool DeprecatedFile::is_char_device() const
  108. {
  109. struct stat stat;
  110. if (fstat(fd(), &stat) < 0)
  111. return false;
  112. return S_ISCHR(stat.st_mode);
  113. }
  114. bool DeprecatedFile::is_directory() const
  115. {
  116. struct stat st;
  117. if (fstat(fd(), &st) < 0)
  118. return false;
  119. return S_ISDIR(st.st_mode);
  120. }
  121. bool DeprecatedFile::is_link() const
  122. {
  123. struct stat stat;
  124. if (fstat(fd(), &stat) < 0)
  125. return false;
  126. return S_ISLNK(stat.st_mode);
  127. }
  128. DeprecatedString DeprecatedFile::real_path_for(DeprecatedString const& filename)
  129. {
  130. if (filename.is_null())
  131. return {};
  132. auto* path = realpath(filename.characters(), nullptr);
  133. DeprecatedString real_path(path);
  134. free(path);
  135. return real_path;
  136. }
  137. DeprecatedString DeprecatedFile::current_working_directory()
  138. {
  139. char* cwd = getcwd(nullptr, 0);
  140. if (!cwd) {
  141. perror("getcwd");
  142. return {};
  143. }
  144. auto cwd_as_string = DeprecatedString(cwd);
  145. free(cwd);
  146. return cwd_as_string;
  147. }
  148. DeprecatedString DeprecatedFile::absolute_path(DeprecatedString const& path)
  149. {
  150. if (!Core::System::stat(path).is_error())
  151. return DeprecatedFile::real_path_for(path);
  152. if (path.starts_with("/"sv))
  153. return LexicalPath::canonicalized_path(path);
  154. auto working_directory = DeprecatedFile::current_working_directory();
  155. auto full_path = LexicalPath::join(working_directory, path);
  156. return LexicalPath::canonicalized_path(full_path.string());
  157. }
  158. #ifdef AK_OS_SERENITY
  159. ErrorOr<DeprecatedString> DeprecatedFile::read_link(DeprecatedString const& link_path)
  160. {
  161. // First, try using a 64-byte buffer, that ought to be enough for anybody.
  162. char small_buffer[64];
  163. int rc = serenity_readlink(link_path.characters(), link_path.length(), small_buffer, sizeof(small_buffer));
  164. if (rc < 0)
  165. return Error::from_errno(errno);
  166. size_t size = rc;
  167. // If the call was successful, the syscall (unlike the LibC wrapper)
  168. // returns the full size of the link. Let's see if our small buffer
  169. // was enough to read the whole link.
  170. if (size <= sizeof(small_buffer))
  171. return DeprecatedString { small_buffer, size };
  172. // Nope, but at least now we know the right size.
  173. char* large_buffer_ptr;
  174. auto large_buffer = StringImpl::create_uninitialized(size, large_buffer_ptr);
  175. rc = serenity_readlink(link_path.characters(), link_path.length(), large_buffer_ptr, size);
  176. if (rc < 0)
  177. return Error::from_errno(errno);
  178. size_t new_size = rc;
  179. if (new_size == size)
  180. return { *large_buffer };
  181. // If we're here, the symlink has changed while we were looking at it.
  182. // If it became shorter, our buffer is valid, we just have to trim it a bit.
  183. if (new_size < size)
  184. return DeprecatedString { large_buffer_ptr, new_size };
  185. // Otherwise, here's not much we can do, unless we want to loop endlessly
  186. // in this case. Let's leave it up to the caller whether to loop.
  187. errno = EAGAIN;
  188. return Error::from_errno(errno);
  189. }
  190. #else
  191. // This is a sad version for other systems. It has to always make a copy of the
  192. // link path, and to always make two syscalls to get the right size first.
  193. ErrorOr<DeprecatedString> DeprecatedFile::read_link(DeprecatedString const& link_path)
  194. {
  195. struct stat statbuf = {};
  196. int rc = lstat(link_path.characters(), &statbuf);
  197. if (rc < 0)
  198. return Error::from_errno(errno);
  199. char* buffer_ptr;
  200. auto buffer = StringImpl::create_uninitialized(statbuf.st_size, buffer_ptr);
  201. if (readlink(link_path.characters(), buffer_ptr, statbuf.st_size) < 0)
  202. return Error::from_errno(errno);
  203. // (See above.)
  204. if (rc == statbuf.st_size)
  205. return { *buffer };
  206. return DeprecatedString { buffer_ptr, (size_t)rc };
  207. }
  208. #endif
  209. static DeprecatedString get_duplicate_name(DeprecatedString const& path, int duplicate_count)
  210. {
  211. if (duplicate_count == 0) {
  212. return path;
  213. }
  214. LexicalPath lexical_path(path);
  215. StringBuilder duplicated_name;
  216. duplicated_name.append('/');
  217. auto& parts = lexical_path.parts_view();
  218. for (size_t i = 0; i < parts.size() - 1; ++i) {
  219. duplicated_name.appendff("{}/", parts[i]);
  220. }
  221. auto prev_duplicate_tag = DeprecatedString::formatted("({})", duplicate_count);
  222. auto title = lexical_path.title();
  223. if (title.ends_with(prev_duplicate_tag)) {
  224. // remove the previous duplicate tag "(n)" so we can add a new tag.
  225. title = title.substring_view(0, title.length() - prev_duplicate_tag.length());
  226. }
  227. duplicated_name.appendff("{} ({})", title, duplicate_count);
  228. if (!lexical_path.extension().is_empty()) {
  229. duplicated_name.appendff(".{}", lexical_path.extension());
  230. }
  231. return duplicated_name.to_deprecated_string();
  232. }
  233. ErrorOr<void, DeprecatedFile::CopyError> DeprecatedFile::copy_file_or_directory(DeprecatedString const& dst_path, DeprecatedString const& src_path, RecursionMode recursion_mode, LinkMode link_mode, AddDuplicateFileMarker add_duplicate_file_marker, PreserveMode preserve_mode)
  234. {
  235. if (add_duplicate_file_marker == AddDuplicateFileMarker::Yes) {
  236. int duplicate_count = 0;
  237. while (access(get_duplicate_name(dst_path, duplicate_count).characters(), F_OK) == 0) {
  238. ++duplicate_count;
  239. }
  240. if (duplicate_count != 0) {
  241. return copy_file_or_directory(get_duplicate_name(dst_path, duplicate_count), src_path, RecursionMode::Allowed, LinkMode::Disallowed, AddDuplicateFileMarker::Yes, preserve_mode);
  242. }
  243. }
  244. auto source_or_error = DeprecatedFile::open(src_path, OpenMode::ReadOnly);
  245. if (source_or_error.is_error())
  246. return CopyError { errno, false };
  247. auto& source = *source_or_error.value();
  248. struct stat src_stat;
  249. if (fstat(source.fd(), &src_stat) < 0)
  250. return CopyError { errno, false };
  251. if (source.is_directory()) {
  252. if (recursion_mode == RecursionMode::Disallowed)
  253. return CopyError { errno, true };
  254. return copy_directory(dst_path, src_path, src_stat);
  255. }
  256. if (link_mode == LinkMode::Allowed) {
  257. if (link(src_path.characters(), dst_path.characters()) < 0)
  258. return CopyError { errno, false };
  259. return {};
  260. }
  261. return copy_file(dst_path, src_stat, source, preserve_mode);
  262. }
  263. ErrorOr<void, DeprecatedFile::CopyError> DeprecatedFile::copy_file(DeprecatedString const& dst_path, struct stat const& src_stat, DeprecatedFile& source, PreserveMode preserve_mode)
  264. {
  265. int dst_fd = creat(dst_path.characters(), 0666);
  266. if (dst_fd < 0) {
  267. if (errno != EISDIR)
  268. return CopyError { errno, false };
  269. auto dst_dir_path = DeprecatedString::formatted("{}/{}", dst_path, LexicalPath::basename(source.filename()));
  270. dst_fd = creat(dst_dir_path.characters(), 0666);
  271. if (dst_fd < 0)
  272. return CopyError { errno, false };
  273. }
  274. ScopeGuard close_fd_guard([dst_fd]() { ::close(dst_fd); });
  275. if (src_stat.st_size > 0) {
  276. if (ftruncate(dst_fd, src_stat.st_size) < 0)
  277. return CopyError { errno, false };
  278. }
  279. for (;;) {
  280. char buffer[32768];
  281. ssize_t nread = ::read(source.fd(), buffer, sizeof(buffer));
  282. if (nread < 0) {
  283. return CopyError { errno, false };
  284. }
  285. if (nread == 0)
  286. break;
  287. ssize_t remaining_to_write = nread;
  288. char* bufptr = buffer;
  289. while (remaining_to_write) {
  290. ssize_t nwritten = ::write(dst_fd, bufptr, remaining_to_write);
  291. if (nwritten < 0)
  292. return CopyError { errno, false };
  293. VERIFY(nwritten > 0);
  294. remaining_to_write -= nwritten;
  295. bufptr += nwritten;
  296. }
  297. }
  298. auto my_umask = umask(0);
  299. umask(my_umask);
  300. // NOTE: We don't copy the set-uid and set-gid bits unless requested.
  301. if (!has_flag(preserve_mode, PreserveMode::Permissions))
  302. my_umask |= 06000;
  303. if (fchmod(dst_fd, src_stat.st_mode & ~my_umask) < 0)
  304. return CopyError { errno, false };
  305. if (has_flag(preserve_mode, PreserveMode::Ownership)) {
  306. if (fchown(dst_fd, src_stat.st_uid, src_stat.st_gid) < 0)
  307. return CopyError { errno, false };
  308. }
  309. if (has_flag(preserve_mode, PreserveMode::Timestamps)) {
  310. struct timespec times[2] = {
  311. #ifdef AK_OS_MACOS
  312. src_stat.st_atimespec,
  313. src_stat.st_mtimespec,
  314. #else
  315. src_stat.st_atim,
  316. src_stat.st_mtim,
  317. #endif
  318. };
  319. if (utimensat(AT_FDCWD, dst_path.characters(), times, 0) < 0)
  320. return CopyError { errno, false };
  321. }
  322. return {};
  323. }
  324. ErrorOr<void, DeprecatedFile::CopyError> DeprecatedFile::copy_directory(DeprecatedString const& dst_path, DeprecatedString const& src_path, struct stat const& src_stat, LinkMode link, PreserveMode preserve_mode)
  325. {
  326. if (mkdir(dst_path.characters(), 0755) < 0)
  327. return CopyError { errno, false };
  328. DeprecatedString src_rp = DeprecatedFile::real_path_for(src_path);
  329. src_rp = DeprecatedString::formatted("{}/", src_rp);
  330. DeprecatedString dst_rp = DeprecatedFile::real_path_for(dst_path);
  331. dst_rp = DeprecatedString::formatted("{}/", dst_rp);
  332. if (!dst_rp.is_empty() && dst_rp.starts_with(src_rp))
  333. return CopyError { errno, false };
  334. DirIterator di(src_path, DirIterator::SkipParentAndBaseDir);
  335. if (di.has_error())
  336. return CopyError { errno, false };
  337. while (di.has_next()) {
  338. DeprecatedString filename = di.next_path();
  339. auto result = copy_file_or_directory(
  340. DeprecatedString::formatted("{}/{}", dst_path, filename),
  341. DeprecatedString::formatted("{}/{}", src_path, filename),
  342. RecursionMode::Allowed, link, AddDuplicateFileMarker::Yes, preserve_mode);
  343. if (result.is_error())
  344. return result.release_error();
  345. }
  346. auto my_umask = umask(0);
  347. umask(my_umask);
  348. if (chmod(dst_path.characters(), src_stat.st_mode & ~my_umask) < 0)
  349. return CopyError { errno, false };
  350. if (has_flag(preserve_mode, PreserveMode::Ownership)) {
  351. if (chown(dst_path.characters(), src_stat.st_uid, src_stat.st_gid) < 0)
  352. return CopyError { errno, false };
  353. }
  354. if (has_flag(preserve_mode, PreserveMode::Timestamps)) {
  355. struct timespec times[2] = {
  356. #ifdef AK_OS_MACOS
  357. src_stat.st_atimespec,
  358. src_stat.st_mtimespec,
  359. #else
  360. src_stat.st_atim,
  361. src_stat.st_mtim,
  362. #endif
  363. };
  364. if (utimensat(AT_FDCWD, dst_path.characters(), times, 0) < 0)
  365. return CopyError { errno, false };
  366. }
  367. return {};
  368. }
  369. Optional<DeprecatedString> DeprecatedFile::resolve_executable_from_environment(StringView filename)
  370. {
  371. if (filename.is_empty())
  372. return {};
  373. // Paths that aren't just a file name generally count as already resolved.
  374. if (filename.contains('/')) {
  375. if (access(DeprecatedString { filename }.characters(), X_OK) != 0)
  376. return {};
  377. return filename;
  378. }
  379. auto const* path_str = getenv("PATH");
  380. StringView path;
  381. if (path_str)
  382. path = { path_str, strlen(path_str) };
  383. if (path.is_empty())
  384. path = DEFAULT_PATH_SV;
  385. auto directories = path.split_view(':');
  386. for (auto directory : directories) {
  387. auto file = DeprecatedString::formatted("{}/{}", directory, filename);
  388. if (access(file.characters(), X_OK) == 0)
  389. return file;
  390. }
  391. return {};
  392. };
  393. }