File.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611
  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/DirIterator.h>
  10. #include <LibCore/File.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<File>> File::open(DeprecatedString filename, OpenMode mode, mode_t permissions)
  29. {
  30. auto file = File::construct(move(filename));
  31. if (!file->open_impl(mode, permissions))
  32. return Error::from_errno(file->error());
  33. return file;
  34. }
  35. File::File(DeprecatedString filename, Object* parent)
  36. : IODevice(parent)
  37. , m_filename(move(filename))
  38. {
  39. }
  40. File::~File()
  41. {
  42. if (m_should_close_file_descriptor == ShouldCloseFileDescriptor::Yes && mode() != OpenMode::NotOpen)
  43. close();
  44. }
  45. bool File::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 File::open(OpenMode mode)
  53. {
  54. return open_impl(mode, 0666);
  55. }
  56. bool File::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 File::leak_fd()
  88. {
  89. m_should_close_file_descriptor = ShouldCloseFileDescriptor::No;
  90. return fd();
  91. }
  92. bool File::is_device() const
  93. {
  94. return is_device(fd());
  95. }
  96. bool File::is_device(DeprecatedString const& filename)
  97. {
  98. struct stat st;
  99. if (stat(filename.characters(), &st) < 0)
  100. return false;
  101. return S_ISBLK(st.st_mode) || S_ISCHR(st.st_mode);
  102. }
  103. bool File::is_device(int fd)
  104. {
  105. struct stat st;
  106. if (fstat(fd, &st) < 0)
  107. return false;
  108. return S_ISBLK(st.st_mode) || S_ISCHR(st.st_mode);
  109. }
  110. bool File::is_block_device() const
  111. {
  112. struct stat stat;
  113. if (fstat(fd(), &stat) < 0)
  114. return false;
  115. return S_ISBLK(stat.st_mode);
  116. }
  117. bool File::is_block_device(DeprecatedString const& filename)
  118. {
  119. struct stat st;
  120. if (stat(filename.characters(), &st) < 0)
  121. return false;
  122. return S_ISBLK(st.st_mode);
  123. }
  124. bool File::is_char_device() const
  125. {
  126. struct stat stat;
  127. if (fstat(fd(), &stat) < 0)
  128. return false;
  129. return S_ISCHR(stat.st_mode);
  130. }
  131. bool File::is_char_device(DeprecatedString const& filename)
  132. {
  133. struct stat st;
  134. if (stat(filename.characters(), &st) < 0)
  135. return false;
  136. return S_ISCHR(st.st_mode);
  137. }
  138. bool File::is_directory() const
  139. {
  140. return is_directory(fd());
  141. }
  142. bool File::is_directory(DeprecatedString const& filename)
  143. {
  144. struct stat st;
  145. if (stat(filename.characters(), &st) < 0)
  146. return false;
  147. return S_ISDIR(st.st_mode);
  148. }
  149. bool File::is_directory(int fd)
  150. {
  151. struct stat st;
  152. if (fstat(fd, &st) < 0)
  153. return false;
  154. return S_ISDIR(st.st_mode);
  155. }
  156. bool File::is_link() const
  157. {
  158. struct stat stat;
  159. if (fstat(fd(), &stat) < 0)
  160. return false;
  161. return S_ISLNK(stat.st_mode);
  162. }
  163. bool File::is_link(DeprecatedString const& filename)
  164. {
  165. struct stat st;
  166. if (lstat(filename.characters(), &st) < 0)
  167. return false;
  168. return S_ISLNK(st.st_mode);
  169. }
  170. bool File::looks_like_shared_library() const
  171. {
  172. return File::looks_like_shared_library(m_filename);
  173. }
  174. bool File::looks_like_shared_library(DeprecatedString const& filename)
  175. {
  176. return filename.ends_with(".so"sv) || filename.contains(".so."sv);
  177. }
  178. bool File::exists(StringView filename)
  179. {
  180. return !Core::System::stat(filename).is_error();
  181. }
  182. ErrorOr<size_t> File::size(DeprecatedString const& filename)
  183. {
  184. struct stat st;
  185. if (stat(filename.characters(), &st) < 0)
  186. return Error::from_errno(errno);
  187. return st.st_size;
  188. }
  189. DeprecatedString File::real_path_for(DeprecatedString const& filename)
  190. {
  191. if (filename.is_null())
  192. return {};
  193. auto* path = realpath(filename.characters(), nullptr);
  194. DeprecatedString real_path(path);
  195. free(path);
  196. return real_path;
  197. }
  198. DeprecatedString File::current_working_directory()
  199. {
  200. char* cwd = getcwd(nullptr, 0);
  201. if (!cwd) {
  202. perror("getcwd");
  203. return {};
  204. }
  205. auto cwd_as_string = DeprecatedString(cwd);
  206. free(cwd);
  207. return cwd_as_string;
  208. }
  209. DeprecatedString File::absolute_path(DeprecatedString const& path)
  210. {
  211. if (File::exists(path))
  212. return File::real_path_for(path);
  213. if (path.starts_with("/"sv))
  214. return LexicalPath::canonicalized_path(path);
  215. auto working_directory = File::current_working_directory();
  216. auto full_path = LexicalPath::join(working_directory, path);
  217. return LexicalPath::canonicalized_path(full_path.string());
  218. }
  219. #ifdef AK_OS_SERENITY
  220. ErrorOr<DeprecatedString> File::read_link(DeprecatedString const& link_path)
  221. {
  222. // First, try using a 64-byte buffer, that ought to be enough for anybody.
  223. char small_buffer[64];
  224. int rc = serenity_readlink(link_path.characters(), link_path.length(), small_buffer, sizeof(small_buffer));
  225. if (rc < 0)
  226. return Error::from_errno(errno);
  227. size_t size = rc;
  228. // If the call was successful, the syscall (unlike the LibC wrapper)
  229. // returns the full size of the link. Let's see if our small buffer
  230. // was enough to read the whole link.
  231. if (size <= sizeof(small_buffer))
  232. return DeprecatedString { small_buffer, size };
  233. // Nope, but at least now we know the right size.
  234. char* large_buffer_ptr;
  235. auto large_buffer = StringImpl::create_uninitialized(size, large_buffer_ptr);
  236. rc = serenity_readlink(link_path.characters(), link_path.length(), large_buffer_ptr, size);
  237. if (rc < 0)
  238. return Error::from_errno(errno);
  239. size_t new_size = rc;
  240. if (new_size == size)
  241. return { *large_buffer };
  242. // If we're here, the symlink has changed while we were looking at it.
  243. // If it became shorter, our buffer is valid, we just have to trim it a bit.
  244. if (new_size < size)
  245. return DeprecatedString { large_buffer_ptr, new_size };
  246. // Otherwise, here's not much we can do, unless we want to loop endlessly
  247. // in this case. Let's leave it up to the caller whether to loop.
  248. errno = EAGAIN;
  249. return Error::from_errno(errno);
  250. }
  251. #else
  252. // This is a sad version for other systems. It has to always make a copy of the
  253. // link path, and to always make two syscalls to get the right size first.
  254. ErrorOr<DeprecatedString> File::read_link(DeprecatedString const& link_path)
  255. {
  256. struct stat statbuf = {};
  257. int rc = lstat(link_path.characters(), &statbuf);
  258. if (rc < 0)
  259. return Error::from_errno(errno);
  260. char* buffer_ptr;
  261. auto buffer = StringImpl::create_uninitialized(statbuf.st_size, buffer_ptr);
  262. if (readlink(link_path.characters(), buffer_ptr, statbuf.st_size) < 0)
  263. return Error::from_errno(errno);
  264. // (See above.)
  265. if (rc == statbuf.st_size)
  266. return { *buffer };
  267. return DeprecatedString { buffer_ptr, (size_t)rc };
  268. }
  269. #endif
  270. static RefPtr<File> stdin_file;
  271. static RefPtr<File> stdout_file;
  272. static RefPtr<File> stderr_file;
  273. NonnullRefPtr<File> File::standard_input()
  274. {
  275. if (!stdin_file) {
  276. stdin_file = File::construct();
  277. stdin_file->open(STDIN_FILENO, OpenMode::ReadOnly, ShouldCloseFileDescriptor::No);
  278. }
  279. return *stdin_file;
  280. }
  281. NonnullRefPtr<File> File::standard_output()
  282. {
  283. if (!stdout_file) {
  284. stdout_file = File::construct();
  285. stdout_file->open(STDOUT_FILENO, OpenMode::WriteOnly, ShouldCloseFileDescriptor::No);
  286. }
  287. return *stdout_file;
  288. }
  289. NonnullRefPtr<File> File::standard_error()
  290. {
  291. if (!stderr_file) {
  292. stderr_file = File::construct();
  293. stderr_file->open(STDERR_FILENO, OpenMode::WriteOnly, ShouldCloseFileDescriptor::No);
  294. }
  295. return *stderr_file;
  296. }
  297. static DeprecatedString get_duplicate_name(DeprecatedString const& path, int duplicate_count)
  298. {
  299. if (duplicate_count == 0) {
  300. return path;
  301. }
  302. LexicalPath lexical_path(path);
  303. StringBuilder duplicated_name;
  304. duplicated_name.append('/');
  305. auto& parts = lexical_path.parts_view();
  306. for (size_t i = 0; i < parts.size() - 1; ++i) {
  307. duplicated_name.appendff("{}/", parts[i]);
  308. }
  309. auto prev_duplicate_tag = DeprecatedString::formatted("({})", duplicate_count);
  310. auto title = lexical_path.title();
  311. if (title.ends_with(prev_duplicate_tag)) {
  312. // remove the previous duplicate tag "(n)" so we can add a new tag.
  313. title = title.substring_view(0, title.length() - prev_duplicate_tag.length());
  314. }
  315. duplicated_name.appendff("{} ({})", title, duplicate_count);
  316. if (!lexical_path.extension().is_empty()) {
  317. duplicated_name.appendff(".{}", lexical_path.extension());
  318. }
  319. return duplicated_name.build();
  320. }
  321. ErrorOr<void, File::CopyError> File::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)
  322. {
  323. if (add_duplicate_file_marker == AddDuplicateFileMarker::Yes) {
  324. int duplicate_count = 0;
  325. while (access(get_duplicate_name(dst_path, duplicate_count).characters(), F_OK) == 0) {
  326. ++duplicate_count;
  327. }
  328. if (duplicate_count != 0) {
  329. return copy_file_or_directory(get_duplicate_name(dst_path, duplicate_count), src_path, RecursionMode::Allowed, LinkMode::Disallowed, AddDuplicateFileMarker::Yes, preserve_mode);
  330. }
  331. }
  332. auto source_or_error = File::open(src_path, OpenMode::ReadOnly);
  333. if (source_or_error.is_error())
  334. return CopyError { errno, false };
  335. auto& source = *source_or_error.value();
  336. struct stat src_stat;
  337. if (fstat(source.fd(), &src_stat) < 0)
  338. return CopyError { errno, false };
  339. if (source.is_directory()) {
  340. if (recursion_mode == RecursionMode::Disallowed)
  341. return CopyError { errno, true };
  342. return copy_directory(dst_path, src_path, src_stat);
  343. }
  344. if (link_mode == LinkMode::Allowed) {
  345. if (link(src_path.characters(), dst_path.characters()) < 0)
  346. return CopyError { errno, false };
  347. return {};
  348. }
  349. return copy_file(dst_path, src_stat, source, preserve_mode);
  350. }
  351. ErrorOr<void, File::CopyError> File::copy_file(DeprecatedString const& dst_path, struct stat const& src_stat, File& source, PreserveMode preserve_mode)
  352. {
  353. int dst_fd = creat(dst_path.characters(), 0666);
  354. if (dst_fd < 0) {
  355. if (errno != EISDIR)
  356. return CopyError { errno, false };
  357. auto dst_dir_path = DeprecatedString::formatted("{}/{}", dst_path, LexicalPath::basename(source.filename()));
  358. dst_fd = creat(dst_dir_path.characters(), 0666);
  359. if (dst_fd < 0)
  360. return CopyError { errno, false };
  361. }
  362. ScopeGuard close_fd_guard([dst_fd]() { ::close(dst_fd); });
  363. if (src_stat.st_size > 0) {
  364. if (ftruncate(dst_fd, src_stat.st_size) < 0)
  365. return CopyError { errno, false };
  366. }
  367. for (;;) {
  368. char buffer[32768];
  369. ssize_t nread = ::read(source.fd(), buffer, sizeof(buffer));
  370. if (nread < 0) {
  371. return CopyError { errno, false };
  372. }
  373. if (nread == 0)
  374. break;
  375. ssize_t remaining_to_write = nread;
  376. char* bufptr = buffer;
  377. while (remaining_to_write) {
  378. ssize_t nwritten = ::write(dst_fd, bufptr, remaining_to_write);
  379. if (nwritten < 0)
  380. return CopyError { errno, false };
  381. VERIFY(nwritten > 0);
  382. remaining_to_write -= nwritten;
  383. bufptr += nwritten;
  384. }
  385. }
  386. auto my_umask = umask(0);
  387. umask(my_umask);
  388. // NOTE: We don't copy the set-uid and set-gid bits unless requested.
  389. if (!has_flag(preserve_mode, PreserveMode::Permissions))
  390. my_umask |= 06000;
  391. if (fchmod(dst_fd, src_stat.st_mode & ~my_umask) < 0)
  392. return CopyError { errno, false };
  393. if (has_flag(preserve_mode, PreserveMode::Ownership)) {
  394. if (fchown(dst_fd, src_stat.st_uid, src_stat.st_gid) < 0)
  395. return CopyError { errno, false };
  396. }
  397. if (has_flag(preserve_mode, PreserveMode::Timestamps)) {
  398. struct timespec times[2] = {
  399. #ifdef AK_OS_MACOS
  400. src_stat.st_atimespec,
  401. src_stat.st_mtimespec,
  402. #else
  403. src_stat.st_atim,
  404. src_stat.st_mtim,
  405. #endif
  406. };
  407. if (utimensat(AT_FDCWD, dst_path.characters(), times, 0) < 0)
  408. return CopyError { errno, false };
  409. }
  410. return {};
  411. }
  412. ErrorOr<void, File::CopyError> File::copy_directory(DeprecatedString const& dst_path, DeprecatedString const& src_path, struct stat const& src_stat, LinkMode link, PreserveMode preserve_mode)
  413. {
  414. if (mkdir(dst_path.characters(), 0755) < 0)
  415. return CopyError { errno, false };
  416. DeprecatedString src_rp = File::real_path_for(src_path);
  417. src_rp = DeprecatedString::formatted("{}/", src_rp);
  418. DeprecatedString dst_rp = File::real_path_for(dst_path);
  419. dst_rp = DeprecatedString::formatted("{}/", dst_rp);
  420. if (!dst_rp.is_empty() && dst_rp.starts_with(src_rp))
  421. return CopyError { errno, false };
  422. DirIterator di(src_path, DirIterator::SkipParentAndBaseDir);
  423. if (di.has_error())
  424. return CopyError { errno, false };
  425. while (di.has_next()) {
  426. DeprecatedString filename = di.next_path();
  427. auto result = copy_file_or_directory(
  428. DeprecatedString::formatted("{}/{}", dst_path, filename),
  429. DeprecatedString::formatted("{}/{}", src_path, filename),
  430. RecursionMode::Allowed, link, AddDuplicateFileMarker::Yes, preserve_mode);
  431. if (result.is_error())
  432. return result.error();
  433. }
  434. auto my_umask = umask(0);
  435. umask(my_umask);
  436. if (chmod(dst_path.characters(), src_stat.st_mode & ~my_umask) < 0)
  437. return CopyError { errno, false };
  438. if (has_flag(preserve_mode, PreserveMode::Ownership)) {
  439. if (chown(dst_path.characters(), src_stat.st_uid, src_stat.st_gid) < 0)
  440. return CopyError { errno, false };
  441. }
  442. if (has_flag(preserve_mode, PreserveMode::Timestamps)) {
  443. struct timespec times[2] = {
  444. #ifdef AK_OS_MACOS
  445. src_stat.st_atimespec,
  446. src_stat.st_mtimespec,
  447. #else
  448. src_stat.st_atim,
  449. src_stat.st_mtim,
  450. #endif
  451. };
  452. if (utimensat(AT_FDCWD, dst_path.characters(), times, 0) < 0)
  453. return CopyError { errno, false };
  454. }
  455. return {};
  456. }
  457. ErrorOr<void> File::link_file(DeprecatedString const& dst_path, DeprecatedString const& src_path)
  458. {
  459. int duplicate_count = 0;
  460. while (access(get_duplicate_name(dst_path, duplicate_count).characters(), F_OK) == 0) {
  461. ++duplicate_count;
  462. }
  463. if (duplicate_count != 0) {
  464. return link_file(get_duplicate_name(dst_path, duplicate_count), src_path);
  465. }
  466. if (symlink(src_path.characters(), dst_path.characters()) < 0)
  467. return Error::from_errno(errno);
  468. return {};
  469. }
  470. ErrorOr<void> File::remove(DeprecatedString const& path, RecursionMode mode)
  471. {
  472. struct stat path_stat;
  473. if (lstat(path.characters(), &path_stat) < 0)
  474. return Error::from_errno(errno);
  475. if (S_ISDIR(path_stat.st_mode) && mode == RecursionMode::Allowed) {
  476. auto di = DirIterator(path, DirIterator::SkipParentAndBaseDir);
  477. if (di.has_error())
  478. return Error::from_errno(di.error());
  479. while (di.has_next()) {
  480. auto result = remove(di.next_full_path(), RecursionMode::Allowed);
  481. if (result.is_error())
  482. return result.error();
  483. }
  484. if (rmdir(path.characters()) < 0)
  485. return Error::from_errno(errno);
  486. } else {
  487. if (unlink(path.characters()) < 0)
  488. return Error::from_errno(errno);
  489. }
  490. return {};
  491. }
  492. Optional<DeprecatedString> File::resolve_executable_from_environment(StringView filename)
  493. {
  494. if (filename.is_empty())
  495. return {};
  496. // Paths that aren't just a file name generally count as already resolved.
  497. if (filename.contains('/')) {
  498. if (access(DeprecatedString { filename }.characters(), X_OK) != 0)
  499. return {};
  500. return filename;
  501. }
  502. auto const* path_str = getenv("PATH");
  503. StringView path;
  504. if (path_str)
  505. path = { path_str, strlen(path_str) };
  506. if (path.is_empty())
  507. path = DEFAULT_PATH_SV;
  508. auto directories = path.split_view(':');
  509. for (auto directory : directories) {
  510. auto file = DeprecatedString::formatted("{}/{}", directory, filename);
  511. if (access(file.characters(), X_OK) == 0)
  512. return file;
  513. }
  514. return {};
  515. };
  516. }