DeprecatedFile.cpp 15 KB

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