tar.c 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939
  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. * Glenn McGrath <bug1@iinet.net.au>
  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 the 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 tarball for details.
  24. */
  25. #include <fnmatch.h>
  26. #include <getopt.h>
  27. #include "libbb.h"
  28. #include "unarchive.h"
  29. #define block_buf bb_common_bufsiz1
  30. #if ENABLE_FEATURE_TAR_CREATE
  31. /* Tar file constants */
  32. #define TAR_BLOCK_SIZE 512
  33. /* POSIX tar Header Block, from POSIX 1003.1-1990 */
  34. #define NAME_SIZE 100
  35. #define NAME_SIZE_STR "100"
  36. typedef struct TarHeader TarHeader;
  37. struct TarHeader { /* byte offset */
  38. char name[NAME_SIZE]; /* 0-99 */
  39. char mode[8]; /* 100-107 */
  40. char uid[8]; /* 108-115 */
  41. char gid[8]; /* 116-123 */
  42. char size[12]; /* 124-135 */
  43. char mtime[12]; /* 136-147 */
  44. char chksum[8]; /* 148-155 */
  45. char typeflag; /* 156-156 */
  46. char linkname[NAME_SIZE]; /* 157-256 */
  47. char magic[6]; /* 257-262 */
  48. char version[2]; /* 263-264 */
  49. char uname[32]; /* 265-296 */
  50. char gname[32]; /* 297-328 */
  51. char devmajor[8]; /* 329-336 */
  52. char devminor[8]; /* 337-344 */
  53. char prefix[155]; /* 345-499 */
  54. char padding[12]; /* 500-512 (pad to exactly the TAR_BLOCK_SIZE) */
  55. };
  56. /*
  57. ** writeTarFile(), writeFileToTarball(), and writeTarHeader() are
  58. ** the only functions that deal with the HardLinkInfo structure.
  59. ** Even these functions use the xxxHardLinkInfo() functions.
  60. */
  61. typedef struct HardLinkInfo HardLinkInfo;
  62. struct HardLinkInfo {
  63. HardLinkInfo *next; /* Next entry in list */
  64. dev_t dev; /* Device number */
  65. ino_t ino; /* Inode number */
  66. short linkCount; /* (Hard) Link Count */
  67. char name[1]; /* Start of filename (must be last) */
  68. };
  69. /* Some info to be carried along when creating a new tarball */
  70. typedef struct TarBallInfo TarBallInfo;
  71. struct TarBallInfo {
  72. int tarFd; /* Open-for-write file descriptor
  73. for the tarball */
  74. struct stat statBuf; /* Stat info for the tarball, letting
  75. us know the inode and device that the
  76. tarball lives, so we can avoid trying
  77. to include the tarball into itself */
  78. int verboseFlag; /* Whether to print extra stuff or not */
  79. const llist_t *excludeList; /* List of files to not include */
  80. HardLinkInfo *hlInfoHead; /* Hard Link Tracking Information */
  81. HardLinkInfo *hlInfo; /* Hard Link Info for the current file */
  82. };
  83. /* A nice enum with all the possible tar file content types */
  84. enum TarFileType {
  85. REGTYPE = '0', /* regular file */
  86. REGTYPE0 = '\0', /* regular file (ancient bug compat) */
  87. LNKTYPE = '1', /* hard link */
  88. SYMTYPE = '2', /* symbolic link */
  89. CHRTYPE = '3', /* character special */
  90. BLKTYPE = '4', /* block special */
  91. DIRTYPE = '5', /* directory */
  92. FIFOTYPE = '6', /* FIFO special */
  93. CONTTYPE = '7', /* reserved */
  94. GNULONGLINK = 'K', /* GNU long (>100 chars) link name */
  95. GNULONGNAME = 'L', /* GNU long (>100 chars) file name */
  96. };
  97. typedef enum TarFileType TarFileType;
  98. /* Might be faster (and bigger) if the dev/ino were stored in numeric order;) */
  99. static void addHardLinkInfo(HardLinkInfo ** hlInfoHeadPtr,
  100. struct stat *statbuf,
  101. const char *fileName)
  102. {
  103. /* Note: hlInfoHeadPtr can never be NULL! */
  104. HardLinkInfo *hlInfo;
  105. hlInfo = xmalloc(sizeof(HardLinkInfo) + strlen(fileName));
  106. hlInfo->next = *hlInfoHeadPtr;
  107. *hlInfoHeadPtr = hlInfo;
  108. hlInfo->dev = statbuf->st_dev;
  109. hlInfo->ino = statbuf->st_ino;
  110. hlInfo->linkCount = statbuf->st_nlink;
  111. strcpy(hlInfo->name, fileName);
  112. }
  113. static void freeHardLinkInfo(HardLinkInfo ** hlInfoHeadPtr)
  114. {
  115. HardLinkInfo *hlInfo;
  116. HardLinkInfo *hlInfoNext;
  117. if (hlInfoHeadPtr) {
  118. hlInfo = *hlInfoHeadPtr;
  119. while (hlInfo) {
  120. hlInfoNext = hlInfo->next;
  121. free(hlInfo);
  122. hlInfo = hlInfoNext;
  123. }
  124. *hlInfoHeadPtr = NULL;
  125. }
  126. }
  127. /* Might be faster (and bigger) if the dev/ino were stored in numeric order;) */
  128. static HardLinkInfo *findHardLinkInfo(HardLinkInfo * hlInfo, struct stat *statbuf)
  129. {
  130. while (hlInfo) {
  131. if ((statbuf->st_ino == hlInfo->ino) && (statbuf->st_dev == hlInfo->dev))
  132. break;
  133. hlInfo = hlInfo->next;
  134. }
  135. return hlInfo;
  136. }
  137. /* Put an octal string into the specified buffer.
  138. * The number is zero padded and possibly null terminated.
  139. * Stores low-order bits only if whole value does not fit. */
  140. static void putOctal(char *cp, int len, off_t value)
  141. {
  142. char tempBuffer[sizeof(off_t)*3+1];
  143. char *tempString = tempBuffer;
  144. int width;
  145. width = sprintf(tempBuffer, "%0*"OFF_FMT"o", len, value);
  146. tempString += (width - len);
  147. /* If string has leading zeroes, we can drop one */
  148. /* and field will have trailing '\0' */
  149. /* (increases chances of compat with other tars) */
  150. if (tempString[0] == '0')
  151. tempString++;
  152. /* Copy the string to the field */
  153. memcpy(cp, tempString, len);
  154. }
  155. #define PUT_OCTAL(a, b) putOctal((a), sizeof(a), (b))
  156. static void chksum_and_xwrite(int fd, struct TarHeader* hp)
  157. {
  158. /* POSIX says that checksum is done on unsigned bytes
  159. * (Sun and HP-UX gets it wrong... more details in
  160. * GNU tar source) */
  161. const unsigned char *cp;
  162. int chksum, size;
  163. strcpy(hp->magic, "ustar ");
  164. /* Calculate and store the checksum (i.e., the sum of all of the bytes of
  165. * the header). The checksum field must be filled with blanks for the
  166. * calculation. The checksum field is formatted differently from the
  167. * other fields: it has 6 digits, a null, then a space -- rather than
  168. * digits, followed by a null like the other fields... */
  169. memset(hp->chksum, ' ', sizeof(hp->chksum));
  170. cp = (const unsigned char *) hp;
  171. chksum = 0;
  172. size = sizeof(*hp);
  173. do { chksum += *cp++; } while (--size);
  174. putOctal(hp->chksum, sizeof(hp->chksum)-1, chksum);
  175. /* Now write the header out to disk */
  176. xwrite(fd, hp, sizeof(*hp));
  177. }
  178. #if ENABLE_FEATURE_TAR_GNU_EXTENSIONS
  179. static void writeLongname(int fd, int type, const char *name, int dir)
  180. {
  181. static const struct {
  182. char mode[8]; /* 100-107 */
  183. char uid[8]; /* 108-115 */
  184. char gid[8]; /* 116-123 */
  185. char size[12]; /* 124-135 */
  186. char mtime[12]; /* 136-147 */
  187. } prefilled = {
  188. "0000000",
  189. "0000000",
  190. "0000000",
  191. "00000000000",
  192. "00000000000",
  193. };
  194. struct TarHeader header;
  195. int size;
  196. dir = !!dir; /* normalize: 0/1 */
  197. size = strlen(name) + 1 + dir; /* GNU tar uses strlen+1 */
  198. /* + dir: account for possible '/' */
  199. memset(&header, 0, sizeof(header));
  200. strcpy(header.name, "././@LongLink");
  201. memcpy(header.mode, prefilled.mode, sizeof(prefilled));
  202. PUT_OCTAL(header.size, size);
  203. header.typeflag = type;
  204. chksum_and_xwrite(fd, &header);
  205. /* Write filename[/] and pad the block. */
  206. /* dir=0: writes 'name<NUL>', pads */
  207. /* dir=1: writes 'name', writes '/<NUL>', pads */
  208. dir *= 2;
  209. xwrite(fd, name, size - dir);
  210. xwrite(fd, "/", dir);
  211. size = (-size) & (TAR_BLOCK_SIZE-1);
  212. memset(&header, 0, size);
  213. xwrite(fd, &header, size);
  214. }
  215. #endif
  216. /* Write out a tar header for the specified file/directory/whatever */
  217. void BUG_tar_header_size(void);
  218. static int writeTarHeader(struct TarBallInfo *tbInfo,
  219. const char *header_name, const char *fileName, struct stat *statbuf)
  220. {
  221. struct TarHeader header;
  222. if (sizeof(header) != 512)
  223. BUG_tar_header_size();
  224. memset(&header, 0, sizeof(struct TarHeader));
  225. strncpy(header.name, header_name, sizeof(header.name));
  226. /* POSIX says to mask mode with 07777. */
  227. PUT_OCTAL(header.mode, statbuf->st_mode & 07777);
  228. PUT_OCTAL(header.uid, statbuf->st_uid);
  229. PUT_OCTAL(header.gid, statbuf->st_gid);
  230. memset(header.size, '0', sizeof(header.size)-1); /* Regular file size is handled later */
  231. PUT_OCTAL(header.mtime, statbuf->st_mtime);
  232. /* Enter the user and group names */
  233. safe_strncpy(header.uname, get_cached_username(statbuf->st_uid), sizeof(header.uname));
  234. safe_strncpy(header.gname, get_cached_groupname(statbuf->st_gid), sizeof(header.gname));
  235. if (tbInfo->hlInfo) {
  236. /* This is a hard link */
  237. header.typeflag = LNKTYPE;
  238. strncpy(header.linkname, tbInfo->hlInfo->name,
  239. sizeof(header.linkname));
  240. #if ENABLE_FEATURE_TAR_GNU_EXTENSIONS
  241. /* Write out long linkname if needed */
  242. if (header.linkname[sizeof(header.linkname)-1])
  243. writeLongname(tbInfo->tarFd, GNULONGLINK,
  244. tbInfo->hlInfo->name, 0);
  245. #endif
  246. } else if (S_ISLNK(statbuf->st_mode)) {
  247. char *lpath = xmalloc_readlink_or_warn(fileName);
  248. if (!lpath)
  249. return FALSE;
  250. header.typeflag = SYMTYPE;
  251. strncpy(header.linkname, lpath, sizeof(header.linkname));
  252. #if ENABLE_FEATURE_TAR_GNU_EXTENSIONS
  253. /* Write out long linkname if needed */
  254. if (header.linkname[sizeof(header.linkname)-1])
  255. writeLongname(tbInfo->tarFd, GNULONGLINK, lpath, 0);
  256. #else
  257. /* If it is larger than 100 bytes, bail out */
  258. if (header.linkname[sizeof(header.linkname)-1]) {
  259. free(lpath);
  260. bb_error_msg("names longer than "NAME_SIZE_STR" chars not supported");
  261. return FALSE;
  262. }
  263. #endif
  264. free(lpath);
  265. } else if (S_ISDIR(statbuf->st_mode)) {
  266. header.typeflag = DIRTYPE;
  267. /* Append '/' only if there is a space for it */
  268. if (!header.name[sizeof(header.name)-1])
  269. header.name[strlen(header.name)] = '/';
  270. } else if (S_ISCHR(statbuf->st_mode)) {
  271. header.typeflag = CHRTYPE;
  272. PUT_OCTAL(header.devmajor, major(statbuf->st_rdev));
  273. PUT_OCTAL(header.devminor, minor(statbuf->st_rdev));
  274. } else if (S_ISBLK(statbuf->st_mode)) {
  275. header.typeflag = BLKTYPE;
  276. PUT_OCTAL(header.devmajor, major(statbuf->st_rdev));
  277. PUT_OCTAL(header.devminor, minor(statbuf->st_rdev));
  278. } else if (S_ISFIFO(statbuf->st_mode)) {
  279. header.typeflag = FIFOTYPE;
  280. } else if (S_ISREG(statbuf->st_mode)) {
  281. if (sizeof(statbuf->st_size) > 4
  282. && statbuf->st_size > (off_t)0777777777777LL
  283. ) {
  284. bb_error_msg_and_die("cannot store file '%s' "
  285. "of size %"OFF_FMT"d, aborting",
  286. fileName, statbuf->st_size);
  287. }
  288. header.typeflag = REGTYPE;
  289. PUT_OCTAL(header.size, statbuf->st_size);
  290. } else {
  291. bb_error_msg("%s: unknown file type", fileName);
  292. return FALSE;
  293. }
  294. #if ENABLE_FEATURE_TAR_GNU_EXTENSIONS
  295. /* Write out long name if needed */
  296. /* (we, like GNU tar, output long linkname *before* long name) */
  297. if (header.name[sizeof(header.name)-1])
  298. writeLongname(tbInfo->tarFd, GNULONGNAME,
  299. header_name, S_ISDIR(statbuf->st_mode));
  300. #endif
  301. /* Now write the header out to disk */
  302. chksum_and_xwrite(tbInfo->tarFd, &header);
  303. /* Now do the verbose thing (or not) */
  304. if (tbInfo->verboseFlag) {
  305. FILE *vbFd = stdout;
  306. if (tbInfo->tarFd == STDOUT_FILENO) /* If the archive goes to stdout, verbose to stderr */
  307. vbFd = stderr;
  308. /* GNU "tar cvvf" prints "extended" listing a-la "ls -l" */
  309. /* We don't have such excesses here: for us "v" == "vv" */
  310. /* '/' is probably a GNUism */
  311. fprintf(vbFd, "%s%s\n", header_name,
  312. S_ISDIR(statbuf->st_mode) ? "/" : "");
  313. }
  314. return TRUE;
  315. }
  316. #if ENABLE_FEATURE_TAR_FROM
  317. static int exclude_file(const llist_t *excluded_files, const char *file)
  318. {
  319. while (excluded_files) {
  320. if (excluded_files->data[0] == '/') {
  321. if (fnmatch(excluded_files->data, file,
  322. FNM_PATHNAME | FNM_LEADING_DIR) == 0)
  323. return 1;
  324. } else {
  325. const char *p;
  326. for (p = file; p[0] != '\0'; p++) {
  327. if ((p == file || p[-1] == '/') && p[0] != '/' &&
  328. fnmatch(excluded_files->data, p,
  329. FNM_PATHNAME | FNM_LEADING_DIR) == 0)
  330. return 1;
  331. }
  332. }
  333. excluded_files = excluded_files->link;
  334. }
  335. return 0;
  336. }
  337. #else
  338. #define exclude_file(excluded_files, file) 0
  339. #endif
  340. static int writeFileToTarball(const char *fileName, struct stat *statbuf,
  341. void *userData, int depth ATTRIBUTE_UNUSED)
  342. {
  343. struct TarBallInfo *tbInfo = (struct TarBallInfo *) userData;
  344. const char *header_name;
  345. int inputFileFd = -1;
  346. /*
  347. * Check to see if we are dealing with a hard link.
  348. * If so -
  349. * Treat the first occurance of a given dev/inode as a file while
  350. * treating any additional occurances as hard links. This is done
  351. * by adding the file information to the HardLinkInfo linked list.
  352. */
  353. tbInfo->hlInfo = NULL;
  354. if (statbuf->st_nlink > 1) {
  355. tbInfo->hlInfo = findHardLinkInfo(tbInfo->hlInfoHead, statbuf);
  356. if (tbInfo->hlInfo == NULL)
  357. addHardLinkInfo(&tbInfo->hlInfoHead, statbuf, fileName);
  358. }
  359. /* It is against the rules to archive a socket */
  360. if (S_ISSOCK(statbuf->st_mode)) {
  361. bb_error_msg("%s: socket ignored", fileName);
  362. return TRUE;
  363. }
  364. /* It is a bad idea to store the archive we are in the process of creating,
  365. * so check the device and inode to be sure that this particular file isn't
  366. * the new tarball */
  367. if (tbInfo->statBuf.st_dev == statbuf->st_dev &&
  368. tbInfo->statBuf.st_ino == statbuf->st_ino) {
  369. bb_error_msg("%s: file is the archive; skipping", fileName);
  370. return TRUE;
  371. }
  372. header_name = fileName;
  373. while (header_name[0] == '/') {
  374. static smallint warned;
  375. if (!warned) {
  376. bb_error_msg("removing leading '/' from member names");
  377. warned = 1;
  378. }
  379. header_name++;
  380. }
  381. #if !ENABLE_FEATURE_TAR_GNU_EXTENSIONS
  382. if (strlen(fileName) >= NAME_SIZE) {
  383. bb_error_msg("names longer than "NAME_SIZE_STR" chars not supported");
  384. return TRUE;
  385. }
  386. #endif
  387. if (header_name[0] == '\0')
  388. return TRUE;
  389. if (exclude_file(tbInfo->excludeList, header_name))
  390. return SKIP;
  391. /* Is this a regular file? */
  392. if (tbInfo->hlInfo == NULL && S_ISREG(statbuf->st_mode)) {
  393. /* open the file we want to archive, and make sure all is well */
  394. inputFileFd = open_or_warn(fileName, O_RDONLY);
  395. if (inputFileFd < 0) {
  396. return FALSE;
  397. }
  398. }
  399. /* Add an entry to the tarball */
  400. if (writeTarHeader(tbInfo, header_name, fileName, statbuf) == FALSE) {
  401. return FALSE;
  402. }
  403. /* If it was a regular file, write out the body */
  404. if (inputFileFd >= 0) {
  405. size_t readSize;
  406. /* Write the file to the archive. */
  407. /* We record size into header first, */
  408. /* and then write out file. If file shrinks in between, */
  409. /* tar will be corrupted. So we don't allow for that. */
  410. /* NB: GNU tar 1.16 warns and pads with zeroes */
  411. /* or even seeks back and updates header */
  412. bb_copyfd_exact_size(inputFileFd, tbInfo->tarFd, statbuf->st_size);
  413. ////off_t readSize;
  414. ////readSize = bb_copyfd_size(inputFileFd, tbInfo->tarFd, statbuf->st_size);
  415. ////if (readSize != statbuf->st_size && readSize >= 0) {
  416. //// bb_error_msg_and_die("short read from %s, aborting", fileName);
  417. ////}
  418. /* Check that file did not grow in between? */
  419. /* if (safe_read(inputFileFd, 1) == 1) warn but continue? */
  420. close(inputFileFd);
  421. /* Pad the file up to the tar block size */
  422. /* (a few tricks here in the name of code size) */
  423. readSize = (-(int)statbuf->st_size) & (TAR_BLOCK_SIZE-1);
  424. memset(block_buf, 0, readSize);
  425. xwrite(tbInfo->tarFd, block_buf, readSize);
  426. }
  427. return TRUE;
  428. }
  429. static int writeTarFile(const int tar_fd, const int verboseFlag,
  430. const unsigned long dereferenceFlag, const llist_t *include,
  431. const llist_t *exclude, const int gzip)
  432. {
  433. pid_t gzipPid = 0;
  434. int errorFlag = FALSE;
  435. struct TarBallInfo tbInfo;
  436. tbInfo.hlInfoHead = NULL;
  437. fchmod(tar_fd, 0644);
  438. tbInfo.tarFd = tar_fd;
  439. tbInfo.verboseFlag = verboseFlag;
  440. /* Store the stat info for the tarball's file, so
  441. * can avoid including the tarball into itself.... */
  442. if (fstat(tbInfo.tarFd, &tbInfo.statBuf) < 0)
  443. bb_perror_msg_and_die("cannot stat tar file");
  444. if ((ENABLE_FEATURE_TAR_GZIP || ENABLE_FEATURE_TAR_BZIP2) && gzip) {
  445. int gzipDataPipe[2] = { -1, -1 };
  446. int gzipStatusPipe[2] = { -1, -1 };
  447. volatile int vfork_exec_errno = 0;
  448. const char *zip_exec = (gzip == 1) ? "gzip" : "bzip2";
  449. xpipe(gzipDataPipe);
  450. xpipe(gzipStatusPipe);
  451. signal(SIGPIPE, SIG_IGN); /* we only want EPIPE on errors */
  452. #if defined(__GNUC__) && __GNUC__
  453. /* Avoid vfork clobbering */
  454. (void) &include;
  455. (void) &errorFlag;
  456. (void) &zip_exec;
  457. #endif
  458. gzipPid = vfork();
  459. if (gzipPid == 0) {
  460. dup2(gzipDataPipe[0], 0);
  461. close(gzipDataPipe[1]);
  462. dup2(tbInfo.tarFd, 1);
  463. close(gzipStatusPipe[0]);
  464. fcntl(gzipStatusPipe[1], F_SETFD, FD_CLOEXEC); /* close on exec shows success */
  465. BB_EXECLP(zip_exec, zip_exec, "-f", NULL);
  466. vfork_exec_errno = errno;
  467. close(gzipStatusPipe[1]);
  468. exit(-1);
  469. } else if (gzipPid > 0) {
  470. close(gzipDataPipe[0]);
  471. close(gzipStatusPipe[1]);
  472. while (1) {
  473. char buf;
  474. int n = full_read(gzipStatusPipe[0], &buf, 1);
  475. if (n == 0 && vfork_exec_errno != 0) {
  476. errno = vfork_exec_errno;
  477. bb_perror_msg_and_die("cannot exec %s", zip_exec);
  478. } else if ((n < 0) && (errno == EAGAIN || errno == EINTR))
  479. continue; /* try it again */
  480. break;
  481. }
  482. close(gzipStatusPipe[0]);
  483. tbInfo.tarFd = gzipDataPipe[1];
  484. } else bb_perror_msg_and_die("vfork gzip");
  485. }
  486. tbInfo.excludeList = exclude;
  487. /* Read the directory/files and iterate over them one at a time */
  488. while (include) {
  489. if (!recursive_action(include->data, ACTION_RECURSE |
  490. (dereferenceFlag ? ACTION_FOLLOWLINKS : 0),
  491. writeFileToTarball, writeFileToTarball, &tbInfo, 0))
  492. {
  493. errorFlag = TRUE;
  494. }
  495. include = include->link;
  496. }
  497. /* Write two empty blocks to the end of the archive */
  498. memset(block_buf, 0, 2*TAR_BLOCK_SIZE);
  499. xwrite(tbInfo.tarFd, block_buf, 2*TAR_BLOCK_SIZE);
  500. /* To be pedantically correct, we would check if the tarball
  501. * is smaller than 20 tar blocks, and pad it if it was smaller,
  502. * but that isn't necessary for GNU tar interoperability, and
  503. * so is considered a waste of space */
  504. /* Close so the child process (if any) will exit */
  505. close(tbInfo.tarFd);
  506. /* Hang up the tools, close up shop, head home */
  507. if (ENABLE_FEATURE_CLEAN_UP)
  508. freeHardLinkInfo(&tbInfo.hlInfoHead);
  509. if (errorFlag)
  510. bb_error_msg("error exit delayed from previous errors");
  511. if (gzipPid) {
  512. int status;
  513. if (waitpid(gzipPid, &status, 0) == -1)
  514. bb_perror_msg("waitpid");
  515. else if (!WIFEXITED(status) || WEXITSTATUS(status))
  516. /* gzip was killed or has exited with nonzero! */
  517. errorFlag = TRUE;
  518. }
  519. return errorFlag;
  520. }
  521. #else
  522. int writeTarFile(const int tar_fd, const int verboseFlag,
  523. const unsigned long dereferenceFlag, const llist_t *include,
  524. const llist_t *exclude, const int gzip);
  525. #endif /* FEATURE_TAR_CREATE */
  526. #if ENABLE_FEATURE_TAR_FROM
  527. static llist_t *append_file_list_to_list(llist_t *list)
  528. {
  529. FILE *src_stream;
  530. llist_t *cur = list;
  531. llist_t *tmp;
  532. char *line;
  533. llist_t *newlist = NULL;
  534. while (cur) {
  535. src_stream = xfopen(cur->data, "r");
  536. tmp = cur;
  537. cur = cur->link;
  538. free(tmp);
  539. while ((line = xmalloc_getline(src_stream)) != NULL) {
  540. /* kill trailing '/' unless the string is just "/" */
  541. char *cp = last_char_is(line, '/');
  542. if (cp > line)
  543. *cp = '\0';
  544. llist_add_to(&newlist, line);
  545. }
  546. fclose(src_stream);
  547. }
  548. return newlist;
  549. }
  550. #else
  551. #define append_file_list_to_list(x) 0
  552. #endif
  553. #if ENABLE_FEATURE_TAR_COMPRESS
  554. static char get_header_tar_Z(archive_handle_t *archive_handle)
  555. {
  556. /* Can't lseek over pipes */
  557. archive_handle->seek = seek_by_read;
  558. /* do the decompression, and cleanup */
  559. if (xread_char(archive_handle->src_fd) != 0x1f
  560. || xread_char(archive_handle->src_fd) != 0x9d
  561. ) {
  562. bb_error_msg_and_die("invalid magic");
  563. }
  564. archive_handle->src_fd = open_transformer(archive_handle->src_fd, uncompress, "uncompress", "uncompress", "-cf", "-", NULL);
  565. archive_handle->offset = 0;
  566. while (get_header_tar(archive_handle) == EXIT_SUCCESS)
  567. /* nothing */;
  568. /* Can only do one file at a time */
  569. return EXIT_FAILURE;
  570. }
  571. #else
  572. #define get_header_tar_Z NULL
  573. #endif
  574. #ifdef CHECK_FOR_CHILD_EXITCODE
  575. /* Looks like it isn't needed - tar detects malformed (truncated)
  576. * archive if e.g. bunzip2 fails */
  577. static int child_error;
  578. static void handle_SIGCHLD(int status)
  579. {
  580. /* Actually, 'status' is a signo. We reuse it for other needs */
  581. /* Wait for any child without blocking */
  582. if (waitpid(-1, &status, WNOHANG) < 0)
  583. /* wait failed?! I'm confused... */
  584. return;
  585. if (WIFEXITED(status) && WEXITSTATUS(status)==0)
  586. /* child exited with 0 */
  587. return;
  588. /* Cannot happen?
  589. if (!WIFSIGNALED(status) && !WIFEXITED(status)) return; */
  590. child_error = 1;
  591. }
  592. #endif
  593. enum {
  594. OPTBIT_KEEP_OLD = 7,
  595. USE_FEATURE_TAR_CREATE( OPTBIT_CREATE ,)
  596. USE_FEATURE_TAR_CREATE( OPTBIT_DEREFERENCE ,)
  597. USE_FEATURE_TAR_BZIP2( OPTBIT_BZIP2 ,)
  598. USE_FEATURE_TAR_LZMA( OPTBIT_LZMA ,)
  599. USE_FEATURE_TAR_FROM( OPTBIT_INCLUDE_FROM,)
  600. USE_FEATURE_TAR_FROM( OPTBIT_EXCLUDE_FROM,)
  601. USE_FEATURE_TAR_GZIP( OPTBIT_GZIP ,)
  602. USE_FEATURE_TAR_COMPRESS(OPTBIT_COMPRESS ,)
  603. OPTBIT_NOPRESERVE_OWN,
  604. OPTBIT_NOPRESERVE_PERM,
  605. OPT_TEST = 1 << 0, // t
  606. OPT_EXTRACT = 1 << 1, // x
  607. OPT_BASEDIR = 1 << 2, // C
  608. OPT_TARNAME = 1 << 3, // f
  609. OPT_2STDOUT = 1 << 4, // O
  610. OPT_P = 1 << 5, // p
  611. OPT_VERBOSE = 1 << 6, // v
  612. OPT_KEEP_OLD = 1 << 7, // k
  613. OPT_CREATE = USE_FEATURE_TAR_CREATE( (1<<OPTBIT_CREATE )) + 0, // c
  614. OPT_DEREFERENCE = USE_FEATURE_TAR_CREATE( (1<<OPTBIT_DEREFERENCE )) + 0, // h
  615. OPT_BZIP2 = USE_FEATURE_TAR_BZIP2( (1<<OPTBIT_BZIP2 )) + 0, // j
  616. OPT_LZMA = USE_FEATURE_TAR_LZMA( (1<<OPTBIT_LZMA )) + 0, // a
  617. OPT_INCLUDE_FROM = USE_FEATURE_TAR_FROM( (1<<OPTBIT_INCLUDE_FROM)) + 0, // T
  618. OPT_EXCLUDE_FROM = USE_FEATURE_TAR_FROM( (1<<OPTBIT_EXCLUDE_FROM)) + 0, // X
  619. OPT_GZIP = USE_FEATURE_TAR_GZIP( (1<<OPTBIT_GZIP )) + 0, // z
  620. OPT_COMPRESS = USE_FEATURE_TAR_COMPRESS((1<<OPTBIT_COMPRESS )) + 0, // Z
  621. OPT_NOPRESERVE_OWN = 1 << OPTBIT_NOPRESERVE_OWN , // no-same-owner
  622. OPT_NOPRESERVE_PERM = 1 << OPTBIT_NOPRESERVE_PERM, // no-same-permissions
  623. };
  624. #if ENABLE_FEATURE_TAR_LONG_OPTIONS
  625. static const char tar_longopts[] ALIGN1 =
  626. "list\0" No_argument "t"
  627. "extract\0" No_argument "x"
  628. "directory\0" Required_argument "C"
  629. "file\0" Required_argument "f"
  630. "to-stdout\0" No_argument "O"
  631. "same-permissions\0" No_argument "p"
  632. "verbose\0" No_argument "v"
  633. "keep-old\0" No_argument "k"
  634. # if ENABLE_FEATURE_TAR_CREATE
  635. "create\0" No_argument "c"
  636. "dereference\0" No_argument "h"
  637. # endif
  638. # if ENABLE_FEATURE_TAR_BZIP2
  639. "bzip2\0" No_argument "j"
  640. # endif
  641. # if ENABLE_FEATURE_TAR_LZMA
  642. "lzma\0" No_argument "a"
  643. # endif
  644. # if ENABLE_FEATURE_TAR_FROM
  645. "files-from\0" Required_argument "T"
  646. "exclude-from\0" Required_argument "X"
  647. # endif
  648. # if ENABLE_FEATURE_TAR_GZIP
  649. "gzip\0" No_argument "z"
  650. # endif
  651. # if ENABLE_FEATURE_TAR_COMPRESS
  652. "compress\0" No_argument "Z"
  653. # endif
  654. "no-same-owner\0" No_argument "\xfd"
  655. "no-same-permissions\0" No_argument "\xfe"
  656. /* --exclude takes next bit position in option mask, */
  657. /* therefore we have to either put it _after_ --no-same-perm */
  658. /* or add OPT[BIT]_EXCLUDE before OPT[BIT]_NOPRESERVE_OWN */
  659. # if ENABLE_FEATURE_TAR_FROM
  660. "exclude\0" Required_argument "\xff"
  661. # endif
  662. ;
  663. #endif
  664. int tar_main(int argc, char **argv);
  665. int tar_main(int argc, char **argv)
  666. {
  667. char (*get_header_ptr)(archive_handle_t *) = get_header_tar;
  668. archive_handle_t *tar_handle;
  669. char *base_dir = NULL;
  670. const char *tar_filename = "-";
  671. unsigned opt;
  672. int verboseFlag = 0;
  673. #if ENABLE_FEATURE_TAR_LONG_OPTIONS && ENABLE_FEATURE_TAR_FROM
  674. llist_t *excludes = NULL;
  675. #endif
  676. /* Initialise default values */
  677. tar_handle = init_handle();
  678. tar_handle->flags = ARCHIVE_CREATE_LEADING_DIRS
  679. | ARCHIVE_PRESERVE_DATE
  680. | ARCHIVE_EXTRACT_UNCONDITIONAL;
  681. /* Prepend '-' to the first argument if required */
  682. opt_complementary = "--:" // first arg is options
  683. "tt:vv:" // count -t,-v
  684. "?:" // bail out with usage instead of error return
  685. "X::T::" // cumulative lists
  686. #if ENABLE_FEATURE_TAR_LONG_OPTIONS && ENABLE_FEATURE_TAR_FROM
  687. "\xff::" // cumulative lists for --exclude
  688. #endif
  689. USE_FEATURE_TAR_CREATE("c:") "t:x:" // at least one of these is reqd
  690. USE_FEATURE_TAR_CREATE("c--tx:t--cx:x--ct") // mutually exclusive
  691. SKIP_FEATURE_TAR_CREATE("t--x:x--t"); // mutually exclusive
  692. #if ENABLE_FEATURE_TAR_LONG_OPTIONS
  693. applet_long_options = tar_longopts;
  694. #endif
  695. opt = getopt32(argv,
  696. "txC:f:Opvk"
  697. USE_FEATURE_TAR_CREATE( "ch" )
  698. USE_FEATURE_TAR_BZIP2( "j" )
  699. USE_FEATURE_TAR_LZMA( "a" )
  700. USE_FEATURE_TAR_FROM( "T:X:")
  701. USE_FEATURE_TAR_GZIP( "z" )
  702. USE_FEATURE_TAR_COMPRESS("Z" )
  703. , &base_dir // -C dir
  704. , &tar_filename // -f filename
  705. USE_FEATURE_TAR_FROM(, &(tar_handle->accept)) // T
  706. USE_FEATURE_TAR_FROM(, &(tar_handle->reject)) // X
  707. #if ENABLE_FEATURE_TAR_LONG_OPTIONS && ENABLE_FEATURE_TAR_FROM
  708. , &excludes // --exclude
  709. #endif
  710. , &verboseFlag // combined count for -t and -v
  711. , &verboseFlag // combined count for -t and -v
  712. );
  713. if (verboseFlag) tar_handle->action_header = header_verbose_list;
  714. if (verboseFlag == 1) tar_handle->action_header = header_list;
  715. if (opt & OPT_EXTRACT)
  716. tar_handle->action_data = data_extract_all;
  717. if (opt & OPT_2STDOUT)
  718. tar_handle->action_data = data_extract_to_stdout;
  719. if (opt & OPT_KEEP_OLD)
  720. tar_handle->flags &= ~ARCHIVE_EXTRACT_UNCONDITIONAL;
  721. if (opt & OPT_NOPRESERVE_OWN)
  722. tar_handle->flags |= ARCHIVE_NOPRESERVE_OWN;
  723. if (opt & OPT_NOPRESERVE_PERM)
  724. tar_handle->flags |= ARCHIVE_NOPRESERVE_PERM;
  725. if (opt & OPT_GZIP)
  726. get_header_ptr = get_header_tar_gz;
  727. if (opt & OPT_BZIP2)
  728. get_header_ptr = get_header_tar_bz2;
  729. if (opt & OPT_LZMA)
  730. get_header_ptr = get_header_tar_lzma;
  731. if (opt & OPT_COMPRESS)
  732. get_header_ptr = get_header_tar_Z;
  733. #if ENABLE_FEATURE_TAR_FROM
  734. tar_handle->reject = append_file_list_to_list(tar_handle->reject);
  735. #if ENABLE_FEATURE_TAR_LONG_OPTIONS
  736. /* Append excludes to reject */
  737. while (excludes) {
  738. llist_t *next = excludes->link;
  739. excludes->link = tar_handle->reject;
  740. tar_handle->reject = excludes;
  741. excludes = next;
  742. }
  743. #endif
  744. tar_handle->accept = append_file_list_to_list(tar_handle->accept);
  745. #endif
  746. /* Check if we are reading from stdin */
  747. if (argv[optind] && *argv[optind] == '-') {
  748. /* Default is to read from stdin, so just skip to next arg */
  749. optind++;
  750. }
  751. /* Setup an array of filenames to work with */
  752. /* TODO: This is the same as in ar, separate function ? */
  753. while (optind < argc) {
  754. /* kill trailing '/' unless the string is just "/" */
  755. char *cp = last_char_is(argv[optind], '/');
  756. if (cp > argv[optind])
  757. *cp = '\0';
  758. llist_add_to_end(&tar_handle->accept, argv[optind]);
  759. optind++;
  760. }
  761. if (tar_handle->accept || tar_handle->reject)
  762. tar_handle->filter = filter_accept_reject_list;
  763. /* Open the tar file */
  764. {
  765. FILE *tar_stream;
  766. int flags;
  767. if (opt & OPT_CREATE) {
  768. /* Make sure there is at least one file to tar up. */
  769. if (tar_handle->accept == NULL)
  770. bb_error_msg_and_die("empty archive");
  771. tar_stream = stdout;
  772. /* Mimicking GNU tar 1.15.1: */
  773. flags = O_WRONLY|O_CREAT|O_TRUNC;
  774. /* was doing unlink; open(O_WRONLY|O_CREAT|O_EXCL); why? */
  775. } else {
  776. tar_stream = stdin;
  777. flags = O_RDONLY;
  778. }
  779. if (LONE_DASH(tar_filename)) {
  780. tar_handle->src_fd = fileno(tar_stream);
  781. tar_handle->seek = seek_by_read;
  782. } else {
  783. tar_handle->src_fd = xopen(tar_filename, flags);
  784. }
  785. }
  786. if (base_dir)
  787. xchdir(base_dir);
  788. #ifdef CHECK_FOR_CHILD_EXITCODE
  789. /* We need to know whether child (gzip/bzip/etc) exits abnormally */
  790. signal(SIGCHLD, handle_SIGCHLD);
  791. #endif
  792. /* create an archive */
  793. if (opt & OPT_CREATE) {
  794. int zipMode = 0;
  795. if (ENABLE_FEATURE_TAR_GZIP && get_header_ptr == get_header_tar_gz)
  796. zipMode = 1;
  797. if (ENABLE_FEATURE_TAR_BZIP2 && get_header_ptr == get_header_tar_bz2)
  798. zipMode = 2;
  799. /* NB: writeTarFile() closes tar_handle->src_fd */
  800. return writeTarFile(tar_handle->src_fd, verboseFlag, opt & OPT_DEREFERENCE,
  801. tar_handle->accept,
  802. tar_handle->reject, zipMode);
  803. }
  804. while (get_header_ptr(tar_handle) == EXIT_SUCCESS)
  805. /* nothing */;
  806. /* Check that every file that should have been extracted was */
  807. while (tar_handle->accept) {
  808. if (!find_list_entry(tar_handle->reject, tar_handle->accept->data)
  809. && !find_list_entry(tar_handle->passed, tar_handle->accept->data)
  810. ) {
  811. bb_error_msg_and_die("%s: not found in archive",
  812. tar_handle->accept->data);
  813. }
  814. tar_handle->accept = tar_handle->accept->link;
  815. }
  816. if (ENABLE_FEATURE_CLEAN_UP /* && tar_handle->src_fd != STDIN_FILENO */)
  817. close(tar_handle->src_fd);
  818. return EXIT_SUCCESS;
  819. }