b68882b520b7a1122d3b219e5a160232670642f9
[oweals/busybox.git] / archival / tar.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * Mini tar implementation for busybox 
4  *
5  * Modifed to use common extraction code used by ar, cpio, dpkg-deb, dpkg
6  *  Glenn McGrath <bug1@optushome.com.au>
7  *
8  * Note, that as of BusyBox-0.43, tar has been completely rewritten from the
9  * ground up.  It still has remnents 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,2000 by Lineo, inc. and Erik Andersen
13  * Copyright (C) 1999-2002 by Erik Andersen <andersee@debian.org>
14  *
15  * Based in part in the tar implementation in sash
16  *  Copyright (c) 1999 by David I. Bell
17  *  Permission is granted to use, distribute, or modify this source,
18  *  provided that this copyright notice remains intact.
19  *  Permission to distribute sash derived code under the GPL has been granted.
20  *
21  * Based in part on the tar implementation from busybox-0.28
22  *  Copyright (C) 1995 Bruce Perens
23  *  This is free software under the GNU General Public License.
24  *
25  * This program is free software; you can redistribute it and/or modify
26  * it under the terms of the GNU General Public License as published by
27  * the Free Software Foundation; either version 2 of the License, or
28  * (at your option) any later version.
29  *
30  * This program is distributed in the hope that it will be useful,
31  * but WITHOUT ANY WARRANTY; without even the implied warranty of
32  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
33  * General Public License for more details.
34  *
35  * You should have received a copy of the GNU General Public License
36  * along with this program; if not, write to the Free Software
37  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
38  *
39  */
40
41 #include <fcntl.h>
42 #include <getopt.h>
43 #include <search.h>
44 #include <stdio.h>
45 #include <stdlib.h>
46 #include <unistd.h>
47 #include <fnmatch.h>
48 #include <string.h>
49 #include <errno.h>
50 #include <signal.h>
51 #include <sys/wait.h>
52 #include <sys/socket.h>
53 #include "unarchive.h"
54 #include "busybox.h"
55
56 #ifdef CONFIG_FEATURE_TAR_CREATE
57
58 /* Tar file constants  */
59 # define TAR_MAGIC          "ustar"        /* ustar and a null */
60 # define TAR_VERSION        "  "           /* Be compatable with GNU tar format */
61
62 # ifndef MAJOR
63 #  define MAJOR(dev) (((dev)>>8)&0xff)
64 #  define MINOR(dev) ((dev)&0xff)
65 # endif
66
67 static const int TAR_BLOCK_SIZE = 512;
68 static const int TAR_MAGIC_LEN = 6;
69 static const int TAR_VERSION_LEN = 2;
70
71 /* POSIX tar Header Block, from POSIX 1003.1-1990  */
72 enum { NAME_SIZE = 100 }; /* because gcc won't let me use 'static const int' */
73 struct TarHeader
74 {                            /* byte offset */
75         char name[NAME_SIZE];         /*   0-99 */
76         char mode[8];                 /* 100-107 */
77         char uid[8];                  /* 108-115 */
78         char gid[8];                  /* 116-123 */
79         char size[12];                /* 124-135 */
80         char mtime[12];               /* 136-147 */
81         char chksum[8];               /* 148-155 */
82         char typeflag;                /* 156-156 */
83         char linkname[NAME_SIZE];     /* 157-256 */
84         char magic[6];                /* 257-262 */
85         char version[2];              /* 263-264 */
86         char uname[32];               /* 265-296 */
87         char gname[32];               /* 297-328 */
88         char devmajor[8];             /* 329-336 */
89         char devminor[8];             /* 337-344 */
90         char prefix[155];             /* 345-499 */
91         char padding[12];             /* 500-512 (pad to exactly the TAR_BLOCK_SIZE) */
92 };
93 typedef struct TarHeader TarHeader;
94
95 /*
96 ** writeTarFile(),  writeFileToTarball(), and writeTarHeader() are
97 ** the only functions that deal with the HardLinkInfo structure.
98 ** Even these functions use the xxxHardLinkInfo() functions.
99 */
100 typedef struct HardLinkInfo HardLinkInfo;
101 struct HardLinkInfo
102 {
103         HardLinkInfo *next;           /* Next entry in list */
104         dev_t dev;                    /* Device number */
105         ino_t ino;                    /* Inode number */
106         short linkCount;              /* (Hard) Link Count */
107         char name[1];                 /* Start of filename (must be last) */
108 };
109
110 /* Some info to be carried along when creating a new tarball */
111 struct TarBallInfo
112 {
113         char* fileName;               /* File name of the tarball */
114         int tarFd;                    /* Open-for-write file descriptor
115                                                                          for the tarball */
116         struct stat statBuf;          /* Stat info for the tarball, letting
117                                                                          us know the inode and device that the
118                                                                          tarball lives, so we can avoid trying 
119                                                                          to include the tarball into itself */
120         int verboseFlag;              /* Whether to print extra stuff or not */
121         char** excludeList;           /* List of files to not include */
122         HardLinkInfo *hlInfoHead;     /* Hard Link Tracking Information */
123         HardLinkInfo *hlInfo;         /* Hard Link Info for the current file */
124 };
125 typedef struct TarBallInfo TarBallInfo;
126
127 /* A nice enum with all the possible tar file content types */
128 enum TarFileType 
129 {
130         REGTYPE  = '0',            /* regular file */
131         REGTYPE0 = '\0',           /* regular file (ancient bug compat)*/
132         LNKTYPE  = '1',            /* hard link */
133         SYMTYPE  = '2',            /* symbolic link */
134         CHRTYPE  = '3',            /* character special */
135         BLKTYPE  = '4',            /* block special */
136         DIRTYPE  = '5',            /* directory */
137         FIFOTYPE = '6',            /* FIFO special */
138         CONTTYPE = '7',            /* reserved */
139         GNULONGLINK = 'K',         /* GNU long (>100 chars) link name */
140         GNULONGNAME = 'L',         /* GNU long (>100 chars) file name */
141 };
142 typedef enum TarFileType TarFileType;
143
144 /* Might be faster (and bigger) if the dev/ino were stored in numeric order;) */
145 extern inline void
146 addHardLinkInfo (HardLinkInfo **hlInfoHeadPtr, dev_t dev, ino_t ino,
147                 short linkCount, const char *name)
148 {
149         /* Note: hlInfoHeadPtr can never be NULL! */
150         HardLinkInfo *hlInfo;
151
152         hlInfo = (HardLinkInfo *)xmalloc(sizeof(HardLinkInfo)+strlen(name)+1);
153         if (hlInfo) {
154                 hlInfo->next = *hlInfoHeadPtr;
155                 *hlInfoHeadPtr = hlInfo;
156                 hlInfo->dev = dev;
157                 hlInfo->ino = ino;
158                 hlInfo->linkCount = linkCount;
159                 strcpy(hlInfo->name, name);
160         }
161         return;
162 }
163
164 static void
165 freeHardLinkInfo (HardLinkInfo **hlInfoHeadPtr)
166 {
167         HardLinkInfo *hlInfo = NULL;
168         HardLinkInfo *hlInfoNext = NULL;
169
170         if (hlInfoHeadPtr) {
171                 hlInfo = *hlInfoHeadPtr;
172                 while (hlInfo) {
173                         hlInfoNext = hlInfo->next;
174                         free(hlInfo);
175                         hlInfo = hlInfoNext;
176                 }
177                 *hlInfoHeadPtr = NULL;
178         }
179         return;
180 }
181
182 /* Might be faster (and bigger) if the dev/ino were stored in numeric order;) */
183 extern inline HardLinkInfo *
184 findHardLinkInfo (HardLinkInfo *hlInfo, dev_t dev, ino_t ino)
185 {
186         while(hlInfo) {
187                 if ((ino == hlInfo->ino) && (dev == hlInfo->dev))
188                         break;
189                 hlInfo = hlInfo->next;
190         }
191         return(hlInfo);
192 }
193
194 /* Put an octal string into the specified buffer.
195  * The number is zero and space padded and possibly null padded.
196  * Returns TRUE if successful.  */ 
197 static int putOctal (char *cp, int len, long value)
198 {
199         int tempLength;
200         char tempBuffer[32];
201         char *tempString = tempBuffer;
202
203         /* Create a string of the specified length with an initial space,
204          * leading zeroes and the octal number, and a trailing null.  */
205         sprintf (tempString, "%0*lo", len - 1, value);
206
207         /* If the string is too large, suppress the leading space.  */
208         tempLength = strlen (tempString) + 1;
209         if (tempLength > len) {
210                 tempLength--;
211                 tempString++;
212         }
213
214         /* If the string is still too large, suppress the trailing null.  */
215         if (tempLength > len)
216                 tempLength--;
217
218         /* If the string is still too large, fail.  */
219         if (tempLength > len)
220                 return FALSE;
221
222         /* Copy the string to the field.  */
223         memcpy (cp, tempString, len);
224
225         return TRUE;
226 }
227
228 /* Write out a tar header for the specified file/directory/whatever */
229 extern inline int
230 writeTarHeader(struct TarBallInfo *tbInfo, const char *header_name,
231                 const char *real_name, struct stat *statbuf)
232 {
233         long chksum=0;
234         struct TarHeader header;
235         const unsigned char *cp = (const unsigned char *) &header;
236         ssize_t size = sizeof(struct TarHeader);
237                 
238         memset( &header, 0, size);
239
240         strncpy(header.name, header_name, sizeof(header.name)); 
241
242         putOctal(header.mode, sizeof(header.mode), statbuf->st_mode);
243         putOctal(header.uid, sizeof(header.uid), statbuf->st_uid);
244         putOctal(header.gid, sizeof(header.gid), statbuf->st_gid);
245         putOctal(header.size, sizeof(header.size), 0); /* Regular file size is handled later */
246         putOctal(header.mtime, sizeof(header.mtime), statbuf->st_mtime);
247         strncpy(header.magic, TAR_MAGIC TAR_VERSION, 
248                         TAR_MAGIC_LEN + TAR_VERSION_LEN );
249
250         /* Enter the user and group names (default to root if it fails) */
251         my_getpwuid(header.uname, statbuf->st_uid);
252         if (! *header.uname)
253                 strcpy(header.uname, "root");
254         my_getgrgid(header.gname, statbuf->st_gid);
255         if (! *header.uname)
256                 strcpy(header.uname, "root");
257
258         if (tbInfo->hlInfo) {
259                 /* This is a hard link */
260                 header.typeflag = LNKTYPE;
261                 strncpy(header.linkname, tbInfo->hlInfo->name, sizeof(header.linkname));
262         } else if (S_ISLNK(statbuf->st_mode)) {
263                 char *lpath = xreadlink(real_name);
264                 if (!lpath) /* Already printed err msg inside xreadlink() */
265                         return ( FALSE);
266                 header.typeflag  = SYMTYPE;
267                 strncpy(header.linkname, lpath, sizeof(header.linkname)); 
268                 free(lpath);
269         } else if (S_ISDIR(statbuf->st_mode)) {
270                 header.typeflag  = DIRTYPE;
271                 strncat(header.name, "/", sizeof(header.name)); 
272         } else if (S_ISCHR(statbuf->st_mode)) {
273                 header.typeflag  = CHRTYPE;
274                 putOctal(header.devmajor, sizeof(header.devmajor), MAJOR(statbuf->st_rdev));
275                 putOctal(header.devminor, sizeof(header.devminor), MINOR(statbuf->st_rdev));
276         } else if (S_ISBLK(statbuf->st_mode)) {
277                 header.typeflag  = BLKTYPE;
278                 putOctal(header.devmajor, sizeof(header.devmajor), MAJOR(statbuf->st_rdev));
279                 putOctal(header.devminor, sizeof(header.devminor), MINOR(statbuf->st_rdev));
280         } else if (S_ISFIFO(statbuf->st_mode)) {
281                 header.typeflag  = FIFOTYPE;
282         } else if (S_ISREG(statbuf->st_mode)) {
283                 header.typeflag  = REGTYPE;
284                 putOctal(header.size, sizeof(header.size), statbuf->st_size);
285         } else {
286                 error_msg("%s: Unknown file type", real_name);
287                 return ( FALSE);
288         }
289
290         /* Calculate and store the checksum (i.e., the sum of all of the bytes of
291          * the header).  The checksum field must be filled with blanks for the
292          * calculation.  The checksum field is formatted differently from the
293          * other fields: it has [6] digits, a null, then a space -- rather than
294          * digits, followed by a null like the other fields... */
295         memset(header.chksum, ' ', sizeof(header.chksum));
296         cp = (const unsigned char *) &header;
297         while (size-- > 0)
298                 chksum += *cp++;
299         putOctal(header.chksum, 7, chksum);
300         
301         /* Now write the header out to disk */
302         if ((size=full_write(tbInfo->tarFd, (char*)&header, sizeof(struct TarHeader))) < 0) {
303                 error_msg(io_error, real_name, strerror(errno)); 
304                 return ( FALSE);
305         }
306         /* Pad the header up to the tar block size */
307         for (; size<TAR_BLOCK_SIZE; size++) {
308                 write(tbInfo->tarFd, "\0", 1);
309         }
310         /* Now do the verbose thing (or not) */
311         
312         if (tbInfo->verboseFlag) {
313                 FILE *vbFd = stdout;
314                 if (tbInfo->verboseFlag == 2)   // If the archive goes to stdout, verbose to stderr
315                         vbFd = stderr;
316                 fprintf(vbFd, "%s\n", header.name);
317         }
318
319         return ( TRUE);
320 }
321
322 # if defined CONFIG_FEATURE_TAR_EXCLUDE
323 extern inline int exclude_file(char **excluded_files, const char *file)
324 {
325         int i;
326
327         if (excluded_files == NULL)
328                 return 0;
329
330         for (i = 0; excluded_files[i] != NULL; i++) {
331                 if (excluded_files[i][0] == '/') {
332                         if (fnmatch(excluded_files[i], file,
333                                                 FNM_PATHNAME | FNM_LEADING_DIR) == 0)
334                                 return 1;
335                 } else {
336                         const char *p;
337
338                         for (p = file; p[0] != '\0'; p++) {
339                                 if ((p == file || p[-1] == '/') && p[0] != '/' &&
340                                                 fnmatch(excluded_files[i], p,
341                                                         FNM_PATHNAME | FNM_LEADING_DIR) == 0)
342                                         return 1;
343                         }
344                 }
345         }
346
347         return 0;
348 }
349 #endif
350
351 static int writeFileToTarball(const char *fileName, struct stat *statbuf, void* userData)
352 {
353         struct TarBallInfo *tbInfo = (struct TarBallInfo *)userData;
354         const char *header_name;
355
356         /*
357         ** Check to see if we are dealing with a hard link.
358         ** If so -
359         ** Treat the first occurance of a given dev/inode as a file while
360         ** treating any additional occurances as hard links.  This is done
361         ** by adding the file information to the HardLinkInfo linked list.
362         */
363         tbInfo->hlInfo = NULL;
364         if (statbuf->st_nlink > 1) {
365                 tbInfo->hlInfo = findHardLinkInfo(tbInfo->hlInfoHead, statbuf->st_dev, 
366                                 statbuf->st_ino);
367                 if (tbInfo->hlInfo == NULL)
368                         addHardLinkInfo (&tbInfo->hlInfoHead, statbuf->st_dev,
369                                         statbuf->st_ino, statbuf->st_nlink, fileName);
370         }
371
372         /* It is against the rules to archive a socket */
373         if (S_ISSOCK(statbuf->st_mode)) {
374                 error_msg("%s: socket ignored", fileName);
375                 return( TRUE);
376         }
377
378         /* It is a bad idea to store the archive we are in the process of creating,
379          * so check the device and inode to be sure that this particular file isn't
380          * the new tarball */
381         if (tbInfo->statBuf.st_dev == statbuf->st_dev &&
382                         tbInfo->statBuf.st_ino == statbuf->st_ino) {
383                 error_msg("%s: file is the archive; skipping", fileName);
384                 return( TRUE);
385         }
386
387         header_name = fileName;
388         while (header_name[0] == '/') {
389                 static int alreadyWarned=FALSE;
390                 if (alreadyWarned==FALSE) {
391                         error_msg("Removing leading '/' from member names");
392                         alreadyWarned=TRUE;
393                 }
394                 header_name++;
395         }
396
397         if (strlen(fileName) >= NAME_SIZE) {
398                 error_msg(name_longer_than_foo, NAME_SIZE);
399                 return ( TRUE);
400         }
401
402         if (header_name[0] == '\0')
403                 return TRUE;
404
405 # if defined CONFIG_FEATURE_TAR_EXCLUDE
406         if (exclude_file(tbInfo->excludeList, header_name)) {
407                 return SKIP;
408         }
409 # endif //CONFIG_FEATURE_TAR_EXCLUDE
410
411         if (writeTarHeader(tbInfo, header_name, fileName, statbuf)==FALSE) {
412                 return( FALSE);
413         } 
414
415         /* Now, if the file is a regular file, copy it out to the tarball */
416         if ((tbInfo->hlInfo == NULL)
417         &&  (S_ISREG(statbuf->st_mode))) {
418                 int  inputFileFd;
419                 char buffer[BUFSIZ];
420                 ssize_t size=0, readSize=0;
421
422                 /* open the file we want to archive, and make sure all is well */
423                 if ((inputFileFd = open(fileName, O_RDONLY)) < 0) {
424                         error_msg("%s: Cannot open: %s", fileName, strerror(errno));
425                         return( FALSE);
426                 }
427                 
428                 /* write the file to the archive */
429                 while ( (size = full_read(inputFileFd, buffer, sizeof(buffer))) > 0 ) {
430                         if (full_write(tbInfo->tarFd, buffer, size) != size ) {
431                                 /* Output file seems to have a problem */
432                                 error_msg(io_error, fileName, strerror(errno)); 
433                                 return( FALSE);
434                         }
435                         readSize+=size;
436                 }
437                 if (size == -1) {
438                         error_msg(io_error, fileName, strerror(errno)); 
439                         return( FALSE);
440                 }
441                 /* Pad the file up to the tar block size */
442                 for (; (readSize%TAR_BLOCK_SIZE) != 0; readSize++) {
443                         write(tbInfo->tarFd, "\0", 1);
444                 }
445                 close( inputFileFd);
446         }
447
448         return( TRUE);
449 }
450
451 extern inline int writeTarFile(const char* tarName, int verboseFlag, char **argv,
452                 char** excludeList, int gzip)
453 {
454 #ifdef CONFIG_FEATURE_TAR_GZIP
455         int gzipDataPipe [2] = { -1, -1 };
456         int gzipStatusPipe [2] = { -1, -1 };
457         pid_t gzipPid = 0;
458 #endif
459         
460         int errorFlag=FALSE;
461         ssize_t size;
462         struct TarBallInfo tbInfo;
463         tbInfo.hlInfoHead = NULL;
464
465         /* Make sure there is at least one file to tar up.  */
466         if (*argv == NULL)
467                 error_msg_and_die("Cowardly refusing to create an empty archive");
468
469         /* Open the tar file for writing.  */
470         if (tarName == NULL) {
471                 tbInfo.tarFd = fileno(stdout);
472                 tbInfo.verboseFlag = verboseFlag ? 2 : 0;
473         }
474         else {
475                 tbInfo.tarFd = open (tarName, O_WRONLY | O_CREAT | O_TRUNC, 0644);
476                 tbInfo.verboseFlag = verboseFlag ? 1 : 0;
477         }
478         
479         if (tbInfo.tarFd < 0) {
480                 perror_msg( "Error opening '%s'", tarName);
481                 freeHardLinkInfo(&tbInfo.hlInfoHead);
482                 return ( FALSE);
483         }
484
485         /* Store the stat info for the tarball's file, so
486          * can avoid including the tarball into itself....  */
487         if (fstat(tbInfo.tarFd, &tbInfo.statBuf) < 0)
488                 error_msg_and_die(io_error, tarName, strerror(errno)); 
489
490 #ifdef CONFIG_FEATURE_TAR_GZIP
491         if ( gzip ) {
492                 if ( socketpair ( AF_UNIX, SOCK_STREAM, 0, gzipDataPipe ) < 0 || pipe ( gzipStatusPipe ) < 0 )
493                         perror_msg_and_die ( "Failed to create gzip pipe" );
494         
495                 signal ( SIGPIPE, SIG_IGN ); // we only want EPIPE on errors
496         
497                 gzipPid = fork ( );
498                 
499                 if ( gzipPid == 0 ) {
500                         dup2 ( gzipDataPipe [0], 0 );
501                         close ( gzipDataPipe [1] );
502
503                         if ( tbInfo. tarFd != 1 );
504                                 dup2 ( tbInfo. tarFd, 1 );
505                         
506                         close ( gzipStatusPipe [0] );                   
507                         fcntl( gzipStatusPipe [1], F_SETFD, FD_CLOEXEC ); // close on exec shows sucess                 
508
509                         execl ( "/bin/gzip", "gzip", "-f", 0 );
510                                         
511                         write ( gzipStatusPipe [1], "", 1 );
512                         close ( gzipStatusPipe [1] );
513                         
514                         exit ( -1 );
515                 }
516                 else if ( gzipPid > 0 ) {
517                         close ( gzipDataPipe [0] );
518                         close ( gzipStatusPipe [1] );
519                         
520                         while ( 1 ) {
521                                 char buf;
522                         
523                             int n = read ( gzipStatusPipe [0], &buf, 1 );
524                             if ( n == 1 )
525                                         error_msg_and_die ( "Could not exec gzip process" );    // socket was not closed => error
526                             else if (( n < 0 ) && ( errno==EAGAIN || errno==EINTR )) 
527                                     continue;   // try it again
528                             break;
529                         }
530                         close ( gzipStatusPipe [0] );
531                         
532                         tbInfo. tarFd = gzipDataPipe [1];
533                 }
534                 else {
535                         perror_msg_and_die ( "Failed to fork gzip process" );
536                 }
537         }
538 #endif
539                 
540         tbInfo.excludeList=excludeList;
541         
542         /* Read the directory/files and iterate over them one at a time */
543         while (*argv != NULL) {
544                 if (! recursive_action(*argv++, TRUE, FALSE, FALSE,
545                                         writeFileToTarball, writeFileToTarball, 
546                                         (void*) &tbInfo)) {
547                         errorFlag = TRUE;
548                 }
549         }
550         /* Write two empty blocks to the end of the archive */
551         for (size=0; size<(2*TAR_BLOCK_SIZE); size++) {
552                 write(tbInfo.tarFd, "\0", 1);
553         }
554
555         /* To be pedantically correct, we would check if the tarball
556          * is smaller than 20 tar blocks, and pad it if it was smaller,
557          * but that isn't necessary for GNU tar interoperability, and
558          * so is considered a waste of space */
559
560         /* Hang up the tools, close up shop, head home */
561         close(tbInfo.tarFd);
562         if (errorFlag) 
563                 error_msg("Error exit delayed from previous errors");
564                 
565         freeHardLinkInfo(&tbInfo.hlInfoHead);
566
567 #ifdef CONFIG_FEATURE_TAR_GZIP  
568         if ( gzip && gzipPid ) {
569                 if ( waitpid ( gzipPid, NULL, 0 ) == -1 ) 
570                         printf ( "Couldnt wait ?" );
571         }
572 #endif
573         
574         return !errorFlag;
575 }
576 #endif //tar_create
577
578 void append_file_to_list(const char *new_name, char ***list, int *list_count)
579 {
580         *list = realloc(*list, sizeof(char *) * (*list_count + 2));
581         (*list)[*list_count] = xstrdup(new_name);
582         (*list_count)++;
583         (*list)[*list_count] = NULL;
584 }
585
586 void append_file_list_to_list(char *filename, char ***name_list, int *num_of_entries)
587 {
588         FILE *src_stream;
589         char *line;
590         
591         src_stream = xfopen(filename, "r");
592         while ((line = get_line_from_file(src_stream)) != NULL) {
593                 chomp (line);
594                 append_file_to_list(line, name_list, num_of_entries);
595                 free(line);
596         }
597         fclose(src_stream);
598 }
599
600 #ifdef CONFIG_FEATURE_TAR_EXCLUDE
601 /*
602  * Create a list of names that are in the include list AND NOT in the exclude lists
603  */
604 #if 0 /* this is unused */
605 char **list_and_not_list(char **include_list, char **exclude_list)
606 {
607         char **new_include_list = NULL;
608         int new_include_count = 0;
609         int include_count = 0;
610         int exclude_count;
611
612         if (include_list == NULL) {
613                 return(NULL);
614         }
615         
616         while (include_list[include_count] != NULL) {
617                 int found = FALSE;
618                 exclude_count = 0;
619                 while (exclude_list[exclude_count] != NULL) {
620                         if (strcmp(include_list[include_count], exclude_list[exclude_count]) == 0) {
621                                 found = TRUE;
622                                 break;
623                         }
624                         exclude_count++;
625                 }
626
627                 if (! found) {
628                         new_include_list = realloc(new_include_list, sizeof(char *) * (include_count + 2));
629                         new_include_list[new_include_count] = include_list[include_count];
630                         new_include_count++;
631                 } else {
632                         free(include_list[include_count]);
633                 }
634                 include_count++;
635         }
636         new_include_list[new_include_count] = NULL;
637         return(new_include_list);
638 }
639 #endif
640 #endif
641
642 int tar_main(int argc, char **argv)
643 {
644         enum untar_funct_e {
645                 /* This is optional */
646                 untar_unzip = 1,
647                 /* Require one and only one of these */
648                 untar_list = 2,
649                 untar_create = 4,
650                 untar_extract = 8
651         };
652
653         FILE *src_stream = NULL;
654         FILE *uncompressed_stream = NULL;
655         char **include_list = NULL;
656         char **exclude_list = NULL;
657         char *src_filename = NULL;
658         char *dst_prefix = NULL;
659         int opt;
660         unsigned short untar_funct = 0;
661         unsigned short untar_funct_required = 0;
662         unsigned short extract_function = 0;
663         int include_list_count = 0;
664 #ifdef CONFIG_FEATURE_TAR_EXCLUDE
665         int exclude_list_count = 0;
666 #endif
667 #ifdef CONFIG_FEATURE_TAR_GZIP
668         int gunzip_pid;
669         int gz_fd = 0;
670 #endif
671
672         if (argc < 2) {
673                 show_usage();
674         }
675
676         /* Prepend '-' to the first argument if required */
677         if (argv[1][0] != '-') {
678                 char *tmp = xmalloc(strlen(argv[1]) + 2);
679                 tmp[0] = '-';
680                 strcpy(tmp + 1, argv[1]);
681                 argv[1] = tmp;
682         }
683
684         while ((opt = getopt(argc, argv, "ctxT:X:C:f:Opvz")) != -1) {
685                 switch (opt) {
686
687                 /* One and only one of these is required */
688                 case 'c':
689                         untar_funct_required |= untar_create;
690                         break;
691                 case 't':
692                         untar_funct_required |= untar_list;
693                         extract_function |= extract_list |extract_unconditional;
694                         break;
695                 case 'x':
696                         untar_funct_required |= untar_extract;
697                         extract_function |= (extract_all_to_fs | extract_unconditional | extract_create_leading_dirs);
698                         break;
699
700                 /* These are optional */
701                 /* Exclude or Include files listed in <filename>*/
702 #ifdef CONFIG_FEATURE_TAR_EXCLUDE
703                 case 'X':
704                         append_file_list_to_list(optarg, &exclude_list, &exclude_list_count);
705                         break;
706 #endif
707                 case 'T':
708                         // by default a list is an include list
709                         append_file_list_to_list(optarg, &include_list, &include_list_count);
710                         break;
711
712                 case 'C':       // Change to dir <optarg>
713                         /* Make sure dst_prefix ends in a '/' */
714                         dst_prefix = concat_path_file(optarg, "/");
715                         break;
716                 case 'f':       // archive filename
717                         if (strcmp(optarg, "-") == 0) {
718                                 src_filename = NULL;
719                         } else {
720                                 src_filename = xstrdup(optarg);
721                         }
722                         break;
723                 case 'O':
724                         extract_function |= extract_to_stdout;
725                         break;
726                 case 'p':
727                         break;
728                 case 'v':
729                         extract_function |= extract_verbose_list;
730                         break;
731 #ifdef CONFIG_FEATURE_TAR_GZIP
732                 case 'z':
733                         untar_funct |= untar_unzip;
734                         break;
735 #endif
736                 default:
737                         show_usage();
738                 }
739         }
740
741         /* Make sure the valid arguments were passed */
742         if (untar_funct_required == 0) {
743                 error_msg_and_die("You must specify one of the `-ctx' options");
744         }
745         if ((untar_funct_required != untar_create) && 
746                         (untar_funct_required != untar_extract) &&
747                         (untar_funct_required != untar_list)) {
748                 error_msg_and_die("You may not specify more than one `ctx' option.");
749         }
750         untar_funct |= untar_funct_required;
751
752         /* Setup an array of filenames to work with */
753         while (optind < argc) {
754                 append_file_to_list(argv[optind], &include_list, &include_list_count);
755                 optind++;
756         }
757         if (extract_function & (extract_list | extract_all_to_fs)) {
758                 if (dst_prefix == NULL) {
759                         dst_prefix = xstrdup("./");
760                 }
761
762                 /* Setup the source of the tar data */
763                 if (src_filename != NULL) {
764                         src_stream = xfopen(src_filename, "r");
765                 } else {
766                         src_stream = stdin;
767                 }
768 #ifdef CONFIG_FEATURE_TAR_GZIP
769                 /* Get a binary tree of all the tar file headers */
770                 if (untar_funct & untar_unzip) {
771                         uncompressed_stream = gz_open(src_stream, &gunzip_pid);
772                 } else
773 #endif // CONFIG_FEATURE_TAR_GZIP
774                         uncompressed_stream = src_stream;
775                 
776                 /* extract or list archive */
777                 unarchive(uncompressed_stream, stdout, &get_header_tar, extract_function, dst_prefix, include_list, exclude_list);
778                 fclose(uncompressed_stream);
779         }
780 #ifdef CONFIG_FEATURE_TAR_CREATE
781         /* create an archive */
782         else if (untar_funct & untar_create) {
783                 int verboseFlag = FALSE;
784                 int gzipFlag = FALSE;
785
786 #ifdef CONFIG_FEATURE_TAR_GZIP
787                 if (untar_funct & untar_unzip)
788                         gzipFlag = TRUE;
789
790 #endif // CONFIG_FEATURE_TAR_GZIP
791                 if (extract_function & extract_verbose_list) 
792                         verboseFlag = TRUE;
793                         
794                 writeTarFile(src_filename, verboseFlag, include_list, exclude_list, gzipFlag);
795         }
796 #endif // CONFIG_FEATURE_TAR_CREATE
797
798         /* Cleanups */
799 #ifdef CONFIG_FEATURE_TAR_GZIP
800         if ( !( untar_funct & untar_create ) && ( untar_funct & untar_unzip )) {
801                 fclose(src_stream);
802                 close(gz_fd);
803                 gz_close(gunzip_pid);
804         }
805 #endif // CONFIG_FEATURE_TAR_GZIP
806 #ifdef CONFIG_FEATURE_CLEAN_UP
807         if (src_filename) {
808                 free(src_filename);
809         }
810 #endif
811         return(EXIT_SUCCESS);
812 }