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