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