FileUtils.cpp 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  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. #include "FileUtils.h"
  27. #include <AK/LexicalPath.h>
  28. #include <AK/ScopeGuard.h>
  29. #include <AK/StringBuilder.h>
  30. #include <LibCore/DirIterator.h>
  31. #include <LibCore/File.h>
  32. #include <LibGUI/MessageBox.h>
  33. #include <stdio.h>
  34. #include <stdlib.h>
  35. #include <sys/stat.h>
  36. #include <unistd.h>
  37. namespace FileUtils {
  38. void delete_paths(const Vector<String>& paths, bool should_confirm, GUI::Window* parent_window)
  39. {
  40. String message;
  41. if (paths.size() == 1) {
  42. message = String::formatted("Really delete {}?", LexicalPath(paths[0]).basename());
  43. } else {
  44. message = String::formatted("Really delete {} files?", paths.size());
  45. }
  46. if (should_confirm) {
  47. auto result = GUI::MessageBox::show(parent_window,
  48. message,
  49. "Confirm deletion",
  50. GUI::MessageBox::Type::Warning,
  51. GUI::MessageBox::InputType::OKCancel);
  52. if (result == GUI::MessageBox::ExecCancel)
  53. return;
  54. }
  55. for (auto& path : paths) {
  56. struct stat st;
  57. if (lstat(path.characters(), &st)) {
  58. GUI::MessageBox::show(parent_window,
  59. String::formatted("lstat({}) failed: {}", path, strerror(errno)),
  60. "Delete failed",
  61. GUI::MessageBox::Type::Error);
  62. break;
  63. }
  64. if (S_ISDIR(st.st_mode)) {
  65. String error_path;
  66. int error = FileUtils::delete_directory(path, error_path);
  67. if (error) {
  68. GUI::MessageBox::show(parent_window,
  69. String::formatted("Failed to delete directory \"{}\": {}", error_path, strerror(error)),
  70. "Delete failed",
  71. GUI::MessageBox::Type::Error);
  72. break;
  73. }
  74. } else if (unlink(path.characters()) < 0) {
  75. int saved_errno = errno;
  76. GUI::MessageBox::show(parent_window,
  77. String::formatted("unlink(\"{}\") failed: {}", path, strerror(saved_errno)),
  78. "Delete failed",
  79. GUI::MessageBox::Type::Error);
  80. break;
  81. }
  82. }
  83. }
  84. int delete_directory(String directory, String& file_that_caused_error)
  85. {
  86. Core::DirIterator iterator(directory, Core::DirIterator::SkipDots);
  87. if (iterator.has_error()) {
  88. file_that_caused_error = directory;
  89. return -1;
  90. }
  91. while (iterator.has_next()) {
  92. auto file_to_delete = String::formatted("{}/{}", directory, iterator.next_path());
  93. struct stat st;
  94. if (lstat(file_to_delete.characters(), &st)) {
  95. file_that_caused_error = file_to_delete;
  96. return errno;
  97. }
  98. if (S_ISDIR(st.st_mode)) {
  99. if (delete_directory(file_to_delete, file_to_delete)) {
  100. file_that_caused_error = file_to_delete;
  101. return errno;
  102. }
  103. } else if (unlink(file_to_delete.characters())) {
  104. file_that_caused_error = file_to_delete;
  105. return errno;
  106. }
  107. }
  108. if (rmdir(directory.characters())) {
  109. file_that_caused_error = directory;
  110. return errno;
  111. }
  112. return 0;
  113. }
  114. bool copy_file_or_directory(const String& src_path, const String& dst_path)
  115. {
  116. int duplicate_count = 0;
  117. while (access(get_duplicate_name(dst_path, duplicate_count).characters(), F_OK) == 0) {
  118. ++duplicate_count;
  119. }
  120. if (duplicate_count != 0) {
  121. return copy_file_or_directory(src_path, get_duplicate_name(dst_path, duplicate_count));
  122. }
  123. auto source_or_error = Core::File::open(src_path, Core::IODevice::ReadOnly);
  124. if (source_or_error.is_error())
  125. return false;
  126. auto& source = *source_or_error.value();
  127. struct stat src_stat;
  128. int rc = fstat(source.fd(), &src_stat);
  129. if (rc < 0)
  130. return false;
  131. if (source.is_directory())
  132. return copy_directory(src_path, dst_path, src_stat);
  133. return copy_file(dst_path, src_stat, source);
  134. }
  135. bool copy_directory(const String& src_path, const String& dst_path, const struct stat& src_stat)
  136. {
  137. int rc = mkdir(dst_path.characters(), 0755);
  138. if (rc < 0) {
  139. return false;
  140. }
  141. Core::DirIterator di(src_path, Core::DirIterator::SkipDots);
  142. if (di.has_error()) {
  143. return false;
  144. }
  145. while (di.has_next()) {
  146. String filename = di.next_path();
  147. bool is_copied = copy_file_or_directory(
  148. String::formatted("{}/{}", src_path, filename),
  149. String::formatted("{}/{}", dst_path, filename));
  150. if (!is_copied) {
  151. return false;
  152. }
  153. }
  154. auto my_umask = umask(0);
  155. umask(my_umask);
  156. rc = chmod(dst_path.characters(), src_stat.st_mode & ~my_umask);
  157. if (rc < 0) {
  158. return false;
  159. }
  160. return true;
  161. }
  162. bool copy_file(const String& dst_path, const struct stat& src_stat, Core::File& source)
  163. {
  164. int dst_fd = creat(dst_path.characters(), 0666);
  165. if (dst_fd < 0) {
  166. if (errno != EISDIR) {
  167. return false;
  168. }
  169. auto dst_dir_path = String::formatted("{}/{}", dst_path, LexicalPath(source.filename()).basename());
  170. dst_fd = creat(dst_dir_path.characters(), 0666);
  171. if (dst_fd < 0) {
  172. return false;
  173. }
  174. }
  175. ScopeGuard close_fd_guard([dst_fd]() { close(dst_fd); });
  176. if (src_stat.st_size > 0) {
  177. if (ftruncate(dst_fd, src_stat.st_size) < 0) {
  178. perror("cp: ftruncate");
  179. return false;
  180. }
  181. }
  182. for (;;) {
  183. char buffer[32768];
  184. ssize_t nread = read(source.fd(), buffer, sizeof(buffer));
  185. if (nread < 0) {
  186. return false;
  187. }
  188. if (nread == 0)
  189. break;
  190. ssize_t remaining_to_write = nread;
  191. char* bufptr = buffer;
  192. while (remaining_to_write) {
  193. ssize_t nwritten = write(dst_fd, bufptr, remaining_to_write);
  194. if (nwritten < 0) {
  195. return false;
  196. }
  197. assert(nwritten > 0);
  198. remaining_to_write -= nwritten;
  199. bufptr += nwritten;
  200. }
  201. }
  202. auto my_umask = umask(0);
  203. umask(my_umask);
  204. int rc = fchmod(dst_fd, src_stat.st_mode & ~my_umask);
  205. if (rc < 0) {
  206. return false;
  207. }
  208. return true;
  209. }
  210. bool link_file(const String& src_path, const String& dst_path)
  211. {
  212. int duplicate_count = 0;
  213. while (access(get_duplicate_name(dst_path, duplicate_count).characters(), F_OK) == 0) {
  214. ++duplicate_count;
  215. }
  216. if (duplicate_count != 0) {
  217. return link_file(src_path, get_duplicate_name(dst_path, duplicate_count));
  218. }
  219. int rc = symlink(src_path.characters(), dst_path.characters());
  220. if (rc < 0) {
  221. return false;
  222. }
  223. return true;
  224. }
  225. String get_duplicate_name(const String& path, int duplicate_count)
  226. {
  227. if (duplicate_count == 0) {
  228. return path;
  229. }
  230. LexicalPath lexical_path(path);
  231. StringBuilder duplicated_name;
  232. duplicated_name.append('/');
  233. for (size_t i = 0; i < lexical_path.parts().size() - 1; ++i) {
  234. duplicated_name.appendff("{}/", lexical_path.parts()[i]);
  235. }
  236. auto prev_duplicate_tag = String::formatted("({})", duplicate_count);
  237. auto title = lexical_path.title();
  238. if (title.ends_with(prev_duplicate_tag)) {
  239. // remove the previous duplicate tag "(n)" so we can add a new tag.
  240. title = title.substring(0, title.length() - prev_duplicate_tag.length());
  241. }
  242. duplicated_name.appendff("{} ({})", lexical_path.title(), duplicate_count);
  243. if (!lexical_path.extension().is_empty()) {
  244. duplicated_name.appendff(".{}", lexical_path.extension());
  245. }
  246. return duplicated_name.build();
  247. }
  248. }