File.cpp 15 KB

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