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