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