tar.c 39 KB

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