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