TarWriter.cpp 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  1. //===-- TarWriter.cpp - Tar archive file creator --------------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // TarWriter class provides a feature to create a tar archive file.
  10. //
  11. // I put emphasis on simplicity over comprehensiveness when implementing this
  12. // class because we don't need a full-fledged archive file generator in LLVM
  13. // at the moment.
  14. //
  15. // The filename field in the Unix V7 tar header is 100 bytes. Longer filenames
  16. // are stored using the PAX extension. The PAX header is standardized in
  17. // POSIX.1-2001.
  18. //
  19. // The struct definition of UstarHeader is copied from
  20. // https://www.freebsd.org/cgi/man.cgi?query=tar&sektion=5
  21. //
  22. //===----------------------------------------------------------------------===//
  23. #include "llvm/Support/TarWriter.h"
  24. #include "llvm/ADT/StringRef.h"
  25. #include "llvm/Support/FileSystem.h"
  26. #include "llvm/Support/MathExtras.h"
  27. #include "llvm/Support/Path.h"
  28. using namespace llvm;
  29. // Each file in an archive must be aligned to this block size.
  30. static const int BlockSize = 512;
  31. struct UstarHeader {
  32. char Name[100];
  33. char Mode[8];
  34. char Uid[8];
  35. char Gid[8];
  36. char Size[12];
  37. char Mtime[12];
  38. char Checksum[8];
  39. char TypeFlag;
  40. char Linkname[100];
  41. char Magic[6];
  42. char Version[2];
  43. char Uname[32];
  44. char Gname[32];
  45. char DevMajor[8];
  46. char DevMinor[8];
  47. char Prefix[155];
  48. char Pad[12];
  49. };
  50. static_assert(sizeof(UstarHeader) == BlockSize, "invalid Ustar header");
  51. static UstarHeader makeUstarHeader() {
  52. UstarHeader Hdr = {};
  53. memcpy(Hdr.Magic, "ustar", 5); // Ustar magic
  54. memcpy(Hdr.Version, "00", 2); // Ustar version
  55. return Hdr;
  56. }
  57. // A PAX attribute is in the form of "<length> <key>=<value>\n"
  58. // where <length> is the length of the entire string including
  59. // the length field itself. An example string is this.
  60. //
  61. // 25 ctime=1084839148.1212\n
  62. //
  63. // This function create such string.
  64. static std::string formatPax(StringRef Key, StringRef Val) {
  65. int Len = Key.size() + Val.size() + 3; // +3 for " ", "=" and "\n"
  66. // We need to compute total size twice because appending
  67. // a length field could change total size by one.
  68. int Total = Len + Twine(Len).str().size();
  69. Total = Len + Twine(Total).str().size();
  70. return (Twine(Total) + " " + Key + "=" + Val + "\n").str();
  71. }
  72. // Headers in tar files must be aligned to 512 byte boundaries.
  73. // This function forwards the current file position to the next boundary.
  74. static void pad(raw_fd_ostream &OS) {
  75. uint64_t Pos = OS.tell();
  76. OS.seek(alignTo(Pos, BlockSize));
  77. }
  78. // Computes a checksum for a tar header.
  79. static void computeChecksum(UstarHeader &Hdr) {
  80. // Before computing a checksum, checksum field must be
  81. // filled with space characters.
  82. memset(Hdr.Checksum, ' ', sizeof(Hdr.Checksum));
  83. // Compute a checksum and set it to the checksum field.
  84. unsigned Chksum = 0;
  85. for (size_t I = 0; I < sizeof(Hdr); ++I)
  86. Chksum += reinterpret_cast<uint8_t *>(&Hdr)[I];
  87. snprintf(Hdr.Checksum, sizeof(Hdr.Checksum), "%06o", Chksum);
  88. }
  89. // Create a tar header and write it to a given output stream.
  90. static void writePaxHeader(raw_fd_ostream &OS, StringRef Path) {
  91. // A PAX header consists of a 512-byte header followed
  92. // by key-value strings. First, create key-value strings.
  93. std::string PaxAttr = formatPax("path", Path);
  94. // Create a 512-byte header.
  95. UstarHeader Hdr = makeUstarHeader();
  96. snprintf(Hdr.Size, sizeof(Hdr.Size), "%011zo", PaxAttr.size());
  97. Hdr.TypeFlag = 'x'; // PAX magic
  98. computeChecksum(Hdr);
  99. // Write them down.
  100. OS << StringRef(reinterpret_cast<char *>(&Hdr), sizeof(Hdr));
  101. OS << PaxAttr;
  102. pad(OS);
  103. }
  104. // Path fits in a Ustar header if
  105. //
  106. // - Path is less than 100 characters long, or
  107. // - Path is in the form of "<prefix>/<name>" where <prefix> is less
  108. // than or equal to 155 characters long and <name> is less than 100
  109. // characters long. Both <prefix> and <name> can contain extra '/'.
  110. //
  111. // If Path fits in a Ustar header, updates Prefix and Name and returns true.
  112. // Otherwise, returns false.
  113. static bool splitUstar(StringRef Path, StringRef &Prefix, StringRef &Name) {
  114. if (Path.size() < sizeof(UstarHeader::Name)) {
  115. Prefix = "";
  116. Name = Path;
  117. return true;
  118. }
  119. // tar 1.13 and earlier unconditionally look at the tar header interpreted
  120. // as an 'oldgnu_header', which has an 'isextended' byte at offset 482 in the
  121. // header, corresponding to offset 137 in the prefix. That's the version of
  122. // tar in gnuwin, so only use 137 of the 155 bytes in the prefix. This means
  123. // we'll need a pax header after 237 bytes of path instead of after 255,
  124. // but in return paths up to 237 bytes work with gnuwin, instead of just
  125. // 137 bytes of directory + 100 bytes of basename previously.
  126. // (tar-1.13 also doesn't support pax headers, but in practice all paths in
  127. // llvm's test suite are short enough for that to not matter.)
  128. const int MaxPrefix = 137;
  129. size_t Sep = Path.rfind('/', MaxPrefix + 1);
  130. if (Sep == StringRef::npos)
  131. return false;
  132. if (Path.size() - Sep - 1 >= sizeof(UstarHeader::Name))
  133. return false;
  134. Prefix = Path.substr(0, Sep);
  135. Name = Path.substr(Sep + 1);
  136. return true;
  137. }
  138. // The PAX header is an extended format, so a PAX header needs
  139. // to be followed by a "real" header.
  140. static void writeUstarHeader(raw_fd_ostream &OS, StringRef Prefix,
  141. StringRef Name, size_t Size) {
  142. UstarHeader Hdr = makeUstarHeader();
  143. memcpy(Hdr.Name, Name.data(), Name.size());
  144. memcpy(Hdr.Mode, "0000664", 8);
  145. snprintf(Hdr.Size, sizeof(Hdr.Size), "%011zo", Size);
  146. memcpy(Hdr.Prefix, Prefix.data(), Prefix.size());
  147. computeChecksum(Hdr);
  148. OS << StringRef(reinterpret_cast<char *>(&Hdr), sizeof(Hdr));
  149. }
  150. // Creates a TarWriter instance and returns it.
  151. Expected<std::unique_ptr<TarWriter>> TarWriter::create(StringRef OutputPath,
  152. StringRef BaseDir) {
  153. using namespace sys::fs;
  154. int FD;
  155. if (std::error_code EC =
  156. openFileForWrite(OutputPath, FD, CD_CreateAlways, OF_None))
  157. return make_error<StringError>("cannot open " + OutputPath, EC);
  158. return std::unique_ptr<TarWriter>(new TarWriter(FD, BaseDir));
  159. }
  160. TarWriter::TarWriter(int FD, StringRef BaseDir)
  161. : OS(FD, /*shouldClose=*/true, /*unbuffered=*/false),
  162. BaseDir(std::string(BaseDir)) {}
  163. // Append a given file to an archive.
  164. void TarWriter::append(StringRef Path, StringRef Data) {
  165. // Write Path and Data.
  166. std::string Fullpath = BaseDir + "/" + sys::path::convert_to_slash(Path);
  167. // We do not want to include the same file more than once.
  168. if (!Files.insert(Fullpath).second)
  169. return;
  170. StringRef Prefix;
  171. StringRef Name;
  172. if (splitUstar(Fullpath, Prefix, Name)) {
  173. writeUstarHeader(OS, Prefix, Name, Data.size());
  174. } else {
  175. writePaxHeader(OS, Fullpath);
  176. writeUstarHeader(OS, "", "", Data.size());
  177. }
  178. OS << Data;
  179. pad(OS);
  180. // POSIX requires tar archives end with two null blocks.
  181. // Here, we write the terminator and then seek back, so that
  182. // the file being output is terminated correctly at any moment.
  183. uint64_t Pos = OS.tell();
  184. OS << std::string(BlockSize * 2, '\0');
  185. OS.seek(Pos);
  186. OS.flush();
  187. }