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