3
0

tar.c 42 KB

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