tar.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  1. /*
  2. * Copyright (c) 2020, Peter Elliott <pelliott@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include "LibCore/Directory.h"
  7. #include <AK/Assertions.h>
  8. #include <AK/LexicalPath.h>
  9. #include <AK/Span.h>
  10. #include <AK/Vector.h>
  11. #include <LibArchive/TarStream.h>
  12. #include <LibCompress/Gzip.h>
  13. #include <LibCore/ArgsParser.h>
  14. #include <LibCore/DirIterator.h>
  15. #include <LibCore/File.h>
  16. #include <LibCore/FileStream.h>
  17. #include <LibCore/System.h>
  18. #include <LibMain/Main.h>
  19. #include <fcntl.h>
  20. #include <stdio.h>
  21. #include <sys/stat.h>
  22. #include <unistd.h>
  23. constexpr size_t buffer_size = 4096;
  24. ErrorOr<int> serenity_main(Main::Arguments arguments)
  25. {
  26. bool create = false;
  27. bool extract = false;
  28. bool list = false;
  29. bool verbose = false;
  30. bool gzip = false;
  31. bool no_auto_compress = false;
  32. StringView archive_file;
  33. StringView directory;
  34. Vector<String> paths;
  35. Core::ArgsParser args_parser;
  36. args_parser.add_option(create, "Create archive", "create", 'c');
  37. args_parser.add_option(extract, "Extract archive", "extract", 'x');
  38. args_parser.add_option(list, "List contents", "list", 't');
  39. args_parser.add_option(verbose, "Print paths", "verbose", 'v');
  40. args_parser.add_option(gzip, "Compress or decompress file using gzip", "gzip", 'z');
  41. args_parser.add_option(no_auto_compress, "Do not use the archive suffix to select the compression algorithm", "no-auto-compress", 0);
  42. args_parser.add_option(directory, "Directory to extract to/create from", "directory", 'C', "DIRECTORY");
  43. args_parser.add_option(archive_file, "Archive file", "file", 'f', "FILE");
  44. args_parser.add_positional_argument(paths, "Paths", "PATHS", Core::ArgsParser::Required::No);
  45. args_parser.parse(arguments);
  46. if (create + extract + list != 1) {
  47. warnln("exactly one of -c, -x, and -t can be used");
  48. return 1;
  49. }
  50. if (!no_auto_compress && !archive_file.is_empty()) {
  51. if (archive_file.ends_with(".gz"sv) || archive_file.ends_with(".tgz"sv))
  52. gzip = true;
  53. }
  54. if (list || extract) {
  55. auto file = Core::File::standard_input();
  56. if (!archive_file.is_empty())
  57. file = TRY(Core::File::open(archive_file, Core::OpenMode::ReadOnly));
  58. if (!directory.is_empty())
  59. TRY(Core::System::chdir(directory));
  60. Core::InputFileStream file_stream(file);
  61. Compress::GzipDecompressor gzip_stream(file_stream);
  62. InputStream& file_input_stream = file_stream;
  63. InputStream& gzip_input_stream = gzip_stream;
  64. Archive::TarInputStream tar_stream((gzip) ? gzip_input_stream : file_input_stream);
  65. // FIXME: implement ErrorOr<TarInputStream>?
  66. if (!tar_stream.valid()) {
  67. warnln("the provided file is not a well-formatted ustar file");
  68. return 1;
  69. }
  70. HashMap<String, String> global_overrides;
  71. HashMap<String, String> local_overrides;
  72. auto get_override = [&](StringView key) -> Optional<String> {
  73. Optional<String> maybe_local = local_overrides.get(key);
  74. if (maybe_local.has_value())
  75. return maybe_local;
  76. Optional<String> maybe_global = global_overrides.get(key);
  77. if (maybe_global.has_value())
  78. return maybe_global;
  79. return {};
  80. };
  81. for (; !tar_stream.finished(); tar_stream.advance()) {
  82. Archive::TarFileHeader const& header = tar_stream.header();
  83. // Handle meta-entries earlier to avoid consuming the file content stream.
  84. if (header.content_is_like_extended_header()) {
  85. switch (header.type_flag()) {
  86. case Archive::TarFileType::GlobalExtendedHeader: {
  87. TRY(tar_stream.for_each_extended_header([&](StringView key, StringView value) {
  88. if (value.length() == 0)
  89. global_overrides.remove(key);
  90. else
  91. global_overrides.set(key, value);
  92. }));
  93. break;
  94. }
  95. case Archive::TarFileType::ExtendedHeader: {
  96. TRY(tar_stream.for_each_extended_header([&](StringView key, StringView value) {
  97. local_overrides.set(key, value);
  98. }));
  99. break;
  100. }
  101. default:
  102. warnln("Unknown extended header type '{}' of {}", (char)header.type_flag(), header.filename());
  103. VERIFY_NOT_REACHED();
  104. }
  105. continue;
  106. }
  107. Archive::TarFileStream file_stream = tar_stream.file_contents();
  108. // Handle other header types that don't just have an effect on extraction.
  109. switch (header.type_flag()) {
  110. case Archive::TarFileType::LongName: {
  111. StringBuilder long_name;
  112. Array<u8, buffer_size> buffer;
  113. size_t bytes_read;
  114. while ((bytes_read = file_stream.read(buffer)) > 0)
  115. long_name.append(reinterpret_cast<char*>(buffer.data()), bytes_read);
  116. local_overrides.set("path", long_name.to_string());
  117. continue;
  118. }
  119. default:
  120. // None of the relevant headers, so continue as normal.
  121. break;
  122. }
  123. LexicalPath path = LexicalPath(header.filename());
  124. if (!header.prefix().is_empty())
  125. path = path.prepend(header.prefix());
  126. String filename = get_override("path"sv).value_or(path.string());
  127. if (list || verbose)
  128. outln("{}", filename);
  129. if (extract) {
  130. String absolute_path = Core::File::absolute_path(filename);
  131. auto parent_path = LexicalPath(absolute_path).parent();
  132. switch (header.type_flag()) {
  133. case Archive::TarFileType::NormalFile:
  134. case Archive::TarFileType::AlternateNormalFile: {
  135. MUST(Core::Directory::create(parent_path, Core::Directory::CreateDirectories::Yes));
  136. int fd = TRY(Core::System::open(absolute_path, O_CREAT | O_WRONLY, header.mode()));
  137. Array<u8, buffer_size> buffer;
  138. size_t bytes_read;
  139. while ((bytes_read = file_stream.read(buffer)) > 0)
  140. TRY(Core::System::write(fd, buffer.span().slice(0, bytes_read)));
  141. TRY(Core::System::close(fd));
  142. break;
  143. }
  144. case Archive::TarFileType::SymLink: {
  145. MUST(Core::Directory::create(parent_path, Core::Directory::CreateDirectories::Yes));
  146. TRY(Core::System::symlink(header.link_name(), absolute_path));
  147. break;
  148. }
  149. case Archive::TarFileType::Directory: {
  150. MUST(Core::Directory::create(parent_path, Core::Directory::CreateDirectories::Yes));
  151. auto result_or_error = Core::System::mkdir(absolute_path, header.mode());
  152. if (result_or_error.is_error() && result_or_error.error().code() != EEXIST)
  153. return result_or_error.error();
  154. break;
  155. }
  156. default:
  157. // FIXME: Implement other file types
  158. warnln("file type '{}' of {} is not yet supported", (char)header.type_flag(), header.filename());
  159. VERIFY_NOT_REACHED();
  160. }
  161. }
  162. // Non-global headers should be cleared after every file.
  163. local_overrides.clear();
  164. }
  165. file_stream.close();
  166. return 0;
  167. }
  168. if (create) {
  169. if (paths.size() == 0) {
  170. warnln("you must provide at least one path to be archived");
  171. return 1;
  172. }
  173. auto file = Core::File::standard_output();
  174. if (!archive_file.is_empty())
  175. file = TRY(Core::File::open(archive_file, Core::OpenMode::WriteOnly));
  176. if (!directory.is_empty())
  177. TRY(Core::System::chdir(directory));
  178. Core::OutputFileStream file_stream(file);
  179. Compress::GzipCompressor gzip_stream(file_stream);
  180. OutputStream& file_output_stream = file_stream;
  181. OutputStream& gzip_output_stream = gzip_stream;
  182. Archive::TarOutputStream tar_stream((gzip) ? gzip_output_stream : file_output_stream);
  183. auto add_file = [&](String path) -> ErrorOr<void> {
  184. auto file = Core::File::construct(path);
  185. if (!file->open(Core::OpenMode::ReadOnly)) {
  186. warnln("Failed to open {}: {}", path, file->error_string());
  187. return {};
  188. }
  189. auto statbuf_or_error = Core::System::lstat(path);
  190. if (statbuf_or_error.is_error())
  191. return statbuf_or_error.error();
  192. auto statbuf = statbuf_or_error.value();
  193. auto canonicalized_path = LexicalPath::canonicalized_path(path);
  194. tar_stream.add_file(canonicalized_path, statbuf.st_mode, file->read_all());
  195. if (verbose)
  196. outln("{}", canonicalized_path);
  197. return {};
  198. };
  199. auto add_directory = [&](String path, auto handle_directory) -> ErrorOr<void> {
  200. auto statbuf_or_error = Core::System::lstat(path);
  201. if (statbuf_or_error.is_error())
  202. return statbuf_or_error.error();
  203. auto statbuf = statbuf_or_error.value();
  204. auto canonicalized_path = LexicalPath::canonicalized_path(path);
  205. tar_stream.add_directory(canonicalized_path, statbuf.st_mode);
  206. if (verbose)
  207. outln("{}", canonicalized_path);
  208. Core::DirIterator it(path, Core::DirIterator::Flags::SkipParentAndBaseDir);
  209. while (it.has_next()) {
  210. auto child_path = it.next_full_path();
  211. if (!Core::File::is_directory(child_path)) {
  212. TRY(add_file(child_path));
  213. } else {
  214. TRY(handle_directory(child_path, handle_directory));
  215. }
  216. }
  217. return {};
  218. };
  219. for (auto const& path : paths) {
  220. if (Core::File::is_directory(path)) {
  221. TRY(add_directory(path, add_directory));
  222. } else {
  223. TRY(add_file(path));
  224. }
  225. }
  226. tar_stream.finish();
  227. return 0;
  228. }
  229. return 0;
  230. }