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