tar.c 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * Mini tar implementation for busybox
  4. *
  5. * Modified to use common extraction code used by ar, cpio, dpkg-deb, dpkg
  6. * by Glenn McGrath
  7. *
  8. * Note, that as of BusyBox-0.43, tar has been completely rewritten from the
  9. * ground up. It still has remnants of the old code lying about, but it is
  10. * very different now (i.e., cleaner, less global variables, etc.)
  11. *
  12. * Copyright (C) 1999-2004 by Erik Andersen <andersen@codepoet.org>
  13. *
  14. * Based in part in the tar implementation in sash
  15. * Copyright (c) 1999 by David I. Bell
  16. * Permission is granted to use, distribute, or modify this source,
  17. * provided that this copyright notice remains intact.
  18. * Permission to distribute sash derived code under GPL has been granted.
  19. *
  20. * Based in part on the tar implementation from busybox-0.28
  21. * Copyright (C) 1995 Bruce Perens
  22. *
  23. * Licensed under GPLv2 or later, see file LICENSE in this source tree.
  24. */
  25. /* TODO: security with -C DESTDIR option can be enhanced.
  26. * Consider tar file created via:
  27. * $ tar cvf bug.tar anything.txt
  28. * $ ln -s /tmp symlink
  29. * $ tar --append -f bug.tar symlink
  30. * $ rm symlink
  31. * $ mkdir symlink
  32. * $ tar --append -f bug.tar symlink/evil.py
  33. *
  34. * This will result in an archive which contains:
  35. * $ tar --list -f bug.tar
  36. * anything.txt
  37. * symlink
  38. * symlink/evil.py
  39. *
  40. * Untarring it puts evil.py in '/tmp' even if the -C DESTDIR is given.
  41. * This doesn't feel right, and IIRC GNU tar doesn't do that.
  42. */
  43. //config:config TAR
  44. //config: bool "tar"
  45. //config: default y
  46. //config: help
  47. //config: tar is an archiving program. It's commonly used with gzip to
  48. //config: create compressed archives. It's probably the most widely used
  49. //config: UNIX archive program.
  50. //config:
  51. //config:config FEATURE_TAR_CREATE
  52. //config: bool "Enable archive creation"
  53. //config: default y
  54. //config: depends on TAR
  55. //config: help
  56. //config: If you enable this option you'll be able to create
  57. //config: tar archives using the `-c' option.
  58. //config:
  59. //config:config FEATURE_TAR_AUTODETECT
  60. //config: bool "Autodetect compressed tarballs"
  61. //config: default y
  62. //config: depends on TAR && (FEATURE_SEAMLESS_Z || FEATURE_SEAMLESS_GZ || FEATURE_SEAMLESS_BZ2 || FEATURE_SEAMLESS_LZMA || FEATURE_SEAMLESS_XZ)
  63. //config: help
  64. //config: With this option tar can automatically detect compressed
  65. //config: tarballs. Currently it works only on files (not pipes etc).
  66. //config:
  67. //config:config FEATURE_TAR_FROM
  68. //config: bool "Enable -X (exclude from) and -T (include from) options)"
  69. //config: default y
  70. //config: depends on TAR
  71. //config: help
  72. //config: If you enable this option you'll be able to specify
  73. //config: a list of files to include or exclude from an archive.
  74. //config:
  75. //config:config FEATURE_TAR_OLDGNU_COMPATIBILITY
  76. //config: bool "Support for old tar header format"
  77. //config: default y
  78. //config: depends on TAR || DPKG
  79. //config: help
  80. //config: This option is required to unpack archives created in
  81. //config: the old GNU format; help to kill this old format by
  82. //config: repacking your ancient archives with the new format.
  83. //config:
  84. //config:config FEATURE_TAR_OLDSUN_COMPATIBILITY
  85. //config: bool "Enable untarring of tarballs with checksums produced by buggy Sun tar"
  86. //config: default y
  87. //config: depends on TAR || DPKG
  88. //config: help
  89. //config: This option is required to unpack archives created by some old
  90. //config: version of Sun's tar (it was calculating checksum using signed
  91. //config: arithmetic). It is said to be fixed in newer Sun tar, but "old"
  92. //config: tarballs still exist.
  93. //config:
  94. //config:config FEATURE_TAR_GNU_EXTENSIONS
  95. //config: bool "Support for GNU tar extensions (long filenames)"
  96. //config: default y
  97. //config: depends on TAR || DPKG
  98. //config: help
  99. //config: With this option busybox supports GNU long filenames and
  100. //config: linknames.
  101. //config:
  102. //config:config FEATURE_TAR_LONG_OPTIONS
  103. //config: bool "Enable long options"
  104. //config: default y
  105. //config: depends on TAR && LONG_OPTS
  106. //config: help
  107. //config: Enable use of long options, increases size by about 400 Bytes
  108. //config:
  109. //config:config FEATURE_TAR_TO_COMMAND
  110. //config: bool "Support for writing to an external program"
  111. //config: default y
  112. //config: depends on TAR && FEATURE_TAR_LONG_OPTIONS
  113. //config: help
  114. //config: If you enable this option you'll be able to instruct tar to send
  115. //config: the contents of each extracted file to the standard input of an
  116. //config: external program.
  117. //config:
  118. //config:config FEATURE_TAR_UNAME_GNAME
  119. //config: bool "Enable use of user and group names"
  120. //config: default y
  121. //config: depends on TAR
  122. //config: help
  123. //config: Enables use of user and group names in tar. This affects contents
  124. //config: listings (-t) and preserving permissions when unpacking (-p).
  125. //config: +200 bytes.
  126. //config:
  127. //config:config FEATURE_TAR_NOPRESERVE_TIME
  128. //config: bool "Enable -m (do not preserve time) option"
  129. //config: default y
  130. //config: depends on TAR
  131. //config: help
  132. //config: With this option busybox supports GNU tar -m
  133. //config: (do not preserve time) option.
  134. //config:
  135. //config:config FEATURE_TAR_SELINUX
  136. //config: bool "Support for extracting SELinux labels"
  137. //config: default n
  138. //config: depends on TAR && SELINUX
  139. //config: help
  140. //config: With this option busybox supports restoring SELinux labels
  141. //config: when extracting files from tar archives.
  142. //applet:IF_TAR(APPLET(tar, BB_DIR_BIN, BB_SUID_DROP))
  143. //kbuild:lib-$(CONFIG_TAR) += tar.o
  144. #include <fnmatch.h>
  145. #include "libbb.h"
  146. #include "bb_archive.h"
  147. /* FIXME: Stop using this non-standard feature */
  148. #ifndef FNM_LEADING_DIR
  149. # define FNM_LEADING_DIR 0
  150. #endif
  151. //#define DBG(fmt, ...) bb_error_msg("%s: " fmt, __func__, ## __VA_ARGS__)
  152. #define DBG(...) ((void)0)
  153. #define block_buf bb_common_bufsiz1
  154. #if ENABLE_FEATURE_TAR_CREATE
  155. /*
  156. ** writeTarFile(), writeFileToTarball(), and writeTarHeader() are
  157. ** the only functions that deal with the HardLinkInfo structure.
  158. ** Even these functions use the xxxHardLinkInfo() functions.
  159. */
  160. typedef struct HardLinkInfo {
  161. struct HardLinkInfo *next; /* Next entry in list */
  162. dev_t dev; /* Device number */
  163. ino_t ino; /* Inode number */
  164. // short linkCount; /* (Hard) Link Count */
  165. char name[1]; /* Start of filename (must be last) */
  166. } HardLinkInfo;
  167. /* Some info to be carried along when creating a new tarball */
  168. typedef struct TarBallInfo {
  169. int tarFd; /* Open-for-write file descriptor
  170. * for the tarball */
  171. int verboseFlag; /* Whether to print extra stuff or not */
  172. const llist_t *excludeList; /* List of files to not include */
  173. HardLinkInfo *hlInfoHead; /* Hard Link Tracking Information */
  174. HardLinkInfo *hlInfo; /* Hard Link Info for the current file */
  175. //TODO: save only st_dev + st_ino
  176. struct stat tarFileStatBuf; /* Stat info for the tarball, letting
  177. * us know the inode and device that the
  178. * tarball lives, so we can avoid trying
  179. * to include the tarball into itself */
  180. } TarBallInfo;
  181. /* A nice enum with all the possible tar file content types */
  182. enum {
  183. REGTYPE = '0', /* regular file */
  184. REGTYPE0 = '\0', /* regular file (ancient bug compat) */
  185. LNKTYPE = '1', /* hard link */
  186. SYMTYPE = '2', /* symbolic link */
  187. CHRTYPE = '3', /* character special */
  188. BLKTYPE = '4', /* block special */
  189. DIRTYPE = '5', /* directory */
  190. FIFOTYPE = '6', /* FIFO special */
  191. CONTTYPE = '7', /* reserved */
  192. GNULONGLINK = 'K', /* GNU long (>100 chars) link name */
  193. GNULONGNAME = 'L', /* GNU long (>100 chars) file name */
  194. };
  195. /* Might be faster (and bigger) if the dev/ino were stored in numeric order;) */
  196. static void addHardLinkInfo(HardLinkInfo **hlInfoHeadPtr,
  197. struct stat *statbuf,
  198. const char *fileName)
  199. {
  200. /* Note: hlInfoHeadPtr can never be NULL! */
  201. HardLinkInfo *hlInfo;
  202. hlInfo = xmalloc(sizeof(HardLinkInfo) + strlen(fileName));
  203. hlInfo->next = *hlInfoHeadPtr;
  204. *hlInfoHeadPtr = hlInfo;
  205. hlInfo->dev = statbuf->st_dev;
  206. hlInfo->ino = statbuf->st_ino;
  207. // hlInfo->linkCount = statbuf->st_nlink;
  208. strcpy(hlInfo->name, fileName);
  209. }
  210. static void freeHardLinkInfo(HardLinkInfo **hlInfoHeadPtr)
  211. {
  212. HardLinkInfo *hlInfo;
  213. HardLinkInfo *hlInfoNext;
  214. if (hlInfoHeadPtr) {
  215. hlInfo = *hlInfoHeadPtr;
  216. while (hlInfo) {
  217. hlInfoNext = hlInfo->next;
  218. free(hlInfo);
  219. hlInfo = hlInfoNext;
  220. }
  221. *hlInfoHeadPtr = NULL;
  222. }
  223. }
  224. /* Might be faster (and bigger) if the dev/ino were stored in numeric order ;) */
  225. static HardLinkInfo *findHardLinkInfo(HardLinkInfo *hlInfo, struct stat *statbuf)
  226. {
  227. while (hlInfo) {
  228. if (statbuf->st_ino == hlInfo->ino
  229. && statbuf->st_dev == hlInfo->dev
  230. ) {
  231. DBG("found hardlink:'%s'", hlInfo->name);
  232. break;
  233. }
  234. hlInfo = hlInfo->next;
  235. }
  236. return hlInfo;
  237. }
  238. /* Put an octal string into the specified buffer.
  239. * The number is zero padded and possibly null terminated.
  240. * Stores low-order bits only if whole value does not fit. */
  241. static void putOctal(char *cp, int len, off_t value)
  242. {
  243. char tempBuffer[sizeof(off_t)*3 + 1];
  244. char *tempString = tempBuffer;
  245. int width;
  246. width = sprintf(tempBuffer, "%0*"OFF_FMT"o", len, value);
  247. tempString += (width - len);
  248. /* If string has leading zeroes, we can drop one */
  249. /* and field will have trailing '\0' */
  250. /* (increases chances of compat with other tars) */
  251. if (tempString[0] == '0')
  252. tempString++;
  253. /* Copy the string to the field */
  254. memcpy(cp, tempString, len);
  255. }
  256. #define PUT_OCTAL(a, b) putOctal((a), sizeof(a), (b))
  257. static void chksum_and_xwrite(int fd, struct tar_header_t* hp)
  258. {
  259. /* POSIX says that checksum is done on unsigned bytes
  260. * (Sun and HP-UX gets it wrong... more details in
  261. * GNU tar source) */
  262. const unsigned char *cp;
  263. int chksum, size;
  264. strcpy(hp->magic, "ustar ");
  265. /* Calculate and store the checksum (i.e., the sum of all of the bytes of
  266. * the header). The checksum field must be filled with blanks for the
  267. * calculation. The checksum field is formatted differently from the
  268. * other fields: it has 6 digits, a null, then a space -- rather than
  269. * digits, followed by a null like the other fields... */
  270. memset(hp->chksum, ' ', sizeof(hp->chksum));
  271. cp = (const unsigned char *) hp;
  272. chksum = 0;
  273. size = sizeof(*hp);
  274. do { chksum += *cp++; } while (--size);
  275. putOctal(hp->chksum, sizeof(hp->chksum)-1, chksum);
  276. /* Now write the header out to disk */
  277. xwrite(fd, hp, sizeof(*hp));
  278. }
  279. #if ENABLE_FEATURE_TAR_GNU_EXTENSIONS
  280. static void writeLongname(int fd, int type, const char *name, int dir)
  281. {
  282. static const struct {
  283. char mode[8]; /* 100-107 */
  284. char uid[8]; /* 108-115 */
  285. char gid[8]; /* 116-123 */
  286. char size[12]; /* 124-135 */
  287. char mtime[12]; /* 136-147 */
  288. } prefilled = {
  289. "0000000",
  290. "0000000",
  291. "0000000",
  292. "00000000000",
  293. "00000000000",
  294. };
  295. struct tar_header_t header;
  296. int size;
  297. dir = !!dir; /* normalize: 0/1 */
  298. size = strlen(name) + 1 + dir; /* GNU tar uses strlen+1 */
  299. /* + dir: account for possible '/' */
  300. memset(&header, 0, sizeof(header));
  301. strcpy(header.name, "././@LongLink");
  302. memcpy(header.mode, prefilled.mode, sizeof(prefilled));
  303. PUT_OCTAL(header.size, size);
  304. header.typeflag = type;
  305. chksum_and_xwrite(fd, &header);
  306. /* Write filename[/] and pad the block. */
  307. /* dir=0: writes 'name<NUL>', pads */
  308. /* dir=1: writes 'name', writes '/<NUL>', pads */
  309. dir *= 2;
  310. xwrite(fd, name, size - dir);
  311. xwrite(fd, "/", dir);
  312. size = (-size) & (TAR_BLOCK_SIZE-1);
  313. memset(&header, 0, size);
  314. xwrite(fd, &header, size);
  315. }
  316. #endif
  317. /* Write out a tar header for the specified file/directory/whatever */
  318. static int writeTarHeader(struct TarBallInfo *tbInfo,
  319. const char *header_name, const char *fileName, struct stat *statbuf)
  320. {
  321. struct tar_header_t header;
  322. memset(&header, 0, sizeof(header));
  323. strncpy(header.name, header_name, sizeof(header.name));
  324. /* POSIX says to mask mode with 07777. */
  325. PUT_OCTAL(header.mode, statbuf->st_mode & 07777);
  326. PUT_OCTAL(header.uid, statbuf->st_uid);
  327. PUT_OCTAL(header.gid, statbuf->st_gid);
  328. memset(header.size, '0', sizeof(header.size)-1); /* Regular file size is handled later */
  329. /* users report that files with negative st_mtime cause trouble, so: */
  330. PUT_OCTAL(header.mtime, statbuf->st_mtime >= 0 ? statbuf->st_mtime : 0);
  331. /* Enter the user and group names */
  332. safe_strncpy(header.uname, get_cached_username(statbuf->st_uid), sizeof(header.uname));
  333. safe_strncpy(header.gname, get_cached_groupname(statbuf->st_gid), sizeof(header.gname));
  334. if (tbInfo->hlInfo) {
  335. /* This is a hard link */
  336. header.typeflag = LNKTYPE;
  337. strncpy(header.linkname, tbInfo->hlInfo->name,
  338. sizeof(header.linkname));
  339. #if ENABLE_FEATURE_TAR_GNU_EXTENSIONS
  340. /* Write out long linkname if needed */
  341. if (header.linkname[sizeof(header.linkname)-1])
  342. writeLongname(tbInfo->tarFd, GNULONGLINK,
  343. tbInfo->hlInfo->name, 0);
  344. #endif
  345. } else if (S_ISLNK(statbuf->st_mode)) {
  346. char *lpath = xmalloc_readlink_or_warn(fileName);
  347. if (!lpath)
  348. return FALSE;
  349. header.typeflag = SYMTYPE;
  350. strncpy(header.linkname, lpath, sizeof(header.linkname));
  351. #if ENABLE_FEATURE_TAR_GNU_EXTENSIONS
  352. /* Write out long linkname if needed */
  353. if (header.linkname[sizeof(header.linkname)-1])
  354. writeLongname(tbInfo->tarFd, GNULONGLINK, lpath, 0);
  355. #else
  356. /* If it is larger than 100 bytes, bail out */
  357. if (header.linkname[sizeof(header.linkname)-1]) {
  358. free(lpath);
  359. bb_error_msg("names longer than "NAME_SIZE_STR" chars not supported");
  360. return FALSE;
  361. }
  362. #endif
  363. free(lpath);
  364. } else if (S_ISDIR(statbuf->st_mode)) {
  365. header.typeflag = DIRTYPE;
  366. /* Append '/' only if there is a space for it */
  367. if (!header.name[sizeof(header.name)-1])
  368. header.name[strlen(header.name)] = '/';
  369. } else if (S_ISCHR(statbuf->st_mode)) {
  370. header.typeflag = CHRTYPE;
  371. PUT_OCTAL(header.devmajor, major(statbuf->st_rdev));
  372. PUT_OCTAL(header.devminor, minor(statbuf->st_rdev));
  373. } else if (S_ISBLK(statbuf->st_mode)) {
  374. header.typeflag = BLKTYPE;
  375. PUT_OCTAL(header.devmajor, major(statbuf->st_rdev));
  376. PUT_OCTAL(header.devminor, minor(statbuf->st_rdev));
  377. } else if (S_ISFIFO(statbuf->st_mode)) {
  378. header.typeflag = FIFOTYPE;
  379. } else if (S_ISREG(statbuf->st_mode)) {
  380. /* header.size field is 12 bytes long */
  381. /* Does octal-encoded size fit? */
  382. uoff_t filesize = statbuf->st_size;
  383. if (sizeof(filesize) <= 4
  384. || filesize <= (uoff_t)0777777777777LL
  385. ) {
  386. PUT_OCTAL(header.size, filesize);
  387. }
  388. /* Does base256-encoded size fit?
  389. * It always does unless off_t is wider than 64 bits.
  390. */
  391. else if (ENABLE_FEATURE_TAR_GNU_EXTENSIONS
  392. #if ULLONG_MAX > 0xffffffffffffffffLL /* 2^64-1 */
  393. && (filesize <= 0x3fffffffffffffffffffffffLL)
  394. #endif
  395. ) {
  396. /* GNU tar uses "base-256 encoding" for very large numbers.
  397. * Encoding is binary, with highest bit always set as a marker
  398. * and sign in next-highest bit:
  399. * 80 00 .. 00 - zero
  400. * bf ff .. ff - largest positive number
  401. * ff ff .. ff - minus 1
  402. * c0 00 .. 00 - smallest negative number
  403. */
  404. char *p8 = header.size + sizeof(header.size);
  405. do {
  406. *--p8 = (uint8_t)filesize;
  407. filesize >>= 8;
  408. } while (p8 != header.size);
  409. *p8 |= 0x80;
  410. } else {
  411. bb_error_msg_and_die("can't store file '%s' "
  412. "of size %"OFF_FMT"u, aborting",
  413. fileName, statbuf->st_size);
  414. }
  415. header.typeflag = REGTYPE;
  416. } else {
  417. bb_error_msg("%s: unknown file type", fileName);
  418. return FALSE;
  419. }
  420. #if ENABLE_FEATURE_TAR_GNU_EXTENSIONS
  421. /* Write out long name if needed */
  422. /* (we, like GNU tar, output long linkname *before* long name) */
  423. if (header.name[sizeof(header.name)-1])
  424. writeLongname(tbInfo->tarFd, GNULONGNAME,
  425. header_name, S_ISDIR(statbuf->st_mode));
  426. #endif
  427. /* Now write the header out to disk */
  428. chksum_and_xwrite(tbInfo->tarFd, &header);
  429. /* Now do the verbose thing (or not) */
  430. if (tbInfo->verboseFlag) {
  431. FILE *vbFd = stdout;
  432. /* If archive goes to stdout, verbose goes to stderr */
  433. if (tbInfo->tarFd == STDOUT_FILENO)
  434. vbFd = stderr;
  435. /* GNU "tar cvvf" prints "extended" listing a-la "ls -l" */
  436. /* We don't have such excesses here: for us "v" == "vv" */
  437. /* '/' is probably a GNUism */
  438. fprintf(vbFd, "%s%s\n", header_name,
  439. S_ISDIR(statbuf->st_mode) ? "/" : "");
  440. }
  441. return TRUE;
  442. }
  443. #if ENABLE_FEATURE_TAR_FROM
  444. static int exclude_file(const llist_t *excluded_files, const char *file)
  445. {
  446. while (excluded_files) {
  447. if (excluded_files->data[0] == '/') {
  448. if (fnmatch(excluded_files->data, file,
  449. FNM_PATHNAME | FNM_LEADING_DIR) == 0)
  450. return 1;
  451. } else {
  452. const char *p;
  453. for (p = file; p[0] != '\0'; p++) {
  454. if ((p == file || p[-1] == '/')
  455. && p[0] != '/'
  456. && fnmatch(excluded_files->data, p,
  457. FNM_PATHNAME | FNM_LEADING_DIR) == 0
  458. ) {
  459. return 1;
  460. }
  461. }
  462. }
  463. excluded_files = excluded_files->link;
  464. }
  465. return 0;
  466. }
  467. #else
  468. # define exclude_file(excluded_files, file) 0
  469. #endif
  470. static int FAST_FUNC writeFileToTarball(const char *fileName, struct stat *statbuf,
  471. void *userData, int depth UNUSED_PARAM)
  472. {
  473. struct TarBallInfo *tbInfo = (struct TarBallInfo *) userData;
  474. const char *header_name;
  475. int inputFileFd = -1;
  476. DBG("writeFileToTarball('%s')", fileName);
  477. /* Strip leading '/' and such (must be before memorizing hardlink's name) */
  478. header_name = strip_unsafe_prefix(fileName);
  479. if (header_name[0] == '\0')
  480. return TRUE;
  481. /* It is against the rules to archive a socket */
  482. if (S_ISSOCK(statbuf->st_mode)) {
  483. bb_error_msg("%s: socket ignored", fileName);
  484. return TRUE;
  485. }
  486. /*
  487. * Check to see if we are dealing with a hard link.
  488. * If so -
  489. * Treat the first occurance of a given dev/inode as a file while
  490. * treating any additional occurances as hard links. This is done
  491. * by adding the file information to the HardLinkInfo linked list.
  492. */
  493. tbInfo->hlInfo = NULL;
  494. if (!S_ISDIR(statbuf->st_mode) && statbuf->st_nlink > 1) {
  495. DBG("'%s': st_nlink > 1", header_name);
  496. tbInfo->hlInfo = findHardLinkInfo(tbInfo->hlInfoHead, statbuf);
  497. if (tbInfo->hlInfo == NULL) {
  498. DBG("'%s': addHardLinkInfo", header_name);
  499. addHardLinkInfo(&tbInfo->hlInfoHead, statbuf, header_name);
  500. }
  501. }
  502. /* It is a bad idea to store the archive we are in the process of creating,
  503. * so check the device and inode to be sure that this particular file isn't
  504. * the new tarball */
  505. if (tbInfo->tarFileStatBuf.st_dev == statbuf->st_dev
  506. && tbInfo->tarFileStatBuf.st_ino == statbuf->st_ino
  507. ) {
  508. bb_error_msg("%s: file is the archive; skipping", fileName);
  509. return TRUE;
  510. }
  511. if (exclude_file(tbInfo->excludeList, header_name))
  512. return SKIP;
  513. #if !ENABLE_FEATURE_TAR_GNU_EXTENSIONS
  514. if (strlen(header_name) >= NAME_SIZE) {
  515. bb_error_msg("names longer than "NAME_SIZE_STR" chars not supported");
  516. return TRUE;
  517. }
  518. #endif
  519. /* Is this a regular file? */
  520. if (tbInfo->hlInfo == NULL && S_ISREG(statbuf->st_mode)) {
  521. /* open the file we want to archive, and make sure all is well */
  522. inputFileFd = open_or_warn(fileName, O_RDONLY);
  523. if (inputFileFd < 0) {
  524. return FALSE;
  525. }
  526. }
  527. /* Add an entry to the tarball */
  528. if (writeTarHeader(tbInfo, header_name, fileName, statbuf) == FALSE) {
  529. return FALSE;
  530. }
  531. /* If it was a regular file, write out the body */
  532. if (inputFileFd >= 0) {
  533. size_t readSize;
  534. /* Write the file to the archive. */
  535. /* We record size into header first, */
  536. /* and then write out file. If file shrinks in between, */
  537. /* tar will be corrupted. So we don't allow for that. */
  538. /* NB: GNU tar 1.16 warns and pads with zeroes */
  539. /* or even seeks back and updates header */
  540. bb_copyfd_exact_size(inputFileFd, tbInfo->tarFd, statbuf->st_size);
  541. ////off_t readSize;
  542. ////readSize = bb_copyfd_size(inputFileFd, tbInfo->tarFd, statbuf->st_size);
  543. ////if (readSize != statbuf->st_size && readSize >= 0) {
  544. //// bb_error_msg_and_die("short read from %s, aborting", fileName);
  545. ////}
  546. /* Check that file did not grow in between? */
  547. /* if (safe_read(inputFileFd, 1) == 1) warn but continue? */
  548. close(inputFileFd);
  549. /* Pad the file up to the tar block size */
  550. /* (a few tricks here in the name of code size) */
  551. readSize = (-(int)statbuf->st_size) & (TAR_BLOCK_SIZE-1);
  552. memset(block_buf, 0, readSize);
  553. xwrite(tbInfo->tarFd, block_buf, readSize);
  554. }
  555. return TRUE;
  556. }
  557. #if SEAMLESS_COMPRESSION
  558. /* Don't inline: vfork scares gcc and pessimizes code */
  559. static void NOINLINE vfork_compressor(int tar_fd, const char *gzip)
  560. {
  561. pid_t gzipPid;
  562. // On Linux, vfork never unpauses parent early, although standard
  563. // allows for that. Do we want to waste bytes checking for it?
  564. # define WAIT_FOR_CHILD 0
  565. volatile int vfork_exec_errno = 0;
  566. struct fd_pair gzipDataPipe;
  567. # if WAIT_FOR_CHILD
  568. struct fd_pair gzipStatusPipe;
  569. xpiped_pair(gzipStatusPipe);
  570. # endif
  571. xpiped_pair(gzipDataPipe);
  572. signal(SIGPIPE, SIG_IGN); /* we only want EPIPE on errors */
  573. gzipPid = xvfork();
  574. if (gzipPid == 0) {
  575. /* child */
  576. /* NB: close _first_, then move fds! */
  577. close(gzipDataPipe.wr);
  578. # if WAIT_FOR_CHILD
  579. close(gzipStatusPipe.rd);
  580. /* gzipStatusPipe.wr will close only on exec -
  581. * parent waits for this close to happen */
  582. fcntl(gzipStatusPipe.wr, F_SETFD, FD_CLOEXEC);
  583. # endif
  584. xmove_fd(gzipDataPipe.rd, 0);
  585. xmove_fd(tar_fd, 1);
  586. /* exec gzip/bzip2 program/applet */
  587. BB_EXECLP(gzip, gzip, "-f", (char *)0);
  588. vfork_exec_errno = errno;
  589. _exit(EXIT_FAILURE);
  590. }
  591. /* parent */
  592. xmove_fd(gzipDataPipe.wr, tar_fd);
  593. close(gzipDataPipe.rd);
  594. # if WAIT_FOR_CHILD
  595. close(gzipStatusPipe.wr);
  596. while (1) {
  597. char buf;
  598. int n;
  599. /* Wait until child execs (or fails to) */
  600. n = full_read(gzipStatusPipe.rd, &buf, 1);
  601. if (n < 0 /* && errno == EAGAIN */)
  602. continue; /* try it again */
  603. }
  604. close(gzipStatusPipe.rd);
  605. # endif
  606. if (vfork_exec_errno) {
  607. errno = vfork_exec_errno;
  608. bb_perror_msg_and_die("can't execute '%s'", gzip);
  609. }
  610. }
  611. #endif /* SEAMLESS_COMPRESSION */
  612. #if !SEAMLESS_COMPRESSION
  613. /* Do not pass gzip flag to writeTarFile() */
  614. #define writeTarFile(tar_fd, verboseFlag, recurseFlags, include, exclude, gzip) \
  615. writeTarFile(tar_fd, verboseFlag, recurseFlags, include, exclude)
  616. #endif
  617. /* gcc 4.2.1 inlines it, making code bigger */
  618. static NOINLINE int writeTarFile(int tar_fd, int verboseFlag,
  619. int recurseFlags, const llist_t *include,
  620. const llist_t *exclude, const char *gzip)
  621. {
  622. int errorFlag = FALSE;
  623. struct TarBallInfo tbInfo;
  624. tbInfo.hlInfoHead = NULL;
  625. tbInfo.tarFd = tar_fd;
  626. tbInfo.verboseFlag = verboseFlag;
  627. /* Store the stat info for the tarball's file, so
  628. * can avoid including the tarball into itself.... */
  629. xfstat(tbInfo.tarFd, &tbInfo.tarFileStatBuf, "can't stat tar file");
  630. #if SEAMLESS_COMPRESSION
  631. if (gzip)
  632. vfork_compressor(tbInfo.tarFd, gzip);
  633. #endif
  634. tbInfo.excludeList = exclude;
  635. /* Read the directory/files and iterate over them one at a time */
  636. while (include) {
  637. if (!recursive_action(include->data, recurseFlags,
  638. writeFileToTarball, writeFileToTarball, &tbInfo, 0)
  639. ) {
  640. errorFlag = TRUE;
  641. }
  642. include = include->link;
  643. }
  644. /* Write two empty blocks to the end of the archive */
  645. memset(block_buf, 0, 2*TAR_BLOCK_SIZE);
  646. xwrite(tbInfo.tarFd, block_buf, 2*TAR_BLOCK_SIZE);
  647. /* To be pedantically correct, we would check if the tarball
  648. * is smaller than 20 tar blocks, and pad it if it was smaller,
  649. * but that isn't necessary for GNU tar interoperability, and
  650. * so is considered a waste of space */
  651. /* Close so the child process (if any) will exit */
  652. close(tbInfo.tarFd);
  653. /* Hang up the tools, close up shop, head home */
  654. if (ENABLE_FEATURE_CLEAN_UP)
  655. freeHardLinkInfo(&tbInfo.hlInfoHead);
  656. if (errorFlag)
  657. bb_error_msg("error exit delayed from previous errors");
  658. #if SEAMLESS_COMPRESSION
  659. if (gzip) {
  660. int status;
  661. if (safe_waitpid(-1, &status, 0) == -1)
  662. bb_perror_msg("waitpid");
  663. else if (!WIFEXITED(status) || WEXITSTATUS(status))
  664. /* gzip was killed or has exited with nonzero! */
  665. errorFlag = TRUE;
  666. }
  667. #endif
  668. return errorFlag;
  669. }
  670. #else /* !FEATURE_TAR_CREATE */
  671. # define writeTarFile(...) 0
  672. #endif
  673. #if ENABLE_FEATURE_TAR_FROM
  674. static llist_t *append_file_list_to_list(llist_t *list)
  675. {
  676. FILE *src_stream;
  677. char *line;
  678. llist_t *newlist = NULL;
  679. while (list) {
  680. src_stream = xfopen_stdin(llist_pop(&list));
  681. while ((line = xmalloc_fgetline(src_stream)) != NULL) {
  682. /* kill trailing '/' unless the string is just "/" */
  683. char *cp = last_char_is(line, '/');
  684. if (cp > line)
  685. *cp = '\0';
  686. llist_add_to_end(&newlist, line);
  687. }
  688. fclose(src_stream);
  689. }
  690. return newlist;
  691. }
  692. #endif
  693. //usage:#define tar_trivial_usage
  694. //usage: "-[" IF_FEATURE_TAR_CREATE("c") "xt"
  695. //usage: IF_FEATURE_SEAMLESS_Z("Z")
  696. //usage: IF_FEATURE_SEAMLESS_GZ("z")
  697. //usage: IF_FEATURE_SEAMLESS_XZ("J")
  698. //usage: IF_FEATURE_SEAMLESS_BZ2("j")
  699. //usage: IF_FEATURE_SEAMLESS_LZMA("a")
  700. //usage: IF_FEATURE_TAR_CREATE("h")
  701. //usage: IF_FEATURE_TAR_NOPRESERVE_TIME("m")
  702. //usage: "vO] "
  703. //usage: IF_FEATURE_TAR_FROM("[-X FILE] [-T FILE] ")
  704. //usage: "[-f TARFILE] [-C DIR] [FILE]..."
  705. //usage:#define tar_full_usage "\n\n"
  706. //usage: IF_FEATURE_TAR_CREATE("Create, extract, ")
  707. //usage: IF_NOT_FEATURE_TAR_CREATE("Extract ")
  708. //usage: "or list files from a tar file\n"
  709. //usage: "\nOperation:"
  710. //usage: IF_FEATURE_TAR_CREATE(
  711. //usage: "\n c Create"
  712. //usage: )
  713. //usage: "\n x Extract"
  714. //usage: "\n t List"
  715. //usage: "\n f Name of TARFILE ('-' for stdin/out)"
  716. //usage: "\n C Change to DIR before operation"
  717. //usage: "\n v Verbose"
  718. //usage: IF_FEATURE_SEAMLESS_Z(
  719. //usage: "\n Z (De)compress using compress"
  720. //usage: )
  721. //usage: IF_FEATURE_SEAMLESS_GZ(
  722. //usage: "\n z (De)compress using gzip"
  723. //usage: )
  724. //usage: IF_FEATURE_SEAMLESS_XZ(
  725. //usage: "\n J (De)compress using xz"
  726. //usage: )
  727. //usage: IF_FEATURE_SEAMLESS_BZ2(
  728. //usage: "\n j (De)compress using bzip2"
  729. //usage: )
  730. //usage: IF_FEATURE_SEAMLESS_LZMA(
  731. //usage: "\n a (De)compress using lzma"
  732. //usage: )
  733. //usage: "\n O Extract to stdout"
  734. //usage: IF_FEATURE_TAR_CREATE(
  735. //usage: "\n h Follow symlinks"
  736. //usage: )
  737. //usage: IF_FEATURE_TAR_NOPRESERVE_TIME(
  738. //usage: "\n m Don't restore mtime"
  739. //usage: )
  740. //usage: IF_FEATURE_TAR_FROM(
  741. //usage: IF_FEATURE_TAR_LONG_OPTIONS(
  742. //usage: "\n exclude File to exclude"
  743. //usage: )
  744. //usage: "\n X File with names to exclude"
  745. //usage: "\n T File with names to include"
  746. //usage: )
  747. //usage:
  748. //usage:#define tar_example_usage
  749. //usage: "$ zcat /tmp/tarball.tar.gz | tar -xf -\n"
  750. //usage: "$ tar -cf /tmp/tarball.tar /usr/local\n"
  751. // Supported but aren't in --help:
  752. // o no-same-owner
  753. // p same-permissions
  754. // k keep-old
  755. // no-recursion
  756. // numeric-owner
  757. // no-same-permissions
  758. // overwrite
  759. //IF_FEATURE_TAR_TO_COMMAND(
  760. // to-command
  761. //)
  762. enum {
  763. OPTBIT_KEEP_OLD = 8,
  764. IF_FEATURE_TAR_CREATE( OPTBIT_CREATE ,)
  765. IF_FEATURE_TAR_CREATE( OPTBIT_DEREFERENCE ,)
  766. IF_FEATURE_SEAMLESS_BZ2( OPTBIT_BZIP2 ,)
  767. IF_FEATURE_SEAMLESS_LZMA(OPTBIT_LZMA ,)
  768. IF_FEATURE_TAR_FROM( OPTBIT_INCLUDE_FROM,)
  769. IF_FEATURE_TAR_FROM( OPTBIT_EXCLUDE_FROM,)
  770. IF_FEATURE_SEAMLESS_GZ( OPTBIT_GZIP ,)
  771. IF_FEATURE_SEAMLESS_XZ( OPTBIT_XZ ,) // 16th bit
  772. IF_FEATURE_SEAMLESS_Z( OPTBIT_COMPRESS ,)
  773. IF_FEATURE_TAR_NOPRESERVE_TIME(OPTBIT_NOPRESERVE_TIME,)
  774. #if ENABLE_FEATURE_TAR_LONG_OPTIONS
  775. OPTBIT_NORECURSION,
  776. IF_FEATURE_TAR_TO_COMMAND(OPTBIT_2COMMAND ,)
  777. OPTBIT_NUMERIC_OWNER,
  778. OPTBIT_NOPRESERVE_PERM,
  779. OPTBIT_OVERWRITE,
  780. #endif
  781. OPT_TEST = 1 << 0, // t
  782. OPT_EXTRACT = 1 << 1, // x
  783. OPT_BASEDIR = 1 << 2, // C
  784. OPT_TARNAME = 1 << 3, // f
  785. OPT_2STDOUT = 1 << 4, // O
  786. OPT_NOPRESERVE_OWNER = 1 << 5, // o == no-same-owner
  787. OPT_P = 1 << 6, // p
  788. OPT_VERBOSE = 1 << 7, // v
  789. OPT_KEEP_OLD = 1 << 8, // k
  790. OPT_CREATE = IF_FEATURE_TAR_CREATE( (1 << OPTBIT_CREATE )) + 0, // c
  791. OPT_DEREFERENCE = IF_FEATURE_TAR_CREATE( (1 << OPTBIT_DEREFERENCE )) + 0, // h
  792. OPT_BZIP2 = IF_FEATURE_SEAMLESS_BZ2( (1 << OPTBIT_BZIP2 )) + 0, // j
  793. OPT_LZMA = IF_FEATURE_SEAMLESS_LZMA((1 << OPTBIT_LZMA )) + 0, // a
  794. OPT_INCLUDE_FROM = IF_FEATURE_TAR_FROM( (1 << OPTBIT_INCLUDE_FROM)) + 0, // T
  795. OPT_EXCLUDE_FROM = IF_FEATURE_TAR_FROM( (1 << OPTBIT_EXCLUDE_FROM)) + 0, // X
  796. OPT_GZIP = IF_FEATURE_SEAMLESS_GZ( (1 << OPTBIT_GZIP )) + 0, // z
  797. OPT_XZ = IF_FEATURE_SEAMLESS_XZ( (1 << OPTBIT_XZ )) + 0, // J
  798. OPT_COMPRESS = IF_FEATURE_SEAMLESS_Z( (1 << OPTBIT_COMPRESS )) + 0, // Z
  799. OPT_NOPRESERVE_TIME = IF_FEATURE_TAR_NOPRESERVE_TIME((1 << OPTBIT_NOPRESERVE_TIME)) + 0, // m
  800. OPT_NORECURSION = IF_FEATURE_TAR_LONG_OPTIONS((1 << OPTBIT_NORECURSION )) + 0, // no-recursion
  801. OPT_2COMMAND = IF_FEATURE_TAR_TO_COMMAND( (1 << OPTBIT_2COMMAND )) + 0, // to-command
  802. OPT_NUMERIC_OWNER = IF_FEATURE_TAR_LONG_OPTIONS((1 << OPTBIT_NUMERIC_OWNER )) + 0, // numeric-owner
  803. OPT_NOPRESERVE_PERM = IF_FEATURE_TAR_LONG_OPTIONS((1 << OPTBIT_NOPRESERVE_PERM)) + 0, // no-same-permissions
  804. OPT_OVERWRITE = IF_FEATURE_TAR_LONG_OPTIONS((1 << OPTBIT_OVERWRITE )) + 0, // overwrite
  805. OPT_ANY_COMPRESS = (OPT_BZIP2 | OPT_LZMA | OPT_GZIP | OPT_XZ | OPT_COMPRESS),
  806. };
  807. #if ENABLE_FEATURE_TAR_LONG_OPTIONS
  808. static const char tar_longopts[] ALIGN1 =
  809. "list\0" No_argument "t"
  810. "extract\0" No_argument "x"
  811. "directory\0" Required_argument "C"
  812. "file\0" Required_argument "f"
  813. "to-stdout\0" No_argument "O"
  814. /* do not restore owner */
  815. /* Note: GNU tar handles 'o' as no-same-owner only on extract,
  816. * on create, 'o' is --old-archive. We do not support --old-archive. */
  817. "no-same-owner\0" No_argument "o"
  818. "same-permissions\0" No_argument "p"
  819. "verbose\0" No_argument "v"
  820. "keep-old\0" No_argument "k"
  821. # if ENABLE_FEATURE_TAR_CREATE
  822. "create\0" No_argument "c"
  823. "dereference\0" No_argument "h"
  824. # endif
  825. # if ENABLE_FEATURE_SEAMLESS_BZ2
  826. "bzip2\0" No_argument "j"
  827. # endif
  828. # if ENABLE_FEATURE_SEAMLESS_LZMA
  829. "lzma\0" No_argument "a"
  830. # endif
  831. # if ENABLE_FEATURE_TAR_FROM
  832. "files-from\0" Required_argument "T"
  833. "exclude-from\0" Required_argument "X"
  834. # endif
  835. # if ENABLE_FEATURE_SEAMLESS_GZ
  836. "gzip\0" No_argument "z"
  837. # endif
  838. # if ENABLE_FEATURE_SEAMLESS_XZ
  839. "xz\0" No_argument "J"
  840. # endif
  841. # if ENABLE_FEATURE_SEAMLESS_Z
  842. "compress\0" No_argument "Z"
  843. # endif
  844. # if ENABLE_FEATURE_TAR_NOPRESERVE_TIME
  845. "touch\0" No_argument "m"
  846. # endif
  847. "no-recursion\0" No_argument "\xfa"
  848. # if ENABLE_FEATURE_TAR_TO_COMMAND
  849. "to-command\0" Required_argument "\xfb"
  850. # endif
  851. /* use numeric uid/gid from tar header, not textual */
  852. "numeric-owner\0" No_argument "\xfc"
  853. /* do not restore mode */
  854. "no-same-permissions\0" No_argument "\xfd"
  855. /* on unpack, open with O_TRUNC and !O_EXCL */
  856. "overwrite\0" No_argument "\xfe"
  857. /* --exclude takes next bit position in option mask, */
  858. /* therefore we have to put it _after_ --no-same-permissions */
  859. # if ENABLE_FEATURE_TAR_FROM
  860. "exclude\0" Required_argument "\xff"
  861. # endif
  862. ;
  863. #endif
  864. int tar_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  865. int tar_main(int argc UNUSED_PARAM, char **argv)
  866. {
  867. archive_handle_t *tar_handle;
  868. char *base_dir = NULL;
  869. const char *tar_filename = "-";
  870. unsigned opt;
  871. int verboseFlag = 0;
  872. #if ENABLE_FEATURE_TAR_LONG_OPTIONS && ENABLE_FEATURE_TAR_FROM
  873. llist_t *excludes = NULL;
  874. #endif
  875. /* Initialise default values */
  876. tar_handle = init_handle();
  877. tar_handle->ah_flags = ARCHIVE_CREATE_LEADING_DIRS
  878. | ARCHIVE_RESTORE_DATE
  879. | ARCHIVE_UNLINK_OLD;
  880. /* Apparently only root's tar preserves perms (see bug 3844) */
  881. if (getuid() != 0)
  882. tar_handle->ah_flags |= ARCHIVE_DONT_RESTORE_PERM;
  883. /* Prepend '-' to the first argument if required */
  884. opt_complementary = "--:" // first arg is options
  885. "tt:vv:" // count -t,-v
  886. IF_FEATURE_TAR_FROM("X::T::") // cumulative lists
  887. #if ENABLE_FEATURE_TAR_LONG_OPTIONS && ENABLE_FEATURE_TAR_FROM
  888. "\xff::" // cumulative lists for --exclude
  889. #endif
  890. IF_FEATURE_TAR_CREATE("c:") "t:x:" // at least one of these is reqd
  891. IF_FEATURE_TAR_CREATE("c--tx:t--cx:x--ct") // mutually exclusive
  892. IF_NOT_FEATURE_TAR_CREATE("t--x:x--t"); // mutually exclusive
  893. #if ENABLE_FEATURE_TAR_LONG_OPTIONS
  894. applet_long_options = tar_longopts;
  895. #endif
  896. #if ENABLE_DESKTOP
  897. if (argv[1] && argv[1][0] != '-') {
  898. /* Compat:
  899. * 1st argument without dash handles options with parameters
  900. * differently from dashed one: it takes *next argv[i]*
  901. * as paramenter even if there are more chars in 1st argument:
  902. * "tar fx TARFILE" - "x" is not taken as f's param
  903. * but is interpreted as -x option
  904. * "tar -xf TARFILE" - dashed equivalent of the above
  905. * "tar -fx ..." - "x" is taken as f's param
  906. * getopt32 wouldn't handle 1st command correctly.
  907. * Unfortunately, people do use such commands.
  908. * We massage argv[1] to work around it by moving 'f'
  909. * to the end of the string.
  910. * More contrived "tar fCx TARFILE DIR" still fails,
  911. * but such commands are much less likely to be used.
  912. */
  913. char *f = strchr(argv[1], 'f');
  914. if (f) {
  915. while (f[1] != '\0') {
  916. *f = f[1];
  917. f++;
  918. }
  919. *f = 'f';
  920. }
  921. }
  922. #endif
  923. opt = getopt32(argv,
  924. "txC:f:Oopvk"
  925. IF_FEATURE_TAR_CREATE( "ch" )
  926. IF_FEATURE_SEAMLESS_BZ2( "j" )
  927. IF_FEATURE_SEAMLESS_LZMA("a" )
  928. IF_FEATURE_TAR_FROM( "T:X:")
  929. IF_FEATURE_SEAMLESS_GZ( "z" )
  930. IF_FEATURE_SEAMLESS_XZ( "J" )
  931. IF_FEATURE_SEAMLESS_Z( "Z" )
  932. IF_FEATURE_TAR_NOPRESERVE_TIME("m")
  933. , &base_dir // -C dir
  934. , &tar_filename // -f filename
  935. IF_FEATURE_TAR_FROM(, &(tar_handle->accept)) // T
  936. IF_FEATURE_TAR_FROM(, &(tar_handle->reject)) // X
  937. IF_FEATURE_TAR_TO_COMMAND(, &(tar_handle->tar__to_command)) // --to-command
  938. #if ENABLE_FEATURE_TAR_LONG_OPTIONS && ENABLE_FEATURE_TAR_FROM
  939. , &excludes // --exclude
  940. #endif
  941. , &verboseFlag // combined count for -t and -v
  942. , &verboseFlag // combined count for -t and -v
  943. );
  944. //bb_error_msg("opt:%08x", opt);
  945. argv += optind;
  946. if (verboseFlag) tar_handle->action_header = header_verbose_list;
  947. if (verboseFlag == 1) tar_handle->action_header = header_list;
  948. if (opt & OPT_EXTRACT)
  949. tar_handle->action_data = data_extract_all;
  950. if (opt & OPT_2STDOUT)
  951. tar_handle->action_data = data_extract_to_stdout;
  952. if (opt & OPT_2COMMAND) {
  953. putenv((char*)"TAR_FILETYPE=f");
  954. signal(SIGPIPE, SIG_IGN);
  955. tar_handle->action_data = data_extract_to_command;
  956. IF_FEATURE_TAR_TO_COMMAND(tar_handle->tar__to_command_shell = xstrdup(get_shell_name());)
  957. }
  958. if (opt & OPT_KEEP_OLD)
  959. tar_handle->ah_flags &= ~ARCHIVE_UNLINK_OLD;
  960. if (opt & OPT_NUMERIC_OWNER)
  961. tar_handle->ah_flags |= ARCHIVE_NUMERIC_OWNER;
  962. if (opt & OPT_NOPRESERVE_OWNER)
  963. tar_handle->ah_flags |= ARCHIVE_DONT_RESTORE_OWNER;
  964. if (opt & OPT_NOPRESERVE_PERM)
  965. tar_handle->ah_flags |= ARCHIVE_DONT_RESTORE_PERM;
  966. if (opt & OPT_OVERWRITE) {
  967. tar_handle->ah_flags &= ~ARCHIVE_UNLINK_OLD;
  968. tar_handle->ah_flags |= ARCHIVE_O_TRUNC;
  969. }
  970. if (opt & OPT_NOPRESERVE_TIME)
  971. tar_handle->ah_flags &= ~ARCHIVE_RESTORE_DATE;
  972. #if ENABLE_FEATURE_TAR_FROM
  973. tar_handle->reject = append_file_list_to_list(tar_handle->reject);
  974. # if ENABLE_FEATURE_TAR_LONG_OPTIONS
  975. /* Append excludes to reject */
  976. while (excludes) {
  977. llist_t *next = excludes->link;
  978. excludes->link = tar_handle->reject;
  979. tar_handle->reject = excludes;
  980. excludes = next;
  981. }
  982. # endif
  983. tar_handle->accept = append_file_list_to_list(tar_handle->accept);
  984. #endif
  985. /* Setup an array of filenames to work with */
  986. /* TODO: This is the same as in ar, make a separate function? */
  987. while (*argv) {
  988. /* kill trailing '/' unless the string is just "/" */
  989. char *cp = last_char_is(*argv, '/');
  990. if (cp > *argv)
  991. *cp = '\0';
  992. llist_add_to_end(&tar_handle->accept, *argv);
  993. argv++;
  994. }
  995. if (tar_handle->accept || tar_handle->reject)
  996. tar_handle->filter = filter_accept_reject_list;
  997. /* Open the tar file */
  998. {
  999. int tar_fd = STDIN_FILENO;
  1000. int flags = O_RDONLY;
  1001. if (opt & OPT_CREATE) {
  1002. /* Make sure there is at least one file to tar up */
  1003. if (tar_handle->accept == NULL)
  1004. bb_error_msg_and_die("empty archive");
  1005. tar_fd = STDOUT_FILENO;
  1006. /* Mimicking GNU tar 1.15.1: */
  1007. flags = O_WRONLY | O_CREAT | O_TRUNC;
  1008. }
  1009. if (LONE_DASH(tar_filename)) {
  1010. tar_handle->src_fd = tar_fd;
  1011. tar_handle->seek = seek_by_read;
  1012. } else {
  1013. if (ENABLE_FEATURE_TAR_AUTODETECT
  1014. && flags == O_RDONLY
  1015. && !(opt & OPT_ANY_COMPRESS)
  1016. ) {
  1017. tar_handle->src_fd = open_zipped(tar_filename, /*fail_if_not_compressed:*/ 0);
  1018. if (tar_handle->src_fd < 0)
  1019. bb_perror_msg_and_die("can't open '%s'", tar_filename);
  1020. } else {
  1021. tar_handle->src_fd = xopen(tar_filename, flags);
  1022. }
  1023. }
  1024. }
  1025. if (base_dir)
  1026. xchdir(base_dir);
  1027. //if (SEAMLESS_COMPRESSION)
  1028. // /* We need to know whether child (gzip/bzip/etc) exits abnormally */
  1029. // signal(SIGCHLD, check_errors_in_children);
  1030. /* Create an archive */
  1031. if (opt & OPT_CREATE) {
  1032. #if SEAMLESS_COMPRESSION
  1033. const char *zipMode = NULL;
  1034. if (opt & OPT_COMPRESS)
  1035. zipMode = "compress";
  1036. if (opt & OPT_GZIP)
  1037. zipMode = "gzip";
  1038. if (opt & OPT_BZIP2)
  1039. zipMode = "bzip2";
  1040. if (opt & OPT_LZMA)
  1041. zipMode = "lzma";
  1042. if (opt & OPT_XZ)
  1043. zipMode = "xz";
  1044. #endif
  1045. /* NB: writeTarFile() closes tar_handle->src_fd */
  1046. return writeTarFile(tar_handle->src_fd, verboseFlag,
  1047. (opt & OPT_DEREFERENCE ? ACTION_FOLLOWLINKS : 0)
  1048. | (opt & OPT_NORECURSION ? 0 : ACTION_RECURSE),
  1049. tar_handle->accept,
  1050. tar_handle->reject, zipMode);
  1051. }
  1052. if (opt & OPT_ANY_COMPRESS) {
  1053. USE_FOR_MMU(IF_DESKTOP(long long) int FAST_FUNC (*xformer)(transformer_state_t *xstate);)
  1054. USE_FOR_NOMMU(const char *xformer_prog;)
  1055. if (opt & OPT_COMPRESS)
  1056. USE_FOR_MMU(xformer = unpack_Z_stream;)
  1057. USE_FOR_NOMMU(xformer_prog = "uncompress";)
  1058. if (opt & OPT_GZIP)
  1059. USE_FOR_MMU(xformer = unpack_gz_stream;)
  1060. USE_FOR_NOMMU(xformer_prog = "gunzip";)
  1061. if (opt & OPT_BZIP2)
  1062. USE_FOR_MMU(xformer = unpack_bz2_stream;)
  1063. USE_FOR_NOMMU(xformer_prog = "bunzip2";)
  1064. if (opt & OPT_LZMA)
  1065. USE_FOR_MMU(xformer = unpack_lzma_stream;)
  1066. USE_FOR_NOMMU(xformer_prog = "unlzma";)
  1067. if (opt & OPT_XZ)
  1068. USE_FOR_MMU(xformer = unpack_xz_stream;)
  1069. USE_FOR_NOMMU(xformer_prog = "unxz";)
  1070. fork_transformer_with_sig(tar_handle->src_fd, xformer, xformer_prog);
  1071. /* Can't lseek over pipes */
  1072. tar_handle->seek = seek_by_read;
  1073. /*tar_handle->offset = 0; - already is */
  1074. }
  1075. /* Zero processed headers (== empty file) is not a valid tarball.
  1076. * We (ab)use bb_got_signal as exitcode here,
  1077. * because check_errors_in_children() uses _it_ as error indicator.
  1078. */
  1079. bb_got_signal = EXIT_FAILURE;
  1080. while (get_header_tar(tar_handle) == EXIT_SUCCESS)
  1081. bb_got_signal = EXIT_SUCCESS; /* saw at least one header, good */
  1082. /* Check that every file that should have been extracted was */
  1083. while (tar_handle->accept) {
  1084. if (!find_list_entry(tar_handle->reject, tar_handle->accept->data)
  1085. && !find_list_entry(tar_handle->passed, tar_handle->accept->data)
  1086. ) {
  1087. bb_error_msg_and_die("%s: not found in archive",
  1088. tar_handle->accept->data);
  1089. }
  1090. tar_handle->accept = tar_handle->accept->link;
  1091. }
  1092. if (ENABLE_FEATURE_CLEAN_UP /* && tar_handle->src_fd != STDIN_FILENO */)
  1093. close(tar_handle->src_fd);
  1094. if (SEAMLESS_COMPRESSION || OPT_COMPRESS) {
  1095. /* Set bb_got_signal to 1 if a child died with !0 exitcode */
  1096. check_errors_in_children(0);
  1097. }
  1098. return bb_got_signal;
  1099. }