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