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