File.cpp 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  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 <Kernel/API/Syscall.h>
  28. # include <serenity.h>
  29. #endif
  30. #include <AK/ScopeGuard.h>
  31. #include <LibCore/File.h>
  32. #include <errno.h>
  33. #include <fcntl.h>
  34. #include <libgen.h>
  35. #include <stdio.h>
  36. #include <string.h>
  37. #include <sys/stat.h>
  38. #include <unistd.h>
  39. namespace Core {
  40. Result<NonnullRefPtr<File>, String> File::open(const String& filename, IODevice::OpenMode mode, mode_t permissions)
  41. {
  42. auto file = File::construct(filename);
  43. if (!file->open_impl(mode, permissions))
  44. return String(file->error_string());
  45. return file;
  46. }
  47. File::File(const StringView& filename, Object* parent)
  48. : IODevice(parent)
  49. , m_filename(filename)
  50. {
  51. }
  52. File::~File()
  53. {
  54. if (m_should_close_file_descriptor == ShouldCloseFileDescriptor::Yes && mode() != NotOpen)
  55. close();
  56. }
  57. bool File::open(int fd, IODevice::OpenMode mode, ShouldCloseFileDescriptor should_close)
  58. {
  59. set_fd(fd);
  60. set_mode(mode);
  61. m_should_close_file_descriptor = should_close;
  62. return true;
  63. }
  64. bool File::open(IODevice::OpenMode mode)
  65. {
  66. return open_impl(mode, 0666);
  67. }
  68. bool File::open_impl(IODevice::OpenMode mode, mode_t permissions)
  69. {
  70. ASSERT(!m_filename.is_null());
  71. int flags = 0;
  72. if ((mode & IODevice::ReadWrite) == IODevice::ReadWrite) {
  73. flags |= O_RDWR | O_CREAT;
  74. } else if (mode & IODevice::ReadOnly) {
  75. flags |= O_RDONLY;
  76. } else if (mode & IODevice::WriteOnly) {
  77. flags |= O_WRONLY | O_CREAT;
  78. bool should_truncate = !((mode & IODevice::Append) || (mode & IODevice::MustBeNew));
  79. if (should_truncate)
  80. flags |= O_TRUNC;
  81. }
  82. if (mode & IODevice::Append)
  83. flags |= O_APPEND;
  84. if (mode & IODevice::Truncate)
  85. flags |= O_TRUNC;
  86. if (mode & IODevice::MustBeNew)
  87. flags |= O_EXCL;
  88. int fd = ::open(m_filename.characters(), flags, permissions);
  89. if (fd < 0) {
  90. set_error(errno);
  91. return false;
  92. }
  93. set_fd(fd);
  94. set_mode(mode);
  95. return true;
  96. }
  97. bool File::is_directory() const
  98. {
  99. struct stat stat;
  100. if (fstat(fd(), &stat) < 0)
  101. return false;
  102. return S_ISDIR(stat.st_mode);
  103. }
  104. bool File::is_directory(const String& filename)
  105. {
  106. struct stat st;
  107. if (stat(filename.characters(), &st) < 0)
  108. return false;
  109. return S_ISDIR(st.st_mode);
  110. }
  111. bool File::exists(const String& filename)
  112. {
  113. struct stat st;
  114. return stat(filename.characters(), &st) == 0;
  115. }
  116. String File::real_path_for(const String& filename)
  117. {
  118. if (filename.is_null())
  119. return {};
  120. auto* path = realpath(filename.characters(), nullptr);
  121. String real_path(path);
  122. free(path);
  123. return real_path;
  124. }
  125. bool File::ensure_parent_directories(const String& path)
  126. {
  127. ASSERT(path.starts_with("/"));
  128. int saved_errno = 0;
  129. ScopeGuard restore_errno = [&saved_errno] { errno = saved_errno; };
  130. char* parent_buffer = strdup(path.characters());
  131. ScopeGuard free_buffer = [parent_buffer] { free(parent_buffer); };
  132. const char* parent = dirname(parent_buffer);
  133. int rc = mkdir(parent, 0755);
  134. saved_errno = errno;
  135. if (rc == 0 || errno == EEXIST)
  136. return true;
  137. if (errno != ENOENT)
  138. return false;
  139. bool ok = ensure_parent_directories(parent);
  140. saved_errno = errno;
  141. if (!ok)
  142. return false;
  143. rc = mkdir(parent, 0755);
  144. saved_errno = errno;
  145. return rc == 0;
  146. }
  147. #ifdef __serenity__
  148. String File::read_link(const StringView& link_path)
  149. {
  150. // First, try using a 64-byte buffer, that ought to be enough for anybody.
  151. char small_buffer[64];
  152. int rc = serenity_readlink(link_path.characters_without_null_termination(), link_path.length(), small_buffer, sizeof(small_buffer));
  153. if (rc < 0)
  154. return {};
  155. size_t size = rc;
  156. // If the call was successful, the syscall (unlike the LibC wrapper)
  157. // returns the full size of the link. Let's see if our small buffer
  158. // was enough to read the whole link.
  159. if (size <= sizeof(small_buffer))
  160. return { small_buffer, size };
  161. // Nope, but at least now we know the right size.
  162. char* large_buffer_ptr;
  163. auto large_buffer = StringImpl::create_uninitialized(size, large_buffer_ptr);
  164. rc = serenity_readlink(link_path.characters_without_null_termination(), link_path.length(), large_buffer_ptr, size);
  165. if (rc < 0)
  166. return {};
  167. size_t new_size = rc;
  168. if (new_size == size)
  169. return { *large_buffer };
  170. // If we're here, the symlink has changed while we were looking at it.
  171. // If it became shorter, our buffer is valid, we just have to trim it a bit.
  172. if (new_size < size)
  173. return { large_buffer_ptr, new_size };
  174. // Otherwise, here's not much we can do, unless we want to loop endlessly
  175. // in this case. Let's leave it up to the caller whether to loop.
  176. errno = EAGAIN;
  177. return {};
  178. }
  179. #else
  180. // This is a sad version for other systems. It has to always make a copy of the
  181. // link path, and to always make two syscalls to get the right size first.
  182. String File::read_link(const StringView& link_path)
  183. {
  184. String link_path_str = link_path;
  185. struct stat statbuf;
  186. int rc = lstat(link_path_str.characters(), &statbuf);
  187. if (rc < 0)
  188. return {};
  189. char* buffer_ptr;
  190. auto buffer = StringImpl::create_uninitialized(statbuf.st_size, buffer_ptr);
  191. rc = readlink(link_path_str.characters(), buffer_ptr, statbuf.st_size);
  192. if (rc < 0)
  193. return {};
  194. // (See above.)
  195. if (rc == statbuf.st_size)
  196. return { *buffer };
  197. return { buffer_ptr, (size_t)rc };
  198. }
  199. #endif
  200. static RefPtr<File> stdin_file;
  201. static RefPtr<File> stdout_file;
  202. static RefPtr<File> stderr_file;
  203. NonnullRefPtr<File> File::standard_input()
  204. {
  205. if (!stdin_file) {
  206. stdin_file = File::construct();
  207. stdin_file->open(STDIN_FILENO, IODevice::ReadOnly, ShouldCloseFileDescriptor::No);
  208. }
  209. return *stdin_file;
  210. }
  211. NonnullRefPtr<File> File::standard_output()
  212. {
  213. if (!stdout_file) {
  214. stdout_file = File::construct();
  215. stdout_file->open(STDOUT_FILENO, IODevice::WriteOnly, ShouldCloseFileDescriptor::No);
  216. }
  217. return *stdout_file;
  218. }
  219. NonnullRefPtr<File> File::standard_error()
  220. {
  221. if (!stderr_file) {
  222. stderr_file = File::construct();
  223. stderr_file->open(STDERR_FILENO, IODevice::WriteOnly, ShouldCloseFileDescriptor::No);
  224. }
  225. return *stderr_file;
  226. }
  227. }