File.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460
  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. for (size_t i = 0; i < lexical_path.parts().size() - 1; ++i) {
  235. duplicated_name.appendff("{}/", lexical_path.parts()[i]);
  236. }
  237. auto prev_duplicate_tag = String::formatted("({})", duplicate_count);
  238. auto title = lexical_path.title();
  239. if (title.ends_with(prev_duplicate_tag)) {
  240. // remove the previous duplicate tag "(n)" so we can add a new tag.
  241. title = title.substring(0, title.length() - prev_duplicate_tag.length());
  242. }
  243. duplicated_name.appendff("{} ({})", lexical_path.title(), duplicate_count);
  244. if (!lexical_path.extension().is_empty()) {
  245. duplicated_name.appendff(".{}", lexical_path.extension());
  246. }
  247. return duplicated_name.build();
  248. }
  249. 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)
  250. {
  251. if (add_duplicate_file_marker == AddDuplicateFileMarker::Yes) {
  252. int duplicate_count = 0;
  253. while (access(get_duplicate_name(dst_path, duplicate_count).characters(), F_OK) == 0) {
  254. ++duplicate_count;
  255. }
  256. if (duplicate_count != 0) {
  257. return copy_file_or_directory(get_duplicate_name(dst_path, duplicate_count), src_path);
  258. }
  259. }
  260. auto source_or_error = File::open(src_path, OpenMode::ReadOnly);
  261. if (source_or_error.is_error())
  262. return CopyError { OSError(errno), false };
  263. auto& source = *source_or_error.value();
  264. struct stat src_stat;
  265. if (fstat(source.fd(), &src_stat) < 0)
  266. return CopyError { OSError(errno), false };
  267. if (source.is_directory()) {
  268. if (recursion_mode == RecursionMode::Disallowed)
  269. return CopyError { OSError(errno), true };
  270. return copy_directory(dst_path, src_path, src_stat);
  271. }
  272. if (link_mode == LinkMode::Allowed) {
  273. if (link(src_path.characters(), dst_path.characters()) < 0)
  274. return CopyError { OSError(errno), false };
  275. return {};
  276. }
  277. return copy_file(dst_path, src_stat, source);
  278. }
  279. Result<void, File::CopyError> File::copy_file(const String& dst_path, const struct stat& src_stat, File& source)
  280. {
  281. int dst_fd = creat(dst_path.characters(), 0666);
  282. if (dst_fd < 0) {
  283. if (errno != EISDIR)
  284. return CopyError { OSError(errno), false };
  285. auto dst_dir_path = String::formatted("{}/{}", dst_path, LexicalPath(source.filename()).basename());
  286. dst_fd = creat(dst_dir_path.characters(), 0666);
  287. if (dst_fd < 0)
  288. return CopyError { OSError(errno), false };
  289. }
  290. ScopeGuard close_fd_guard([dst_fd]() { ::close(dst_fd); });
  291. if (src_stat.st_size > 0) {
  292. if (ftruncate(dst_fd, src_stat.st_size) < 0)
  293. return CopyError { OSError(errno), false };
  294. }
  295. for (;;) {
  296. char buffer[32768];
  297. ssize_t nread = ::read(source.fd(), buffer, sizeof(buffer));
  298. if (nread < 0) {
  299. return CopyError { OSError(errno), false };
  300. }
  301. if (nread == 0)
  302. break;
  303. ssize_t remaining_to_write = nread;
  304. char* bufptr = buffer;
  305. while (remaining_to_write) {
  306. ssize_t nwritten = ::write(dst_fd, bufptr, remaining_to_write);
  307. if (nwritten < 0)
  308. return CopyError { OSError(errno), false };
  309. VERIFY(nwritten > 0);
  310. remaining_to_write -= nwritten;
  311. bufptr += nwritten;
  312. }
  313. }
  314. // NOTE: We don't copy the set-uid and set-gid bits.
  315. auto my_umask = umask(0);
  316. umask(my_umask);
  317. if (fchmod(dst_fd, (src_stat.st_mode & ~my_umask) & ~06000) < 0)
  318. return CopyError { OSError(errno), false };
  319. return {};
  320. }
  321. Result<void, File::CopyError> File::copy_directory(const String& dst_path, const String& src_path, const struct stat& src_stat, LinkMode link)
  322. {
  323. if (mkdir(dst_path.characters(), 0755) < 0)
  324. return CopyError { OSError(errno), false };
  325. String src_rp = File::real_path_for(src_path);
  326. src_rp = String::formatted("{}/", src_rp);
  327. String dst_rp = File::real_path_for(dst_path);
  328. dst_rp = String::formatted("{}/", dst_rp);
  329. if (!dst_rp.is_empty() && dst_rp.starts_with(src_rp))
  330. return CopyError { OSError(errno), false };
  331. DirIterator di(src_path, DirIterator::SkipDots);
  332. if (di.has_error())
  333. return CopyError { OSError(errno), false };
  334. while (di.has_next()) {
  335. String filename = di.next_path();
  336. auto result = copy_file_or_directory(
  337. String::formatted("{}/{}", dst_path, filename),
  338. String::formatted("{}/{}", src_path, filename),
  339. RecursionMode::Allowed, link);
  340. if (result.is_error())
  341. return result.error();
  342. }
  343. auto my_umask = umask(0);
  344. umask(my_umask);
  345. if (chmod(dst_path.characters(), src_stat.st_mode & ~my_umask) < 0)
  346. return CopyError { OSError(errno), false };
  347. return {};
  348. }
  349. Result<void, OSError> File::link_file(const String& dst_path, const String& src_path)
  350. {
  351. int duplicate_count = 0;
  352. while (access(get_duplicate_name(dst_path, duplicate_count).characters(), F_OK) == 0) {
  353. ++duplicate_count;
  354. }
  355. if (duplicate_count != 0) {
  356. return link_file(src_path, get_duplicate_name(dst_path, duplicate_count));
  357. }
  358. int rc = symlink(src_path.characters(), dst_path.characters());
  359. if (rc < 0) {
  360. return OSError(errno);
  361. }
  362. return {};
  363. }
  364. Result<void, File::RemoveError> File::remove(const String& path, RecursionMode mode, bool force)
  365. {
  366. struct stat path_stat;
  367. if (lstat(path.characters(), &path_stat) < 0) {
  368. if (!force)
  369. return RemoveError { path, OSError(errno) };
  370. return {};
  371. }
  372. if (S_ISDIR(path_stat.st_mode) && mode == RecursionMode::Allowed) {
  373. auto di = DirIterator(path, DirIterator::SkipParentAndBaseDir);
  374. if (di.has_error())
  375. return RemoveError { path, OSError(di.error()) };
  376. while (di.has_next()) {
  377. auto result = remove(di.next_full_path(), RecursionMode::Allowed, true);
  378. if (result.is_error())
  379. return result.error();
  380. }
  381. if (rmdir(path.characters()) < 0 && !force)
  382. return RemoveError { path, OSError(errno) };
  383. } else {
  384. if (unlink(path.characters()) < 0 && !force)
  385. return RemoveError { path, OSError(errno) };
  386. }
  387. return {};
  388. }
  389. }