3
0

tar.c 35 KB

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