tar.c 30 KB

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