File.cpp 14 KB

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