DeprecatedFile.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498
  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 RefPtr<DeprecatedFile> stdin_file;
  210. static RefPtr<DeprecatedFile> stdout_file;
  211. static RefPtr<DeprecatedFile> stderr_file;
  212. NonnullRefPtr<DeprecatedFile> DeprecatedFile::standard_input()
  213. {
  214. if (!stdin_file) {
  215. stdin_file = DeprecatedFile::construct();
  216. stdin_file->open(STDIN_FILENO, OpenMode::ReadOnly, ShouldCloseFileDescriptor::No);
  217. }
  218. return *stdin_file;
  219. }
  220. NonnullRefPtr<DeprecatedFile> DeprecatedFile::standard_output()
  221. {
  222. if (!stdout_file) {
  223. stdout_file = DeprecatedFile::construct();
  224. stdout_file->open(STDOUT_FILENO, OpenMode::WriteOnly, ShouldCloseFileDescriptor::No);
  225. }
  226. return *stdout_file;
  227. }
  228. NonnullRefPtr<DeprecatedFile> DeprecatedFile::standard_error()
  229. {
  230. if (!stderr_file) {
  231. stderr_file = DeprecatedFile::construct();
  232. stderr_file->open(STDERR_FILENO, OpenMode::WriteOnly, ShouldCloseFileDescriptor::No);
  233. }
  234. return *stderr_file;
  235. }
  236. static DeprecatedString get_duplicate_name(DeprecatedString const& path, int duplicate_count)
  237. {
  238. if (duplicate_count == 0) {
  239. return path;
  240. }
  241. LexicalPath lexical_path(path);
  242. StringBuilder duplicated_name;
  243. duplicated_name.append('/');
  244. auto& parts = lexical_path.parts_view();
  245. for (size_t i = 0; i < parts.size() - 1; ++i) {
  246. duplicated_name.appendff("{}/", parts[i]);
  247. }
  248. auto prev_duplicate_tag = DeprecatedString::formatted("({})", duplicate_count);
  249. auto title = lexical_path.title();
  250. if (title.ends_with(prev_duplicate_tag)) {
  251. // remove the previous duplicate tag "(n)" so we can add a new tag.
  252. title = title.substring_view(0, title.length() - prev_duplicate_tag.length());
  253. }
  254. duplicated_name.appendff("{} ({})", title, duplicate_count);
  255. if (!lexical_path.extension().is_empty()) {
  256. duplicated_name.appendff(".{}", lexical_path.extension());
  257. }
  258. return duplicated_name.to_deprecated_string();
  259. }
  260. 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)
  261. {
  262. if (add_duplicate_file_marker == AddDuplicateFileMarker::Yes) {
  263. int duplicate_count = 0;
  264. while (access(get_duplicate_name(dst_path, duplicate_count).characters(), F_OK) == 0) {
  265. ++duplicate_count;
  266. }
  267. if (duplicate_count != 0) {
  268. return copy_file_or_directory(get_duplicate_name(dst_path, duplicate_count), src_path, RecursionMode::Allowed, LinkMode::Disallowed, AddDuplicateFileMarker::Yes, preserve_mode);
  269. }
  270. }
  271. auto source_or_error = DeprecatedFile::open(src_path, OpenMode::ReadOnly);
  272. if (source_or_error.is_error())
  273. return CopyError { errno, false };
  274. auto& source = *source_or_error.value();
  275. struct stat src_stat;
  276. if (fstat(source.fd(), &src_stat) < 0)
  277. return CopyError { errno, false };
  278. if (source.is_directory()) {
  279. if (recursion_mode == RecursionMode::Disallowed)
  280. return CopyError { errno, true };
  281. return copy_directory(dst_path, src_path, src_stat);
  282. }
  283. if (link_mode == LinkMode::Allowed) {
  284. if (link(src_path.characters(), dst_path.characters()) < 0)
  285. return CopyError { errno, false };
  286. return {};
  287. }
  288. return copy_file(dst_path, src_stat, source, preserve_mode);
  289. }
  290. ErrorOr<void, DeprecatedFile::CopyError> DeprecatedFile::copy_file(DeprecatedString const& dst_path, struct stat const& src_stat, DeprecatedFile& source, PreserveMode preserve_mode)
  291. {
  292. int dst_fd = creat(dst_path.characters(), 0666);
  293. if (dst_fd < 0) {
  294. if (errno != EISDIR)
  295. return CopyError { errno, false };
  296. auto dst_dir_path = DeprecatedString::formatted("{}/{}", dst_path, LexicalPath::basename(source.filename()));
  297. dst_fd = creat(dst_dir_path.characters(), 0666);
  298. if (dst_fd < 0)
  299. return CopyError { errno, false };
  300. }
  301. ScopeGuard close_fd_guard([dst_fd]() { ::close(dst_fd); });
  302. if (src_stat.st_size > 0) {
  303. if (ftruncate(dst_fd, src_stat.st_size) < 0)
  304. return CopyError { errno, false };
  305. }
  306. for (;;) {
  307. char buffer[32768];
  308. ssize_t nread = ::read(source.fd(), buffer, sizeof(buffer));
  309. if (nread < 0) {
  310. return CopyError { errno, false };
  311. }
  312. if (nread == 0)
  313. break;
  314. ssize_t remaining_to_write = nread;
  315. char* bufptr = buffer;
  316. while (remaining_to_write) {
  317. ssize_t nwritten = ::write(dst_fd, bufptr, remaining_to_write);
  318. if (nwritten < 0)
  319. return CopyError { errno, false };
  320. VERIFY(nwritten > 0);
  321. remaining_to_write -= nwritten;
  322. bufptr += nwritten;
  323. }
  324. }
  325. auto my_umask = umask(0);
  326. umask(my_umask);
  327. // NOTE: We don't copy the set-uid and set-gid bits unless requested.
  328. if (!has_flag(preserve_mode, PreserveMode::Permissions))
  329. my_umask |= 06000;
  330. if (fchmod(dst_fd, src_stat.st_mode & ~my_umask) < 0)
  331. return CopyError { errno, false };
  332. if (has_flag(preserve_mode, PreserveMode::Ownership)) {
  333. if (fchown(dst_fd, src_stat.st_uid, src_stat.st_gid) < 0)
  334. return CopyError { errno, false };
  335. }
  336. if (has_flag(preserve_mode, PreserveMode::Timestamps)) {
  337. struct timespec times[2] = {
  338. #ifdef AK_OS_MACOS
  339. src_stat.st_atimespec,
  340. src_stat.st_mtimespec,
  341. #else
  342. src_stat.st_atim,
  343. src_stat.st_mtim,
  344. #endif
  345. };
  346. if (utimensat(AT_FDCWD, dst_path.characters(), times, 0) < 0)
  347. return CopyError { errno, false };
  348. }
  349. return {};
  350. }
  351. 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)
  352. {
  353. if (mkdir(dst_path.characters(), 0755) < 0)
  354. return CopyError { errno, false };
  355. DeprecatedString src_rp = DeprecatedFile::real_path_for(src_path);
  356. src_rp = DeprecatedString::formatted("{}/", src_rp);
  357. DeprecatedString dst_rp = DeprecatedFile::real_path_for(dst_path);
  358. dst_rp = DeprecatedString::formatted("{}/", dst_rp);
  359. if (!dst_rp.is_empty() && dst_rp.starts_with(src_rp))
  360. return CopyError { errno, false };
  361. DirIterator di(src_path, DirIterator::SkipParentAndBaseDir);
  362. if (di.has_error())
  363. return CopyError { errno, false };
  364. while (di.has_next()) {
  365. DeprecatedString filename = di.next_path();
  366. auto result = copy_file_or_directory(
  367. DeprecatedString::formatted("{}/{}", dst_path, filename),
  368. DeprecatedString::formatted("{}/{}", src_path, filename),
  369. RecursionMode::Allowed, link, AddDuplicateFileMarker::Yes, preserve_mode);
  370. if (result.is_error())
  371. return result.release_error();
  372. }
  373. auto my_umask = umask(0);
  374. umask(my_umask);
  375. if (chmod(dst_path.characters(), src_stat.st_mode & ~my_umask) < 0)
  376. return CopyError { errno, false };
  377. if (has_flag(preserve_mode, PreserveMode::Ownership)) {
  378. if (chown(dst_path.characters(), src_stat.st_uid, src_stat.st_gid) < 0)
  379. return CopyError { errno, false };
  380. }
  381. if (has_flag(preserve_mode, PreserveMode::Timestamps)) {
  382. struct timespec times[2] = {
  383. #ifdef AK_OS_MACOS
  384. src_stat.st_atimespec,
  385. src_stat.st_mtimespec,
  386. #else
  387. src_stat.st_atim,
  388. src_stat.st_mtim,
  389. #endif
  390. };
  391. if (utimensat(AT_FDCWD, dst_path.characters(), times, 0) < 0)
  392. return CopyError { errno, false };
  393. }
  394. return {};
  395. }
  396. Optional<DeprecatedString> DeprecatedFile::resolve_executable_from_environment(StringView filename)
  397. {
  398. if (filename.is_empty())
  399. return {};
  400. // Paths that aren't just a file name generally count as already resolved.
  401. if (filename.contains('/')) {
  402. if (access(DeprecatedString { filename }.characters(), X_OK) != 0)
  403. return {};
  404. return filename;
  405. }
  406. auto const* path_str = getenv("PATH");
  407. StringView path;
  408. if (path_str)
  409. path = { path_str, strlen(path_str) };
  410. if (path.is_empty())
  411. path = DEFAULT_PATH_SV;
  412. auto directories = path.split_view(':');
  413. for (auto directory : directories) {
  414. auto file = DeprecatedString::formatted("{}/{}", directory, filename);
  415. if (access(file.characters(), X_OK) == 0)
  416. return file;
  417. }
  418. return {};
  419. };
  420. }