File.cpp 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270
  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. #endif
  29. #include <AK/ScopeGuard.h>
  30. #include <LibCore/File.h>
  31. #include <errno.h>
  32. #include <fcntl.h>
  33. #include <libgen.h>
  34. #include <stdio.h>
  35. #include <string.h>
  36. #include <sys/stat.h>
  37. #include <unistd.h>
  38. namespace Core {
  39. Result<NonnullRefPtr<File>, String> File::open(const String& filename, IODevice::OpenMode mode, mode_t permissions)
  40. {
  41. auto file = File::construct(filename);
  42. if (!file->open_impl(mode, permissions))
  43. return String(file->error_string());
  44. return file;
  45. }
  46. File::File(const StringView& filename, Object* parent)
  47. : IODevice(parent)
  48. , m_filename(filename)
  49. {
  50. }
  51. File::~File()
  52. {
  53. if (m_should_close_file_descriptor == ShouldCloseFileDescriptor::Yes && mode() != NotOpen)
  54. close();
  55. }
  56. bool File::open(int fd, IODevice::OpenMode mode, ShouldCloseFileDescriptor should_close)
  57. {
  58. set_fd(fd);
  59. set_mode(mode);
  60. m_should_close_file_descriptor = should_close;
  61. return true;
  62. }
  63. bool File::open(IODevice::OpenMode mode)
  64. {
  65. return open_impl(mode, 0666);
  66. }
  67. bool File::open_impl(IODevice::OpenMode mode, mode_t permissions)
  68. {
  69. ASSERT(!m_filename.is_null());
  70. int flags = 0;
  71. if ((mode & IODevice::ReadWrite) == IODevice::ReadWrite) {
  72. flags |= O_RDWR | O_CREAT;
  73. } else if (mode & IODevice::ReadOnly) {
  74. flags |= O_RDONLY;
  75. } else if (mode & IODevice::WriteOnly) {
  76. flags |= O_WRONLY | O_CREAT;
  77. bool should_truncate = !((mode & IODevice::Append) || (mode & IODevice::MustBeNew));
  78. if (should_truncate)
  79. flags |= O_TRUNC;
  80. }
  81. if (mode & IODevice::Append)
  82. flags |= O_APPEND;
  83. if (mode & IODevice::Truncate)
  84. flags |= O_TRUNC;
  85. if (mode & IODevice::MustBeNew)
  86. flags |= O_EXCL;
  87. int fd = ::open(m_filename.characters(), flags, permissions);
  88. if (fd < 0) {
  89. set_error(errno);
  90. return false;
  91. }
  92. set_fd(fd);
  93. set_mode(mode);
  94. return true;
  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. ASSERT(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(const StringView& link_path)
  148. {
  149. // First, try using a 64-byte buffer, that ought to be enough for anybody.
  150. char small_buffer[64];
  151. Syscall::SC_readlink_params small_params {
  152. { link_path.characters_without_null_termination(), link_path.length() },
  153. { small_buffer, sizeof(small_buffer) }
  154. };
  155. int rc = syscall(SC_readlink, &small_params);
  156. if (rc < 0) {
  157. errno = -rc;
  158. return {};
  159. }
  160. size_t size = rc;
  161. // If the call was successful, the syscall (unlike the LibC wrapper)
  162. // returns the full size of the link. Let's see if our small buffer
  163. // was enough to read the whole link.
  164. if (size <= sizeof(small_buffer))
  165. return { small_buffer, size };
  166. // Nope, but at least now we know the right size.
  167. char* large_buffer_ptr;
  168. auto large_buffer = StringImpl::create_uninitialized(size, large_buffer_ptr);
  169. Syscall::SC_readlink_params large_params {
  170. { link_path.characters_without_null_termination(), link_path.length() },
  171. { large_buffer_ptr, (size_t)size }
  172. };
  173. rc = syscall(SC_readlink, &large_params);
  174. if (rc < 0) {
  175. errno = -rc;
  176. return {};
  177. }
  178. size_t new_size = rc;
  179. if (new_size == size)
  180. return { *large_buffer };
  181. // If we're here, the symlink has changed while we were looking at it.
  182. // If it became shorter, our buffer is valid, we just have to trim it a bit.
  183. if (new_size < size)
  184. return { large_buffer_ptr, new_size };
  185. // Otherwise, here's not much we can do, unless we want to loop endlessly
  186. // in this case. Let's leave it up to the caller whether to loop.
  187. errno = -EAGAIN;
  188. return {};
  189. }
  190. #else
  191. // This is a sad version for other systems. It has to always make a copy of the
  192. // link path, and to always make two syscalls to get the right size first.
  193. String File::read_link(const StringView& link_path)
  194. {
  195. String link_path_str = link_path;
  196. struct stat statbuf;
  197. int rc = lstat(link_path_str.characters(), &statbuf);
  198. if (rc < 0)
  199. return {};
  200. char* buffer_ptr;
  201. auto buffer = StringImpl::create_uninitialized(statbuf.st_size, buffer_ptr);
  202. rc = readlink(link_path_str.characters(), buffer_ptr, statbuf.st_size);
  203. if (rc < 0)
  204. return {};
  205. // (See above.)
  206. if (rc == statbuf.st_size)
  207. return { *buffer };
  208. return { buffer_ptr, (size_t)rc };
  209. }
  210. #endif
  211. static RefPtr<File> stdin_file;
  212. static RefPtr<File> stdout_file;
  213. static RefPtr<File> stderr_file;
  214. NonnullRefPtr<File> File::standard_input()
  215. {
  216. if (!stdin_file) {
  217. stdin_file = File::construct();
  218. stdin_file->open(STDIN_FILENO, IODevice::ReadOnly, ShouldCloseFileDescriptor::No);
  219. }
  220. return *stdin_file;
  221. }
  222. NonnullRefPtr<File> File::standard_output()
  223. {
  224. if (!stdout_file) {
  225. stdout_file = File::construct();
  226. stdout_file->open(STDOUT_FILENO, IODevice::WriteOnly, ShouldCloseFileDescriptor::No);
  227. }
  228. return *stdout_file;
  229. }
  230. NonnullRefPtr<File> File::standard_error()
  231. {
  232. if (!stderr_file) {
  233. stderr_file = File::construct();
  234. stderr_file->open(STDERR_FILENO, IODevice::WriteOnly, ShouldCloseFileDescriptor::No);
  235. }
  236. return *stderr_file;
  237. }
  238. }