File.cpp 13 KB

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