File.cpp 16 KB

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