tar.c 41 KB

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