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