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