3
0

get_header_tar.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * Licensed under GPLv2 or later, see file LICENSE in this source tree.
  4. *
  5. * FIXME:
  6. * In privileged mode if uname and gname map to a uid and gid then use the
  7. * mapped value instead of the uid/gid values in tar header
  8. *
  9. * References:
  10. * GNU tar and star man pages,
  11. * Opengroup's ustar interchange format,
  12. * http://www.opengroup.org/onlinepubs/007904975/utilities/pax.html
  13. */
  14. #include "libbb.h"
  15. #include "bb_archive.h"
  16. typedef uint32_t aliased_uint32_t FIX_ALIASING;
  17. typedef off_t aliased_off_t FIX_ALIASING;
  18. /* NB: _DESTROYS_ str[len] character! */
  19. static unsigned long long getOctal(char *str, int len)
  20. {
  21. unsigned long long v;
  22. char *end;
  23. /* NB: leading spaces are allowed. Using strtoull to handle that.
  24. * The downside is that we accept e.g. "-123" too :(
  25. */
  26. str[len] = '\0';
  27. v = strtoull(str, &end, 8);
  28. /* std: "Each numeric field is terminated by one or more
  29. * <space> or NUL characters". We must support ' '! */
  30. if (*end != '\0' && *end != ' ') {
  31. int8_t first = str[0];
  32. if (!(first & 0x80))
  33. bb_simple_error_msg_and_die("corrupted octal value in tar header");
  34. /*
  35. * GNU tar uses "base-256 encoding" for very large numbers.
  36. * Encoding is binary, with highest bit always set as a marker
  37. * and sign in next-highest bit:
  38. * 80 00 .. 00 - zero
  39. * bf ff .. ff - largest positive number
  40. * ff ff .. ff - minus 1
  41. * c0 00 .. 00 - smallest negative number
  42. *
  43. * Example of tar file with 8914993153 (0x213600001) byte file.
  44. * Field starts at offset 7c:
  45. * 00070 30 30 30 00 30 30 30 30 30 30 30 00 80 00 00 00 |000.0000000.....|
  46. * 00080 00 00 00 02 13 60 00 01 31 31 31 32 30 33 33 36 |.....`..11120336|
  47. *
  48. * NB: tarballs with NEGATIVE unix times encoded that way were seen!
  49. */
  50. /* Sign-extend 7bit 'first' to 64bit 'v' (that is, using 6th bit as sign): */
  51. first <<= 1;
  52. first >>= 1; /* now 7th bit = 6th bit */
  53. v = first; /* sign-extend 8 bits to 64 */
  54. while (--len != 0)
  55. v = (v << 8) + (uint8_t) *++str;
  56. }
  57. return v;
  58. }
  59. #define GET_OCTAL(a) getOctal((a), sizeof(a))
  60. #define TAR_EXTD (ENABLE_FEATURE_TAR_GNU_EXTENSIONS || ENABLE_FEATURE_TAR_SELINUX)
  61. #if !TAR_EXTD
  62. #define process_pax_hdr(archive_handle, sz, global) \
  63. process_pax_hdr(archive_handle, sz)
  64. #endif
  65. /* "global" is 0 or 1 */
  66. static void process_pax_hdr(archive_handle_t *archive_handle, unsigned sz, int global)
  67. {
  68. #if !TAR_EXTD
  69. unsigned blk_sz = (sz + 511) & (~511);
  70. seek_by_read(archive_handle->src_fd, blk_sz);
  71. #else
  72. unsigned blk_sz = (sz + 511) & (~511);
  73. char *buf, *p;
  74. p = buf = xmalloc(blk_sz + 1);
  75. xread(archive_handle->src_fd, buf, blk_sz);
  76. archive_handle->offset += blk_sz;
  77. /* prevent bb_strtou from running off the buffer */
  78. buf[sz] = '\0';
  79. while (sz != 0) {
  80. char *end, *value;
  81. unsigned len;
  82. /* Every record has this format: "LEN NAME=VALUE\n" */
  83. len = bb_strtou(p, &end, 10);
  84. /* expect errno to be EINVAL, because the character
  85. * following the digits should be a space
  86. */
  87. p += len;
  88. sz -= len;
  89. if (
  90. /** (int)sz < 0 - not good enough for huge malicious VALUE of 2^32-1 */
  91. (int)(sz|len) < 0 /* this works */
  92. || len == 0
  93. || errno != EINVAL
  94. || *end != ' '
  95. ) {
  96. bb_simple_error_msg("malformed extended header, skipped");
  97. // More verbose version:
  98. //bb_error_msg("malformed extended header at %"OFF_FMT"d, skipped",
  99. // archive_handle->offset - (sz + len));
  100. break;
  101. }
  102. /* overwrite the terminating newline with NUL
  103. * (we do not bother to check that it *was* a newline)
  104. */
  105. p[-1] = '\0';
  106. value = end + 1;
  107. # if ENABLE_FEATURE_TAR_GNU_EXTENSIONS
  108. if (!global) {
  109. if (is_prefixed_with(value, "path=")) {
  110. value += sizeof("path=") - 1;
  111. free(archive_handle->tar__longname);
  112. archive_handle->tar__longname = xstrdup(value);
  113. continue;
  114. }
  115. if (is_prefixed_with(value, "linkpath=")) {
  116. value += sizeof("linkpath=") - 1;
  117. free(archive_handle->tar__linkname);
  118. archive_handle->tar__linkname = xstrdup(value);
  119. continue;
  120. }
  121. }
  122. # endif
  123. # if ENABLE_FEATURE_TAR_SELINUX
  124. /* Scan for SELinux contexts, via "RHT.security.selinux" keyword.
  125. * This is what Red Hat's patched version of tar uses.
  126. */
  127. # define SELINUX_CONTEXT_KEYWORD "RHT.security.selinux"
  128. if (is_prefixed_with(value, SELINUX_CONTEXT_KEYWORD"=")) {
  129. value += sizeof(SELINUX_CONTEXT_KEYWORD"=") - 1;
  130. free(archive_handle->tar__sctx[global]);
  131. archive_handle->tar__sctx[global] = xstrdup(value);
  132. continue;
  133. }
  134. # endif
  135. }
  136. free(buf);
  137. #endif
  138. }
  139. static void die_if_bad_fnamesize(off_t sz)
  140. {
  141. if ((uoff_t)sz > 0xfff) /* more than 4k?! no funny business please */
  142. bb_simple_error_msg_and_die("bad archive");
  143. }
  144. char FAST_FUNC get_header_tar(archive_handle_t *archive_handle)
  145. {
  146. file_header_t *file_header = archive_handle->file_header;
  147. struct tar_header_t tar;
  148. char *cp;
  149. int tar_typeflag; /* can be "char", "int" seems give smaller code */
  150. int i, sum_u, sum;
  151. #if ENABLE_FEATURE_TAR_OLDSUN_COMPATIBILITY
  152. int sum_s;
  153. #endif
  154. int parse_names;
  155. /* Our "private data" */
  156. #if ENABLE_FEATURE_TAR_GNU_EXTENSIONS
  157. # define p_longname (archive_handle->tar__longname)
  158. # define p_linkname (archive_handle->tar__linkname)
  159. #else
  160. # define p_longname 0
  161. # define p_linkname 0
  162. #endif
  163. #if ENABLE_FEATURE_TAR_GNU_EXTENSIONS || ENABLE_FEATURE_TAR_SELINUX
  164. again:
  165. #endif
  166. /* Align header */
  167. data_align(archive_handle, 512);
  168. again_after_align:
  169. #if ENABLE_DESKTOP || ENABLE_FEATURE_TAR_AUTODETECT
  170. /* to prevent misdetection of bz2 sig */
  171. *(aliased_uint32_t*)&tar = 0;
  172. i = full_read(archive_handle->src_fd, &tar, 512);
  173. /* If GNU tar sees EOF in above read, it says:
  174. * "tar: A lone zero block at N", where N = kilobyte
  175. * where EOF was met (not EOF block, actual EOF!),
  176. * and exits with EXIT_SUCCESS.
  177. * We will mimic exit(EXIT_SUCCESS), although we will not mimic
  178. * the message and we don't check whether we indeed
  179. * saw zero block directly before this. */
  180. if (i == 0) {
  181. /* GNU tar 1.29 will be silent if tar archive ends abruptly
  182. * (if there are no zero blocks at all, and last read returns zero,
  183. * not short read 0 < len < 512). Complain only if
  184. * the very first read fails. Grrr.
  185. */
  186. if (archive_handle->offset == 0)
  187. bb_simple_error_msg("short read");
  188. /* this merely signals end of archive, not exit(1): */
  189. return EXIT_FAILURE;
  190. }
  191. if (i != 512) {
  192. IF_FEATURE_TAR_AUTODETECT(goto autodetect;)
  193. bb_simple_error_msg_and_die("short read");
  194. }
  195. #else
  196. i = 512;
  197. xread(archive_handle->src_fd, &tar, i);
  198. #endif
  199. archive_handle->offset += i;
  200. /* If there is no filename its an empty header */
  201. if (tar.name[0] == 0 && tar.prefix[0] == 0
  202. /* Have seen a tar archive with pax 'x' header supplying UTF8 filename,
  203. * with actual file having all name fields NUL-filled. Check this: */
  204. && !p_longname
  205. ) {
  206. if (archive_handle->tar__end) {
  207. /* Second consecutive empty header - end of archive.
  208. * Read until the end to empty the pipe from gz or bz2
  209. */
  210. while (full_read(archive_handle->src_fd, &tar, 512) == 512)
  211. continue;
  212. return EXIT_FAILURE; /* "end of archive" */
  213. }
  214. archive_handle->tar__end = 1;
  215. return EXIT_SUCCESS; /* "decoded one header" */
  216. }
  217. archive_handle->tar__end = 0;
  218. /* Check header has valid magic, "ustar" is for the proper tar,
  219. * five NULs are for the old tar format */
  220. if (!is_prefixed_with(tar.magic, "ustar")
  221. && (!ENABLE_FEATURE_TAR_OLDGNU_COMPATIBILITY
  222. || memcmp(tar.magic, "\0\0\0\0", 5) != 0)
  223. ) {
  224. #if ENABLE_FEATURE_TAR_AUTODETECT
  225. autodetect:
  226. /* Two different causes for lseek() != 0:
  227. * unseekable fd (would like to support that too, but...),
  228. * or not first block (false positive, it's not .gz/.bz2!) */
  229. if (lseek(archive_handle->src_fd, -i, SEEK_CUR) != 0)
  230. goto err;
  231. if (setup_unzip_on_fd(archive_handle->src_fd, /*fail_if_not_compressed:*/ 0) != 0)
  232. err:
  233. bb_simple_error_msg_and_die("invalid tar magic");
  234. archive_handle->offset = 0;
  235. goto again_after_align;
  236. #endif
  237. bb_simple_error_msg_and_die("invalid tar magic");
  238. }
  239. /* Do checksum on headers.
  240. * POSIX says that checksum is done on unsigned bytes, but
  241. * Sun and HP-UX gets it wrong... more details in
  242. * GNU tar source. */
  243. sum_u = ' ' * sizeof(tar.chksum);
  244. #if ENABLE_FEATURE_TAR_OLDSUN_COMPATIBILITY
  245. sum_s = sum_u;
  246. #endif
  247. for (i = 0; i < 148; i++) {
  248. sum_u += ((unsigned char*)&tar)[i];
  249. #if ENABLE_FEATURE_TAR_OLDSUN_COMPATIBILITY
  250. sum_s += ((signed char*)&tar)[i];
  251. #endif
  252. }
  253. for (i = 156; i < 512; i++) {
  254. sum_u += ((unsigned char*)&tar)[i];
  255. #if ENABLE_FEATURE_TAR_OLDSUN_COMPATIBILITY
  256. sum_s += ((signed char*)&tar)[i];
  257. #endif
  258. }
  259. /* Most tarfiles have tar.chksum NUL or space terminated, but
  260. * github.com decided to be "special" and have unterminated field:
  261. * 0090: 30343300 30303031 33323731 30000000 |043.000132710...|
  262. * ^^^^^^^^|
  263. * Need to use GET_OCTAL. This overwrites tar.typeflag ---+
  264. * (the '0' char immediately after chksum in example above) with NUL.
  265. */
  266. tar_typeflag = (uint8_t)tar.typeflag; /* save it */
  267. sum = GET_OCTAL(tar.chksum);
  268. if (sum_u != sum
  269. IF_FEATURE_TAR_OLDSUN_COMPATIBILITY(&& sum_s != sum)
  270. ) {
  271. bb_simple_error_msg_and_die("invalid tar header checksum");
  272. }
  273. /* GET_OCTAL trashes subsequent field, therefore we call it
  274. * on fields in reverse order */
  275. if (tar.devmajor[0]) {
  276. char t = tar.prefix[0];
  277. /* we trash prefix[0] here, but we DO need it later! */
  278. unsigned minor = GET_OCTAL(tar.devminor);
  279. unsigned major = GET_OCTAL(tar.devmajor);
  280. file_header->device = makedev(major, minor);
  281. tar.prefix[0] = t;
  282. }
  283. /* 0 is reserved for high perf file, treat as normal file */
  284. if (tar_typeflag == '\0') tar_typeflag = '0';
  285. parse_names = (tar_typeflag >= '0' && tar_typeflag <= '7');
  286. file_header->link_target = NULL;
  287. if (!p_linkname && parse_names && tar.linkname[0]) {
  288. file_header->link_target = xstrndup(tar.linkname, sizeof(tar.linkname));
  289. /* FIXME: what if we have non-link object with link_target? */
  290. /* Will link_target be free()ed? */
  291. }
  292. #if ENABLE_FEATURE_TAR_UNAME_GNAME
  293. file_header->tar__uname = tar.uname[0] ? xstrndup(tar.uname, sizeof(tar.uname)) : NULL;
  294. file_header->tar__gname = tar.gname[0] ? xstrndup(tar.gname, sizeof(tar.gname)) : NULL;
  295. #endif
  296. file_header->mtime = GET_OCTAL(tar.mtime);
  297. file_header->size = GET_OCTAL(tar.size);
  298. file_header->gid = GET_OCTAL(tar.gid);
  299. file_header->uid = GET_OCTAL(tar.uid);
  300. /* Set bits 0-11 of the files mode */
  301. file_header->mode = 07777 & GET_OCTAL(tar.mode);
  302. file_header->name = NULL;
  303. if (!p_longname && parse_names) {
  304. /* we trash mode[0] here, it's ok */
  305. //tar.name[sizeof(tar.name)] = '\0'; - gcc 4.3.0 would complain
  306. tar.mode[0] = '\0';
  307. if (tar.prefix[0]) {
  308. /* and padding[0] */
  309. //tar.prefix[sizeof(tar.prefix)] = '\0'; - gcc 4.3.0 would complain
  310. tar.padding[0] = '\0';
  311. file_header->name = concat_path_file(tar.prefix, tar.name);
  312. } else
  313. file_header->name = xstrdup(tar.name);
  314. }
  315. switch (tar_typeflag) {
  316. case '1': /* hardlink */
  317. /* we mark hardlinks as regular files with zero size and a link name */
  318. file_header->mode |= S_IFREG;
  319. /* on size of link fields from star(4)
  320. * ... For tar archives written by pre POSIX.1-1988
  321. * implementations, the size field usually contains the size of
  322. * the file and needs to be ignored as no data may follow this
  323. * header type. For POSIX.1-1988 compliant archives, the size
  324. * field needs to be 0. For POSIX.1-2001 compliant archives,
  325. * the size field may be non zero, indicating that file data is
  326. * included in the archive.
  327. * i.e; always assume this is zero for safety.
  328. */
  329. goto size0;
  330. case '7':
  331. /* case 0: */
  332. case '0':
  333. #if ENABLE_FEATURE_TAR_OLDGNU_COMPATIBILITY
  334. if (file_header->name && last_char_is(file_header->name, '/')) {
  335. goto set_dir;
  336. }
  337. #endif
  338. file_header->mode |= S_IFREG;
  339. break;
  340. case '2':
  341. file_header->mode |= S_IFLNK;
  342. /* have seen tarballs with size field containing
  343. * the size of the link target's name */
  344. size0:
  345. file_header->size = 0;
  346. break;
  347. case '3':
  348. file_header->mode |= S_IFCHR;
  349. goto size0; /* paranoia */
  350. case '4':
  351. file_header->mode |= S_IFBLK;
  352. goto size0;
  353. case '5':
  354. IF_FEATURE_TAR_OLDGNU_COMPATIBILITY(set_dir:)
  355. file_header->mode |= S_IFDIR;
  356. goto size0;
  357. case '6':
  358. file_header->mode |= S_IFIFO;
  359. goto size0;
  360. case 'g': /* pax global header */
  361. case 'x': { /* pax extended header */
  362. if ((uoff_t)file_header->size > 0xfffff) /* paranoia */
  363. goto skip_ext_hdr;
  364. process_pax_hdr(archive_handle, file_header->size, (tar_typeflag == 'g'));
  365. goto again_after_align;
  366. #if ENABLE_FEATURE_TAR_GNU_EXTENSIONS
  367. /* See http://www.gnu.org/software/tar/manual/html_node/Extensions.html */
  368. case 'L':
  369. /* free: paranoia: tar with several consecutive longnames */
  370. free(p_longname);
  371. /* For paranoia reasons we allocate extra NUL char */
  372. die_if_bad_fnamesize(file_header->size);
  373. p_longname = xzalloc(file_header->size + 1);
  374. /* We read ASCIZ string, including NUL */
  375. xread(archive_handle->src_fd, p_longname, file_header->size);
  376. archive_handle->offset += file_header->size;
  377. /* return get_header_tar(archive_handle); */
  378. /* gcc 4.1.1 didn't optimize it into jump */
  379. /* so we will do it ourself, this also saves stack */
  380. goto again;
  381. case 'K':
  382. free(p_linkname);
  383. die_if_bad_fnamesize(file_header->size);
  384. p_linkname = xzalloc(file_header->size + 1);
  385. xread(archive_handle->src_fd, p_linkname, file_header->size);
  386. archive_handle->offset += file_header->size;
  387. /* return get_header_tar(archive_handle); */
  388. goto again;
  389. /*
  390. * case 'S': // Sparse file
  391. * Was seen in the wild. Not supported (yet?).
  392. * See https://www.gnu.org/software/tar/manual/html_section/tar_92.html
  393. * for the format. (An "Old GNU Format" was seen, not PAX formats).
  394. */
  395. // case 'D': /* GNU dump dir */
  396. // case 'M': /* Continuation of multi volume archive */
  397. // case 'N': /* Old GNU for names > 100 characters */
  398. case 'V': /* Volume header */
  399. ; /* Fall through to skip it */
  400. #endif
  401. }
  402. skip_ext_hdr:
  403. {
  404. off_t sz;
  405. bb_error_msg("warning: skipping header '%c'", tar_typeflag);
  406. sz = (file_header->size + 511) & ~(off_t)511;
  407. archive_handle->offset += sz;
  408. sz >>= 9; /* sz /= 512 but w/o contortions for signed div */
  409. while (sz--)
  410. xread(archive_handle->src_fd, &tar, 512);
  411. /* return get_header_tar(archive_handle); */
  412. goto again_after_align;
  413. }
  414. default:
  415. bb_error_msg_and_die("unknown typeflag: 0x%x", tar_typeflag);
  416. }
  417. #if ENABLE_FEATURE_TAR_GNU_EXTENSIONS
  418. if (p_longname) {
  419. file_header->name = p_longname;
  420. p_longname = NULL;
  421. }
  422. if (p_linkname) {
  423. file_header->link_target = p_linkname;
  424. p_linkname = NULL;
  425. }
  426. #endif
  427. /* Everything up to and including last ".." component is stripped */
  428. overlapping_strcpy(file_header->name, strip_unsafe_prefix(file_header->name));
  429. //TODO: do the same for file_header->link_target?
  430. /* Strip trailing '/' in directories */
  431. /* Must be done after mode is set as '/' is used to check if it's a directory */
  432. cp = last_char_is(file_header->name, '/');
  433. if (archive_handle->filter(archive_handle) == EXIT_SUCCESS) {
  434. archive_handle->action_header(/*archive_handle->*/ file_header);
  435. /* Note that we kill the '/' only after action_header() */
  436. /* (like GNU tar 1.15.1: verbose mode outputs "dir/dir/") */
  437. if (cp)
  438. *cp = '\0';
  439. archive_handle->action_data(archive_handle);
  440. if (archive_handle->accept || archive_handle->reject
  441. || (archive_handle->ah_flags & ARCHIVE_REMEMBER_NAMES)
  442. ) {
  443. llist_add_to(&archive_handle->passed, file_header->name);
  444. } else /* Caller isn't interested in list of unpacked files */
  445. free(file_header->name);
  446. } else {
  447. data_skip(archive_handle);
  448. free(file_header->name);
  449. }
  450. archive_handle->offset += file_header->size;
  451. free(file_header->link_target);
  452. /* Do not free(file_header->name)!
  453. * It might be inserted in archive_handle->passed - see above */
  454. #if ENABLE_FEATURE_TAR_UNAME_GNAME
  455. free(file_header->tar__uname);
  456. free(file_header->tar__gname);
  457. #endif
  458. return EXIT_SUCCESS; /* "decoded one header" */
  459. }