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