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