BellTar.cpp 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  1. #include "BellTar.h"
  2. #include <sys/stat.h> // for mkdir
  3. using namespace bell::BellTar;
  4. #include <algorithm> // for min
  5. #include <cassert> // for assert
  6. #include <cstdint> // for uint8_t
  7. #include <cstdio> // for sprintf, size_t, sscanf, EOF, NULL
  8. #include <cstdlib> // for rand
  9. #include <cstring> // for memset, strlen
  10. #include <ctime> // for time
  11. #include <fstream> // for ofstream
  12. #include <vector> // for vector
  13. #ifdef _WIN32
  14. #include <direct.h>
  15. #endif
  16. #ifdef ENABLE_LOGGING
  17. #define LOG printf
  18. #else
  19. #ifdef _WIN32
  20. #define LOG(fmt, ...) ((void)0)
  21. #else
  22. #define LOG(fmt, args...) ((void)0)
  23. #endif
  24. #endif
  25. const char FILL_CHAR = '\0';
  26. const int FILE_NAME_LENGTH = 100;
  27. // From http://en.wikipedia.org/wiki/Tar_(computing)#UStar_format
  28. typedef enum tar_file_type {
  29. tar_file_type_normal = '0',
  30. tar_file_type_hard_link = '1',
  31. tar_file_type_soft_link = '2',
  32. tar_file_type_directory = '5'
  33. } tar_file_type_t;
  34. struct tar_header {
  35. char name[FILE_NAME_LENGTH]; // file name
  36. char mode[8]; // file mode
  37. char uid[8]; // Owner's numeric user ID
  38. char gid[8]; // Group's numeric user ID
  39. char size[12]; // File size in bytes (octal base)
  40. char mtime[12]; // Last modification time in
  41. // numeric Unix time format (octal)
  42. char checksum[8]; // Checksum for header record
  43. char typeflag[1]; // file type, see tar_file_type_t
  44. char linkname[100]; // Name of linked file
  45. char magic[6]; // UStar indicator "ustar"
  46. char version[2]; // UStar version "00"
  47. char uname[32]; // Owner user name
  48. char gname[32]; // Owner group name
  49. char devmajor[8]; // Device major number
  50. char devminor[8]; // Device minor number
  51. char prefix[155]; // Filename prefix
  52. char pad[12]; // padding
  53. };
  54. void header_set_metadata(tar_header* header) {
  55. std::memset(header, 0, sizeof(tar_header));
  56. std::sprintf(header->magic, "ustar");
  57. std::sprintf(header->mtime, "%011lo", (unsigned long)std::time(NULL));
  58. std::sprintf(header->mode, "%07o", 0644);
  59. std::sprintf(header->uname, "unkown"); // ... a bit random
  60. std::sprintf(header->gname, "users");
  61. header->typeflag[0] = 0; // always just a normal file
  62. }
  63. /* From Wikipedia: The checksum is calculated by taking the sum of the
  64. * unsigned byte values of the header record with the eight checksum
  65. * bytes taken to be ascii spaces. */
  66. void header_set_checksum(tar_header* header) {
  67. unsigned int sum = 0;
  68. char* pointer = (char*)header;
  69. char* end = pointer + sizeof(tar_header);
  70. // Iterate over header struct until we are at checksum field.
  71. while (pointer < header->checksum) {
  72. sum += *pointer & 0xff;
  73. pointer++;
  74. }
  75. // ... then add eight 'ascii spaces' ...
  76. sum += ' ' * 8;
  77. pointer += 8;
  78. // ... and go until the end.
  79. while (pointer < end) {
  80. sum += *pointer & 0xff;
  81. pointer++;
  82. }
  83. std::sprintf(header->checksum, "%06o", sum);
  84. }
  85. void header_set_filetype(tar_header* header, tar_file_type_t file_type) {
  86. header->typeflag[0] = file_type;
  87. }
  88. tar_file_type_t header_get_filetype(tar_header* header) {
  89. return tar_file_type_t(header->typeflag[0]);
  90. }
  91. void header_set_filesize(tar_header* header, file_size_t file_size) {
  92. std::sprintf(header->size, "%011llo", file_size);
  93. }
  94. file_size_t header_get_filesize(tar_header* header) {
  95. file_size_t file_size;
  96. std::sscanf(header->size, "%011llo", &file_size);
  97. return file_size;
  98. }
  99. void header_set_filename(tar_header* header, const char* file_name) {
  100. size_t len = std::strlen(file_name);
  101. // len > 0 also ensures that the header does not start with \0
  102. if (len == 0 || len >= FILE_NAME_LENGTH) {
  103. LOG("Invalid file name for tar: %s\n", file_name);
  104. std::sprintf(header->name, "INVALID_%d", std::rand());
  105. } else {
  106. std::sprintf(header->name, "%s", file_name);
  107. }
  108. }
  109. std::string header_get_filename(tar_header* header) {
  110. return std::string(header->name);
  111. }
  112. ////////////////////////////////////////
  113. /* Every file in a tar file starts with the tar header */
  114. void _write_header(std::ostream& dst, const char* file_name,
  115. file_size_t file_size,
  116. tar_file_type_t file_type = tar_file_type_normal) {
  117. tar_header header;
  118. header_set_metadata(&header);
  119. header_set_filename(&header, file_name);
  120. header_set_filesize(&header, file_size);
  121. header_set_filetype(&header, file_type);
  122. header_set_checksum(&header);
  123. dst.write((const char*)&header, sizeof(tar_header));
  124. }
  125. void _read_header(std::istream& inp, tar_header* header) {
  126. inp.read((char*)header, sizeof(tar_header));
  127. }
  128. /* The length of the data after the header must be rounded up to a
  129. multiple of 512 bytes, the length of the header. */
  130. void _fill(std::ostream& dst, unsigned long file_size) {
  131. while (file_size % sizeof(tar_header) != 0) {
  132. dst.put(FILL_CHAR);
  133. file_size++;
  134. }
  135. }
  136. bool _check_if_header_is_next(std::istream& inp) {
  137. if (inp.eof() || inp.peek() == EOF) {
  138. LOG("Can not read next file info, istream at EOF.\n");
  139. return false;
  140. }
  141. if (inp.peek() == FILL_CHAR) {
  142. LOG("Can not read next file info, istream is pointing "
  143. "to %d, which a tar header can not start with.\n",
  144. FILL_CHAR);
  145. return false;
  146. }
  147. return true;
  148. }
  149. void _seek_to_next_header(std::istream& inp) {
  150. // Advance to start of next header or to end of file
  151. // Works because
  152. // - header never starts with FILL_CHAR
  153. // - at end of file, peek() returns EOF.
  154. // - FILL_CHAR != EOF
  155. while (inp.peek() == FILL_CHAR)
  156. inp.get();
  157. }
  158. ////////////////////////////////////////
  159. // writer Implementation
  160. ////////////////////////////////////////
  161. void writer::put(std::string path_in_tar, char const* const data,
  162. const file_size_t data_size) {
  163. _write_header(_dst, path_in_tar.c_str(), data_size);
  164. _dst.write(data, data_size);
  165. _fill(_dst, data_size);
  166. }
  167. void writer::put_directory(std::string path_in_tar) {
  168. _write_header(_dst, path_in_tar.c_str(), 0, tar_file_type_directory);
  169. }
  170. /* The end of an tar is marked by at least two consecutive zero-filled
  171. * records, a record having the size of the header. */
  172. void writer::finish() {
  173. unsigned long i = 0;
  174. while (i < 2 * sizeof(tar_header)) {
  175. _dst.put(FILL_CHAR);
  176. i++;
  177. }
  178. }
  179. ////////////////////////////////////////
  180. // reader Implementation
  181. ////////////////////////////////////////
  182. bool reader::contains_another_file() {
  183. return _check_if_header_is_next(_inp);
  184. }
  185. void reader::_cache_header() {
  186. if (_cached_header_data_valid)
  187. return;
  188. assert(contains_another_file());
  189. tar_header h;
  190. _read_header(_inp, &h);
  191. _cached_header_data.file_name = header_get_filename(&h);
  192. _cached_header_data.file_size = header_get_filesize(&h);
  193. _cached_header_data.file_type = h.typeflag[0];
  194. _cached_header_data_valid = true;
  195. }
  196. std::string reader::get_next_file_name() {
  197. _cache_header();
  198. return _cached_header_data.file_name;
  199. }
  200. file_size_t reader::get_next_file_size() {
  201. _cache_header();
  202. return _cached_header_data.file_size;
  203. }
  204. void reader::read_next_file(char* const data) {
  205. _inp.read(data, get_next_file_size());
  206. _cached_header_data_valid = false;
  207. _seek_to_next_header(_inp);
  208. }
  209. void reader::skip_next_file() {
  210. _inp.seekg(get_next_file_size(), std::ios::cur);
  211. _cached_header_data_valid = false;
  212. _seek_to_next_header(_inp);
  213. }
  214. char reader::get_next_file_type() {
  215. _cache_header();
  216. return _cached_header_data.file_type;
  217. }
  218. int reader::number_of_files() {
  219. if (_number_of_files == -1) {
  220. std::streampos current_position = _inp.tellg();
  221. _inp.seekg(0, std::ios::beg);
  222. _number_of_files = 0;
  223. while (contains_another_file()) {
  224. _number_of_files++;
  225. skip_next_file();
  226. }
  227. _inp.seekg(current_position);
  228. }
  229. return _number_of_files;
  230. }
  231. void reader::extract_all_files(std::string dest_directory) {
  232. std::vector<uint8_t> scratch_buffer(1024);
  233. while (contains_another_file()) {
  234. char fileType = get_next_file_type();
  235. auto fileName = get_next_file_name();
  236. // 0 is the normal file type, skip apple's ._ files
  237. #if __cplusplus >= 202002L
  238. if (fileType == '0' && !fileName.starts_with("._")) {
  239. #else
  240. if (fileType == '0' && fileName.find("._") != 0) {
  241. #endif
  242. std::string path = dest_directory + "/" + fileName;
  243. size_t pos = 0;
  244. while ((pos = path.find('/', pos)) != std::string::npos) {
  245. std::string dir = path.substr(0, pos);
  246. // Create the directory if it doesn't exist
  247. #ifdef _WIN32
  248. mkdir(dir.c_str());
  249. #else
  250. mkdir(dir.c_str(), 0777);
  251. #endif
  252. pos++;
  253. }
  254. std::ofstream out(path, std::ios::binary);
  255. size_t read_size = 0;
  256. size_t file_size = get_next_file_size();
  257. while (read_size < file_size) {
  258. size_t to_read = std::min(file_size - read_size, scratch_buffer.size());
  259. _inp.read((char*)scratch_buffer.data(), to_read);
  260. // Move the read size forward
  261. read_size += _inp.gcount();
  262. // Write the data to the destination file
  263. out.write((char*)scratch_buffer.data(), _inp.gcount());
  264. }
  265. _cached_header_data_valid = false;
  266. _seek_to_next_header(_inp);
  267. } else {
  268. skip_next_file();
  269. }
  270. }
  271. }