File.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632
  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::can_delete_or_move(StringView path)
  179. {
  180. VERIFY(!path.is_empty());
  181. auto directory = LexicalPath::dirname(path);
  182. auto directory_has_write_access = !Core::System::access(directory, W_OK).is_error();
  183. if (!directory_has_write_access)
  184. return false;
  185. auto stat_or_empty = [](StringView path) {
  186. auto stat_or_error = Core::System::stat(path);
  187. if (stat_or_error.is_error()) {
  188. struct stat stat { };
  189. return stat;
  190. }
  191. return stat_or_error.release_value();
  192. };
  193. auto directory_stat = stat_or_empty(directory);
  194. bool is_directory_sticky = directory_stat.st_mode & S_ISVTX;
  195. if (!is_directory_sticky)
  196. return true;
  197. // Directory is sticky, only the file owner, directory owner, and root can modify (rename, remove) it.
  198. auto user_id = geteuid();
  199. return user_id == 0 || directory_stat.st_uid == user_id || stat_or_empty(path).st_uid == user_id;
  200. }
  201. bool File::exists(StringView filename)
  202. {
  203. return !Core::System::stat(filename).is_error();
  204. }
  205. ErrorOr<size_t> File::size(DeprecatedString const& filename)
  206. {
  207. struct stat st;
  208. if (stat(filename.characters(), &st) < 0)
  209. return Error::from_errno(errno);
  210. return st.st_size;
  211. }
  212. DeprecatedString File::real_path_for(DeprecatedString const& filename)
  213. {
  214. if (filename.is_null())
  215. return {};
  216. auto* path = realpath(filename.characters(), nullptr);
  217. DeprecatedString real_path(path);
  218. free(path);
  219. return real_path;
  220. }
  221. DeprecatedString File::current_working_directory()
  222. {
  223. char* cwd = getcwd(nullptr, 0);
  224. if (!cwd) {
  225. perror("getcwd");
  226. return {};
  227. }
  228. auto cwd_as_string = DeprecatedString(cwd);
  229. free(cwd);
  230. return cwd_as_string;
  231. }
  232. DeprecatedString File::absolute_path(DeprecatedString const& path)
  233. {
  234. if (File::exists(path))
  235. return File::real_path_for(path);
  236. if (path.starts_with("/"sv))
  237. return LexicalPath::canonicalized_path(path);
  238. auto working_directory = File::current_working_directory();
  239. auto full_path = LexicalPath::join(working_directory, path);
  240. return LexicalPath::canonicalized_path(full_path.string());
  241. }
  242. #ifdef AK_OS_SERENITY
  243. ErrorOr<DeprecatedString> File::read_link(DeprecatedString const& link_path)
  244. {
  245. // First, try using a 64-byte buffer, that ought to be enough for anybody.
  246. char small_buffer[64];
  247. int rc = serenity_readlink(link_path.characters(), link_path.length(), small_buffer, sizeof(small_buffer));
  248. if (rc < 0)
  249. return Error::from_errno(errno);
  250. size_t size = rc;
  251. // If the call was successful, the syscall (unlike the LibC wrapper)
  252. // returns the full size of the link. Let's see if our small buffer
  253. // was enough to read the whole link.
  254. if (size <= sizeof(small_buffer))
  255. return DeprecatedString { small_buffer, size };
  256. // Nope, but at least now we know the right size.
  257. char* large_buffer_ptr;
  258. auto large_buffer = StringImpl::create_uninitialized(size, large_buffer_ptr);
  259. rc = serenity_readlink(link_path.characters(), link_path.length(), large_buffer_ptr, size);
  260. if (rc < 0)
  261. return Error::from_errno(errno);
  262. size_t new_size = rc;
  263. if (new_size == size)
  264. return { *large_buffer };
  265. // If we're here, the symlink has changed while we were looking at it.
  266. // If it became shorter, our buffer is valid, we just have to trim it a bit.
  267. if (new_size < size)
  268. return DeprecatedString { large_buffer_ptr, new_size };
  269. // Otherwise, here's not much we can do, unless we want to loop endlessly
  270. // in this case. Let's leave it up to the caller whether to loop.
  271. errno = EAGAIN;
  272. return Error::from_errno(errno);
  273. }
  274. #else
  275. // This is a sad version for other systems. It has to always make a copy of the
  276. // link path, and to always make two syscalls to get the right size first.
  277. ErrorOr<DeprecatedString> File::read_link(DeprecatedString const& link_path)
  278. {
  279. struct stat statbuf = {};
  280. int rc = lstat(link_path.characters(), &statbuf);
  281. if (rc < 0)
  282. return Error::from_errno(errno);
  283. char* buffer_ptr;
  284. auto buffer = StringImpl::create_uninitialized(statbuf.st_size, buffer_ptr);
  285. if (readlink(link_path.characters(), buffer_ptr, statbuf.st_size) < 0)
  286. return Error::from_errno(errno);
  287. // (See above.)
  288. if (rc == statbuf.st_size)
  289. return { *buffer };
  290. return DeprecatedString { buffer_ptr, (size_t)rc };
  291. }
  292. #endif
  293. static RefPtr<File> stdin_file;
  294. static RefPtr<File> stdout_file;
  295. static RefPtr<File> stderr_file;
  296. NonnullRefPtr<File> File::standard_input()
  297. {
  298. if (!stdin_file) {
  299. stdin_file = File::construct();
  300. stdin_file->open(STDIN_FILENO, OpenMode::ReadOnly, ShouldCloseFileDescriptor::No);
  301. }
  302. return *stdin_file;
  303. }
  304. NonnullRefPtr<File> File::standard_output()
  305. {
  306. if (!stdout_file) {
  307. stdout_file = File::construct();
  308. stdout_file->open(STDOUT_FILENO, OpenMode::WriteOnly, ShouldCloseFileDescriptor::No);
  309. }
  310. return *stdout_file;
  311. }
  312. NonnullRefPtr<File> File::standard_error()
  313. {
  314. if (!stderr_file) {
  315. stderr_file = File::construct();
  316. stderr_file->open(STDERR_FILENO, OpenMode::WriteOnly, ShouldCloseFileDescriptor::No);
  317. }
  318. return *stderr_file;
  319. }
  320. static DeprecatedString get_duplicate_name(DeprecatedString const& path, int duplicate_count)
  321. {
  322. if (duplicate_count == 0) {
  323. return path;
  324. }
  325. LexicalPath lexical_path(path);
  326. StringBuilder duplicated_name;
  327. duplicated_name.append('/');
  328. auto& parts = lexical_path.parts_view();
  329. for (size_t i = 0; i < parts.size() - 1; ++i) {
  330. duplicated_name.appendff("{}/", parts[i]);
  331. }
  332. auto prev_duplicate_tag = DeprecatedString::formatted("({})", duplicate_count);
  333. auto title = lexical_path.title();
  334. if (title.ends_with(prev_duplicate_tag)) {
  335. // remove the previous duplicate tag "(n)" so we can add a new tag.
  336. title = title.substring_view(0, title.length() - prev_duplicate_tag.length());
  337. }
  338. duplicated_name.appendff("{} ({})", title, duplicate_count);
  339. if (!lexical_path.extension().is_empty()) {
  340. duplicated_name.appendff(".{}", lexical_path.extension());
  341. }
  342. return duplicated_name.to_deprecated_string();
  343. }
  344. 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)
  345. {
  346. if (add_duplicate_file_marker == AddDuplicateFileMarker::Yes) {
  347. int duplicate_count = 0;
  348. while (access(get_duplicate_name(dst_path, duplicate_count).characters(), F_OK) == 0) {
  349. ++duplicate_count;
  350. }
  351. if (duplicate_count != 0) {
  352. return copy_file_or_directory(get_duplicate_name(dst_path, duplicate_count), src_path, RecursionMode::Allowed, LinkMode::Disallowed, AddDuplicateFileMarker::Yes, preserve_mode);
  353. }
  354. }
  355. auto source_or_error = File::open(src_path, OpenMode::ReadOnly);
  356. if (source_or_error.is_error())
  357. return CopyError { errno, false };
  358. auto& source = *source_or_error.value();
  359. struct stat src_stat;
  360. if (fstat(source.fd(), &src_stat) < 0)
  361. return CopyError { errno, false };
  362. if (source.is_directory()) {
  363. if (recursion_mode == RecursionMode::Disallowed)
  364. return CopyError { errno, true };
  365. return copy_directory(dst_path, src_path, src_stat);
  366. }
  367. if (link_mode == LinkMode::Allowed) {
  368. if (link(src_path.characters(), dst_path.characters()) < 0)
  369. return CopyError { errno, false };
  370. return {};
  371. }
  372. return copy_file(dst_path, src_stat, source, preserve_mode);
  373. }
  374. ErrorOr<void, File::CopyError> File::copy_file(DeprecatedString const& dst_path, struct stat const& src_stat, File& source, PreserveMode preserve_mode)
  375. {
  376. int dst_fd = creat(dst_path.characters(), 0666);
  377. if (dst_fd < 0) {
  378. if (errno != EISDIR)
  379. return CopyError { errno, false };
  380. auto dst_dir_path = DeprecatedString::formatted("{}/{}", dst_path, LexicalPath::basename(source.filename()));
  381. dst_fd = creat(dst_dir_path.characters(), 0666);
  382. if (dst_fd < 0)
  383. return CopyError { errno, false };
  384. }
  385. ScopeGuard close_fd_guard([dst_fd]() { ::close(dst_fd); });
  386. if (src_stat.st_size > 0) {
  387. if (ftruncate(dst_fd, src_stat.st_size) < 0)
  388. return CopyError { errno, false };
  389. }
  390. for (;;) {
  391. char buffer[32768];
  392. ssize_t nread = ::read(source.fd(), buffer, sizeof(buffer));
  393. if (nread < 0) {
  394. return CopyError { errno, false };
  395. }
  396. if (nread == 0)
  397. break;
  398. ssize_t remaining_to_write = nread;
  399. char* bufptr = buffer;
  400. while (remaining_to_write) {
  401. ssize_t nwritten = ::write(dst_fd, bufptr, remaining_to_write);
  402. if (nwritten < 0)
  403. return CopyError { errno, false };
  404. VERIFY(nwritten > 0);
  405. remaining_to_write -= nwritten;
  406. bufptr += nwritten;
  407. }
  408. }
  409. auto my_umask = umask(0);
  410. umask(my_umask);
  411. // NOTE: We don't copy the set-uid and set-gid bits unless requested.
  412. if (!has_flag(preserve_mode, PreserveMode::Permissions))
  413. my_umask |= 06000;
  414. if (fchmod(dst_fd, src_stat.st_mode & ~my_umask) < 0)
  415. return CopyError { errno, false };
  416. if (has_flag(preserve_mode, PreserveMode::Ownership)) {
  417. if (fchown(dst_fd, src_stat.st_uid, src_stat.st_gid) < 0)
  418. return CopyError { errno, false };
  419. }
  420. if (has_flag(preserve_mode, PreserveMode::Timestamps)) {
  421. struct timespec times[2] = {
  422. #ifdef AK_OS_MACOS
  423. src_stat.st_atimespec,
  424. src_stat.st_mtimespec,
  425. #else
  426. src_stat.st_atim,
  427. src_stat.st_mtim,
  428. #endif
  429. };
  430. if (utimensat(AT_FDCWD, dst_path.characters(), times, 0) < 0)
  431. return CopyError { errno, false };
  432. }
  433. return {};
  434. }
  435. 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)
  436. {
  437. if (mkdir(dst_path.characters(), 0755) < 0)
  438. return CopyError { errno, false };
  439. DeprecatedString src_rp = File::real_path_for(src_path);
  440. src_rp = DeprecatedString::formatted("{}/", src_rp);
  441. DeprecatedString dst_rp = File::real_path_for(dst_path);
  442. dst_rp = DeprecatedString::formatted("{}/", dst_rp);
  443. if (!dst_rp.is_empty() && dst_rp.starts_with(src_rp))
  444. return CopyError { errno, false };
  445. DirIterator di(src_path, DirIterator::SkipParentAndBaseDir);
  446. if (di.has_error())
  447. return CopyError { errno, false };
  448. while (di.has_next()) {
  449. DeprecatedString filename = di.next_path();
  450. auto result = copy_file_or_directory(
  451. DeprecatedString::formatted("{}/{}", dst_path, filename),
  452. DeprecatedString::formatted("{}/{}", src_path, filename),
  453. RecursionMode::Allowed, link, AddDuplicateFileMarker::Yes, preserve_mode);
  454. if (result.is_error())
  455. return result.release_error();
  456. }
  457. auto my_umask = umask(0);
  458. umask(my_umask);
  459. if (chmod(dst_path.characters(), src_stat.st_mode & ~my_umask) < 0)
  460. return CopyError { errno, false };
  461. if (has_flag(preserve_mode, PreserveMode::Ownership)) {
  462. if (chown(dst_path.characters(), src_stat.st_uid, src_stat.st_gid) < 0)
  463. return CopyError { errno, false };
  464. }
  465. if (has_flag(preserve_mode, PreserveMode::Timestamps)) {
  466. struct timespec times[2] = {
  467. #ifdef AK_OS_MACOS
  468. src_stat.st_atimespec,
  469. src_stat.st_mtimespec,
  470. #else
  471. src_stat.st_atim,
  472. src_stat.st_mtim,
  473. #endif
  474. };
  475. if (utimensat(AT_FDCWD, dst_path.characters(), times, 0) < 0)
  476. return CopyError { errno, false };
  477. }
  478. return {};
  479. }
  480. ErrorOr<void> File::link_file(DeprecatedString const& dst_path, DeprecatedString const& src_path)
  481. {
  482. int duplicate_count = 0;
  483. while (access(get_duplicate_name(dst_path, duplicate_count).characters(), F_OK) == 0) {
  484. ++duplicate_count;
  485. }
  486. if (duplicate_count != 0) {
  487. return link_file(get_duplicate_name(dst_path, duplicate_count), src_path);
  488. }
  489. if (symlink(src_path.characters(), dst_path.characters()) < 0)
  490. return Error::from_errno(errno);
  491. return {};
  492. }
  493. ErrorOr<void> File::remove(StringView path, RecursionMode mode)
  494. {
  495. auto path_stat = TRY(Core::System::lstat(path));
  496. if (S_ISDIR(path_stat.st_mode) && mode == RecursionMode::Allowed) {
  497. auto di = DirIterator(path, DirIterator::SkipParentAndBaseDir);
  498. if (di.has_error())
  499. return Error::from_errno(di.error());
  500. while (di.has_next()) {
  501. TRY(remove(di.next_full_path(), RecursionMode::Allowed));
  502. }
  503. TRY(Core::System::rmdir(path));
  504. } else {
  505. TRY(Core::System::unlink(path));
  506. }
  507. return {};
  508. }
  509. Optional<DeprecatedString> File::resolve_executable_from_environment(StringView filename)
  510. {
  511. if (filename.is_empty())
  512. return {};
  513. // Paths that aren't just a file name generally count as already resolved.
  514. if (filename.contains('/')) {
  515. if (access(DeprecatedString { filename }.characters(), X_OK) != 0)
  516. return {};
  517. return filename;
  518. }
  519. auto const* path_str = getenv("PATH");
  520. StringView path;
  521. if (path_str)
  522. path = { path_str, strlen(path_str) };
  523. if (path.is_empty())
  524. path = DEFAULT_PATH_SV;
  525. auto directories = path.split_view(':');
  526. for (auto directory : directories) {
  527. auto file = DeprecatedString::formatted("{}/{}", directory, filename);
  528. if (access(file.characters(), X_OK) == 0)
  529. return file;
  530. }
  531. return {};
  532. };
  533. }