Fix tar -z, calls gz_open now
[oweals/busybox.git] / archival / tar.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * Mini tar implementation for busybox 
4  *
5  * Note, that as of BusyBox-0.43, tar has been completely rewritten from the
6  * ground up.  It still has remnents of the old code lying about, but it is
7  * very different now (i.e. cleaner, less global variables, etc)
8  *
9  * Copyright (C) 1999,2000,2001 by Lineo, inc.
10  * Written by Erik Andersen <andersen@lineo.com>, <andersee@debian.org>
11  *
12  * Based in part in the tar implementation in sash
13  *  Copyright (c) 1999 by David I. Bell
14  *  Permission is granted to use, distribute, or modify this source,
15  *  provided that this copyright notice remains intact.
16  *  Permission to distribute sash derived code under the GPL has been granted.
17  *
18  * Based in part on the tar implementation from busybox-0.28
19  *  Copyright (C) 1995 Bruce Perens
20  *  This is free software under the GNU General Public License.
21  *
22  * This program is free software; you can redistribute it and/or modify
23  * it under the terms of the GNU General Public License as published by
24  * the Free Software Foundation; either version 2 of the License, or
25  * (at your option) any later version.
26  *
27  * This program is distributed in the hope that it will be useful,
28  * but WITHOUT ANY WARRANTY; without even the implied warranty of
29  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
30  * General Public License for more details.
31  *
32  * You should have received a copy of the GNU General Public License
33  * along with this program; if not, write to the Free Software
34  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
35  *
36  */
37
38
39 #include <stdio.h>
40 #include <dirent.h>
41 #include <errno.h>
42 #include <fcntl.h>
43 #include <signal.h>
44 #include <time.h>
45 #include <utime.h>
46 #include <sys/types.h>
47 #include <sys/sysmacros.h>
48 #include <getopt.h>
49 #include <fnmatch.h>
50 #include <string.h>
51 #include <stdlib.h>
52 #include <unistd.h>
53 #include "busybox.h"
54 #define BB_DECLARE_EXTERN
55 #define bb_need_io_error
56 #define bb_need_name_longer_than_foo
57 #include "messages.c"
58
59 #ifdef BB_FEATURE_TAR_GZIP
60 extern int unzip(int in, int out);
61 extern int gz_open(FILE *compressed_file, int *pid);
62 extern void gz_close(int gunzip_pid);
63 #endif
64
65 /* Tar file constants  */
66 #ifndef MAJOR
67 #define MAJOR(dev) (((dev)>>8)&0xff)
68 #define MINOR(dev) ((dev)&0xff)
69 #endif
70
71 enum { NAME_SIZE = 100 }; /* because gcc won't let me use 'static const int' */
72
73 /* POSIX tar Header Block, from POSIX 1003.1-1990  */
74 struct TarHeader
75 {
76                                 /* byte offset */
77         char name[NAME_SIZE];         /*   0-99 */
78         char mode[8];                 /* 100-107 */
79         char uid[8];                  /* 108-115 */
80         char gid[8];                  /* 116-123 */
81         char size[12];                /* 124-135 */
82         char mtime[12];               /* 136-147 */
83         char chksum[8];               /* 148-155 */
84         char typeflag;                /* 156-156 */
85         char linkname[NAME_SIZE];     /* 157-256 */
86         char magic[6];                /* 257-262 */
87         char version[2];              /* 263-264 */
88         char uname[32];               /* 265-296 */
89         char gname[32];               /* 297-328 */
90         char devmajor[8];             /* 329-336 */
91         char devminor[8];             /* 337-344 */
92         char prefix[155];             /* 345-499 */
93         char padding[12];             /* 500-512 (pad to exactly the TAR_BLOCK_SIZE) */
94 };
95 typedef struct TarHeader TarHeader;
96
97
98 /* A few useful constants */
99 #define TAR_MAGIC          "ustar"        /* ustar and a null */
100 #define TAR_VERSION        "  "           /* Be compatable with GNU tar format */
101 static const int TAR_MAGIC_LEN = 6;
102 static const int TAR_VERSION_LEN = 2;
103 static const int TAR_BLOCK_SIZE = 512;
104
105 /* A nice enum with all the possible tar file content types */
106 enum TarFileType 
107 {
108         REGTYPE  = '0',            /* regular file */
109         REGTYPE0 = '\0',           /* regular file (ancient bug compat)*/
110         LNKTYPE  = '1',            /* hard link */
111         SYMTYPE  = '2',            /* symbolic link */
112         CHRTYPE  = '3',            /* character special */
113         BLKTYPE  = '4',            /* block special */
114         DIRTYPE  = '5',            /* directory */
115         FIFOTYPE = '6',            /* FIFO special */
116         CONTTYPE = '7',            /* reserved */
117         GNULONGLINK = 'K',         /* GNU long (>100 chars) link name */
118         GNULONGNAME = 'L',         /* GNU long (>100 chars) file name */
119 };
120 typedef enum TarFileType TarFileType;
121
122 /* This struct ignores magic, non-numeric user name, 
123  * non-numeric group name, and the checksum, since
124  * these are all ignored by BusyBox tar. */ 
125 struct TarInfo
126 {
127         int              tarFd;          /* An open file descriptor for reading from the tarball */
128         char *           name;           /* File name */
129         mode_t           mode;           /* Unix mode, including device bits. */
130         uid_t            uid;            /* Numeric UID */
131         gid_t            gid;            /* Numeric GID */
132         size_t           size;           /* Size of file */
133         time_t           mtime;          /* Last-modified time */
134         enum TarFileType type;           /* Regular, directory, link, etc */
135         char *           linkname;       /* Name for symbolic and hard links */
136         long             devmajor;       /* Major number for special device */
137         long             devminor;       /* Minor number for special device */
138 };
139 typedef struct TarInfo TarInfo;
140
141 /* Local procedures to restore files from a tar file.  */
142 extern int readTarFile(int tarFd, int extractFlag, int listFlag, 
143                 int tostdoutFlag, int verboseFlag, char** extractList,
144                 char** excludeList);
145
146 #ifdef BB_FEATURE_TAR_CREATE
147 /* Local procedures to save files into a tar file.  */
148 static int writeTarFile(const char* tarName, int verboseFlag, char **argv,
149                 char** excludeList);
150 #endif
151
152 #ifdef BB_FEATURE_TAR_GZIP
153 /* Signal handler for when child gzip process dies...  */
154 static void child_died()
155 {
156         fflush(stdout);
157         fflush(stderr);
158         exit(EXIT_FAILURE);
159 }
160
161 extern int tar_unzip_init(int tarFd)
162 {
163         int child_pid;
164         static int unzip_pipe[2];
165         /* Cope if child dies... Otherwise we block forever in read()... */
166         signal(SIGCHLD, child_died);
167
168         if (pipe(unzip_pipe)!=0)
169                 error_msg_and_die("pipe error");
170
171         if ( (child_pid = fork()) == -1)
172                 error_msg_and_die("fork failure");
173
174         if (child_pid==0) {
175                 /* child process */
176                 close(unzip_pipe[0]);
177 //              gunzip_init();
178                 unzip(tarFd, unzip_pipe[1]);
179                 exit(EXIT_SUCCESS);
180         }
181         else {
182                 /* return fd of uncompressed data to parent process */
183                 close(unzip_pipe[1]);
184                 return(unzip_pipe[0]);
185         }
186 }
187 #endif
188
189 #if defined BB_FEATURE_TAR_EXCLUDE
190 static struct option longopts[] = {
191         { "exclude", 1, NULL, 'e' },
192         { NULL, 0, NULL, 0 }
193 };
194 #endif
195
196 extern int tar_main(int argc, char **argv)
197 {
198         char** excludeList=NULL;
199         char** extractList=NULL;
200         const char *tarName="-";
201 #if defined BB_FEATURE_TAR_EXCLUDE
202         int excludeListSize=0;
203         FILE *fileList;
204         char file[256];
205 #endif
206 #if defined BB_FEATURE_TAR_GZIP
207         FILE *comp_file = NULL;
208         int unzipFlag    = FALSE;
209 #endif
210         int listFlag     = FALSE;
211         int extractFlag  = FALSE;
212         int createFlag   = FALSE;
213         int verboseFlag  = FALSE;
214         int tostdoutFlag = FALSE;
215         int status       = FALSE;
216         int opt;
217         pid_t pid;
218
219         if (argc <= 1)
220                 show_usage();
221
222         if (argv[1][0] != '-') {
223                 char *tmp = xmalloc(strlen(argv[1]) + 2);
224                 tmp[0] = '-';
225                 strcpy(tmp + 1, argv[1]);
226                 argv[1] = tmp;
227         }
228
229         while (
230 #ifndef BB_FEATURE_TAR_EXCLUDE
231                         (opt = getopt(argc, argv, "cxtzvOf:"))
232 #else
233                         (opt = getopt_long(argc, argv, "cxtzvOf:X:", longopts, NULL))
234 #endif
235                         > 0) {
236                 switch (opt) {
237                         case 'c':
238                                 if (extractFlag == TRUE || listFlag == TRUE)
239                                         goto flagError;
240                                 createFlag = TRUE;
241                                 break;
242                         case 'x':
243                                 if (listFlag == TRUE || createFlag == TRUE)
244                                         goto flagError;
245                                 extractFlag = TRUE;
246                                 break;
247                         case 't':
248                                 if (extractFlag == TRUE || createFlag == TRUE)
249                                         goto flagError;
250                                 listFlag = TRUE;
251                                 break;
252 #ifdef BB_FEATURE_TAR_GZIP
253                         case 'z':
254                                 unzipFlag = TRUE;
255                                 break;
256 #endif
257                         case 'v':
258                                 verboseFlag = TRUE;
259                                 break;
260                         case 'O':
261                                 tostdoutFlag = TRUE;
262                                 break;
263                         case 'f':
264                                 if (*tarName != '-')
265                                         error_msg_and_die( "Only one 'f' option allowed");
266                                 tarName = optarg;
267                                 break;
268 #if defined BB_FEATURE_TAR_EXCLUDE
269                         case 'e':
270                                 excludeList=xrealloc( excludeList,
271                                                 sizeof(char *) * (excludeListSize+2));
272                                 excludeList[excludeListSize] = optarg;
273                                 /* Tack a NULL onto the end of the list */
274                                 excludeList[++excludeListSize] = NULL;
275                         case 'X':
276                                 fileList = xfopen(optarg, "r");
277                                 while (fgets(file, sizeof(file), fileList) != NULL) {
278                                         excludeList = xrealloc(excludeList,
279                                                         sizeof(char *) * (excludeListSize+2));
280                                         chomp(file);
281                                         excludeList[excludeListSize] = xstrdup(file);
282                                         /* Tack a NULL onto the end of the list */
283                                         excludeList[++excludeListSize] = NULL;
284                                 }
285                                 fclose(fileList);
286                                 break;
287 #endif
288                                 default:
289                                         show_usage();
290                 }
291         }
292
293         /*
294          * Do the correct type of action supplying the rest of the
295          * command line arguments as the list of files to process.
296          */
297         if (createFlag == TRUE) {
298 #ifndef BB_FEATURE_TAR_CREATE
299                 error_msg_and_die( "This version of tar was not compiled with tar creation support.");
300 #else
301 #ifdef BB_FEATURE_TAR_GZIP
302                 if (unzipFlag==TRUE)
303                         error_msg_and_die("Creation of compressed not internally support by tar, pipe to busybox gunzip");
304 #endif
305                 status = writeTarFile(tarName, verboseFlag, argv + optind, excludeList);
306 #endif
307         }
308         if (listFlag == TRUE || extractFlag == TRUE) {
309                 int tarFd;
310                 if (argv[optind])
311                         extractList = argv + optind;
312                 /* Open the tar file for reading.  */
313                 if (!strcmp(tarName, "-"))
314                         tarFd = fileno(stdin);
315                 else
316                         tarFd = open(tarName, O_RDONLY);
317                 if (tarFd < 0)
318                         perror_msg_and_die("Error opening '%s'", tarName);
319
320 #ifdef BB_FEATURE_TAR_GZIP      
321                 /* unzip tarFd in a seperate process */
322                 if (unzipFlag == TRUE) {
323                         comp_file = fdopen(tarFd, "r");
324                         printf("1\n");
325                         if ((tarFd = gz_open(comp_file, &pid)) == EXIT_FAILURE) {
326                                 error_msg_and_die("Couldnt unzip file");
327                         }
328                         printf("2\n");
329                 }
330 #endif                  
331                 status = readTarFile(tarFd, extractFlag, listFlag, tostdoutFlag,
332                                         verboseFlag, extractList, excludeList);
333                 close(tarFd);
334         }
335
336 #ifdef BB_FEATURE_TAR_GZIP      
337         gz_close(pid);
338         fclose(comp_file);
339 #endif                  
340
341         if (status == TRUE)
342                 return EXIT_SUCCESS;
343         else
344                 return EXIT_FAILURE;
345
346   flagError:
347         error_msg_and_die( "Exactly one of 'c', 'x' or 't' must be specified");
348 }
349                                         
350 static void
351 fixUpPermissions(TarInfo *header)
352 {
353         struct utimbuf t;
354         /* Now set permissions etc for the new file */
355         chown(header->name, header->uid, header->gid);
356         chmod(header->name, header->mode);
357         /* Reset the time */
358         t.actime = time(0);
359         t.modtime = header->mtime;
360         utime(header->name, &t);
361 }
362                                 
363 static int
364 tarExtractRegularFile(TarInfo *header, int extractFlag, int tostdoutFlag)
365 {
366         size_t  writeSize;
367         size_t  readSize;
368         size_t  actualWriteSz;
369         char    buffer[BUFSIZ];
370         size_t  size = header->size;
371         int outFd=fileno(stdout);
372
373         /* Open the file to be written, if a file is supposed to be written */
374         if (extractFlag==TRUE && tostdoutFlag==FALSE) {
375                 /* Create the path to the file, just in case it isn't there...
376                  * This should not screw up path permissions or anything. */
377                 create_path(header->name, 0777);
378                 if ((outFd=open(header->name, O_CREAT|O_TRUNC|O_WRONLY, 
379                                                 header->mode & ~S_IFMT)) < 0) {
380                         error_msg(io_error, header->name, strerror(errno)); 
381                         return( FALSE);
382                 }
383         }
384
385         /* Write out the file, if we are supposed to be doing that */
386         while ( size > 0 ) {
387                 actualWriteSz=0;
388                 if ( size > sizeof(buffer) )
389                         writeSize = readSize = sizeof(buffer);
390                 else {
391                         int mod = size % 512;
392                         if ( mod != 0 )
393                                 readSize = size + (512 - mod);
394                         else
395                                 readSize = size;
396                         writeSize = size;
397                 }
398                 if ( (readSize = full_read(header->tarFd, buffer, readSize)) <= 0 ) {
399                         /* Tarball seems to have a problem */
400                         error_msg("Unexpected EOF in archive"); 
401                         return( FALSE);
402                 }
403                 if ( readSize < writeSize )
404                         writeSize = readSize;
405
406                 /* Write out the file, if we are supposed to be doing that */
407                 if (extractFlag==TRUE) {
408
409                         if ((actualWriteSz=full_write(outFd, buffer, writeSize)) != writeSize ) {
410                                 /* Output file seems to have a problem */
411                                 error_msg(io_error, header->name, strerror(errno)); 
412                                 return( FALSE);
413                         }
414                 } else {
415                         actualWriteSz=writeSize;
416                 }
417
418                 size -= actualWriteSz;
419         }
420
421         /* Now we are done writing the file out, so try 
422          * and fix up the permissions and whatnot */
423         if (extractFlag==TRUE && tostdoutFlag==FALSE) {
424                 close(outFd);
425                 fixUpPermissions(header);
426         }
427         return( TRUE);
428 }
429
430 static int
431 tarExtractDirectory(TarInfo *header, int extractFlag, int tostdoutFlag)
432 {
433
434         if (extractFlag==FALSE || tostdoutFlag==TRUE)
435                 return( TRUE);
436
437         if (create_path(header->name, header->mode) != TRUE) {
438                 perror_msg("%s: Cannot mkdir", header->name); 
439                 return( FALSE);
440         }
441         /* make the final component, just in case it was
442          * omitted by create_path() (which will skip the
443          * directory if it doesn't have a terminating '/') */
444         if (mkdir(header->name, header->mode) < 0 && errno != EEXIST) {
445                 perror_msg("%s", header->name);
446                 return FALSE;
447         }
448
449         fixUpPermissions(header);
450         return( TRUE);
451 }
452
453 static int
454 tarExtractHardLink(TarInfo *header, int extractFlag, int tostdoutFlag)
455 {
456         if (extractFlag==FALSE || tostdoutFlag==TRUE)
457                 return( TRUE);
458
459         if (link(header->linkname, header->name) < 0) {
460                 perror_msg("%s: Cannot create hard link to '%s'", header->name,
461                                 header->linkname); 
462                 return( FALSE);
463         }
464
465         /* Now set permissions etc for the new directory */
466         fixUpPermissions(header);
467         return( TRUE);
468 }
469
470 static int
471 tarExtractSymLink(TarInfo *header, int extractFlag, int tostdoutFlag)
472 {
473         if (extractFlag==FALSE || tostdoutFlag==TRUE)
474                 return( TRUE);
475
476 #ifdef  S_ISLNK
477         if (symlink(header->linkname, header->name) < 0) {
478                 perror_msg("%s: Cannot create symlink to '%s'", header->name,
479                                 header->linkname); 
480                 return( FALSE);
481         }
482         /* Try to change ownership of the symlink.
483          * If libs doesn't support that, don't bother.
484          * Changing the pointed-to-file is the Wrong Thing(tm).
485          */
486 #if (__GLIBC__ >= 2) && (__GLIBC_MINOR__ >= 1)
487         lchown(header->name, header->uid, header->gid);
488 #endif
489
490         /* Do not change permissions or date on symlink,
491          * since it changes the pointed to file instead.  duh. */
492 #else
493         error_msg("%s: Cannot create symlink to '%s': %s", 
494                         header->name, header->linkname, 
495                         "symlinks not supported"); 
496 #endif
497         return( TRUE);
498 }
499
500 static int
501 tarExtractSpecial(TarInfo *header, int extractFlag, int tostdoutFlag)
502 {
503         if (extractFlag==FALSE || tostdoutFlag==TRUE)
504                 return( TRUE);
505
506         if (S_ISCHR(header->mode) || S_ISBLK(header->mode) || S_ISSOCK(header->mode)) {
507                 if (mknod(header->name, header->mode, makedev(header->devmajor, header->devminor)) < 0) {
508                         perror_msg("%s: Cannot mknod", header->name); 
509                         return( FALSE);
510                 }
511         } else if (S_ISFIFO(header->mode)) {
512                 if (mkfifo(header->name, header->mode) < 0) {
513                         perror_msg("%s: Cannot mkfifo", header->name); 
514                         return( FALSE);
515                 }
516         }
517
518         /* Now set permissions etc for the new directory */
519         fixUpPermissions(header);
520         return( TRUE);
521 }
522
523 /* Read an octal value in a field of the specified width, with optional
524  * spaces on both sides of the number and with an optional null character
525  * at the end.  Returns -1 on an illegal format.  */
526 static long getOctal(const char *cp, int size)
527 {
528         long val = 0;
529
530         for(;(size > 0) && (*cp == ' '); cp++, size--);
531         if ((size == 0) || !is_octal(*cp))
532                 return -1;
533         for(; (size > 0) && is_octal(*cp); size--) {
534                 val = val * 8 + *cp++ - '0';
535         }
536         for (;(size > 0) && (*cp == ' '); cp++, size--);
537         if ((size > 0) && *cp)
538                 return -1;
539         return val;
540 }
541
542
543 /* Parse the tar header and fill in the nice struct with the details */
544 static int
545 readTarHeader(struct TarHeader *rawHeader, struct TarInfo *header)
546 {
547         int i;
548         long chksum, sum=0;
549         unsigned char *s = (unsigned char *)rawHeader;
550
551         header->name  = rawHeader->name;
552         /* Check for and relativify any absolute paths */
553         if ( *(header->name) == '/' ) {
554                 static int alreadyWarned=FALSE;
555
556                 while (*(header->name) == '/')
557                         ++*(header->name);
558
559                 if (alreadyWarned == FALSE) {
560                         error_msg("Removing leading '/' from member names");
561                         alreadyWarned = TRUE;
562                 }
563         }
564
565         header->mode  = getOctal(rawHeader->mode, sizeof(rawHeader->mode));
566         header->uid   =  getOctal(rawHeader->uid, sizeof(rawHeader->uid));
567         header->gid   =  getOctal(rawHeader->gid, sizeof(rawHeader->gid));
568         header->size  = getOctal(rawHeader->size, sizeof(rawHeader->size));
569         header->mtime = getOctal(rawHeader->mtime, sizeof(rawHeader->mtime));
570         chksum = getOctal(rawHeader->chksum, sizeof(rawHeader->chksum));
571         header->type  = rawHeader->typeflag;
572         header->linkname  = rawHeader->linkname;
573         header->devmajor  = getOctal(rawHeader->devmajor, sizeof(rawHeader->devmajor));
574         header->devminor  = getOctal(rawHeader->devminor, sizeof(rawHeader->devminor));
575
576         /* Check the checksum */
577         for (i = sizeof(*rawHeader); i-- != 0;) {
578                 sum += *s++;
579         }
580         /* Remove the effects of the checksum field (replace 
581          * with blanks for the purposes of the checksum) */
582         s = rawHeader->chksum;
583         for (i = sizeof(rawHeader->chksum) ; i-- != 0;) {
584                 sum -= *s++;
585         }
586         sum += ' ' * sizeof(rawHeader->chksum);
587         if (sum == chksum )
588                 return ( TRUE);
589         return( FALSE);
590 }
591
592 static int exclude_file(char **excluded_files, const char *file)
593 {
594         int i;
595
596         if (excluded_files == NULL)
597                 return 0;
598
599         for (i = 0; excluded_files[i] != NULL; i++) {
600                 if (excluded_files[i][0] == '/') {
601                         if (fnmatch(excluded_files[i], file,
602                                                 FNM_PATHNAME | FNM_LEADING_DIR) == 0)
603                                 return 1;
604                 } else {
605                         const char *p;
606
607                         for (p = file; p[0] != '\0'; p++) {
608                                 if ((p == file || p[-1] == '/') && p[0] != '/' &&
609                                                 fnmatch(excluded_files[i], p,
610                                                         FNM_PATHNAME | FNM_LEADING_DIR) == 0)
611                                         return 1;
612                         }
613                 }
614         }
615
616         return 0;
617 }
618
619 static int extract_file(char **extract_files, const char *file)
620 {
621         int i;
622
623         if (extract_files == NULL)
624                 return 1;
625
626         for (i = 0; extract_files[i] != NULL; i++) {
627                 if (fnmatch(extract_files[i], file, FNM_LEADING_DIR) == 0)
628                         return 1;
629         }
630
631         return 0;
632 }
633
634 /*
635  * Read a tar file and extract or list the specified files within it.
636  * If the list is empty than all files are extracted or listed.
637  */
638 extern int readTarFile(int tarFd, int extractFlag, int listFlag, 
639                 int tostdoutFlag, int verboseFlag, char** extractList,
640                 char** excludeList)
641 {
642         int status;
643         int errorFlag=FALSE;
644         int skipNextHeaderFlag=FALSE;
645         TarHeader rawHeader;
646         TarInfo header;
647
648         /* Set the umask for this process so it doesn't 
649          * screw up permission setting for us later. */
650         umask(0);
651
652         /* Read the tar file, and iterate over it one file at a time */
653         while ( (status = full_read(tarFd, (char*)&rawHeader, TAR_BLOCK_SIZE)) == TAR_BLOCK_SIZE ) {
654
655                 /* Try to read the header */
656                 if ( readTarHeader(&rawHeader, &header) == FALSE ) {
657                         if ( *(header.name) == '\0' ) {
658                                 goto endgame;
659                         } else {
660                                 errorFlag=TRUE;
661                                 error_msg("Bad tar header, skipping");
662                                 continue;
663                         }
664                 }
665                 if ( *(header.name) == '\0' )
666                                 goto endgame;
667                 header.tarFd = tarFd;
668
669                 /* Skip funky extra GNU headers that precede long files */
670                 if ( (header.type == GNULONGNAME) || (header.type == GNULONGLINK) ) {
671                         skipNextHeaderFlag=TRUE;
672                         if (tarExtractRegularFile(&header, FALSE, FALSE) == FALSE)
673                                 errorFlag = TRUE;
674                         continue;
675                 }
676                 if ( skipNextHeaderFlag == TRUE ) { 
677                         skipNextHeaderFlag=FALSE;
678                         error_msg(name_longer_than_foo, NAME_SIZE); 
679                         if (tarExtractRegularFile(&header, FALSE, FALSE) == FALSE)
680                                 errorFlag = TRUE;
681                         continue;
682                 }
683
684 #if defined BB_FEATURE_TAR_EXCLUDE
685                 if (exclude_file(excludeList, header.name)) {
686                         /* There are not the droids you're looking for, move along */
687                         /* If it is a regular file, pretend to extract it with
688                          * the extractFlag set to FALSE, so the junk in the tarball
689                          * is properly skipped over */
690                         if ( header.type==REGTYPE || header.type==REGTYPE0 ) {
691                                 if (tarExtractRegularFile(&header, FALSE, FALSE) == FALSE)
692                                         errorFlag = TRUE;
693                         }
694                         continue;
695                 }
696 #endif
697
698                 if (!extract_file(extractList, header.name)) {
699                         /* There are not the droids you're looking for, move along */
700                         /* If it is a regular file, pretend to extract it with
701                          * the extractFlag set to FALSE, so the junk in the tarball
702                          * is properly skipped over */
703                         if ( header.type==REGTYPE || header.type==REGTYPE0 ) {
704                                 if (tarExtractRegularFile(&header, FALSE, FALSE) == FALSE)
705                                         errorFlag = TRUE;
706                         }
707                         continue;
708                 }
709
710                 if (listFlag == TRUE) {
711                         /* Special treatment if the list (-t) flag is on */
712                         if (verboseFlag == TRUE) {
713                                 int len, len1;
714                                 char buf[35];
715                                 struct tm *tm = localtime (&(header.mtime));
716
717                                 len=printf("%s ", mode_string(header.mode));
718                                 my_getpwuid(buf, header.uid);
719                                 if (! *buf)
720                                         len+=printf("%d", header.uid);
721                                 else
722                                         len+=printf("%s", buf);
723                                 my_getgrgid(buf, header.gid);
724                                 if (! *buf)
725                                         len+=printf("/%-d ", header.gid);
726                                 else
727                                         len+=printf("/%-s ", buf);
728
729                                 if (header.type==CHRTYPE || header.type==BLKTYPE) {
730                                         len1=snprintf(buf, sizeof(buf), "%ld,%-ld ", 
731                                                         header.devmajor, header.devminor);
732                                 } else {
733                                         len1=snprintf(buf, sizeof(buf), "%lu ", (long)header.size);
734                                 }
735                                 /* Jump through some hoops to make the columns match up */
736                                 for(;(len+len1)<31;len++)
737                                         printf(" ");
738                                 printf(buf);
739
740                                 /* Use ISO 8610 time format */
741                                 if (tm) { 
742                                         printf ("%04d-%02d-%02d %02d:%02d:%02d ", 
743                                                         tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday, 
744                                                         tm->tm_hour, tm->tm_min, tm->tm_sec);
745                                 }
746                         }
747                         printf("%s", header.name);
748                         if (verboseFlag == TRUE) {
749                                 if (header.type==LNKTYPE)       /* If this is a link, say so */
750                                         printf(" link to %s", header.linkname);
751                                 else if (header.type==SYMTYPE)
752                                         printf(" -> %s", header.linkname);
753                         }
754                         printf("\n");
755                 }
756
757                 /* List contents if we are supposed to do that */
758                 if (verboseFlag == TRUE && extractFlag == TRUE) {
759                         /* Now the normal listing */
760                         FILE *vbFd = stdout;
761                         if (tostdoutFlag == TRUE)       // If the archive goes to stdout, verbose to stderr
762                                 vbFd = stderr;
763                         fprintf(vbFd, "%s\n", header.name);
764                 }
765                         
766                 /* Remove files if we would overwrite them */
767                 if (extractFlag == TRUE && tostdoutFlag == FALSE)
768                         unlink(header.name);
769
770                 /* If we got here, we can be certain we have a legitimate 
771                  * header to work with.  So work with it.  */
772                 switch ( header.type ) {
773                         case REGTYPE:
774                         case REGTYPE0:
775                                 /* If the name ends in a '/' then assume it is
776                                  * supposed to be a directory, and fall through */
777                                 if (header.name[strlen(header.name)-1] != '/') {
778                                         if (tarExtractRegularFile(&header, extractFlag, tostdoutFlag)==FALSE)
779                                                 errorFlag=TRUE;
780                                         break;
781                                 }
782                         case DIRTYPE:
783                                 if (tarExtractDirectory( &header, extractFlag, tostdoutFlag)==FALSE)
784                                         errorFlag=TRUE;
785                                 break;
786                         case LNKTYPE:
787                                 if (tarExtractHardLink( &header, extractFlag, tostdoutFlag)==FALSE)
788                                         errorFlag=TRUE;
789                                 break;
790                         case SYMTYPE:
791                                 if (tarExtractSymLink( &header, extractFlag, tostdoutFlag)==FALSE)
792                                         errorFlag=TRUE;
793                                 break;
794                         case CHRTYPE:
795                         case BLKTYPE:
796                         case FIFOTYPE:
797                                 if (tarExtractSpecial( &header, extractFlag, tostdoutFlag)==FALSE)
798                                         errorFlag=TRUE;
799                                 break;
800 #if 0
801                         /* Handled earlier */
802                         case GNULONGNAME:
803                         case GNULONGLINK:
804                                 skipNextHeaderFlag=TRUE;
805                                 break;
806 #endif
807                         default:
808                                 error_msg("Unknown file type '%c' in tar file", header.type);
809                                 close( tarFd);
810                                 return( FALSE);
811                 }
812         }
813         close(tarFd);
814         if (status > 0) {
815                 /* Bummer - we read a partial header */
816                 perror_msg("Error reading tar file");
817                 return ( FALSE);
818         }
819         else if (errorFlag==TRUE) {
820                 error_msg( "Error exit delayed from previous errors");
821                 return( FALSE);
822         } else 
823                 return( status);
824
825         /* Stuff to do when we are done */
826 endgame:
827         close( tarFd);
828         if ( *(header.name) == '\0' ) {
829                 if (errorFlag==TRUE)
830                         error_msg( "Error exit delayed from previous errors");
831                 else
832                         return( TRUE);
833         } 
834         return( FALSE);
835 }
836
837
838 #ifdef BB_FEATURE_TAR_CREATE
839
840 /*
841 ** writeTarFile(),  writeFileToTarball(), and writeTarHeader() are
842 ** the only functions that deal with the HardLinkInfo structure.
843 ** Even these functions use the xxxHardLinkInfo() functions.
844 */
845 typedef struct HardLinkInfo HardLinkInfo;
846 struct HardLinkInfo
847 {
848         HardLinkInfo *next;           /* Next entry in list */
849         dev_t dev;                    /* Device number */
850         ino_t ino;                    /* Inode number */
851         short linkCount;              /* (Hard) Link Count */
852         char name[1];                 /* Start of filename (must be last) */
853 };
854
855 /* Some info to be carried along when creating a new tarball */
856 struct TarBallInfo
857 {
858         char* fileName;               /* File name of the tarball */
859         int tarFd;                    /* Open-for-write file descriptor
860                                                                          for the tarball */
861         struct stat statBuf;          /* Stat info for the tarball, letting
862                                                                          us know the inode and device that the
863                                                                          tarball lives, so we can avoid trying 
864                                                                          to include the tarball into itself */
865         int verboseFlag;              /* Whether to print extra stuff or not */
866         char** excludeList;           /* List of files to not include */
867         HardLinkInfo *hlInfoHead;     /* Hard Link Tracking Information */
868         HardLinkInfo *hlInfo;         /* Hard Link Info for the current file */
869 };
870 typedef struct TarBallInfo TarBallInfo;
871
872
873 /* Might be faster (and bigger) if the dev/ino were stored in numeric order;) */
874 static void
875 addHardLinkInfo (HardLinkInfo **hlInfoHeadPtr, dev_t dev, ino_t ino,
876                 short linkCount, const char *name)
877 {
878         /* Note: hlInfoHeadPtr can never be NULL! */
879         HardLinkInfo *hlInfo;
880
881         hlInfo = (HardLinkInfo *)xmalloc(sizeof(HardLinkInfo)+strlen(name)+1);
882         if (hlInfo) {
883                 hlInfo->next = *hlInfoHeadPtr;
884                 *hlInfoHeadPtr = hlInfo;
885                 hlInfo->dev = dev;
886                 hlInfo->ino = ino;
887                 hlInfo->linkCount = linkCount;
888                 strcpy(hlInfo->name, name);
889         }
890         return;
891 }
892
893 static void
894 freeHardLinkInfo (HardLinkInfo **hlInfoHeadPtr)
895 {
896         HardLinkInfo *hlInfo = NULL;
897         HardLinkInfo *hlInfoNext = NULL;
898
899         if (hlInfoHeadPtr) {
900                 hlInfo = *hlInfoHeadPtr;
901                 while (hlInfo) {
902                         hlInfoNext = hlInfo->next;
903                         free(hlInfo);
904                         hlInfo = hlInfoNext;
905                 }
906                 *hlInfoHeadPtr = NULL;
907         }
908         return;
909 }
910
911 /* Might be faster (and bigger) if the dev/ino were stored in numeric order;) */
912 static HardLinkInfo *
913 findHardLinkInfo (HardLinkInfo *hlInfo, dev_t dev, ino_t ino)
914 {
915         while(hlInfo) {
916                 if ((ino == hlInfo->ino) && (dev == hlInfo->dev))
917                         break;
918                 hlInfo = hlInfo->next;
919         }
920         return(hlInfo);
921 }
922
923 /* Put an octal string into the specified buffer.
924  * The number is zero and space padded and possibly null padded.
925  * Returns TRUE if successful.  */ 
926 static int putOctal (char *cp, int len, long value)
927 {
928         int tempLength;
929         char tempBuffer[32];
930         char *tempString = tempBuffer;
931
932         /* Create a string of the specified length with an initial space,
933          * leading zeroes and the octal number, and a trailing null.  */
934         sprintf (tempString, "%0*lo", len - 1, value);
935
936         /* If the string is too large, suppress the leading space.  */
937         tempLength = strlen (tempString) + 1;
938         if (tempLength > len) {
939                 tempLength--;
940                 tempString++;
941         }
942
943         /* If the string is still too large, suppress the trailing null.  */
944         if (tempLength > len)
945                 tempLength--;
946
947         /* If the string is still too large, fail.  */
948         if (tempLength > len)
949                 return FALSE;
950
951         /* Copy the string to the field.  */
952         memcpy (cp, tempString, len);
953
954         return TRUE;
955 }
956
957 /* Write out a tar header for the specified file/directory/whatever */
958 static int
959 writeTarHeader(struct TarBallInfo *tbInfo, const char *header_name,
960                 const char *real_name, struct stat *statbuf)
961 {
962         long chksum=0;
963         struct TarHeader header;
964         const unsigned char *cp = (const unsigned char *) &header;
965         ssize_t size = sizeof(struct TarHeader);
966                 
967         memset( &header, 0, size);
968
969         strncpy(header.name, header_name, sizeof(header.name)); 
970
971         putOctal(header.mode, sizeof(header.mode), statbuf->st_mode);
972         putOctal(header.uid, sizeof(header.uid), statbuf->st_uid);
973         putOctal(header.gid, sizeof(header.gid), statbuf->st_gid);
974         putOctal(header.size, sizeof(header.size), 0); /* Regular file size is handled later */
975         putOctal(header.mtime, sizeof(header.mtime), statbuf->st_mtime);
976         strncpy(header.magic, TAR_MAGIC TAR_VERSION, 
977                         TAR_MAGIC_LEN + TAR_VERSION_LEN );
978
979         /* Enter the user and group names (default to root if it fails) */
980         my_getpwuid(header.uname, statbuf->st_uid);
981         if (! *header.uname)
982                 strcpy(header.uname, "root");
983         my_getgrgid(header.gname, statbuf->st_gid);
984         if (! *header.uname)
985                 strcpy(header.uname, "root");
986
987         if (tbInfo->hlInfo) {
988                 /* This is a hard link */
989                 header.typeflag = LNKTYPE;
990                 strncpy(header.linkname, tbInfo->hlInfo->name, sizeof(header.linkname));
991         } else if (S_ISLNK(statbuf->st_mode)) {
992                 int link_size=0;
993                 char buffer[BUFSIZ];
994                 header.typeflag  = SYMTYPE;
995                 link_size = readlink(real_name, buffer, sizeof(buffer) - 1);
996                 if ( link_size < 0) {
997                         perror_msg("Error reading symlink '%s'", header.name);
998                         return ( FALSE);
999                 }
1000                 buffer[link_size] = '\0';
1001                 strncpy(header.linkname, buffer, sizeof(header.linkname)); 
1002         } else if (S_ISDIR(statbuf->st_mode)) {
1003                 header.typeflag  = DIRTYPE;
1004                 strncat(header.name, "/", sizeof(header.name)); 
1005         } else if (S_ISCHR(statbuf->st_mode)) {
1006                 header.typeflag  = CHRTYPE;
1007                 putOctal(header.devmajor, sizeof(header.devmajor), MAJOR(statbuf->st_rdev));
1008                 putOctal(header.devminor, sizeof(header.devminor), MINOR(statbuf->st_rdev));
1009         } else if (S_ISBLK(statbuf->st_mode)) {
1010                 header.typeflag  = BLKTYPE;
1011                 putOctal(header.devmajor, sizeof(header.devmajor), MAJOR(statbuf->st_rdev));
1012                 putOctal(header.devminor, sizeof(header.devminor), MINOR(statbuf->st_rdev));
1013         } else if (S_ISFIFO(statbuf->st_mode)) {
1014                 header.typeflag  = FIFOTYPE;
1015         } else if (S_ISREG(statbuf->st_mode)) {
1016                 header.typeflag  = REGTYPE;
1017                 putOctal(header.size, sizeof(header.size), statbuf->st_size);
1018         } else {
1019                 error_msg("%s: Unknown file type", real_name);
1020                 return ( FALSE);
1021         }
1022
1023         /* Calculate and store the checksum (i.e. the sum of all of the bytes of
1024          * the header).  The checksum field must be filled with blanks for the
1025          * calculation.  The checksum field is formatted differently from the
1026          * other fields: it has [6] digits, a null, then a space -- rather than
1027          * digits, followed by a null like the other fields... */
1028         memset(header.chksum, ' ', sizeof(header.chksum));
1029         cp = (const unsigned char *) &header;
1030         while (size-- > 0)
1031                 chksum += *cp++;
1032         putOctal(header.chksum, 7, chksum);
1033         
1034         /* Now write the header out to disk */
1035         if ((size=full_write(tbInfo->tarFd, (char*)&header, sizeof(struct TarHeader))) < 0) {
1036                 error_msg(io_error, real_name, strerror(errno)); 
1037                 return ( FALSE);
1038         }
1039         /* Pad the header up to the tar block size */
1040         for (; size<TAR_BLOCK_SIZE; size++) {
1041                 write(tbInfo->tarFd, "\0", 1);
1042         }
1043         /* Now do the verbose thing (or not) */
1044         if (tbInfo->verboseFlag==TRUE) {
1045                 FILE *vbFd = stdout;
1046                 if (tbInfo->tarFd == fileno(stdout))    // If the archive goes to stdout, verbose to stderr
1047                         vbFd = stderr;
1048                 fprintf(vbFd, "%s\n", header.name);
1049         }
1050
1051         return ( TRUE);
1052 }
1053
1054
1055 static int writeFileToTarball(const char *fileName, struct stat *statbuf, void* userData)
1056 {
1057         struct TarBallInfo *tbInfo = (struct TarBallInfo *)userData;
1058         const char *header_name;
1059
1060         /*
1061         ** Check to see if we are dealing with a hard link.
1062         ** If so -
1063         ** Treat the first occurance of a given dev/inode as a file while
1064         ** treating any additional occurances as hard links.  This is done
1065         ** by adding the file information to the HardLinkInfo linked list.
1066         */
1067         tbInfo->hlInfo = NULL;
1068         if (statbuf->st_nlink > 1) {
1069                 tbInfo->hlInfo = findHardLinkInfo(tbInfo->hlInfoHead, statbuf->st_dev, 
1070                                 statbuf->st_ino);
1071                 if (tbInfo->hlInfo == NULL)
1072                         addHardLinkInfo (&tbInfo->hlInfoHead, statbuf->st_dev,
1073                                         statbuf->st_ino, statbuf->st_nlink, fileName);
1074         }
1075
1076         /* It is against the rules to archive a socket */
1077         if (S_ISSOCK(statbuf->st_mode)) {
1078                 error_msg("%s: socket ignored", fileName);
1079                 return( TRUE);
1080         }
1081
1082         /* It is a bad idea to store the archive we are in the process of creating,
1083          * so check the device and inode to be sure that this particular file isn't
1084          * the new tarball */
1085         if (tbInfo->statBuf.st_dev == statbuf->st_dev &&
1086                         tbInfo->statBuf.st_ino == statbuf->st_ino) {
1087                 error_msg("%s: file is the archive; skipping", fileName);
1088                 return( TRUE);
1089         }
1090
1091         header_name = fileName;
1092         while (header_name[0] == '/') {
1093                 static int alreadyWarned=FALSE;
1094                 if (alreadyWarned==FALSE) {
1095                         error_msg("Removing leading '/' from member names");
1096                         alreadyWarned=TRUE;
1097                 }
1098                 header_name++;
1099         }
1100
1101         if (strlen(fileName) >= NAME_SIZE) {
1102                 error_msg(name_longer_than_foo, NAME_SIZE);
1103                 return ( TRUE);
1104         }
1105
1106         if (header_name[0] == '\0')
1107                 return TRUE;
1108
1109 #if defined BB_FEATURE_TAR_EXCLUDE
1110         if (exclude_file(tbInfo->excludeList, header_name)) {
1111                 return SKIP;
1112         }
1113 #endif
1114
1115         if (writeTarHeader(tbInfo, header_name, fileName, statbuf)==FALSE) {
1116                 return( FALSE);
1117         } 
1118
1119         /* Now, if the file is a regular file, copy it out to the tarball */
1120         if ((tbInfo->hlInfo == NULL)
1121         &&  (S_ISREG(statbuf->st_mode))) {
1122                 int  inputFileFd;
1123                 char buffer[BUFSIZ];
1124                 ssize_t size=0, readSize=0;
1125
1126                 /* open the file we want to archive, and make sure all is well */
1127                 if ((inputFileFd = open(fileName, O_RDONLY)) < 0) {
1128                         error_msg("%s: Cannot open: %s", fileName, strerror(errno));
1129                         return( FALSE);
1130                 }
1131                 
1132                 /* write the file to the archive */
1133                 while ( (size = full_read(inputFileFd, buffer, sizeof(buffer))) > 0 ) {
1134                         if (full_write(tbInfo->tarFd, buffer, size) != size ) {
1135                                 /* Output file seems to have a problem */
1136                                 error_msg(io_error, fileName, strerror(errno)); 
1137                                 return( FALSE);
1138                         }
1139                         readSize+=size;
1140                 }
1141                 if (size == -1) {
1142                         error_msg(io_error, fileName, strerror(errno)); 
1143                         return( FALSE);
1144                 }
1145                 /* Pad the file up to the tar block size */
1146                 for (; (readSize%TAR_BLOCK_SIZE) != 0; readSize++) {
1147                         write(tbInfo->tarFd, "\0", 1);
1148                 }
1149                 close( inputFileFd);
1150         }
1151
1152         return( TRUE);
1153 }
1154
1155 static int writeTarFile(const char* tarName, int verboseFlag, char **argv,
1156                 char** excludeList)
1157 {
1158         int tarFd=-1;
1159         int errorFlag=FALSE;
1160         ssize_t size;
1161         struct TarBallInfo tbInfo;
1162         tbInfo.verboseFlag = verboseFlag;
1163         tbInfo.hlInfoHead = NULL;
1164
1165         /* Make sure there is at least one file to tar up.  */
1166         if (*argv == NULL)
1167                 error_msg_and_die("Cowardly refusing to create an empty archive");
1168
1169         /* Open the tar file for writing.  */
1170         if (!strcmp(tarName, "-"))
1171                 tbInfo.tarFd = fileno(stdout);
1172         else
1173                 tbInfo.tarFd = open (tarName, O_WRONLY | O_CREAT | O_TRUNC, 0644);
1174         if (tbInfo.tarFd < 0) {
1175                 perror_msg( "Error opening '%s'", tarName);
1176                 freeHardLinkInfo(&tbInfo.hlInfoHead);
1177                 return ( FALSE);
1178         }
1179         tbInfo.excludeList=excludeList;
1180         /* Store the stat info for the tarball's file, so
1181          * can avoid including the tarball into itself....  */
1182         if (fstat(tbInfo.tarFd, &tbInfo.statBuf) < 0)
1183                 error_msg_and_die(io_error, tarName, strerror(errno)); 
1184
1185         /* Set the umask for this process so it doesn't 
1186          * screw up permission setting for us later. */
1187         umask(0);
1188
1189         /* Read the directory/files and iterate over them one at a time */
1190         while (*argv != NULL) {
1191                 if (recursive_action(*argv++, TRUE, FALSE, FALSE,
1192                                         writeFileToTarball, writeFileToTarball, 
1193                                         (void*) &tbInfo) == FALSE) {
1194                         errorFlag = TRUE;
1195                 }
1196         }
1197         /* Write two empty blocks to the end of the archive */
1198         for (size=0; size<(2*TAR_BLOCK_SIZE); size++) {
1199                 write(tbInfo.tarFd, "\0", 1);
1200         }
1201
1202         /* To be pedantically correct, we would check if the tarball
1203          * is smaller than 20 tar blocks, and pad it if it was smaller,
1204          * but that isn't necessary for GNU tar interoperability, and
1205          * so is considered a waste of space */
1206
1207         /* Hang up the tools, close up shop, head home */
1208         close(tarFd);
1209         if (errorFlag == TRUE) {
1210                 error_msg("Error exit delayed from previous errors");
1211                 freeHardLinkInfo(&tbInfo.hlInfoHead);
1212                 return(FALSE);
1213         }
1214         freeHardLinkInfo(&tbInfo.hlInfoHead);
1215         return( TRUE);
1216 }
1217
1218
1219 #endif
1220