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