Update applet define from BB_CP_MV to BB_CP and BB_MV.
[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 #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 static 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 /* Parse the tar header and fill in the nice struct with the details */
480 static int
481 readTarHeader(struct TarHeader *rawHeader, struct TarInfo *header)
482 {
483         int i;
484         long chksum, sum=0;
485         unsigned char *s = (unsigned char *)rawHeader;
486
487         header->name  = rawHeader->name;
488         /* Check for and relativify any absolute paths */
489         if ( *(header->name) == '/' ) {
490                 static int alreadyWarned=FALSE;
491
492                 while (*(header->name) == '/')
493                         ++*(header->name);
494
495                 if (alreadyWarned == FALSE) {
496                         error_msg("Removing leading '/' from member names");
497                         alreadyWarned = TRUE;
498                 }
499         }
500
501         header->mode  = strtol(rawHeader->mode, NULL, 8);
502         header->uid   = strtol(rawHeader->uid, NULL, 8);
503         header->gid   = strtol(rawHeader->gid, NULL, 8);
504         header->size  = strtol(rawHeader->size, NULL, 8);
505         header->mtime = strtol(rawHeader->mtime, NULL, 8);
506         chksum = strtol(rawHeader->chksum, NULL, 8);
507         header->type  = rawHeader->typeflag;
508         header->linkname  = rawHeader->linkname;
509         header->devmajor  = strtol(rawHeader->devmajor, NULL, 8);
510         header->devminor  = strtol(rawHeader->devminor, NULL, 8);
511
512         /* Check the checksum */
513         for (i = sizeof(*rawHeader); i-- != 0;) {
514                 sum += *s++;
515         }
516         /* Remove the effects of the checksum field (replace 
517          * with blanks for the purposes of the checksum) */
518         s = rawHeader->chksum;
519         for (i = sizeof(rawHeader->chksum) ; i-- != 0;) {
520                 sum -= *s++;
521         }
522         sum += ' ' * sizeof(rawHeader->chksum);
523         if (sum == chksum )
524                 return ( TRUE);
525         return( FALSE);
526 }
527
528 static int exclude_file(char **excluded_files, const char *file)
529 {
530         int i;
531
532         if (excluded_files == NULL)
533                 return 0;
534
535         for (i = 0; excluded_files[i] != NULL; i++) {
536                 if (excluded_files[i][0] == '/') {
537                         if (fnmatch(excluded_files[i], file,
538                                                 FNM_PATHNAME | FNM_LEADING_DIR) == 0)
539                                 return 1;
540                 } else {
541                         const char *p;
542
543                         for (p = file; p[0] != '\0'; p++) {
544                                 if ((p == file || p[-1] == '/') && p[0] != '/' &&
545                                                 fnmatch(excluded_files[i], p,
546                                                         FNM_PATHNAME | FNM_LEADING_DIR) == 0)
547                                         return 1;
548                         }
549                 }
550         }
551
552         return 0;
553 }
554
555 static int extract_file(char **extract_files, const char *file)
556 {
557         int i;
558
559         if (extract_files == NULL)
560                 return 1;
561
562         for (i = 0; extract_files[i] != NULL; i++) {
563                 if (fnmatch(extract_files[i], file, FNM_LEADING_DIR) == 0)
564                         return 1;
565         }
566
567         return 0;
568 }
569
570 /*
571  * Read a tar file and extract or list the specified files within it.
572  * If the list is empty than all files are extracted or listed.
573  */
574 static int readTarFile(int tarFd, int extractFlag, int listFlag, 
575                 int tostdoutFlag, int verboseFlag, char** extractList,
576                 char** excludeList)
577 {
578         int status;
579         int errorFlag=FALSE;
580         int skipNextHeaderFlag=FALSE;
581         TarHeader rawHeader;
582         TarInfo header;
583
584         /* Set the umask for this process so it doesn't 
585          * screw up permission setting for us later. */
586         umask(0);
587
588         /* Read the tar file, and iterate over it one file at a time */
589         while ( (status = full_read(tarFd, (char*)&rawHeader, TAR_BLOCK_SIZE)) == TAR_BLOCK_SIZE ) {
590
591                 /* Try to read the header */
592                 if ( readTarHeader(&rawHeader, &header) == FALSE ) {
593                         if ( *(header.name) == '\0' ) {
594                                 goto endgame;
595                         } else {
596                                 errorFlag=TRUE;
597                                 error_msg("Bad tar header, skipping");
598                                 continue;
599                         }
600                 }
601                 if ( *(header.name) == '\0' )
602                                 goto endgame;
603                 header.tarFd = tarFd;
604
605                 /* Skip funky extra GNU headers that precede long files */
606                 if ( (header.type == GNULONGNAME) || (header.type == GNULONGLINK) ) {
607                         skipNextHeaderFlag=TRUE;
608                         if (tarExtractRegularFile(&header, FALSE, FALSE) == FALSE)
609                                 errorFlag = TRUE;
610                         continue;
611                 }
612                 if ( skipNextHeaderFlag == TRUE ) { 
613                         skipNextHeaderFlag=FALSE;
614                         error_msg(name_longer_than_foo, NAME_SIZE); 
615                         if (tarExtractRegularFile(&header, FALSE, FALSE) == FALSE)
616                                 errorFlag = TRUE;
617                         continue;
618                 }
619
620 #if defined BB_FEATURE_TAR_EXCLUDE
621                 if (exclude_file(excludeList, header.name)) {
622                         /* There are not the droids you're looking for, move along */
623                         /* If it is a regular file, pretend to extract it with
624                          * the extractFlag set to FALSE, so the junk in the tarball
625                          * is properly skipped over */
626                         if ( header.type==REGTYPE || header.type==REGTYPE0 ) {
627                                 if (tarExtractRegularFile(&header, FALSE, FALSE) == FALSE)
628                                         errorFlag = TRUE;
629                         }
630                         continue;
631                 }
632 #endif
633
634                 if (!extract_file(extractList, header.name)) {
635                         /* There are not the droids you're looking for, move along */
636                         /* If it is a regular file, pretend to extract it with
637                          * the extractFlag set to FALSE, so the junk in the tarball
638                          * is properly skipped over */
639                         if ( header.type==REGTYPE || header.type==REGTYPE0 ) {
640                                 if (tarExtractRegularFile(&header, FALSE, FALSE) == FALSE)
641                                         errorFlag = TRUE;
642                         }
643                         continue;
644                 }
645
646                 if (listFlag == TRUE) {
647                         /* Special treatment if the list (-t) flag is on */
648                         if (verboseFlag == TRUE) {
649                                 int len, len1;
650                                 char buf[35];
651                                 struct tm *tm = localtime (&(header.mtime));
652
653                                 len=printf("%s ", mode_string(header.mode));
654                                 my_getpwuid(buf, header.uid);
655                                 if (! *buf)
656                                         len+=printf("%d", header.uid);
657                                 else
658                                         len+=printf("%s", buf);
659                                 my_getgrgid(buf, header.gid);
660                                 if (! *buf)
661                                         len+=printf("/%-d ", header.gid);
662                                 else
663                                         len+=printf("/%-s ", buf);
664
665                                 if (header.type==CHRTYPE || header.type==BLKTYPE) {
666                                         len1=snprintf(buf, sizeof(buf), "%ld,%-ld ", 
667                                                         header.devmajor, header.devminor);
668                                 } else {
669                                         len1=snprintf(buf, sizeof(buf), "%lu ", (long)header.size);
670                                 }
671                                 /* Jump through some hoops to make the columns match up */
672                                 for(;(len+len1)<31;len++)
673                                         printf(" ");
674                                 printf(buf);
675
676                                 /* Use ISO 8610 time format */
677                                 if (tm) { 
678                                         printf ("%04d-%02d-%02d %02d:%02d:%02d ", 
679                                                         tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday, 
680                                                         tm->tm_hour, tm->tm_min, tm->tm_sec);
681                                 }
682                         }
683                         printf("%s", header.name);
684                         if (verboseFlag == TRUE) {
685                                 if (header.type==LNKTYPE)       /* If this is a link, say so */
686                                         printf(" link to %s", header.linkname);
687                                 else if (header.type==SYMTYPE)
688                                         printf(" -> %s", header.linkname);
689                         }
690                         printf("\n");
691                 }
692
693                 /* List contents if we are supposed to do that */
694                 if (verboseFlag == TRUE && extractFlag == TRUE) {
695                         /* Now the normal listing */
696                         FILE *vbFd = stdout;
697                         if (tostdoutFlag == TRUE)       // If the archive goes to stdout, verbose to stderr
698                                 vbFd = stderr;
699                         fprintf(vbFd, "%s\n", header.name);
700                 }
701                         
702                 /* Remove files if we would overwrite them */
703                 if (extractFlag == TRUE && tostdoutFlag == FALSE)
704                         unlink(header.name);
705
706                 /* If we got here, we can be certain we have a legitimate 
707                  * header to work with.  So work with it.  */
708                 switch ( header.type ) {
709                         case REGTYPE:
710                         case REGTYPE0:
711                                 /* If the name ends in a '/' then assume it is
712                                  * supposed to be a directory, and fall through */
713                                 if (header.name[strlen(header.name)-1] != '/') {
714                                         if (tarExtractRegularFile(&header, extractFlag, tostdoutFlag)==FALSE)
715                                                 errorFlag=TRUE;
716                                         break;
717                                 }
718                         case DIRTYPE:
719                                 if (tarExtractDirectory( &header, extractFlag, tostdoutFlag)==FALSE)
720                                         errorFlag=TRUE;
721                                 break;
722                         case LNKTYPE:
723                                 if (tarExtractHardLink( &header, extractFlag, tostdoutFlag)==FALSE)
724                                         errorFlag=TRUE;
725                                 break;
726                         case SYMTYPE:
727                                 if (tarExtractSymLink( &header, extractFlag, tostdoutFlag)==FALSE)
728                                         errorFlag=TRUE;
729                                 break;
730                         case CHRTYPE:
731                         case BLKTYPE:
732                         case FIFOTYPE:
733                                 if (tarExtractSpecial( &header, extractFlag, tostdoutFlag)==FALSE)
734                                         errorFlag=TRUE;
735                                 break;
736 #if 0
737                         /* Handled earlier */
738                         case GNULONGNAME:
739                         case GNULONGLINK:
740                                 skipNextHeaderFlag=TRUE;
741                                 break;
742 #endif
743                         default:
744                                 error_msg("Unknown file type '%c' in tar file", header.type);
745                                 close( tarFd);
746                                 return( FALSE);
747                 }
748         }
749         close(tarFd);
750         if (status > 0) {
751                 /* Bummer - we read a partial header */
752                 perror_msg("Error reading tar file");
753                 return ( FALSE);
754         }
755         else if (errorFlag==TRUE) {
756                 error_msg( "Error exit delayed from previous errors");
757                 return( FALSE);
758         } else 
759                 return( status);
760
761         /* Stuff to do when we are done */
762 endgame:
763         close( tarFd);
764         if ( *(header.name) == '\0' ) {
765                 if (errorFlag==TRUE)
766                         error_msg( "Error exit delayed from previous errors");
767                 else
768                         return( TRUE);
769         } 
770         return( FALSE);
771 }
772
773
774 #ifdef BB_FEATURE_TAR_CREATE
775
776 /*
777 ** writeTarFile(),  writeFileToTarball(), and writeTarHeader() are
778 ** the only functions that deal with the HardLinkInfo structure.
779 ** Even these functions use the xxxHardLinkInfo() functions.
780 */
781 typedef struct HardLinkInfo HardLinkInfo;
782 struct HardLinkInfo
783 {
784         HardLinkInfo *next;           /* Next entry in list */
785         dev_t dev;                    /* Device number */
786         ino_t ino;                    /* Inode number */
787         short linkCount;              /* (Hard) Link Count */
788         char name[1];                 /* Start of filename (must be last) */
789 };
790
791 /* Some info to be carried along when creating a new tarball */
792 struct TarBallInfo
793 {
794         char* fileName;               /* File name of the tarball */
795         int tarFd;                    /* Open-for-write file descriptor
796                                                                          for the tarball */
797         struct stat statBuf;          /* Stat info for the tarball, letting
798                                                                          us know the inode and device that the
799                                                                          tarball lives, so we can avoid trying 
800                                                                          to include the tarball into itself */
801         int verboseFlag;              /* Whether to print extra stuff or not */
802         char** excludeList;           /* List of files to not include */
803         HardLinkInfo *hlInfoHead;     /* Hard Link Tracking Information */
804         HardLinkInfo *hlInfo;         /* Hard Link Info for the current file */
805 };
806 typedef struct TarBallInfo TarBallInfo;
807
808
809 /* Might be faster (and bigger) if the dev/ino were stored in numeric order;) */
810 static void
811 addHardLinkInfo (HardLinkInfo **hlInfoHeadPtr, dev_t dev, ino_t ino,
812                 short linkCount, const char *name)
813 {
814         /* Note: hlInfoHeadPtr can never be NULL! */
815         HardLinkInfo *hlInfo;
816
817         hlInfo = (HardLinkInfo *)xmalloc(sizeof(HardLinkInfo)+strlen(name)+1);
818         if (hlInfo) {
819                 hlInfo->next = *hlInfoHeadPtr;
820                 *hlInfoHeadPtr = hlInfo;
821                 hlInfo->dev = dev;
822                 hlInfo->ino = ino;
823                 hlInfo->linkCount = linkCount;
824                 strcpy(hlInfo->name, name);
825         }
826         return;
827 }
828
829 static void
830 freeHardLinkInfo (HardLinkInfo **hlInfoHeadPtr)
831 {
832         HardLinkInfo *hlInfo = NULL;
833         HardLinkInfo *hlInfoNext = NULL;
834
835         if (hlInfoHeadPtr) {
836                 hlInfo = *hlInfoHeadPtr;
837                 while (hlInfo) {
838                         hlInfoNext = hlInfo->next;
839                         free(hlInfo);
840                         hlInfo = hlInfoNext;
841                 }
842                 *hlInfoHeadPtr = NULL;
843         }
844         return;
845 }
846
847 /* Might be faster (and bigger) if the dev/ino were stored in numeric order;) */
848 static HardLinkInfo *
849 findHardLinkInfo (HardLinkInfo *hlInfo, dev_t dev, ino_t ino)
850 {
851         while(hlInfo) {
852                 if ((ino == hlInfo->ino) && (dev == hlInfo->dev))
853                         break;
854                 hlInfo = hlInfo->next;
855         }
856         return(hlInfo);
857 }
858
859 /* Put an octal string into the specified buffer.
860  * The number is zero and space padded and possibly null padded.
861  * Returns TRUE if successful.  */ 
862 static int putOctal (char *cp, int len, long value)
863 {
864         int tempLength;
865         char tempBuffer[32];
866         char *tempString = tempBuffer;
867
868         /* Create a string of the specified length with an initial space,
869          * leading zeroes and the octal number, and a trailing null.  */
870         sprintf (tempString, "%0*lo", len - 1, value);
871
872         /* If the string is too large, suppress the leading space.  */
873         tempLength = strlen (tempString) + 1;
874         if (tempLength > len) {
875                 tempLength--;
876                 tempString++;
877         }
878
879         /* If the string is still too large, suppress the trailing null.  */
880         if (tempLength > len)
881                 tempLength--;
882
883         /* If the string is still too large, fail.  */
884         if (tempLength > len)
885                 return FALSE;
886
887         /* Copy the string to the field.  */
888         memcpy (cp, tempString, len);
889
890         return TRUE;
891 }
892
893 /* Write out a tar header for the specified file/directory/whatever */
894 static int
895 writeTarHeader(struct TarBallInfo *tbInfo, const char *header_name,
896                 const char *real_name, struct stat *statbuf)
897 {
898         long chksum=0;
899         struct TarHeader header;
900         const unsigned char *cp = (const unsigned char *) &header;
901         ssize_t size = sizeof(struct TarHeader);
902                 
903         memset( &header, 0, size);
904
905         strncpy(header.name, header_name, sizeof(header.name)); 
906
907         putOctal(header.mode, sizeof(header.mode), statbuf->st_mode);
908         putOctal(header.uid, sizeof(header.uid), statbuf->st_uid);
909         putOctal(header.gid, sizeof(header.gid), statbuf->st_gid);
910         putOctal(header.size, sizeof(header.size), 0); /* Regular file size is handled later */
911         putOctal(header.mtime, sizeof(header.mtime), statbuf->st_mtime);
912         strncpy(header.magic, TAR_MAGIC TAR_VERSION, 
913                         TAR_MAGIC_LEN + TAR_VERSION_LEN );
914
915         /* Enter the user and group names (default to root if it fails) */
916         my_getpwuid(header.uname, statbuf->st_uid);
917         if (! *header.uname)
918                 strcpy(header.uname, "root");
919         my_getgrgid(header.gname, statbuf->st_gid);
920         if (! *header.uname)
921                 strcpy(header.uname, "root");
922
923         if (tbInfo->hlInfo) {
924                 /* This is a hard link */
925                 header.typeflag = LNKTYPE;
926                 strncpy(header.linkname, tbInfo->hlInfo->name, sizeof(header.linkname));
927         } else if (S_ISLNK(statbuf->st_mode)) {
928                 int link_size=0;
929                 char buffer[BUFSIZ];
930                 header.typeflag  = SYMTYPE;
931                 link_size = readlink(real_name, buffer, sizeof(buffer) - 1);
932                 if ( link_size < 0) {
933                         perror_msg("Error reading symlink '%s'", header.name);
934                         return ( FALSE);
935                 }
936                 buffer[link_size] = '\0';
937                 strncpy(header.linkname, buffer, sizeof(header.linkname)); 
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         /* Set the umask for this process so it doesn't 
1122          * screw up permission setting for us later. */
1123         umask(0);
1124
1125         /* Read the directory/files and iterate over them one at a time */
1126         while (*argv != NULL) {
1127                 if (recursive_action(*argv++, TRUE, FALSE, FALSE,
1128                                         writeFileToTarball, writeFileToTarball, 
1129                                         (void*) &tbInfo) == FALSE) {
1130                         errorFlag = TRUE;
1131                 }
1132         }
1133         /* Write two empty blocks to the end of the archive */
1134         for (size=0; size<(2*TAR_BLOCK_SIZE); size++) {
1135                 write(tbInfo.tarFd, "\0", 1);
1136         }
1137
1138         /* To be pedantically correct, we would check if the tarball
1139          * is smaller than 20 tar blocks, and pad it if it was smaller,
1140          * but that isn't necessary for GNU tar interoperability, and
1141          * so is considered a waste of space */
1142
1143         /* Hang up the tools, close up shop, head home */
1144         close(tarFd);
1145         if (errorFlag == TRUE) {
1146                 error_msg("Error exit delayed from previous errors");
1147                 freeHardLinkInfo(&tbInfo.hlInfoHead);
1148                 return(FALSE);
1149         }
1150         freeHardLinkInfo(&tbInfo.hlInfoHead);
1151         return( TRUE);
1152 }
1153
1154
1155 #endif
1156