File.cpp 13 KB

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