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