3e1a65062499e77a056021833c6d03c7d2ff3d30
[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 "internal.h"
40 #define BB_DECLARE_EXTERN
41 #define bb_need_io_error
42 #include "messages.c"
43 #include <stdio.h>
44 #include <dirent.h>
45 #include <errno.h>
46 #include <fcntl.h>
47 #include <signal.h>
48 #include <time.h>
49 #include <utime.h>
50 #include <sys/types.h>
51 #include <sys/sysmacros.h>
52 #include <getopt.h>
53
54 /* Tar file constants  */
55 #ifndef MAJOR
56 #define MAJOR(dev) (((dev)>>8)&0xff)
57 #define MINOR(dev) ((dev)&0xff)
58 #endif
59
60
61 /* POSIX tar Header Block, from POSIX 1003.1-1990  */
62 struct TarHeader
63 {
64                                 /* byte offset */
65         char name[100];               /*   0-99 */
66         char mode[8];                 /* 100-107 */
67         char uid[8];                  /* 108-115 */
68         char gid[8];                  /* 116-123 */
69         char size[12];                /* 124-135 */
70         char mtime[12];               /* 136-147 */
71         char chksum[8];               /* 148-155 */
72         char typeflag;                /* 156-156 */
73         char linkname[100];           /* 157-256 */
74         char magic[6];                /* 257-262 */
75         char version[2];              /* 263-264 */
76         char uname[32];               /* 265-296 */
77         char gname[32];               /* 297-328 */
78         char devmajor[8];             /* 329-336 */
79         char devminor[8];             /* 337-344 */
80         char prefix[155];             /* 345-499 */
81         char padding[12];             /* 500-512 (pad to exactly the TAR_BLOCK_SIZE) */
82 };
83 typedef struct TarHeader TarHeader;
84
85
86 /* A few useful constants */
87 #define TAR_MAGIC          "ustar"        /* ustar and a null */
88 #define TAR_VERSION        "  "           /* Be compatable with GNU tar format */
89 #define TAR_MAGIC_LEN       6
90 #define TAR_VERSION_LEN     2
91 #define TAR_BLOCK_SIZE      512
92
93 /* A nice enum with all the possible tar file content types */
94 enum TarFileType 
95 {
96         REGTYPE  = '0',            /* regular file */
97         REGTYPE0 = '\0',           /* regular file (ancient bug compat)*/
98         LNKTYPE  = '1',            /* hard link */
99         SYMTYPE  = '2',            /* symbolic link */
100         CHRTYPE  = '3',            /* character special */
101         BLKTYPE  = '4',            /* block special */
102         DIRTYPE  = '5',            /* directory */
103         FIFOTYPE = '6',            /* FIFO special */
104         CONTTYPE = '7',            /* reserved */
105 };
106 typedef enum TarFileType TarFileType;
107
108 /* This struct ignores magic, non-numeric user name, 
109  * non-numeric group name, and the checksum, since
110  * these are all ignored by BusyBox tar. */ 
111 struct TarInfo
112 {
113         int              tarFd;          /* An open file descriptor for reading from the tarball */
114         char *           name;           /* File name */
115         mode_t           mode;           /* Unix mode, including device bits. */
116         uid_t            uid;            /* Numeric UID */
117         gid_t            gid;            /* Numeric GID */
118         size_t           size;           /* Size of file */
119         time_t           mtime;          /* Last-modified time */
120         enum TarFileType type;           /* Regular, directory, link, etc */
121         char *           linkname;       /* Name for symbolic and hard links */
122         long             devmajor;       /* Major number for special device */
123         long             devminor;       /* Minor number for special device */
124 };
125 typedef struct TarInfo TarInfo;
126
127 /* Local procedures to restore files from a tar file.  */
128 static int readTarFile(const char* tarName, int extractFlag, int listFlag, 
129                 int tostdoutFlag, int verboseFlag, char** extractList,
130                 char** excludeList);
131
132
133
134 #ifdef BB_FEATURE_TAR_CREATE
135 /* Local procedures to save files into a tar file.  */
136 static int writeTarFile(const char* tarName, int tostdoutFlag, 
137                 int verboseFlag, int argc, char **argv, char** excludeList);
138 #endif
139
140 static struct option longopts[] =
141 {
142 #ifdef BB_FEATURE_TAR_EXCLUDE
143         {"exclude",required_argument,NULL,'e'},
144 #endif
145                 {NULL,0,NULL,0}
146 };
147
148 extern int tar_main(int argc, char **argv)
149 {
150         char** excludeList=NULL;
151 #if defined BB_FEATURE_TAR_EXCLUDE
152         int excludeListSize=0;
153 #endif
154         const char *tarName="-";
155         int listFlag     = FALSE;
156         int extractFlag  = FALSE;
157         int createFlag   = FALSE;
158         int verboseFlag  = FALSE;
159         int tostdoutFlag = FALSE;
160         int opt;
161
162         if (argc <= 1)
163                 usage(tar_usage);
164
165         /* do normal option parsing */
166         while ((opt = getopt_long(argc, argv, "cxtvOf:", longopts, NULL)) != EOF) {
167                 switch (opt) {
168                                 case 'c':
169                                         if (extractFlag == TRUE || listFlag == TRUE)
170                                                 goto flagError;
171                                         createFlag = TRUE;
172                                         break;
173                                 case 'x':
174                                         if (listFlag == TRUE || createFlag == TRUE)
175                                                 goto flagError;
176                                         extractFlag = TRUE;
177                                         break;
178                                 case 't':
179                                         if (extractFlag == TRUE || createFlag == TRUE)
180                                                 goto flagError;
181                                         listFlag = TRUE;
182                                         break;
183                                 case 'v':
184                                         verboseFlag = TRUE;
185                                         break;
186                                 case 'O':
187                                         tostdoutFlag = TRUE;
188                                         tarName = "-";
189                                         break;                                  
190                                 case 'f':
191                                         if (*tarName != '-')
192                                                 fatalError( "Only one 'f' option allowed\n");
193                                         tarName = optarg;
194                                         if (!strcmp(tarName, "-") && createFlag == TRUE)
195                                                 tostdoutFlag = TRUE;
196                                         break;
197 #if defined BB_FEATURE_TAR_EXCLUDE
198                                 case 'e':
199                                         excludeList=xrealloc( excludeList, sizeof(char**) * (excludeListSize+2));
200                                         excludeList[excludeListSize] = optarg;
201                                         /* Remove leading "/"s */
202                                         if (*excludeList[excludeListSize] =='/')
203                                                 excludeList[excludeListSize] = (excludeList[excludeListSize])+1;
204                                         /* Tack a NULL onto the end of the list */
205                                         excludeList[++excludeListSize] = NULL;
206                                         break;
207 #endif
208                                 default:
209                                         usage(tar_usage);
210                 }
211         }
212
213         /* 
214          * Do the correct type of action supplying the rest of the
215          * command line arguments as the list of files to process.
216          */
217         if (createFlag == TRUE) {
218 #ifndef BB_FEATURE_TAR_CREATE
219                 fatalError( "This version of tar was not compiled with tar creation support.\n");
220 #else
221                 exit(writeTarFile(tarName, tostdoutFlag, verboseFlag, argc-optind, &argv[optind], excludeList));
222 #endif
223         }
224         if (listFlag == TRUE || extractFlag == TRUE) {
225                 exit(readTarFile(tarName, extractFlag, listFlag, tostdoutFlag, verboseFlag, &argv[optind], excludeList));
226         }
227
228   flagError:
229         fatalError( "Exactly one of 'c', 'x' or 't' must be specified\n");
230 }
231                                         
232 static void
233 fixUpPermissions(TarInfo *header)
234 {
235         struct utimbuf t;
236         /* Now set permissions etc for the new file */
237         chown(header->name, header->uid, header->gid);
238         chmod(header->name, header->mode);
239         /* Reset the time */
240         t.actime = time(0);
241         t.modtime = header->mtime;
242         utime(header->name, &t);
243 }
244                                 
245 static int
246 tarExtractRegularFile(TarInfo *header, int extractFlag, int tostdoutFlag)
247 {
248         size_t  writeSize;
249         size_t  readSize;
250         size_t  actualWriteSz;
251         char    buffer[BUFSIZ];
252         size_t  size = header->size;
253         int outFd=fileno(stdout);
254
255         /* Open the file to be written, if a file is supposed to be written */
256         if (extractFlag==TRUE && tostdoutFlag==FALSE) {
257                 /* Create the path to the file, just in case it isn't there...
258                  * This should not screw up path permissions or anything. */
259                 createPath(header->name, 0777);
260                 if ((outFd=open(header->name, O_CREAT|O_TRUNC|O_WRONLY, 
261                                                 header->mode & ~S_IFMT)) < 0) {
262                         errorMsg(io_error, header->name, strerror(errno)); 
263                         return( FALSE);
264                 }
265         }
266
267         /* Write out the file, if we are supposed to be doing that */
268         while ( size > 0 ) {
269                 actualWriteSz=0;
270                 if ( size > sizeof(buffer) )
271                         writeSize = readSize = sizeof(buffer);
272                 else {
273                         int mod = size % 512;
274                         if ( mod != 0 )
275                                 readSize = size + (512 - mod);
276                         else
277                                 readSize = size;
278                         writeSize = size;
279                 }
280                 if ( (readSize = fullRead(header->tarFd, buffer, readSize)) <= 0 ) {
281                         /* Tarball seems to have a problem */
282                         errorMsg("Unexpected EOF in archive\n"); 
283                         return( FALSE);
284                 }
285                 if ( readSize < writeSize )
286                         writeSize = readSize;
287
288                 /* Write out the file, if we are supposed to be doing that */
289                 if (extractFlag==TRUE) {
290
291                         if ((actualWriteSz=fullWrite(outFd, buffer, writeSize)) != writeSize ) {
292                                 /* Output file seems to have a problem */
293                                 errorMsg(io_error, header->name, strerror(errno)); 
294                                 return( FALSE);
295                         }
296                 } else {
297                         actualWriteSz=writeSize;
298                 }
299
300                 size -= actualWriteSz;
301         }
302
303         /* Now we are done writing the file out, so try 
304          * and fix up the permissions and whatnot */
305         if (extractFlag==TRUE && tostdoutFlag==FALSE) {
306                 close(outFd);
307                 fixUpPermissions(header);
308         }
309         return( TRUE);
310 }
311
312 static int
313 tarExtractDirectory(TarInfo *header, int extractFlag, int tostdoutFlag)
314 {
315
316         if (extractFlag==FALSE || tostdoutFlag==TRUE)
317                 return( TRUE);
318
319         if (createPath(header->name, header->mode) != TRUE) {
320                 errorMsg("%s: Cannot mkdir: %s\n", 
321                                 header->name, strerror(errno)); 
322                 return( FALSE);
323         }
324         /* make the final component, just in case it was
325          * omitted by createPath() (which will skip the
326          * directory if it doesn't have a terminating '/') */
327         if (mkdir(header->name, header->mode) == 0) {
328                 fixUpPermissions(header);
329         }
330         return( TRUE);
331 }
332
333 static int
334 tarExtractHardLink(TarInfo *header, int extractFlag, int tostdoutFlag)
335 {
336         if (extractFlag==FALSE || tostdoutFlag==TRUE)
337                 return( TRUE);
338
339         if (link(header->linkname, header->name) < 0) {
340                 errorMsg("%s: Cannot create hard link to '%s': %s\n", 
341                                 header->name, header->linkname, strerror(errno)); 
342                 return( FALSE);
343         }
344
345         /* Now set permissions etc for the new directory */
346         fixUpPermissions(header);
347         return( TRUE);
348 }
349
350 static int
351 tarExtractSymLink(TarInfo *header, int extractFlag, int tostdoutFlag)
352 {
353         if (extractFlag==FALSE || tostdoutFlag==TRUE)
354                 return( TRUE);
355
356 #ifdef  S_ISLNK
357         if (symlink(header->linkname, header->name) < 0) {
358                 errorMsg("%s: Cannot create symlink to '%s': %s\n", 
359                                 header->name, header->linkname, strerror(errno)); 
360                 return( FALSE);
361         }
362         /* Try to change ownership of the symlink.
363          * If libs doesn't support that, don't bother.
364          * Changing the pointed-to-file is the Wrong Thing(tm).
365          */
366 #if (__GLIBC__ >= 2) && (__GLIBC_MINOR__ >= 1)
367         lchown(header->name, header->uid, header->gid);
368 #endif
369
370         /* Do not change permissions or date on symlink,
371          * since it changes the pointed to file instead.  duh. */
372 #else
373         errorMsg("%s: Cannot create symlink to '%s': %s\n", 
374                         header->name, header->linkname, 
375                         "symlinks not supported"); 
376 #endif
377         return( TRUE);
378 }
379
380 static int
381 tarExtractSpecial(TarInfo *header, int extractFlag, int tostdoutFlag)
382 {
383         if (extractFlag==FALSE || tostdoutFlag==TRUE)
384                 return( TRUE);
385
386         if (S_ISCHR(header->mode) || S_ISBLK(header->mode) || S_ISSOCK(header->mode)) {
387                 if (mknod(header->name, header->mode, makedev(header->devmajor, header->devminor)) < 0) {
388                         errorMsg("%s: Cannot mknod: %s\n",
389                                 header->name, strerror(errno)); 
390                         return( FALSE);
391                 }
392         } else if (S_ISFIFO(header->mode)) {
393                 if (mkfifo(header->name, header->mode) < 0) {
394                         errorMsg("%s: Cannot mkfifo: %s\n",
395                                 header->name, strerror(errno)); 
396                         return( FALSE);
397                 }
398         }
399
400         /* Now set permissions etc for the new directory */
401         fixUpPermissions(header);
402         return( TRUE);
403 }
404
405 /* Read an octal value in a field of the specified width, with optional
406  * spaces on both sides of the number and with an optional null character
407  * at the end.  Returns -1 on an illegal format.  */
408 static long getOctal(const char *cp, int size)
409 {
410         long val = 0;
411
412         for(;(size > 0) && (*cp == ' '); cp++, size--);
413         if ((size == 0) || !isOctal(*cp))
414                 return -1;
415         for(; (size > 0) && isOctal(*cp); size--) {
416                 val = val * 8 + *cp++ - '0';
417         }
418         for (;(size > 0) && (*cp == ' '); cp++, size--);
419         if ((size > 0) && *cp)
420                 return -1;
421         return val;
422 }
423
424
425 /* Parse the tar header and fill in the nice struct with the details */
426 static int
427 readTarHeader(struct TarHeader *rawHeader, struct TarInfo *header)
428 {
429         int i;
430         long chksum, sum=0;
431         unsigned char *s = (unsigned char *)rawHeader;
432
433         header->name  = rawHeader->name;
434         /* Check for and relativify any absolute paths */
435         if ( *(header->name) == '/' ) {
436                 static int alreadyWarned=FALSE;
437
438                 while (*(header->name) == '/')
439                         ++*(header->name);
440
441                 if (alreadyWarned == FALSE) {
442                         errorMsg("Removing leading '/' from member names\n");
443                         alreadyWarned = TRUE;
444                 }
445         }
446
447         header->mode  = getOctal(rawHeader->mode, sizeof(rawHeader->mode));
448         header->uid   =  getOctal(rawHeader->uid, sizeof(rawHeader->uid));
449         header->gid   =  getOctal(rawHeader->gid, sizeof(rawHeader->gid));
450         header->size  = getOctal(rawHeader->size, sizeof(rawHeader->size));
451         header->mtime = getOctal(rawHeader->mtime, sizeof(rawHeader->mtime));
452         chksum = getOctal(rawHeader->chksum, sizeof(rawHeader->chksum));
453         header->type  = rawHeader->typeflag;
454         header->linkname  = rawHeader->linkname;
455         header->devmajor  = getOctal(rawHeader->devmajor, sizeof(rawHeader->devmajor));
456         header->devminor  = getOctal(rawHeader->devminor, sizeof(rawHeader->devminor));
457
458         /* Check the checksum */
459         for (i = sizeof(*rawHeader); i-- != 0;) {
460                 sum += *s++;
461         }
462         /* Remove the effects of the checksum field (replace 
463          * with blanks for the purposes of the checksum) */
464         s = rawHeader->chksum;
465         for (i = sizeof(rawHeader->chksum) ; i-- != 0;) {
466                 sum -= *s++;
467         }
468         sum += ' ' * sizeof(rawHeader->chksum);
469         if (sum == chksum )
470                 return ( TRUE);
471         return( FALSE);
472 }
473
474
475 /*
476  * Read a tar file and extract or list the specified files within it.
477  * If the list is empty than all files are extracted or listed.
478  */
479 static int readTarFile(const char* tarName, int extractFlag, int listFlag, 
480                 int tostdoutFlag, int verboseFlag, char** extractList,
481                 char** excludeList)
482 {
483         int status, tarFd=-1;
484         int errorFlag=FALSE;
485         TarHeader rawHeader;
486         TarInfo header;
487         char** tmpList;
488
489         /* Open the tar file for reading.  */
490         if (!strcmp(tarName, "-"))
491                 tarFd = fileno(stdin);
492         else
493                 tarFd = open(tarName, O_RDONLY);
494         if (tarFd < 0) {
495                 errorMsg( "Error opening '%s': %s\n", tarName, strerror(errno));
496                 return ( FALSE);
497         }
498
499         /* Set the umask for this process so it doesn't 
500          * screw up permission setting for us later. */
501         umask(0);
502
503         /* Read the tar file, and iterate over it one file at a time */
504         while ( (status = fullRead(tarFd, (char*)&rawHeader, TAR_BLOCK_SIZE)) == TAR_BLOCK_SIZE ) {
505
506                 /* First, try to read the header */
507                 if ( readTarHeader(&rawHeader, &header) == FALSE ) {
508                         if ( *(header.name) == '\0' ) {
509                                 goto endgame;
510                         } else {
511                                 errorFlag=TRUE;
512                                 errorMsg("Bad tar header, skipping\n");
513                                 continue;
514                         }
515                 }
516                 if ( *(header.name) == '\0' )
517                                 goto endgame;
518                 header.tarFd = tarFd;
519
520 #if defined BB_FEATURE_TAR_EXCLUDE
521                 {
522                         int skipFlag=FALSE;
523                         /* Check for excluded files....  */
524                         for (tmpList=excludeList; tmpList && *tmpList; tmpList++) {
525                                 /* Do some extra hoop jumping for when directory names
526                                  * end in '/' but the entry in tmpList doesn't */
527                                 if (strncmp( *tmpList, header.name, strlen(*tmpList))==0 || (
528                                                         header.name[strlen(header.name)-1]=='/'
529                                                         && strncmp( *tmpList, header.name, 
530                                                                 MIN(strlen(header.name)-1, strlen(*tmpList)))==0)) {
531                                         /* If it is a regular file, pretend to extract it with
532                                          * the extractFlag set to FALSE, so the junk in the tarball
533                                          * is properly skipped over */
534                                         if ( header.type==REGTYPE || header.type==REGTYPE0 ) {
535                                                         tarExtractRegularFile(&header, FALSE, FALSE);
536                                         }
537                                         skipFlag=TRUE;
538                                         break;
539                                 }
540                         }
541                         /* There are not the droids you're looking for, move along */
542                         if (skipFlag==TRUE)
543                                 continue;
544                 }
545 #endif
546                 if (*extractList != NULL) {
547                         int skipFlag = TRUE;
548                         for (tmpList = extractList; *tmpList != NULL; tmpList++) {
549                                 if (strncmp( *tmpList, header.name, strlen(*tmpList))==0 || (
550                                                         header.name[strlen(header.name)-1]=='/'
551                                                         && strncmp( *tmpList, header.name, 
552                                                                 MIN(strlen(header.name)-1, strlen(*tmpList)))==0)) {
553                                         /* If it is a regular file, pretend to extract it with
554                                          * the extractFlag set to FALSE, so the junk in the tarball
555                                          * is properly skipped over */
556                                         skipFlag = FALSE;
557                                         break;
558                                 }
559                         }
560                         /* There are not the droids you're looking for, move along */
561                         if (skipFlag == TRUE) {
562                                 if ( header.type==REGTYPE || header.type==REGTYPE0 )
563                                                 tarExtractRegularFile(&header, FALSE, FALSE);
564                                 continue;
565                         }
566                 }
567
568                 if (listFlag == TRUE) {
569                         /* Special treatment if the list (-t) flag is on */
570                         if (verboseFlag == TRUE) {
571                                 int len, len1;
572                                 char buf[35];
573                                 struct tm *tm = localtime (&(header.mtime));
574
575                                 len=printf("%s ", modeString(header.mode));
576                                 memset(buf, 0, 8*sizeof(char));
577                                 my_getpwuid(buf, header.uid);
578                                 if (! *buf)
579                                         len+=printf("%d", header.uid);
580                                 else
581                                         len+=printf("%s", buf);
582                                 memset(buf, 0, 8*sizeof(char));
583                                 my_getgrgid(buf, header.gid);
584                                 if (! *buf)
585                                         len+=printf("/%-d ", header.gid);
586                                 else
587                                         len+=printf("/%-s ", buf);
588
589                                 if (header.type==CHRTYPE || header.type==BLKTYPE) {
590                                         len1=snprintf(buf, sizeof(buf), "%ld,%-ld ", 
591                                                         header.devmajor, header.devminor);
592                                 } else {
593                                         len1=snprintf(buf, sizeof(buf), "%lu ", (long)header.size);
594                                 }
595                                 /* Jump through some hoops to make the columns match up */
596                                 for(;(len+len1)<31;len++)
597                                         printf(" ");
598                                 printf(buf);
599
600                                 /* Use ISO 8610 time format */
601                                 if (tm) { 
602                                         printf ("%04d-%02d-%02d %02d:%02d:%02d ", 
603                                                         tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday, 
604                                                         tm->tm_hour, tm->tm_min, tm->tm_sec);
605                                 }
606                         }
607                         printf("%s", header.name);
608                         if (verboseFlag == TRUE) {
609                                 if (header.type==LNKTYPE)       /* If this is a link, say so */
610                                         printf(" link to %s", header.linkname);
611                                 else if (header.type==SYMTYPE)
612                                         printf(" -> %s", header.linkname);
613                         }
614                         printf("\n");
615                 }
616
617                 /* List contents if we are supposed to do that */
618                 if (verboseFlag == TRUE && extractFlag == TRUE) {
619                         /* Now the normal listing */
620                         FILE *vbFd = stdout;
621                         if (tostdoutFlag == TRUE)       // If the archive goes to stdout, verbose to stderr
622                                 vbFd = stderr;
623                         fprintf(vbFd, "%s\n", header.name);
624                 }
625                         
626                 /* Remove files if we would overwrite them */
627                 if (extractFlag == TRUE && tostdoutFlag == FALSE)
628                         unlink(header.name);
629
630                 /* If we got here, we can be certain we have a legitimate 
631                  * header to work with.  So work with it.  */
632                 switch ( header.type ) {
633                         case REGTYPE:
634                         case REGTYPE0:
635                                 /* If the name ends in a '/' then assume it is
636                                  * supposed to be a directory, and fall through */
637                                 if (header.name[strlen(header.name)-1] != '/') {
638                                         if (tarExtractRegularFile(&header, extractFlag, tostdoutFlag)==FALSE)
639                                                 errorFlag=TRUE;
640                                         break;
641                                 }
642                         case DIRTYPE:
643                                 if (tarExtractDirectory( &header, extractFlag, tostdoutFlag)==FALSE)
644                                         errorFlag=TRUE;
645                                 break;
646                         case LNKTYPE:
647                                 if (tarExtractHardLink( &header, extractFlag, tostdoutFlag)==FALSE)
648                                         errorFlag=TRUE;
649                                 break;
650                         case SYMTYPE:
651                                 if (tarExtractSymLink( &header, extractFlag, tostdoutFlag)==FALSE)
652                                         errorFlag=TRUE;
653                                 break;
654                         case CHRTYPE:
655                         case BLKTYPE:
656                         case FIFOTYPE:
657                                 if (tarExtractSpecial( &header, extractFlag, tostdoutFlag)==FALSE)
658                                         errorFlag=TRUE;
659                                 break;
660                         default:
661                                 close( tarFd);
662                                 return( FALSE);
663                 }
664         }
665         close(tarFd);
666         if (status > 0) {
667                 /* Bummer - we read a partial header */
668                 errorMsg( "Error reading '%s': %s\n", tarName, strerror(errno));
669                 return ( FALSE);
670         }
671         else if (errorFlag==TRUE) {
672                 errorMsg( "Error exit delayed from previous errors\n");
673                 return( FALSE);
674         } else 
675                 return( status);
676
677         /* Stuff to do when we are done */
678 endgame:
679         close( tarFd);
680         if ( *(header.name) == '\0' ) {
681                 if (errorFlag==TRUE)
682                         errorMsg( "Error exit delayed from previous errors\n");
683                 else
684                         return( TRUE);
685         } 
686         return( FALSE);
687 }
688
689
690 #ifdef BB_FEATURE_TAR_CREATE
691
692 /* Some info to be carried along when creating a new tarball */
693 struct TarBallInfo
694 {
695         char* fileName;               /* File name of the tarball */
696         int tarFd;                    /* Open-for-write file descriptor
697                                                                          for the tarball */
698         struct stat statBuf;          /* Stat info for the tarball, letting
699                                                                          us know the inode and device that the
700                                                                          tarball lives, so we can avoid trying 
701                                                                          to include the tarball into itself */
702         int verboseFlag;              /* Whether to print extra stuff or not */
703         char** excludeList;           /* List of files to not include */
704 };
705 typedef struct TarBallInfo TarBallInfo;
706
707
708 /* Put an octal string into the specified buffer.
709  * The number is zero and space padded and possibly null padded.
710  * Returns TRUE if successful.  */ 
711 static int putOctal (char *cp, int len, long value)
712 {
713         int tempLength;
714         char tempBuffer[32];
715         char *tempString = tempBuffer;
716
717         /* Create a string of the specified length with an initial space,
718          * leading zeroes and the octal number, and a trailing null.  */
719         sprintf (tempString, "%0*lo", len - 1, value);
720
721         /* If the string is too large, suppress the leading space.  */
722         tempLength = strlen (tempString) + 1;
723         if (tempLength > len) {
724                 tempLength--;
725                 tempString++;
726         }
727
728         /* If the string is still too large, suppress the trailing null.  */
729         if (tempLength > len)
730                 tempLength--;
731
732         /* If the string is still too large, fail.  */
733         if (tempLength > len)
734                 return FALSE;
735
736         /* Copy the string to the field.  */
737         memcpy (cp, tempString, len);
738
739         return TRUE;
740 }
741
742 /* Write out a tar header for the specified file/directory/whatever */
743 static int
744 writeTarHeader(struct TarBallInfo *tbInfo, const char *fileName, struct stat *statbuf)
745 {
746         long chksum=0;
747         struct TarHeader header;
748 #if defined BB_FEATURE_TAR_EXCLUDE
749         char** tmpList;
750 #endif
751         const unsigned char *cp = (const unsigned char *) &header;
752         ssize_t size = sizeof(struct TarHeader);
753                 
754         memset( &header, 0, size);
755
756         if (*fileName=='/') {
757                 static int alreadyWarned=FALSE;
758                 if (alreadyWarned==FALSE) {
759                         errorMsg("Removing leading '/' from member names\n");
760                         alreadyWarned=TRUE;
761                 }
762                 strncpy(header.name, fileName+1, sizeof(header.name)); 
763         }
764         else {
765                 strncpy(header.name, fileName, sizeof(header.name)); 
766         }
767
768 #if defined BB_FEATURE_TAR_EXCLUDE
769         /* Check for excluded files....  */
770         for (tmpList=tbInfo->excludeList; tmpList && *tmpList; tmpList++) {
771                 /* Do some extra hoop jumping for when directory names
772                  * end in '/' but the entry in tmpList doesn't */
773                 if (strncmp( *tmpList, header.name, strlen(*tmpList))==0 || (
774                                         header.name[strlen(header.name)-1]=='/'
775                                         && strncmp( *tmpList, header.name, 
776                                                 MIN(strlen(header.name)-1, strlen(*tmpList)))==0)) {
777                         /* Set the mode to something that is not a regular file, thereby
778                          * faking out writeTarFile into thinking that nothing further need
779                          * be done for this file.  Yes, I know this is ugly, but it works. */
780                         statbuf->st_mode = 0;
781                         return( TRUE);
782                 }
783         }
784 #endif
785
786         putOctal(header.mode, sizeof(header.mode), statbuf->st_mode);
787         putOctal(header.uid, sizeof(header.uid), statbuf->st_uid);
788         putOctal(header.gid, sizeof(header.gid), statbuf->st_gid);
789         putOctal(header.size, sizeof(header.size), 0); /* Regular file size is handled later */
790         putOctal(header.mtime, sizeof(header.mtime), statbuf->st_mtime);
791         strncpy(header.magic, TAR_MAGIC TAR_VERSION, 
792                         TAR_MAGIC_LEN + TAR_VERSION_LEN );
793
794         /* Enter the user and group names (default to root if it fails) */
795         my_getpwuid(header.uname, statbuf->st_uid);
796         if (! *header.uname)
797                 strcpy(header.uname, "root");
798         my_getgrgid(header.gname, statbuf->st_gid);
799         if (! *header.uname)
800                 strcpy(header.uname, "root");
801
802         /* WARNING/NOTICE: I break Hard Links */
803         if (S_ISLNK(statbuf->st_mode)) {
804                 int link_size=0;
805                 char buffer[BUFSIZ];
806                 header.typeflag  = SYMTYPE;
807                 link_size = readlink(fileName, buffer, sizeof(buffer) - 1);
808                 if ( link_size < 0) {
809                         errorMsg("Error reading symlink '%s': %s\n", header.name, strerror(errno));
810                         return ( FALSE);
811                 }
812                 buffer[link_size] = '\0';
813                 strncpy(header.linkname, buffer, sizeof(header.linkname)); 
814         } else if (S_ISDIR(statbuf->st_mode)) {
815                 header.typeflag  = DIRTYPE;
816                 strncat(header.name, "/", sizeof(header.name)); 
817         } else if (S_ISCHR(statbuf->st_mode)) {
818                 header.typeflag  = CHRTYPE;
819                 putOctal(header.devmajor, sizeof(header.devmajor), MAJOR(statbuf->st_rdev));
820                 putOctal(header.devminor, sizeof(header.devminor), MINOR(statbuf->st_rdev));
821         } else if (S_ISBLK(statbuf->st_mode)) {
822                 header.typeflag  = BLKTYPE;
823                 putOctal(header.devmajor, sizeof(header.devmajor), MAJOR(statbuf->st_rdev));
824                 putOctal(header.devminor, sizeof(header.devminor), MINOR(statbuf->st_rdev));
825         } else if (S_ISFIFO(statbuf->st_mode)) {
826                 header.typeflag  = FIFOTYPE;
827         } else if (S_ISREG(statbuf->st_mode)) {
828                 header.typeflag  = REGTYPE;
829                 putOctal(header.size, sizeof(header.size), statbuf->st_size);
830         } else {
831                 errorMsg("%s: Unknown file type\n", fileName);
832                 return ( FALSE);
833         }
834
835         /* Calculate and store the checksum (i.e. the sum of all of the bytes of
836          * the header).  The checksum field must be filled with blanks for the
837          * calculation.  The checksum field is formatted differently from the
838          * other fields: it has [6] digits, a null, then a space -- rather than
839          * digits, followed by a null like the other fields... */
840         memset(header.chksum, ' ', sizeof(header.chksum));
841         cp = (const unsigned char *) &header;
842         while (size-- > 0)
843                 chksum += *cp++;
844         putOctal(header.chksum, 7, chksum);
845         
846         /* Now write the header out to disk */
847         if ((size=fullWrite(tbInfo->tarFd, (char*)&header, sizeof(struct TarHeader))) < 0) {
848                 errorMsg(io_error, fileName, strerror(errno)); 
849                 return ( FALSE);
850         }
851         /* Pad the header up to the tar block size */
852         for (; size<TAR_BLOCK_SIZE; size++) {
853                 write(tbInfo->tarFd, "\0", 1);
854         }
855         /* Now do the verbose thing (or not) */
856         if (tbInfo->verboseFlag==TRUE) {
857                 FILE *vbFd = stdout;
858                 if (tbInfo->tarFd == fileno(stdout))    // If the archive goes to stdout, verbose to stderr
859                         vbFd = stderr;
860                 fprintf(vbFd, "%s\n", header.name);
861         }
862
863         return ( TRUE);
864 }
865
866
867 static int writeFileToTarball(const char *fileName, struct stat *statbuf, void* userData)
868 {
869         struct TarBallInfo *tbInfo = (struct TarBallInfo *)userData;
870
871         /* It is against the rules to archive a socket */
872         if (S_ISSOCK(statbuf->st_mode)) {
873                 errorMsg("%s: socket ignored\n", fileName);
874                 return( TRUE);
875         }
876
877         /* It is a bad idea to store the archive we are in the process of creating,
878          * so check the device and inode to be sure that this particular file isn't
879          * the new tarball */
880         if (tbInfo->statBuf.st_dev == statbuf->st_dev &&
881                         tbInfo->statBuf.st_ino == statbuf->st_ino) {
882                 errorMsg("%s: file is the archive; skipping\n", fileName);
883                 return( TRUE);
884         }
885
886         if (writeTarHeader(tbInfo, fileName, statbuf)==FALSE) {
887                 return( FALSE);
888         } 
889
890         /* Now, if the file is a regular file, copy it out to the tarball */
891         if (S_ISREG(statbuf->st_mode)) {
892                 int  inputFileFd;
893                 char buffer[BUFSIZ];
894                 ssize_t size=0, readSize=0;
895
896                 /* open the file we want to archive, and make sure all is well */
897                 if ((inputFileFd = open(fileName, O_RDONLY)) < 0) {
898                         errorMsg("%s: Cannot open: %s\n", fileName, strerror(errno));
899                         return( FALSE);
900                 }
901                 
902                 /* write the file to the archive */
903                 while ( (size = fullRead(inputFileFd, buffer, sizeof(buffer))) > 0 ) {
904                         if (fullWrite(tbInfo->tarFd, buffer, size) != size ) {
905                                 /* Output file seems to have a problem */
906                                 errorMsg(io_error, fileName, strerror(errno)); 
907                                 return( FALSE);
908                         }
909                         readSize+=size;
910                 }
911                 if (size == -1) {
912                         errorMsg(io_error, fileName, strerror(errno)); 
913                         return( FALSE);
914                 }
915                 /* Pad the file up to the tar block size */
916                 for (; (readSize%TAR_BLOCK_SIZE) != 0; readSize++) {
917                         write(tbInfo->tarFd, "\0", 1);
918                 }
919                 close( inputFileFd);
920         }
921
922         return( TRUE);
923 }
924
925 static int writeTarFile(const char* tarName, int tostdoutFlag, 
926                 int verboseFlag, int argc, char **argv, char** excludeList)
927 {
928         int tarFd=-1;
929         int errorFlag=FALSE;
930         ssize_t size;
931         struct TarBallInfo tbInfo;
932         tbInfo.verboseFlag = verboseFlag;
933
934         /* Make sure there is at least one file to tar up.  */
935         if (argc <= 0)
936                 fatalError("Cowardly refusing to create an empty archive\n");
937
938         /* Open the tar file for writing.  */
939         if (tostdoutFlag == TRUE)
940                 tbInfo.tarFd = fileno(stdout);
941         else
942                 tbInfo.tarFd = open (tarName, O_WRONLY | O_CREAT | O_TRUNC, 0644);
943         if (tbInfo.tarFd < 0) {
944                 errorMsg( "Error opening '%s': %s\n", tarName, strerror(errno));
945                 return ( FALSE);
946         }
947         tbInfo.excludeList=excludeList;
948         /* Store the stat info for the tarball's file, so
949          * can avoid including the tarball into itself....  */
950         if (fstat(tbInfo.tarFd, &tbInfo.statBuf) < 0)
951                 fatalError(io_error, tarName, strerror(errno)); 
952
953         /* Set the umask for this process so it doesn't 
954          * screw up permission setting for us later. */
955         umask(0);
956
957         /* Read the directory/files and iterate over them one at a time */
958         while (argc-- > 0) {
959                 if (recursiveAction(*argv++, TRUE, FALSE, FALSE,
960                                         writeFileToTarball, writeFileToTarball, 
961                                         (void*) &tbInfo) == FALSE) {
962                         errorFlag = TRUE;
963                 }
964         }
965         /* Write two empty blocks to the end of the archive */
966         for (size=0; size<(2*TAR_BLOCK_SIZE); size++) {
967                 write(tbInfo.tarFd, "\0", 1);
968         }
969
970         /* To be pedantically correct, we would check if the tarball
971          * is smaller then 20 tar blocks, and pad it if it was smaller,
972          * but that isn't necessary for GNU tar interoperability, and
973          * so is considered a waste of space */
974
975         /* Hang up the tools, close up shop, head home */
976         close(tarFd);
977         if (errorFlag == TRUE) {
978                 errorMsg("Error exit delayed from previous errors\n");
979                 return(FALSE);
980         }
981         return( TRUE);
982 }
983
984
985 #endif
986