tar.cpp 11 KB

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