My latest ramblings.
[oweals/busybox.git] / tar.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * Mini tar implementation for busybox based on code taken from sash.
4  *
5  * Copyright (c) 1999 by David I. Bell
6  * Permission is granted to use, distribute, or modify this source,
7  * provided that this copyright notice remains intact.
8  *
9  * Permission to distribute this code under the GPL has been granted.
10  *
11  * Modified for busybox by Erik Andersen <andersee@debian.org>
12  * Adjusted to grok stdin/stdout options.
13  *
14  * Modified to handle device special files by Matt Porter
15  * <porter@debian.org>
16  *
17  * This program is free software; you can redistribute it and/or modify
18  * it under the terms of the GNU General Public License as published by
19  * the Free Software Foundation; either version 2 of the License, or
20  * (at your option) any later version.
21  *
22  * This program is distributed in the hope that it will be useful,
23  * but WITHOUT ANY WARRANTY; without even the implied warranty of
24  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
25  * General Public License for more details.
26  *
27  * You should have received a copy of the GNU General Public License
28  * along with this program; if not, write to the Free Software
29  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
30  *
31  */
32
33
34 #include "internal.h"
35 #include <stdio.h>
36 #include <dirent.h>
37 #include <errno.h>
38 #include <fcntl.h>
39 #include <signal.h>
40 #include <time.h>
41 #include <utime.h>
42 #include <sys/types.h>
43 #include <sys/sysmacros.h>
44 #include <sys/param.h>                  /* for PATH_MAX */
45
46
47 #ifdef BB_FEATURE_TAR_CREATE
48
49 static const char tar_usage[] =
50         "tar -[cxtvOf] [tarFileName] [FILE] ...\n\n"
51         "Create, extract, or list files from a tar file.\n\n"
52         "Options:\n"
53
54         "\tc=create, x=extract, t=list contents, v=verbose,\n"
55         "\tO=extract to stdout, f=tarfile or \"-\" for stdin\n";
56
57 #else
58
59 static const char tar_usage[] =
60         "tar -[xtvOf] [tarFileName] [FILE] ...\n\n"
61         "Extract, or list files stored in a tar file.  This\n"
62         "version of tar does not support creation of tar files.\n\n"
63         "Options:\n"
64
65         "\tx=extract, t=list contents, v=verbose,\n"
66         "\tO=extract to stdout, f=tarfile or \"-\" for stdin\n";
67
68 #endif
69
70
71 /* Tar file constants  */
72
73
74 /* POSIX tar Header Block, from POSIX 1003.1-1990  */
75 struct TarHeader
76 {
77                                 /* byte offset */
78         char name[100];               /*   0 */
79         char mode[8];                 /* 100 */
80         char uid[8];                  /* 108 */
81         char gid[8];                  /* 116 */
82         char size[12];                /* 124 */
83         char mtime[12];               /* 136 */
84         char chksum[8];               /* 148 */
85         char typeflag;                /* 156 */
86         char linkname[100];           /* 157 */
87         char magic[6];                /* 257 */
88         char version[2];              /* 263 */
89         char uname[32];               /* 265 */
90         char gname[32];               /* 297 */
91         char devmajor[8];             /* 329 */
92         char devminor[8];             /* 337 */
93         char prefix[155];             /* 345 */
94         /* padding                       500 */
95 };
96 typedef struct TarHeader TarHeader;
97
98
99 /* A few useful constants */
100 #define TAR_MAGIC          "ustar"        /* ustar and a null */
101 #define TAR_VERSION        "00"           /* 00 and no null */
102 #define TAR_MAGIC_LEN       6
103 #define TAR_VERSION_LEN     2
104 #define TAR_NAME_LEN        100
105 #define TAR_BLOCK_SIZE      512
106
107 /* A nice enum with all the possible tar file content types */
108 enum TarFileType 
109 {
110         REGTYPE  = '0',            /* regular file */
111         REGTYPE0 = '\0',           /* regular file (ancient bug compat)*/
112         LNKTYPE  = '1',            /* hard link */
113         SYMTYPE  = '2',            /* symbolic link */
114         CHRTYPE  = '3',            /* character special */
115         BLKTYPE  = '4',            /* block special */
116         DIRTYPE  = '5',            /* directory */
117         FIFOTYPE = '6',            /* FIFO special */
118         CONTTYPE = '7',            /* reserved */
119 };
120 typedef enum TarFileType TarFileType;
121
122 /* This struct ignores magic, non-numeric user name, 
123  * non-numeric group name, and the checksum, since
124  * these are all ignored by BusyBox tar. */ 
125 struct TarInfo
126 {
127         int              tarFd;          /* An open file descriptor for reading from the tarball */
128         char *           name;           /* File name */
129         mode_t           mode;           /* Unix mode, including device bits. */
130         uid_t            uid;            /* Numeric UID */
131         gid_t            gid;            /* Numeric GID */
132         size_t           size;           /* Size of file */
133         time_t           mtime;          /* Last-modified time */
134         enum TarFileType type;           /* Regular, directory, link, etc */
135         char *           linkname;       /* Name for symbolic and hard links */
136         dev_t            device;         /* Special device for mknod() */
137 };
138 typedef struct TarInfo TarInfo;
139
140 /* Static data  */
141 static const unsigned long TarChecksumOffset = (const unsigned long)&(((TarHeader *)0)->chksum);
142
143
144 /*
145  * Static data.
146  */
147 static int inHeader;                    // <- check me
148 static int badHeader;
149 static int skipFileFlag;
150 static int warnedRoot;
151 static int eofFlag;
152 static long dataCc;
153 static int outFd;
154 static const char *outName;
155
156 static int mode;
157 static int uid;
158 static int gid;
159 static time_t mtime;
160
161 /*
162  * Static data associated with the tar file.
163  */
164 static int tarFd;
165 static dev_t tarDev;
166 static ino_t tarInode;
167
168
169 /*
170  * Local procedures to restore files from a tar file.
171  */
172 static int readTarFile(const char* tarName, int extractFlag, int listFlag, 
173                 int tostdoutFlag, int verboseFlag);
174 static void readData(const char *cp, int count);
175 static long getOctal(const char *cp, int len);
176 static int parseTarHeader(struct TarHeader *rawHeader, struct TarInfo *header);
177 static int wantFileName(const char *fileName,
178                                                 int argc, char **argv);
179
180 #ifdef BB_FEATURE_TAR_CREATE
181 /*
182  * Local procedures to save files into a tar file.
183  */
184 static void saveFile(const char *fileName, int seeLinks);
185 static void saveRegularFile(const char *fileName,
186                                                         const struct stat *statbuf);
187 static void saveDirectory(const char *fileName,
188                                                   const struct stat *statbuf);
189 static void writeHeader(const char *fileName, const struct stat *statbuf);
190 static void writeTarFile(int argc, char **argv);
191 static void writeTarBlock(const char *buf, int len);
192 static int putOctal(char *cp, int len, long value);
193
194 #endif
195
196
197 extern int tar_main(int argc, char **argv)
198 {
199         const char *tarName=NULL;
200         const char *options;
201         int listFlag     = FALSE;
202         int extractFlag  = FALSE;
203         int createFlag   = FALSE;
204         int verboseFlag  = FALSE;
205         int tostdoutFlag = FALSE;
206
207         argc--;
208         argv++;
209
210         if (argc < 1)
211                 usage(tar_usage);
212
213         /* Parse options  */
214         if (**argv == '-')
215                 options = (*argv++) + 1;
216         else
217                 options = (*argv++);
218         argc--;
219
220         for (; *options; options++) {
221                 switch (*options) {
222                 case 'f':
223                         if (tarName != NULL)
224                                 fatalError( "Only one 'f' option allowed\n");
225
226                         tarName = *argv++;
227                         if (tarName == NULL)
228                                 fatalError( "Option requires an argument: No file specified\n");
229                         argc--;
230
231                         break;
232
233                 case 't':
234                         if (extractFlag == TRUE || createFlag == TRUE)
235                                 goto flagError;
236                         listFlag = TRUE;
237                         break;
238
239                 case 'x':
240                         if (listFlag == TRUE || createFlag == TRUE)
241                                 goto flagError;
242                         extractFlag = TRUE;
243                         break;
244                 case 'c':
245                         if (extractFlag == TRUE || listFlag == TRUE)
246                                 goto flagError;
247                         createFlag = TRUE;
248                         break;
249
250                 case 'v':
251                         verboseFlag = TRUE;
252                         break;
253
254                 case 'O':
255                         tostdoutFlag = TRUE;
256                         break;
257
258                 case '-':
259                         usage(tar_usage);
260                         break;
261
262                 default:
263                         fatalError( "Unknown tar flag '%c'\n" 
264                                         "Try `tar --help' for more information\n", *options);
265                 }
266         }
267
268         /* 
269          * Do the correct type of action supplying the rest of the
270          * command line arguments as the list of files to process.
271          */
272         if (createFlag == TRUE) {
273 #ifndef BB_FEATURE_TAR_CREATE
274                 fatalError( "This version of tar was not compiled with tar creation support.\n");
275 #else
276                 exit(writeTarFile(argc, argv));
277 #endif
278         } else {
279                 exit(readTarFile(tarName, extractFlag, listFlag, tostdoutFlag, verboseFlag));
280         }
281
282   flagError:
283         fatalError( "Exactly one of 'c', 'x' or 't' must be specified\n");
284 }
285                                         
286 static void
287 tarExtractRegularFile(TarInfo *header, int extractFlag, int listFlag, int tostdoutFlag, int verboseFlag)
288 {
289
290 }
291
292
293 /*
294  * Read a tar file and extract or list the specified files within it.
295  * If the list is empty than all files are extracted or listed.
296  */
297 static int readTarFile(const char* tarName, int extractFlag, int listFlag, 
298                 int tostdoutFlag, int verboseFlag)
299 {
300         int status, tarFd=0;
301         int errorFlag=FALSE;
302         TarHeader rawHeader;
303         TarInfo header;
304
305         /* Open the tar file for reading.  */
306         if (!strcmp(tarName, "-"))
307                 tarFd = fileno(stdin);
308         else
309                 tarFd = open(tarName, O_RDONLY);
310         if (tarFd < 0) {
311                 errorMsg( "Error opening '%s': %s", tarName, strerror(errno));
312                 return ( FALSE);
313         }
314
315         /* Read the tar file */
316         while ( (status = fullRead(tarFd, (char*)&rawHeader, TAR_BLOCK_SIZE)) == TAR_BLOCK_SIZE ) {
317                 /* Now see if the header looks ok */
318                 if ( parseTarHeader(&rawHeader, &header) == FALSE ) {
319                         close( tarFd);
320                         if ( *(header.name) == '\0' ) {
321                                 goto endgame;
322                         } else {
323                                 errorFlag=TRUE;
324                                 errorMsg("Bad tar header, skipping\n");
325                                 continue;
326                         }
327                 }
328                 if ( *(header.name) == '\0' )
329                                 goto endgame;
330
331                 /* If we got here, we can be certain we have a legitimate 
332                  * header to work with.  So work with it.  */
333                 switch ( header.type ) {
334                         case REGTYPE:
335                         case REGTYPE0:
336                                 /* If the name ends in a '/' then assume it is
337                                  * supposed to be a directory, and fall through */
338                                 if (header.name[strlen(header.name)-1] != '/') {
339                                         tarExtractRegularFile(&header, extractFlag, listFlag, tostdoutFlag, verboseFlag);
340                                         break;
341                                 }
342 #if 0
343                         case Directory:
344                                 tarExtractDirectory( &header, extractFlag, listFlag, tostdoutFlag, verboseFlag);
345                                 break;
346                         case HardLink:
347                                 tarExtractHardLink( &header, extractFlag, listFlag, tostdoutFlag, verboseFlag);
348                                 break;
349                         case SymbolicLink:
350                                 tarExtractSymLink( &header, extractFlag, listFlag, tostdoutFlag, verboseFlag);
351                                 break;
352                         case CharacterDevice:
353                         case BlockDevice:
354                         case FIFO:
355                                 tarExtractSpecial( &header, extractFlag, listFlag, tostdoutFlag, verboseFlag);
356                                 break;
357 #endif
358                         default:
359                                 close( tarFd);
360                                 return( FALSE);
361                 }
362         }
363
364         close(tarFd);
365         if (status > 0) {
366                 /* Bummer - we read a partial header */
367                 errorMsg( "Error reading '%s': %s", tarName, strerror(errno));
368                 return ( FALSE);
369         }
370         else 
371                 return( status);
372
373         /* Stuff we do when we know we are done with the file */
374 endgame:
375         close( tarFd);
376         if ( *(header.name) == '\0' ) {
377                 if (errorFlag==FALSE)
378                         return( TRUE);
379         } 
380         return( FALSE);
381 }
382
383 /*
384  * Read an octal value in a field of the specified width, with optional
385  * spaces on both sides of the number and with an optional null character
386  * at the end.  Returns -1 on an illegal format.
387  */
388 static long getOctal(const char *cp, int size)
389 {
390         long val = 0;
391
392         for(;(size > 0) && (*cp == ' '); cp++, size--);
393         if ((size == 0) || !isOctal(*cp))
394                 return -1;
395         for(; (size > 0) && isOctal(*cp); size--) {
396                 val = val * 8 + *cp++ - '0';
397         }
398         for (;(size > 0) && (*cp == ' '); cp++, size--);
399         if ((size > 0) && *cp)
400                 return -1;
401         return val;
402 }
403
404 /* Parse the tar header and fill in the nice struct with the details */
405 static int
406 parseTarHeader(struct TarHeader *rawHeader, struct TarInfo *header)
407 {
408         long major, minor, chksum, sum;
409
410         header->name  = rawHeader->name;
411         header->mode  = getOctal(rawHeader->mode, sizeof(rawHeader->mode));
412         header->uid   =  getOctal(rawHeader->uid, sizeof(rawHeader->uid));
413         header->gid   =  getOctal(rawHeader->gid, sizeof(rawHeader->gid));
414         header->size  = getOctal(rawHeader->size, sizeof(rawHeader->size));
415         header->mtime = getOctal(rawHeader->mtime, sizeof(rawHeader->mtime));
416         chksum = getOctal(rawHeader->chksum, sizeof(rawHeader->chksum));
417         header->type  = rawHeader->typeflag;
418         header->linkname  = rawHeader->linkname;
419         header->device  = MAJOR(getOctal(rawHeader->devmajor, sizeof(rawHeader->devmajor))) |
420                 MINOR(getOctal(rawHeader->devminor, sizeof(rawHeader->devminor)));
421
422         /* Check the checksum */
423         sum = ' ' * sizeof(rawHeader->chksum);
424         for ( i = TarChecksumOffset; i > 0; i-- )
425                 sum += *s++;
426         s += sizeof(h->chksum);       
427         for ( i = (512 - TarChecksumOffset - sizeof(h->chksum)); i > 0; i-- )
428                 sum += *s++;
429         if (sum == checksum )
430                 return ( TRUE);
431         return( FALSE);
432 }
433
434 #if 0
435         if ((header->mode < 0) || (header->uid < 0) || 
436                         (header->gid < 0) || (header->size < 0)) {
437                 errorMsg(stderr, "Bad tar header, skipping\n");
438                 return( FALSE);
439         }
440
441         badHeader = FALSE;
442         skipFileFlag = FALSE;
443         devFileFlag = FALSE;
444
445         /* 
446          * Check for the file modes.
447          */
448         hardLink = ((hp->typeFlag == TAR_TYPE_HARD_LINK) ||
449                                 (hp->typeFlag == TAR_TYPE_HARD_LINK - '0'));
450
451         softLink = ((hp->typeFlag == TAR_TYPE_SOFT_LINK) ||
452                                 (hp->typeFlag == TAR_TYPE_SOFT_LINK - '0'));
453
454         /* 
455          * Check for a directory.
456          */
457         if (outName[strlen(outName) - 1] == '/')
458                 mode |= S_IFDIR;
459
460         /* 
461          * Check for absolute paths in the file.
462          * If we find any, then warn the user and make them relative.
463          */
464         if (*outName == '/') {
465                 while (*outName == '/')
466                         outName++;
467
468                 if (warnedRoot == FALSE) {
469                         fprintf(stderr,
470                                         "Absolute path detected, removing leading slashes\n");
471                 }
472
473                 warnedRoot = TRUE;
474         }
475
476         /* 
477          * See if we want this file to be restored.
478          * If not, then set up to skip it.
479          */
480         if (wantFileName(outName, argc, argv) == FALSE) {
481                 if (!hardLink && !softLink && (S_ISREG(mode) || S_ISCHR(mode)
482                                                                            || S_ISBLK(mode) || S_ISSOCK(mode)
483                                                                            || S_ISFIFO(mode))) {
484                         inHeader = (size == 0) ? TRUE : FALSE;
485                         dataCc = size;
486                 }
487
488                 skipFileFlag = TRUE;
489
490                 return;
491         }
492
493         /* 
494          * This file is to be handled.
495          * If we aren't extracting then just list information about the file.
496          */
497         if (extractFlag == FALSE) {
498                 if (verboseFlag == TRUE) {
499                         printf("%s %3d/%-d ", modeString(mode), uid, gid);
500                         if (S_ISCHR(mode) || S_ISBLK(mode))
501                                 printf("%4d,%4d %s ", major, minor, timeString(mtime));
502                         else
503                                 printf("%9ld %s ", size, timeString(mtime));
504                 }
505                 printf("%s", outName);
506
507                 if (hardLink)
508                         printf(" (link to \"%s\")", hp->linkName);
509                 else if (softLink)
510                         printf(" (symlink to \"%s\")", hp->linkName);
511                 else if (S_ISREG(mode) || S_ISCHR(mode) || S_ISBLK(mode) ||
512                                  S_ISSOCK(mode) || S_ISFIFO(mode)) {
513                         inHeader = (size == 0) ? TRUE : FALSE;
514                         dataCc = size;
515                 }
516
517                 printf("\n");
518
519                 return;
520         }
521
522         /* 
523          * We really want to extract the file.
524          */
525         if (verboseFlag == TRUE)
526                 printf("x %s\n", outName);
527
528         if (hardLink) {
529                 if (link(hp->linkName, outName) < 0) {
530                         perror(outName);
531                         return;
532                 }
533                 /* Set the file time */
534                 utb.actime = mtime;
535                 utb.modtime = mtime;
536                 utime(outName, &utb);
537                 /* Set the file permissions */
538                 chown(outName, uid, gid);
539                 chmod(outName, mode);
540                 return;
541         }
542
543         if (softLink) {
544 #ifdef  S_ISLNK
545                 if (symlink(hp->linkName, outName) < 0) {
546                         perror(outName);
547                         return;
548                 }
549                 /* Try to change ownership of the symlink.
550                  * If libs doesn't support that, don't bother.
551                  * Changing the pointed-to file is the Wrong Thing(tm).
552                  */
553 #if (__GLIBC__ >= 2) && (__GLIBC_MINOR__ >= 1)
554                 lchown(outName, uid, gid);
555 #endif
556
557                 /* Do not change permissions or date on symlink,
558                  * since it changes the pointed to file instead.  duh. */
559 #else
560                 fprintf(stderr, "Cannot create symbolic links\n");
561 #endif
562                 return;
563         }
564
565         /* Set the umask for this process so it doesn't 
566          * screw things up. */
567         umask(0);
568
569         /* 
570          * If the file is a directory, then just create the path.
571          */
572         if (S_ISDIR(mode)) {
573                 if (createPath(outName, mode) == TRUE) {
574                         /* make the final component, just in case it was
575                          * omitted by createPath() (which will skip the
576                          * directory if it doesn't have a terminating '/')
577                          */
578                         mkdir(outName, mode);
579
580                         /* Set the file time */
581                         utb.actime = mtime;
582                         utb.modtime = mtime;
583                         utime(outName, &utb);
584                         /* Set the file permissions */
585                         chown(outName, uid, gid);
586                         chmod(outName, mode);
587                         return;
588                 }
589                 return;
590         }
591
592         /* 
593          * There is a file to write.
594          * First create the path to it if necessary with default permissions.
595          */
596         createPath(outName, 0777);
597
598         inHeader = (size == 0) ? TRUE : FALSE;
599         dataCc = size;
600
601         /* 
602          * Start the output file.
603          */
604         if (tostdoutFlag == TRUE)
605                 outFd = fileno(stdout);
606         else {
607                 if (S_ISCHR(mode) || S_ISBLK(mode) || S_ISSOCK(mode)) {
608                         devFileFlag = TRUE;
609                         outFd = mknod(outName, mode, makedev(major, minor));
610                 } else if (S_ISFIFO(mode)) {
611                         devFileFlag = TRUE;
612                         outFd = mkfifo(outName, mode);
613                 } else {
614                         outFd = open(outName, O_WRONLY | O_CREAT | O_TRUNC, mode);
615                 }
616                 if (outFd < 0) {
617                         perror(outName);
618                         skipFileFlag = TRUE;
619                         return;
620                 }
621                 /* Set the file time */
622                 utb.actime = mtime;
623                 utb.modtime = mtime;
624                 utime(outName, &utb);
625                 /* Set the file permissions */
626                 chown(outName, uid, gid);
627                 chmod(outName, mode);
628         }
629
630
631         /* 
632          * If the file is empty, then that's all we need to do.
633          */
634         if (size == 0 && (tostdoutFlag == FALSE) && (devFileFlag == FALSE)) {
635                 close(outFd);
636                 outFd = -1;
637         }
638 }
639
640
641 /*
642  * Handle a data block of some specified size that was read.
643  */
644 static void readData(const char *cp, int count)
645 {
646         /* 
647          * Reduce the amount of data left in this file.
648          * If there is no more data left, then we need to read
649          * the header again.
650          */
651         dataCc -= count;
652
653         if (dataCc <= 0)
654                 inHeader = TRUE;
655
656         /* 
657          * If we aren't extracting files or this file is being
658          * skipped then do nothing more.
659          */
660         if (extractFlag == FALSE || skipFileFlag == TRUE)
661                 return;
662
663         /* 
664          * Write the data to the output file.
665          */
666         if (fullWrite(outFd, cp, count) < 0) {
667                 perror(outName);
668                 if (tostdoutFlag == FALSE) {
669                         close(outFd);
670                         outFd = -1;
671                 }
672                 skipFileFlag = TRUE;
673                 return;
674         }
675
676         /* 
677          * Check if we are done writing to the file now.
678          */
679         if (dataCc <= 0 && tostdoutFlag == FALSE) {
680                 struct utimbuf utb;
681
682                 if (close(outFd))
683                         perror(outName);
684
685                 /* Set the file time */
686                 utb.actime = mtime;
687                 utb.modtime = mtime;
688                 utime(outName, &utb);
689                 /* Set the file permissions */
690                 chown(outName, uid, gid);
691                 chmod(outName, mode);
692
693                 outFd = -1;
694         }
695 }
696
697
698 /*
699  * See if the specified file name belongs to one of the specified list
700  * of path prefixes.  An empty list implies that all files are wanted.
701  * Returns TRUE if the file is selected.
702  */
703 static int
704 wantFileName(const char *fileName, int argc, char **argv)
705 {
706         const char *pathName;
707         int fileLength;
708         int pathLength;
709
710         /* 
711          * If there are no files in the list, then the file is wanted.
712          */
713         if (argc == 0)
714                 return TRUE;
715
716         fileLength = strlen(fileName);
717
718         /* 
719          * Check each of the test paths.
720          */
721         while (argc-- > 0) {
722                 pathName = *argv++;
723
724                 pathLength = strlen(pathName);
725
726                 if (fileLength < pathLength)
727                         continue;
728
729                 if (memcmp(fileName, pathName, pathLength) != 0)
730                         continue;
731
732                 if ((fileLength == pathLength) || (fileName[pathLength] == '/')) {
733                         return TRUE;
734                 }
735         }
736
737         return FALSE;
738 }
739
740
741 /* From here to the end of the file is the tar writing stuff.
742  * If you do not have BB_FEATURE_TAR_CREATE defined, this will
743  * not be built.
744  * */
745 #ifdef BB_FEATURE_TAR_CREATE
746
747 /*
748  * Write a tar file containing the specified files.
749  */
750 static void writeTarFile(int argc, char **argv)
751 {
752         struct stat statbuf;
753
754         /* 
755          * Make sure there is at least one file specified.
756          */
757         if (argc <= 0) {
758                 fprintf(stderr, "No files specified to be saved\n");
759                 errorFlag = TRUE;
760         }
761
762         /* 
763          * Create the tar file for writing.
764          */
765         if ((tarName == NULL) || !strcmp(tarName, "-")) {
766                 tostdoutFlag = TRUE;
767                 tarFd = fileno(stdout);
768         } else
769                 tarFd = open(tarName, O_WRONLY | O_CREAT | O_TRUNC, 0666);
770
771         if (tarFd < 0) {
772                 perror(tarName);
773                 errorFlag = TRUE;
774                 return;
775         }
776
777         /* 
778          * Get the device and inode of the tar file for checking later.
779          */
780         if (fstat(tarFd, &statbuf) < 0) {
781                 perror(tarName);
782                 errorFlag = TRUE;
783                 goto done;
784         }
785
786         tarDev = statbuf.st_dev;
787         tarInode = statbuf.st_ino;
788
789         /* 
790          * Append each file name into the archive file.
791          * Follow symbolic links for these top level file names.
792          */
793         while (errorFlag == FALSE && (argc-- > 0)) {
794                 saveFile(*argv++, FALSE);
795         }
796
797         /* 
798          * Now write an empty block of zeroes to end the archive.
799          */
800         writeTarBlock("", 1);
801
802
803   done:
804         /* 
805          * Close the tar file and check for errors if it was opened.
806          */
807         if ((tostdoutFlag == FALSE) && (tarFd >= 0) && (close(tarFd) < 0))
808                 perror(tarName);
809 }
810
811 /*
812  * Save one file into the tar file.
813  * If the file is a directory, then this will recursively save all of
814  * the files and directories within the directory.  The seeLinks
815  * flag indicates whether or not we want to see symbolic links as
816  * they really are, instead of blindly following them.
817  */
818 static void saveFile(const char *fileName, int seeLinks)
819 {
820         int status;
821         struct stat statbuf;
822
823         if (verboseFlag == TRUE)
824                 printf("a %s\n", fileName);
825
826         /* 
827          * Check that the file name will fit in the header.
828          */
829         if (strlen(fileName) >= TAR_NAME_SIZE) {
830                 fprintf(stderr, "%s: File name is too long\n", fileName);
831
832                 return;
833         }
834
835         /* 
836          * Find out about the file.
837          */
838 #ifdef  S_ISLNK
839         if (seeLinks == TRUE)
840                 status = lstat(fileName, &statbuf);
841         else
842 #endif
843                 status = stat(fileName, &statbuf);
844
845         if (status < 0) {
846                 perror(fileName);
847
848                 return;
849         }
850
851         /* 
852          * Make sure we aren't trying to save our file into itself.
853          */
854         if ((statbuf.st_dev == tarDev) && (statbuf.st_ino == tarInode)) {
855                 fprintf(stderr, "Skipping saving of archive file itself\n");
856
857                 return;
858         }
859
860         /* 
861          * Check the type of file.
862          */
863         mode = statbuf.st_mode;
864
865         if (S_ISDIR(mode)) {
866                 saveDirectory(fileName, &statbuf);
867
868                 return;
869         }
870         if (S_ISREG(mode)) {
871                 saveRegularFile(fileName, &statbuf);
872
873                 return;
874         }
875
876         /* Some day add support for tarring these up... but not today. :) */
877 //  if (S_ISLNK(mode) || S_ISFIFO(mode) || S_ISBLK(mode) || S_ISCHR (mode) ) {
878 //  fprintf (stderr, "%s: This version of tar can't store this type of file\n", fileName);
879 //  }
880
881         /* 
882          * The file is a strange type of file, ignore it.
883          */
884         fprintf(stderr, "%s: not a directory or regular file\n", fileName);
885 }
886
887
888 /*
889  * Save a regular file to the tar file.
890  */
891 static void
892 saveRegularFile(const char *fileName, const struct stat *statbuf)
893 {
894         int sawEof;
895         int fileFd;
896         int cc;
897         int dataCount;
898         long fullDataCount;
899         char data[TAR_BLOCK_SIZE * 16];
900
901         /* 
902          * Open the file for reading.
903          */
904         fileFd = open(fileName, O_RDONLY);
905
906         if (fileFd < 0) {
907                 perror(fileName);
908
909                 return;
910         }
911
912         /* 
913          * Write out the header for the file.
914          */
915         writeHeader(fileName, statbuf);
916
917         /* 
918          * Write the data blocks of the file.
919          * We must be careful to write the amount of data that the stat
920          * buffer indicated, even if the file has changed size.  Otherwise
921          * the tar file will be incorrect.
922          */
923         fullDataCount = statbuf->st_size;
924         sawEof = FALSE;
925
926         while (fullDataCount > 0) {
927                 /* 
928                  * Get the amount to write this iteration which is
929                  * the minumum of the amount left to write and the
930                  * buffer size.
931                  */
932                 dataCount = sizeof(data);
933
934                 if (dataCount > fullDataCount)
935                         dataCount = (int) fullDataCount;
936
937                 /* 
938                  * Read the data from the file if we haven't seen the
939                  * end of file yet.
940                  */
941                 cc = 0;
942
943                 if (sawEof == FALSE) {
944                         cc = fullRead(fileFd, data, dataCount);
945
946                         if (cc < 0) {
947                                 perror(fileName);
948
949                                 (void) close(fileFd);
950                                 errorFlag = TRUE;
951
952                                 return;
953                         }
954
955                         /* 
956                          * If the file ended too soon, complain and set
957                          * a flag so we will zero fill the rest of it.
958                          */
959                         if (cc < dataCount) {
960                                 fprintf(stderr, "%s: Short read - zero filling", fileName);
961
962                                 sawEof = TRUE;
963                         }
964                 }
965
966                 /* 
967                  * Zero fill the rest of the data if necessary.
968                  */
969                 if (cc < dataCount)
970                         memset(data + cc, 0, dataCount - cc);
971
972                 /* 
973                  * Write the buffer to the TAR file.
974                  */
975                 writeTarBlock(data, dataCount);
976
977                 fullDataCount -= dataCount;
978         }
979
980         /* 
981          * Close the file.
982          */
983         if ((tostdoutFlag == FALSE) && close(fileFd) < 0)
984                 fprintf(stderr, "%s: close: %s\n", fileName, strerror(errno));
985 }
986
987
988 /*
989  * Save a directory and all of its files to the tar file.
990  */
991 static void saveDirectory(const char *dirName, const struct stat *statbuf)
992 {
993         DIR *dir;
994         struct dirent *entry;
995         int needSlash;
996         char fullName[PATH_MAX + 1];
997
998         /* 
999          * Construct the directory name as used in the tar file by appending
1000          * a slash character to it.
1001          */
1002         strcpy(fullName, dirName);
1003         strcat(fullName, "/");
1004
1005         /* 
1006          * Write out the header for the directory entry.
1007          */
1008         writeHeader(fullName, statbuf);
1009
1010         /* 
1011          * Open the directory.
1012          */
1013         dir = opendir(dirName);
1014
1015         if (dir == NULL) {
1016                 fprintf(stderr, "Cannot read directory \"%s\": %s\n",
1017                                 dirName, strerror(errno));
1018
1019                 return;
1020         }
1021
1022         /* 
1023          * See if a slash is needed.
1024          */
1025         needSlash = (*dirName && (dirName[strlen(dirName) - 1] != '/'));
1026
1027         /* 
1028          * Read all of the directory entries and check them,
1029          * except for the current and parent directory entries.
1030          */
1031         while (errorFlag == FALSE && ((entry = readdir(dir)) != NULL)) {
1032                 if ((strcmp(entry->d_name, ".") == 0) ||
1033                         (strcmp(entry->d_name, "..") == 0)) {
1034                         continue;
1035                 }
1036
1037                 /* 
1038                  * Build the full path name to the file.
1039                  */
1040                 strcpy(fullName, dirName);
1041
1042                 if (needSlash)
1043                         strcat(fullName, "/");
1044
1045                 strcat(fullName, entry->d_name);
1046
1047                 /* 
1048                  * Write this file to the tar file, noticing whether or not
1049                  * the file is a symbolic link.
1050                  */
1051                 saveFile(fullName, TRUE);
1052         }
1053
1054         /* 
1055          * All done, close the directory.
1056          */
1057         closedir(dir);
1058 }
1059
1060
1061 /*
1062  * Write a tar header for the specified file name and status.
1063  * It is assumed that the file name fits.
1064  */
1065 static void writeHeader(const char *fileName, const struct stat *statbuf)
1066 {
1067         long checkSum;
1068         const unsigned char *cp;
1069         int len;
1070         TarHeader header;
1071
1072         /* 
1073          * Zero the header block in preparation for filling it in.
1074          */
1075         memset((char *) &header, 0, sizeof(header));
1076
1077         /* 
1078          * Fill in the header.
1079          */
1080         strcpy(header.name, fileName);
1081
1082         strncpy(header.magic, TAR_MAGIC, sizeof(header.magic));
1083         strncpy(header.version, TAR_VERSION, sizeof(header.version));
1084
1085         putOctal(header.mode, sizeof(header.mode), statbuf->st_mode & 0777);
1086         putOctal(header.uid, sizeof(header.uid), statbuf->st_uid);
1087         putOctal(header.gid, sizeof(header.gid), statbuf->st_gid);
1088         putOctal(header.size, sizeof(header.size), statbuf->st_size);
1089         putOctal(header.mtime, sizeof(header.mtime), statbuf->st_mtime);
1090
1091         header.typeFlag = TAR_TYPE_REGULAR;
1092
1093         /* 
1094          * Calculate and store the checksum.
1095          * This is the sum of all of the bytes of the header,
1096          * with the checksum field itself treated as blanks.
1097          */
1098         memset(header.checkSum, ' ', sizeof(header.checkSum));
1099
1100         cp = (const unsigned char *) &header;
1101         len = sizeof(header);
1102         checkSum = 0;
1103
1104         while (len-- > 0)
1105                 checkSum += *cp++;
1106
1107         putOctal(header.checkSum, sizeof(header.checkSum), checkSum);
1108
1109         /* 
1110          * Write the tar header.
1111          */
1112         writeTarBlock((const char *) &header, sizeof(header));
1113 }
1114
1115
1116 /*
1117  * Write data to one or more blocks of the tar file.
1118  * The data is always padded out to a multiple of TAR_BLOCK_SIZE.
1119  * The errorFlag static variable is set on an error.
1120  */
1121 static void writeTarBlock(const char *buf, int len)
1122 {
1123         int partialLength;
1124         int completeLength;
1125         char fullBlock[TAR_BLOCK_SIZE];
1126
1127         /* 
1128          * If we had a write error before, then do nothing more.
1129          */
1130         if (errorFlag == TRUE)
1131                 return;
1132
1133         /* 
1134          * Get the amount of complete and partial blocks.
1135          */
1136         partialLength = len % TAR_BLOCK_SIZE;
1137         completeLength = len - partialLength;
1138
1139         /* 
1140          * Write all of the complete blocks.
1141          */
1142         if ((completeLength > 0) && !fullWrite(tarFd, buf, completeLength)) {
1143                 perror(tarName);
1144
1145                 errorFlag = TRUE;
1146
1147                 return;
1148         }
1149
1150         /* 
1151          * If there are no partial blocks left, we are done.
1152          */
1153         if (partialLength == 0)
1154                 return;
1155
1156         /* 
1157          * Copy the partial data into a complete block, and pad the rest
1158          * of it with zeroes.
1159          */
1160         memcpy(fullBlock, buf + completeLength, partialLength);
1161         memset(fullBlock + partialLength, 0, TAR_BLOCK_SIZE - partialLength);
1162
1163         /* 
1164          * Write the last complete block.
1165          */
1166         if (!fullWrite(tarFd, fullBlock, TAR_BLOCK_SIZE)) {
1167                 perror(tarName);
1168
1169                 errorFlag = TRUE;
1170         }
1171 }
1172
1173
1174 /*
1175  * Put an octal string into the specified buffer.
1176  * The number is zero and space padded and possibly null padded.
1177  * Returns TRUE if successful.
1178  */
1179 static int putOctal(char *cp, int len, long value)
1180 {
1181         int tempLength;
1182         char *tempString;
1183         char tempBuffer[32];
1184
1185         /* 
1186          * Create a string of the specified length with an initial space,
1187          * leading zeroes and the octal number, and a trailing null.
1188          */
1189         tempString = tempBuffer;
1190
1191         sprintf(tempString, " %0*lo", len - 2, value);
1192
1193         tempLength = strlen(tempString) + 1;
1194
1195         /* 
1196          * If the string is too large, suppress the leading space.
1197          */
1198         if (tempLength > len) {
1199                 tempLength--;
1200                 tempString++;
1201         }
1202
1203         /* 
1204          * If the string is still too large, suppress the trailing null.
1205          */
1206         if (tempLength > len)
1207                 tempLength--;
1208
1209         /* 
1210          * If the string is still too large, fail.
1211          */
1212         if (tempLength > len)
1213                 return FALSE;
1214
1215         /* 
1216          * Copy the string to the field.
1217          */
1218         memcpy(cp, tempString, len);
1219
1220         return TRUE;
1221 }
1222 #endif
1223
1224 /* END CODE */
1225 #endif