1 /* vi: set sw=4 ts=4: */
3 * Mini tar implementation for busybox
5 * Note, that as of BusyBox-0.43, tar has been completely rewritten from the
6 * ground up. It still has remnents of the old code lying about, but it is
7 * very different now (i.e. cleaner, less global variables, etc)
9 * Copyright (C) 2000 by Lineo, inc.
10 * Written by Erik Andersen <andersen@lineo.com>, <andersee@debian.org>
12 * Based in part in the tar implementation in sash
13 * Copyright (c) 1999 by David I. Bell
14 * Permission is granted to use, distribute, or modify this source,
15 * provided that this copyright notice remains intact.
16 * Permission to distribute sash derived code under the GPL has been granted.
18 * Based in part on the tar implementation from busybox-0.28
19 * Copyright (C) 1995 Bruce Perens
20 * This is free software under the GNU General Public License.
22 * This program is free software; you can redistribute it and/or modify
23 * it under the terms of the GNU General Public License as published by
24 * the Free Software Foundation; either version 2 of the License, or
25 * (at your option) any later version.
27 * This program is distributed in the hope that it will be useful,
28 * but WITHOUT ANY WARRANTY; without even the implied warranty of
29 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
30 * General Public License for more details.
32 * You should have received a copy of the GNU General Public License
33 * along with this program; if not, write to the Free Software
34 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
40 #define BB_DECLARE_EXTERN
41 #define bb_need_io_error
50 #include <sys/types.h>
51 #include <sys/sysmacros.h>
54 static const char tar_usage[] =
55 #ifdef BB_FEATURE_TAR_CREATE
60 #if defined BB_FEATURE_TAR_EXCLUDE
63 "[-f tarFile] [FILE] ...\n"
64 #ifndef BB_FEATURE_TRIVIAL_HELP
65 "\nCreate, extract, or list files from a tar file. Note that\n"
66 "this version of tar treats hard links as separate files.\n\n"
67 "Main operation mode:\n"
68 #ifdef BB_FEATURE_TAR_CREATE
74 "\tf\t\tname of tarfile or \"-\" for stdin\n"
75 "\tO\t\textract to stdout\n"
76 #if defined BB_FEATURE_TAR_EXCLUDE
77 "\t--exclude\tfile to exclude\n"
79 "\nInformative output:\n"
80 "\tv\t\tverbosely list files processed\n"
84 /* Tar file constants */
86 #define MAJOR(dev) (((dev)>>8)&0xff)
87 #define MINOR(dev) ((dev)&0xff)
91 /* POSIX tar Header Block, from POSIX 1003.1-1990 */
95 char name[100]; /* 0-99 */
96 char mode[8]; /* 100-107 */
97 char uid[8]; /* 108-115 */
98 char gid[8]; /* 116-123 */
99 char size[12]; /* 124-135 */
100 char mtime[12]; /* 136-147 */
101 char chksum[8]; /* 148-155 */
102 char typeflag; /* 156-156 */
103 char linkname[100]; /* 157-256 */
104 char magic[6]; /* 257-262 */
105 char version[2]; /* 263-264 */
106 char uname[32]; /* 265-296 */
107 char gname[32]; /* 297-328 */
108 char devmajor[8]; /* 329-336 */
109 char devminor[8]; /* 337-344 */
110 char prefix[155]; /* 345-499 */
111 char padding[12]; /* 500-512 (pad to exactly the TAR_BLOCK_SIZE) */
113 typedef struct TarHeader TarHeader;
116 /* A few useful constants */
117 #define TAR_MAGIC "ustar" /* ustar and a null */
118 #define TAR_VERSION " " /* Be compatable with GNU tar format */
119 #define TAR_MAGIC_LEN 6
120 #define TAR_VERSION_LEN 2
121 #define TAR_BLOCK_SIZE 512
123 /* A nice enum with all the possible tar file content types */
126 REGTYPE = '0', /* regular file */
127 REGTYPE0 = '\0', /* regular file (ancient bug compat)*/
128 LNKTYPE = '1', /* hard link */
129 SYMTYPE = '2', /* symbolic link */
130 CHRTYPE = '3', /* character special */
131 BLKTYPE = '4', /* block special */
132 DIRTYPE = '5', /* directory */
133 FIFOTYPE = '6', /* FIFO special */
134 CONTTYPE = '7', /* reserved */
136 typedef enum TarFileType TarFileType;
138 /* This struct ignores magic, non-numeric user name,
139 * non-numeric group name, and the checksum, since
140 * these are all ignored by BusyBox tar. */
143 int tarFd; /* An open file descriptor for reading from the tarball */
144 char * name; /* File name */
145 mode_t mode; /* Unix mode, including device bits. */
146 uid_t uid; /* Numeric UID */
147 gid_t gid; /* Numeric GID */
148 size_t size; /* Size of file */
149 time_t mtime; /* Last-modified time */
150 enum TarFileType type; /* Regular, directory, link, etc */
151 char * linkname; /* Name for symbolic and hard links */
152 long devmajor; /* Major number for special device */
153 long devminor; /* Minor number for special device */
155 typedef struct TarInfo TarInfo;
157 /* Local procedures to restore files from a tar file. */
158 static int readTarFile(const char* tarName, int extractFlag, int listFlag,
159 int tostdoutFlag, int verboseFlag, char** excludeList);
163 #ifdef BB_FEATURE_TAR_CREATE
164 /* Local procedures to save files into a tar file. */
165 static int writeTarFile(const char* tarName, int tostdoutFlag,
166 int verboseFlag, int argc, char **argv, char** excludeList);
170 extern int tar_main(int argc, char **argv)
172 char** excludeList=NULL;
173 #if defined BB_FEATURE_TAR_EXCLUDE
174 int excludeListSize=0;
176 const char *tarName="-";
177 int listFlag = FALSE;
178 int extractFlag = FALSE;
179 int createFlag = FALSE;
180 int verboseFlag = FALSE;
181 int tostdoutFlag = FALSE;
187 /* Parse any options */
188 while (--argc > 0 && strspn(*(++argv), "-cxt") >0 ) {
190 while (stopIt==FALSE && *argv && **argv) {
194 fatalError( "Option requires an argument: No file specified\n");
197 fatalError( "Only one 'f' option allowed\n");
200 fatalError( "Option requires an argument: No file specified\n");
205 if (extractFlag == TRUE || createFlag == TRUE)
211 if (listFlag == TRUE || createFlag == TRUE)
216 if (extractFlag == TRUE || listFlag == TRUE)
230 #if defined BB_FEATURE_TAR_EXCLUDE
231 if (strcmp(*argv, "-exclude")==0) {
233 fatalError( "Option requires an argument: No file specified\n");
235 excludeList=realloc( excludeList, sizeof(char**) * (excludeListSize+2));
236 excludeList[excludeListSize] = *(++argv);
237 /* Remove leading "/"s */
238 if (*excludeList[excludeListSize] =='/') {
239 excludeList[excludeListSize] = (excludeList[excludeListSize])+1;
241 if (excludeList[excludeListSize++] == NULL)
242 fatalError( "Option requires an argument: No file specified\n");
243 /* Tack a NULL onto the end of the list */
244 excludeList[excludeListSize] = NULL;
252 fatalError( "Unknown tar flag '%c'\n"
253 "Try `tar --help' for more information\n", **argv);
260 * Do the correct type of action supplying the rest of the
261 * command line arguments as the list of files to process.
263 if (createFlag == TRUE) {
264 #ifndef BB_FEATURE_TAR_CREATE
265 fatalError( "This version of tar was not compiled with tar creation support.\n");
267 exit(writeTarFile(tarName, tostdoutFlag, verboseFlag, argc, argv, excludeList));
270 if (listFlag == TRUE || extractFlag == TRUE) {
271 exit(readTarFile(tarName, extractFlag, listFlag, tostdoutFlag, verboseFlag, excludeList));
275 fatalError( "Exactly one of 'c', 'x' or 't' must be specified\n");
279 fixUpPermissions(TarInfo *header)
282 /* Now set permissions etc for the new file */
283 chown(header->name, header->uid, header->gid);
284 chmod(header->name, header->mode);
287 t.modtime = header->mtime;
288 utime(header->name, &t);
292 tarExtractRegularFile(TarInfo *header, int extractFlag, int tostdoutFlag)
296 size_t actualWriteSz;
298 size_t size = header->size;
299 int outFd=fileno(stdout);
301 /* Open the file to be written, if a file is supposed to be written */
302 if (extractFlag==TRUE && tostdoutFlag==FALSE) {
303 /* Create the path to the file, just in case it isn't there...
304 * This should not screw up path permissions or anything. */
305 createPath(header->name, 0777);
306 if ((outFd=open(header->name, O_CREAT|O_TRUNC|O_WRONLY,
307 header->mode & ~S_IFMT)) < 0) {
308 errorMsg(io_error, header->name, strerror(errno));
313 /* Write out the file, if we are supposed to be doing that */
316 if ( size > sizeof(buffer) )
317 writeSize = readSize = sizeof(buffer);
319 int mod = size % 512;
321 readSize = size + (512 - mod);
326 if ( (readSize = fullRead(header->tarFd, buffer, readSize)) <= 0 ) {
327 /* Tarball seems to have a problem */
328 errorMsg("tar: Unexpected EOF in archive\n");
331 if ( readSize < writeSize )
332 writeSize = readSize;
334 /* Write out the file, if we are supposed to be doing that */
335 if (extractFlag==TRUE) {
337 if ((actualWriteSz=fullWrite(outFd, buffer, writeSize)) != writeSize ) {
338 /* Output file seems to have a problem */
339 errorMsg(io_error, header->name, strerror(errno));
343 actualWriteSz=writeSize;
346 size -= actualWriteSz;
349 /* Now we are done writing the file out, so try
350 * and fix up the permissions and whatnot */
351 if (extractFlag==TRUE && tostdoutFlag==FALSE) {
353 fixUpPermissions(header);
359 tarExtractDirectory(TarInfo *header, int extractFlag, int tostdoutFlag)
362 if (extractFlag==FALSE || tostdoutFlag==TRUE)
365 if (createPath(header->name, header->mode) != TRUE) {
366 errorMsg("tar: %s: Cannot mkdir: %s\n",
367 header->name, strerror(errno));
370 /* make the final component, just in case it was
371 * omitted by createPath() (which will skip the
372 * directory if it doesn't have a terminating '/') */
373 if (mkdir(header->name, header->mode) == 0) {
374 fixUpPermissions(header);
380 tarExtractHardLink(TarInfo *header, int extractFlag, int tostdoutFlag)
382 if (extractFlag==FALSE || tostdoutFlag==TRUE)
385 if (link(header->linkname, header->name) < 0) {
386 errorMsg("tar: %s: Cannot create hard link to '%s': %s\n",
387 header->name, header->linkname, strerror(errno));
391 /* Now set permissions etc for the new directory */
392 fixUpPermissions(header);
397 tarExtractSymLink(TarInfo *header, int extractFlag, int tostdoutFlag)
399 if (extractFlag==FALSE || tostdoutFlag==TRUE)
403 if (symlink(header->linkname, header->name) < 0) {
404 errorMsg("tar: %s: Cannot create symlink to '%s': %s\n",
405 header->name, header->linkname, strerror(errno));
408 /* Try to change ownership of the symlink.
409 * If libs doesn't support that, don't bother.
410 * Changing the pointed-to-file is the Wrong Thing(tm).
412 #if (__GLIBC__ >= 2) && (__GLIBC_MINOR__ >= 1)
413 lchown(header->name, header->uid, header->gid);
416 /* Do not change permissions or date on symlink,
417 * since it changes the pointed to file instead. duh. */
419 errorMsg("tar: %s: Cannot create symlink to '%s': %s\n",
420 header->name, header->linkname,
421 "symlinks not supported");
427 tarExtractSpecial(TarInfo *header, int extractFlag, int tostdoutFlag)
429 if (extractFlag==FALSE || tostdoutFlag==TRUE)
432 if (S_ISCHR(header->mode) || S_ISBLK(header->mode) || S_ISSOCK(header->mode)) {
433 if (mknod(header->name, header->mode, makedev(header->devmajor, header->devminor)) < 0) {
434 errorMsg("tar: %s: Cannot mknod: %s\n",
435 header->name, strerror(errno));
438 } else if (S_ISFIFO(header->mode)) {
439 if (mkfifo(header->name, header->mode) < 0) {
440 errorMsg("tar: %s: Cannot mkfifo: %s\n",
441 header->name, strerror(errno));
446 /* Now set permissions etc for the new directory */
447 fixUpPermissions(header);
451 /* Read an octal value in a field of the specified width, with optional
452 * spaces on both sides of the number and with an optional null character
453 * at the end. Returns -1 on an illegal format. */
454 static long getOctal(const char *cp, int size)
458 for(;(size > 0) && (*cp == ' '); cp++, size--);
459 if ((size == 0) || !isOctal(*cp))
461 for(; (size > 0) && isOctal(*cp); size--) {
462 val = val * 8 + *cp++ - '0';
464 for (;(size > 0) && (*cp == ' '); cp++, size--);
465 if ((size > 0) && *cp)
471 /* Parse the tar header and fill in the nice struct with the details */
473 readTarHeader(struct TarHeader *rawHeader, struct TarInfo *header)
477 unsigned char *s = (unsigned char *)rawHeader;
479 header->name = rawHeader->name;
480 /* Check for and relativify any absolute paths */
481 if ( *(header->name) == '/' ) {
482 static int alreadyWarned=FALSE;
484 while (*(header->name) == '/')
487 if (alreadyWarned == FALSE) {
488 errorMsg("tar: Removing leading '/' from member names\n");
489 alreadyWarned = TRUE;
493 header->mode = getOctal(rawHeader->mode, sizeof(rawHeader->mode));
494 header->uid = getOctal(rawHeader->uid, sizeof(rawHeader->uid));
495 header->gid = getOctal(rawHeader->gid, sizeof(rawHeader->gid));
496 header->size = getOctal(rawHeader->size, sizeof(rawHeader->size));
497 header->mtime = getOctal(rawHeader->mtime, sizeof(rawHeader->mtime));
498 chksum = getOctal(rawHeader->chksum, sizeof(rawHeader->chksum));
499 header->type = rawHeader->typeflag;
500 header->linkname = rawHeader->linkname;
501 header->devmajor = getOctal(rawHeader->devmajor, sizeof(rawHeader->devmajor));
502 header->devminor = getOctal(rawHeader->devminor, sizeof(rawHeader->devminor));
504 /* Check the checksum */
505 for (i = sizeof(*rawHeader); i-- != 0;) {
508 /* Remove the effects of the checksum field (replace
509 * with blanks for the purposes of the checksum) */
510 s = rawHeader->chksum;
511 for (i = sizeof(rawHeader->chksum) ; i-- != 0;) {
514 sum += ' ' * sizeof(rawHeader->chksum);
522 * Read a tar file and extract or list the specified files within it.
523 * If the list is empty than all files are extracted or listed.
525 static int readTarFile(const char* tarName, int extractFlag, int listFlag,
526 int tostdoutFlag, int verboseFlag, char** excludeList)
528 int status, tarFd=-1;
532 #if defined BB_FEATURE_TAR_EXCLUDE
536 /* Open the tar file for reading. */
537 if (!strcmp(tarName, "-"))
538 tarFd = fileno(stdin);
540 tarFd = open(tarName, O_RDONLY);
542 errorMsg( "Error opening '%s': %s\n", tarName, strerror(errno));
546 /* Set the umask for this process so it doesn't
547 * screw up permission setting for us later. */
550 /* Read the tar file, and iterate over it one file at a time */
551 while ( (status = fullRead(tarFd, (char*)&rawHeader, TAR_BLOCK_SIZE)) == TAR_BLOCK_SIZE ) {
553 /* First, try to read the header */
554 if ( readTarHeader(&rawHeader, &header) == FALSE ) {
555 if ( *(header.name) == '\0' ) {
559 errorMsg("Bad tar header, skipping\n");
563 if ( *(header.name) == '\0' )
565 header.tarFd = tarFd;
567 #if defined BB_FEATURE_TAR_EXCLUDE
570 /* Check for excluded files.... */
571 for (tmpList=excludeList; tmpList && *tmpList; tmpList++) {
572 /* Do some extra hoop jumping for when directory names
573 * end in '/' but the entry in tmpList doesn't */
574 if (strncmp( *tmpList, header.name, strlen(*tmpList))==0 || (
575 header.name[strlen(header.name)-1]=='/'
576 && strncmp( *tmpList, header.name,
577 MIN(strlen(header.name)-1, strlen(*tmpList)))==0)) {
578 /* If it is a regular file, pretend to extract it with
579 * the extractFlag set to FALSE, so the junk in the tarball
580 * is properly skipped over */
581 if ( header.type==REGTYPE || header.type==REGTYPE0 ) {
582 tarExtractRegularFile(&header, FALSE, FALSE);
588 /* There are not the droids you're looking for, move along */
593 /* Special treatment if the list (-t) flag is on */
594 if (verboseFlag == TRUE && extractFlag == FALSE) {
597 struct tm *tm = localtime (&(header.mtime));
599 len=printf("%s ", modeString(header.mode));
600 memset(buf, 0, 8*sizeof(char));
601 my_getpwuid(buf, header.uid);
603 len+=printf("%d", header.uid);
605 len+=printf("%s", buf);
606 memset(buf, 0, 8*sizeof(char));
607 my_getgrgid(buf, header.gid);
609 len+=printf("/%-d ", header.gid);
611 len+=printf("/%-s ", buf);
613 if (header.type==CHRTYPE || header.type==BLKTYPE) {
614 len1=snprintf(buf, sizeof(buf), "%ld,%-ld ",
615 header.devmajor, header.devminor);
617 len1=snprintf(buf, sizeof(buf), "%lu ", (long)header.size);
619 /* Jump through some hoops to make the columns match up */
620 for(;(len+len1)<31;len++)
624 /* Use ISO 8610 time format */
626 printf ("%04d-%02d-%02d %02d:%02d:%02d ",
627 tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday,
628 tm->tm_hour, tm->tm_min, tm->tm_sec);
631 /* List contents if we are supposed to do that */
632 if (verboseFlag == TRUE || listFlag == TRUE) {
633 /* Now the normal listing */
634 printf("%s", header.name);
636 if (verboseFlag == TRUE && listFlag == TRUE) {
637 /* If this is a link, say so */
638 if (header.type==LNKTYPE)
639 printf(" link to %s", header.linkname);
640 else if (header.type==SYMTYPE)
641 printf(" -> %s", header.linkname);
643 if (verboseFlag == TRUE || listFlag == TRUE) {
647 /* Remove any clutter lying in our way */
648 unlink( header.name);
650 /* If we got here, we can be certain we have a legitimate
651 * header to work with. So work with it. */
652 switch ( header.type ) {
655 /* If the name ends in a '/' then assume it is
656 * supposed to be a directory, and fall through */
657 if (header.name[strlen(header.name)-1] != '/') {
658 if (tarExtractRegularFile(&header, extractFlag, tostdoutFlag)==FALSE)
663 if (tarExtractDirectory( &header, extractFlag, tostdoutFlag)==FALSE)
667 if (tarExtractHardLink( &header, extractFlag, tostdoutFlag)==FALSE)
671 if (tarExtractSymLink( &header, extractFlag, tostdoutFlag)==FALSE)
677 if (tarExtractSpecial( &header, extractFlag, tostdoutFlag)==FALSE)
687 /* Bummer - we read a partial header */
688 errorMsg( "Error reading '%s': %s\n", tarName, strerror(errno));
691 else if (errorFlag==TRUE) {
692 errorMsg( "tar: Error exit delayed from previous errors\n");
697 /* Stuff to do when we are done */
700 if ( *(header.name) == '\0' ) {
702 errorMsg( "tar: Error exit delayed from previous errors\n");
710 #ifdef BB_FEATURE_TAR_CREATE
712 /* Some info to be carried along when creating a new tarball */
715 char* fileName; /* File name of the tarball */
716 int tarFd; /* Open-for-write file descriptor
718 struct stat statBuf; /* Stat info for the tarball, letting
719 us know the inode and device that the
720 tarball lives, so we can avoid trying
721 to include the tarball into itself */
722 int verboseFlag; /* Whether to print extra stuff or not */
723 char** excludeList; /* List of files to not include */
725 typedef struct TarBallInfo TarBallInfo;
728 /* Put an octal string into the specified buffer.
729 * The number is zero and space padded and possibly null padded.
730 * Returns TRUE if successful. */
731 static int putOctal (char *cp, int len, long value)
735 char *tempString = tempBuffer;
737 /* Create a string of the specified length with an initial space,
738 * leading zeroes and the octal number, and a trailing null. */
739 sprintf (tempString, "%0*lo", len - 1, value);
741 /* If the string is too large, suppress the leading space. */
742 tempLength = strlen (tempString) + 1;
743 if (tempLength > len) {
748 /* If the string is still too large, suppress the trailing null. */
749 if (tempLength > len)
752 /* If the string is still too large, fail. */
753 if (tempLength > len)
756 /* Copy the string to the field. */
757 memcpy (cp, tempString, len);
762 /* Write out a tar header for the specified file/directory/whatever */
764 writeTarHeader(struct TarBallInfo *tbInfo, const char *fileName, struct stat *statbuf)
767 struct TarHeader header;
768 #if defined BB_FEATURE_TAR_EXCLUDE
771 const unsigned char *cp = (const unsigned char *) &header;
772 ssize_t size = sizeof(struct TarHeader);
774 memset( &header, 0, size);
776 if (*fileName=='/') {
777 static int alreadyWarned=FALSE;
778 if (alreadyWarned==FALSE) {
779 errorMsg("tar: Removing leading '/' from member names\n");
782 strncpy(header.name, fileName+1, sizeof(header.name));
785 strncpy(header.name, fileName, sizeof(header.name));
788 #if defined BB_FEATURE_TAR_EXCLUDE
789 /* Check for excluded files.... */
790 for (tmpList=tbInfo->excludeList; tmpList && *tmpList; tmpList++) {
791 /* Do some extra hoop jumping for when directory names
792 * end in '/' but the entry in tmpList doesn't */
793 if (strncmp( *tmpList, header.name, strlen(*tmpList))==0 || (
794 header.name[strlen(header.name)-1]=='/'
795 && strncmp( *tmpList, header.name,
796 MIN(strlen(header.name)-1, strlen(*tmpList)))==0)) {
797 /* Set the mode to something that is not a regular file, thereby
798 * faking out writeTarFile into thinking that nothing further need
799 * be done for this file. Yes, I know this is ugly, but it works. */
800 statbuf->st_mode = 0;
806 putOctal(header.mode, sizeof(header.mode), statbuf->st_mode);
807 putOctal(header.uid, sizeof(header.uid), statbuf->st_uid);
808 putOctal(header.gid, sizeof(header.gid), statbuf->st_gid);
809 putOctal(header.size, sizeof(header.size), 0); /* Regular file size is handled later */
810 putOctal(header.mtime, sizeof(header.mtime), statbuf->st_mtime);
811 strncpy(header.magic, TAR_MAGIC TAR_VERSION,
812 TAR_MAGIC_LEN + TAR_VERSION_LEN );
814 /* Enter the user and group names (default to root if it fails) */
815 my_getpwuid(header.uname, statbuf->st_uid);
817 strcpy(header.uname, "root");
818 my_getgrgid(header.gname, statbuf->st_gid);
820 strcpy(header.uname, "root");
822 /* WARNING/NOTICE: I break Hard Links */
823 if (S_ISLNK(statbuf->st_mode)) {
825 header.typeflag = SYMTYPE;
826 if ( readlink(fileName, buffer, sizeof(buffer) - 1) < 0) {
827 errorMsg("Error reading symlink '%s': %s\n", header.name, strerror(errno));
830 strncpy(header.linkname, buffer, sizeof(header.linkname));
831 } else if (S_ISDIR(statbuf->st_mode)) {
832 header.typeflag = DIRTYPE;
833 strncat(header.name, "/", sizeof(header.name));
834 } else if (S_ISCHR(statbuf->st_mode)) {
835 header.typeflag = CHRTYPE;
836 putOctal(header.devmajor, sizeof(header.devmajor), MAJOR(statbuf->st_rdev));
837 putOctal(header.devminor, sizeof(header.devminor), MINOR(statbuf->st_rdev));
838 } else if (S_ISBLK(statbuf->st_mode)) {
839 header.typeflag = BLKTYPE;
840 putOctal(header.devmajor, sizeof(header.devmajor), MAJOR(statbuf->st_rdev));
841 putOctal(header.devminor, sizeof(header.devminor), MINOR(statbuf->st_rdev));
842 } else if (S_ISFIFO(statbuf->st_mode)) {
843 header.typeflag = FIFOTYPE;
844 } else if (S_ISREG(statbuf->st_mode)) {
845 header.typeflag = REGTYPE;
846 putOctal(header.size, sizeof(header.size), statbuf->st_size);
848 errorMsg("tar: %s: Unknown file type\n", fileName);
852 /* Calculate and store the checksum (i.e. the sum of all of the bytes of
853 * the header). The checksum field must be filled with blanks for the
854 * calculation. The checksum field is formatted differently from the
855 * other fields: it has [6] digits, a null, then a space -- rather than
856 * digits, followed by a null like the other fields... */
857 memset(header.chksum, ' ', sizeof(header.chksum));
858 cp = (const unsigned char *) &header;
861 putOctal(header.chksum, 7, chksum);
863 /* Now write the header out to disk */
864 if ((size=fullWrite(tbInfo->tarFd, (char*)&header, sizeof(struct TarHeader))) < 0) {
865 errorMsg(io_error, fileName, strerror(errno));
868 /* Pad the header up to the tar block size */
869 for (; size<TAR_BLOCK_SIZE; size++) {
870 write(tbInfo->tarFd, "\0", 1);
872 /* Now do the verbose thing (or not) */
873 if (tbInfo->verboseFlag==TRUE)
874 fprintf(stdout, "%s\n", header.name);
880 static int writeFileToTarball(const char *fileName, struct stat *statbuf, void* userData)
882 struct TarBallInfo *tbInfo = (struct TarBallInfo *)userData;
884 /* It is against the rules to archive a socket */
885 if (S_ISSOCK(statbuf->st_mode)) {
886 errorMsg("tar: %s: socket ignored\n", fileName);
890 /* It is a bad idea to store the archive we are in the process of creating,
891 * so check the device and inode to be sure that this particular file isn't
893 if (tbInfo->statBuf.st_dev == statbuf->st_dev &&
894 tbInfo->statBuf.st_ino == statbuf->st_ino) {
895 errorMsg("tar: %s: file is the archive; skipping\n", fileName);
899 if (writeTarHeader(tbInfo, fileName, statbuf)==FALSE) {
903 /* Now, if the file is a regular file, copy it out to the tarball */
904 if (S_ISREG(statbuf->st_mode)) {
907 ssize_t size=0, readSize=0;
909 /* open the file we want to archive, and make sure all is well */
910 if ((inputFileFd = open(fileName, O_RDONLY)) < 0) {
911 errorMsg("tar: %s: Cannot open: %s\n", fileName, strerror(errno));
915 /* write the file to the archive */
916 while ( (size = fullRead(inputFileFd, buffer, sizeof(buffer))) > 0 ) {
917 if (fullWrite(tbInfo->tarFd, buffer, size) != size ) {
918 /* Output file seems to have a problem */
919 errorMsg(io_error, fileName, strerror(errno));
925 errorMsg(io_error, fileName, strerror(errno));
928 /* Pad the file up to the tar block size */
929 for (; (readSize%TAR_BLOCK_SIZE) != 0; readSize++) {
930 write(tbInfo->tarFd, "\0", 1);
938 static int writeTarFile(const char* tarName, int tostdoutFlag,
939 int verboseFlag, int argc, char **argv, char** excludeList)
944 struct TarBallInfo tbInfo;
945 tbInfo.verboseFlag = verboseFlag;
947 /* Make sure there is at least one file to tar up. */
949 fatalError("tar: Cowardly refusing to create an empty archive\n");
951 /* Open the tar file for writing. */
952 if (tostdoutFlag == TRUE)
953 tbInfo.tarFd = fileno(stdout);
955 tbInfo.tarFd = open (tarName, O_WRONLY | O_CREAT | O_TRUNC, 0644);
956 if (tbInfo.tarFd < 0) {
957 errorMsg( "tar: Error opening '%s': %s\n", tarName, strerror(errno));
960 tbInfo.excludeList=excludeList;
961 /* Store the stat info for the tarball's file, so
962 * can avoid including the tarball into itself.... */
963 if (fstat(tbInfo.tarFd, &tbInfo.statBuf) < 0)
964 fatalError(io_error, tarName, strerror(errno));
966 /* Set the umask for this process so it doesn't
967 * screw up permission setting for us later. */
970 /* Read the directory/files and iterate over them one at a time */
972 if (recursiveAction(*argv++, TRUE, FALSE, FALSE,
973 writeFileToTarball, writeFileToTarball,
974 (void*) &tbInfo) == FALSE) {
978 /* Write two empty blocks to the end of the archive */
979 for (size=0; size<(2*TAR_BLOCK_SIZE); size++) {
980 write(tbInfo.tarFd, "\0", 1);
983 /* To be pedantically correct, we would check if the tarball
984 * is smaller then 20 tar blocks, and pad it if it was smaller,
985 * but that isn't necessary for GNU tar interoperability, and
986 * so is considered a waste of space */
988 /* Hang up the tools, close up shop, head home */
990 if (errorFlag == TRUE) {
991 errorMsg("tar: Error exit delayed from previous errors\n");