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