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