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 /* Tar file constants */
56 #define MAJOR(dev) (((dev)>>8)&0xff)
57 #define MINOR(dev) ((dev)&0xff)
61 /* POSIX tar Header Block, from POSIX 1003.1-1990 */
65 char name[100]; /* 0-99 */
66 char mode[8]; /* 100-107 */
67 char uid[8]; /* 108-115 */
68 char gid[8]; /* 116-123 */
69 char size[12]; /* 124-135 */
70 char mtime[12]; /* 136-147 */
71 char chksum[8]; /* 148-155 */
72 char typeflag; /* 156-156 */
73 char linkname[100]; /* 157-256 */
74 char magic[6]; /* 257-262 */
75 char version[2]; /* 263-264 */
76 char uname[32]; /* 265-296 */
77 char gname[32]; /* 297-328 */
78 char devmajor[8]; /* 329-336 */
79 char devminor[8]; /* 337-344 */
80 char prefix[155]; /* 345-499 */
81 char padding[12]; /* 500-512 (pad to exactly the TAR_BLOCK_SIZE) */
83 typedef struct TarHeader TarHeader;
86 /* A few useful constants */
87 #define TAR_MAGIC "ustar" /* ustar and a null */
88 #define TAR_VERSION " " /* Be compatable with GNU tar format */
89 #define TAR_MAGIC_LEN 6
90 #define TAR_VERSION_LEN 2
91 #define TAR_BLOCK_SIZE 512
93 /* A nice enum with all the possible tar file content types */
96 REGTYPE = '0', /* regular file */
97 REGTYPE0 = '\0', /* regular file (ancient bug compat)*/
98 LNKTYPE = '1', /* hard link */
99 SYMTYPE = '2', /* symbolic link */
100 CHRTYPE = '3', /* character special */
101 BLKTYPE = '4', /* block special */
102 DIRTYPE = '5', /* directory */
103 FIFOTYPE = '6', /* FIFO special */
104 CONTTYPE = '7', /* reserved */
106 typedef enum TarFileType TarFileType;
108 /* This struct ignores magic, non-numeric user name,
109 * non-numeric group name, and the checksum, since
110 * these are all ignored by BusyBox tar. */
113 int tarFd; /* An open file descriptor for reading from the tarball */
114 char * name; /* File name */
115 mode_t mode; /* Unix mode, including device bits. */
116 uid_t uid; /* Numeric UID */
117 gid_t gid; /* Numeric GID */
118 size_t size; /* Size of file */
119 time_t mtime; /* Last-modified time */
120 enum TarFileType type; /* Regular, directory, link, etc */
121 char * linkname; /* Name for symbolic and hard links */
122 long devmajor; /* Major number for special device */
123 long devminor; /* Minor number for special device */
125 typedef struct TarInfo TarInfo;
127 /* Local procedures to restore files from a tar file. */
128 static int readTarFile(const char* tarName, int extractFlag, int listFlag,
129 int tostdoutFlag, int verboseFlag, char** extractList,
134 #ifdef BB_FEATURE_TAR_CREATE
135 /* Local procedures to save files into a tar file. */
136 static int writeTarFile(const char* tarName, int tostdoutFlag,
137 int verboseFlag, int argc, char **argv, char** excludeList);
140 extern int tar_main(int argc, char **argv)
142 char** excludeList=NULL;
143 #if defined BB_FEATURE_TAR_EXCLUDE
144 int excludeListSize=0;
146 const char *tarName="-";
147 int listFlag = FALSE;
148 int extractFlag = FALSE;
149 int createFlag = FALSE;
150 int verboseFlag = FALSE;
151 int tostdoutFlag = FALSE;
159 /* do normal option parsing */
160 while (--argc > 0 && ((*argv && **(++argv) == '-') ||
161 (firstOpt==TRUE && strspn(*argv, "-cxt") ))) {
164 while (stopIt==FALSE && *argv && **argv) {
167 if (extractFlag == TRUE || listFlag == TRUE)
172 if (listFlag == TRUE || createFlag == TRUE)
177 if (extractFlag == TRUE || createFlag == TRUE)
190 fatalError( "Option requires an argument: No file specified\n");
193 fatalError( "Only one 'f' option allowed\n");
196 fatalError( "Option requires an argument: No file specified\n");
197 if (!strcmp(tarName, "-") && createFlag == TRUE)
201 #if defined BB_FEATURE_TAR_EXCLUDE
203 if (strcmp(*argv, "-exclude")==0) {
205 fatalError( "Option requires an argument: No file specified\n");
207 excludeList=xrealloc( excludeList, sizeof(char**) * (excludeListSize+2));
208 excludeList[excludeListSize] = *(++argv);
209 /* Remove leading "/"s */
210 if (*excludeList[excludeListSize] =='/')
211 excludeList[excludeListSize] = (excludeList[excludeListSize])+1;
212 /* Tack a NULL onto the end of the list */
213 excludeList[++excludeListSize] = NULL;
228 * Do the correct type of action supplying the rest of the
229 * command line arguments as the list of files to process.
231 if (createFlag == TRUE) {
232 #ifndef BB_FEATURE_TAR_CREATE
233 fatalError( "This version of tar was not compiled with tar creation support.\n");
235 exit(writeTarFile(tarName, tostdoutFlag, verboseFlag, argc, argv, excludeList));
238 if (listFlag == TRUE || extractFlag == TRUE) {
239 exit(readTarFile(tarName, extractFlag, listFlag, tostdoutFlag, verboseFlag, &argv[optind], excludeList));
243 fatalError( "Exactly one of 'c', 'x' or 't' must be specified\n");
247 fixUpPermissions(TarInfo *header)
250 /* Now set permissions etc for the new file */
251 chown(header->name, header->uid, header->gid);
252 chmod(header->name, header->mode);
255 t.modtime = header->mtime;
256 utime(header->name, &t);
260 tarExtractRegularFile(TarInfo *header, int extractFlag, int tostdoutFlag)
264 size_t actualWriteSz;
266 size_t size = header->size;
267 int outFd=fileno(stdout);
269 /* Open the file to be written, if a file is supposed to be written */
270 if (extractFlag==TRUE && tostdoutFlag==FALSE) {
271 /* Create the path to the file, just in case it isn't there...
272 * This should not screw up path permissions or anything. */
273 createPath(header->name, 0777);
274 if ((outFd=open(header->name, O_CREAT|O_TRUNC|O_WRONLY,
275 header->mode & ~S_IFMT)) < 0) {
276 errorMsg(io_error, header->name, strerror(errno));
281 /* Write out the file, if we are supposed to be doing that */
284 if ( size > sizeof(buffer) )
285 writeSize = readSize = sizeof(buffer);
287 int mod = size % 512;
289 readSize = size + (512 - mod);
294 if ( (readSize = fullRead(header->tarFd, buffer, readSize)) <= 0 ) {
295 /* Tarball seems to have a problem */
296 errorMsg("Unexpected EOF in archive\n");
299 if ( readSize < writeSize )
300 writeSize = readSize;
302 /* Write out the file, if we are supposed to be doing that */
303 if (extractFlag==TRUE) {
305 if ((actualWriteSz=fullWrite(outFd, buffer, writeSize)) != writeSize ) {
306 /* Output file seems to have a problem */
307 errorMsg(io_error, header->name, strerror(errno));
311 actualWriteSz=writeSize;
314 size -= actualWriteSz;
317 /* Now we are done writing the file out, so try
318 * and fix up the permissions and whatnot */
319 if (extractFlag==TRUE && tostdoutFlag==FALSE) {
321 fixUpPermissions(header);
327 tarExtractDirectory(TarInfo *header, int extractFlag, int tostdoutFlag)
330 if (extractFlag==FALSE || tostdoutFlag==TRUE)
333 if (createPath(header->name, header->mode) != TRUE) {
334 errorMsg("%s: Cannot mkdir: %s\n",
335 header->name, strerror(errno));
338 /* make the final component, just in case it was
339 * omitted by createPath() (which will skip the
340 * directory if it doesn't have a terminating '/') */
341 if (mkdir(header->name, header->mode) == 0) {
342 fixUpPermissions(header);
348 tarExtractHardLink(TarInfo *header, int extractFlag, int tostdoutFlag)
350 if (extractFlag==FALSE || tostdoutFlag==TRUE)
353 if (link(header->linkname, header->name) < 0) {
354 errorMsg("%s: Cannot create hard link to '%s': %s\n",
355 header->name, header->linkname, strerror(errno));
359 /* Now set permissions etc for the new directory */
360 fixUpPermissions(header);
365 tarExtractSymLink(TarInfo *header, int extractFlag, int tostdoutFlag)
367 if (extractFlag==FALSE || tostdoutFlag==TRUE)
371 if (symlink(header->linkname, header->name) < 0) {
372 errorMsg("%s: Cannot create symlink to '%s': %s\n",
373 header->name, header->linkname, strerror(errno));
376 /* Try to change ownership of the symlink.
377 * If libs doesn't support that, don't bother.
378 * Changing the pointed-to-file is the Wrong Thing(tm).
380 #if (__GLIBC__ >= 2) && (__GLIBC_MINOR__ >= 1)
381 lchown(header->name, header->uid, header->gid);
384 /* Do not change permissions or date on symlink,
385 * since it changes the pointed to file instead. duh. */
387 errorMsg("%s: Cannot create symlink to '%s': %s\n",
388 header->name, header->linkname,
389 "symlinks not supported");
395 tarExtractSpecial(TarInfo *header, int extractFlag, int tostdoutFlag)
397 if (extractFlag==FALSE || tostdoutFlag==TRUE)
400 if (S_ISCHR(header->mode) || S_ISBLK(header->mode) || S_ISSOCK(header->mode)) {
401 if (mknod(header->name, header->mode, makedev(header->devmajor, header->devminor)) < 0) {
402 errorMsg("%s: Cannot mknod: %s\n",
403 header->name, strerror(errno));
406 } else if (S_ISFIFO(header->mode)) {
407 if (mkfifo(header->name, header->mode) < 0) {
408 errorMsg("%s: Cannot mkfifo: %s\n",
409 header->name, strerror(errno));
414 /* Now set permissions etc for the new directory */
415 fixUpPermissions(header);
419 /* Read an octal value in a field of the specified width, with optional
420 * spaces on both sides of the number and with an optional null character
421 * at the end. Returns -1 on an illegal format. */
422 static long getOctal(const char *cp, int size)
426 for(;(size > 0) && (*cp == ' '); cp++, size--);
427 if ((size == 0) || !isOctal(*cp))
429 for(; (size > 0) && isOctal(*cp); size--) {
430 val = val * 8 + *cp++ - '0';
432 for (;(size > 0) && (*cp == ' '); cp++, size--);
433 if ((size > 0) && *cp)
439 /* Parse the tar header and fill in the nice struct with the details */
441 readTarHeader(struct TarHeader *rawHeader, struct TarInfo *header)
445 unsigned char *s = (unsigned char *)rawHeader;
447 header->name = rawHeader->name;
448 /* Check for and relativify any absolute paths */
449 if ( *(header->name) == '/' ) {
450 static int alreadyWarned=FALSE;
452 while (*(header->name) == '/')
455 if (alreadyWarned == FALSE) {
456 errorMsg("Removing leading '/' from member names\n");
457 alreadyWarned = TRUE;
461 header->mode = getOctal(rawHeader->mode, sizeof(rawHeader->mode));
462 header->uid = getOctal(rawHeader->uid, sizeof(rawHeader->uid));
463 header->gid = getOctal(rawHeader->gid, sizeof(rawHeader->gid));
464 header->size = getOctal(rawHeader->size, sizeof(rawHeader->size));
465 header->mtime = getOctal(rawHeader->mtime, sizeof(rawHeader->mtime));
466 chksum = getOctal(rawHeader->chksum, sizeof(rawHeader->chksum));
467 header->type = rawHeader->typeflag;
468 header->linkname = rawHeader->linkname;
469 header->devmajor = getOctal(rawHeader->devmajor, sizeof(rawHeader->devmajor));
470 header->devminor = getOctal(rawHeader->devminor, sizeof(rawHeader->devminor));
472 /* Check the checksum */
473 for (i = sizeof(*rawHeader); i-- != 0;) {
476 /* Remove the effects of the checksum field (replace
477 * with blanks for the purposes of the checksum) */
478 s = rawHeader->chksum;
479 for (i = sizeof(rawHeader->chksum) ; i-- != 0;) {
482 sum += ' ' * sizeof(rawHeader->chksum);
490 * Read a tar file and extract or list the specified files within it.
491 * If the list is empty than all files are extracted or listed.
493 static int readTarFile(const char* tarName, int extractFlag, int listFlag,
494 int tostdoutFlag, int verboseFlag, char** extractList,
497 int status, tarFd=-1;
503 /* Open the tar file for reading. */
504 if (!strcmp(tarName, "-"))
505 tarFd = fileno(stdin);
507 tarFd = open(tarName, O_RDONLY);
509 errorMsg( "Error opening '%s': %s\n", tarName, strerror(errno));
513 /* Set the umask for this process so it doesn't
514 * screw up permission setting for us later. */
517 /* Read the tar file, and iterate over it one file at a time */
518 while ( (status = fullRead(tarFd, (char*)&rawHeader, TAR_BLOCK_SIZE)) == TAR_BLOCK_SIZE ) {
520 /* First, try to read the header */
521 if ( readTarHeader(&rawHeader, &header) == FALSE ) {
522 if ( *(header.name) == '\0' ) {
526 errorMsg("Bad tar header, skipping\n");
530 if ( *(header.name) == '\0' )
532 header.tarFd = tarFd;
534 #if defined BB_FEATURE_TAR_EXCLUDE
537 /* Check for excluded files.... */
538 for (tmpList=excludeList; tmpList && *tmpList; tmpList++) {
539 /* Do some extra hoop jumping for when directory names
540 * end in '/' but the entry in tmpList doesn't */
541 if (strncmp( *tmpList, header.name, strlen(*tmpList))==0 || (
542 header.name[strlen(header.name)-1]=='/'
543 && strncmp( *tmpList, header.name,
544 MIN(strlen(header.name)-1, strlen(*tmpList)))==0)) {
545 /* If it is a regular file, pretend to extract it with
546 * the extractFlag set to FALSE, so the junk in the tarball
547 * is properly skipped over */
548 if ( header.type==REGTYPE || header.type==REGTYPE0 ) {
549 tarExtractRegularFile(&header, FALSE, FALSE);
555 /* There are not the droids you're looking for, move along */
560 if (*extractList != NULL) {
562 for (tmpList = extractList; *tmpList != NULL; tmpList++) {
563 if (strncmp( *tmpList, header.name, strlen(*tmpList))==0 || (
564 header.name[strlen(header.name)-1]=='/'
565 && strncmp( *tmpList, header.name,
566 MIN(strlen(header.name)-1, strlen(*tmpList)))==0)) {
567 /* If it is a regular file, pretend to extract it with
568 * the extractFlag set to FALSE, so the junk in the tarball
569 * is properly skipped over */
574 /* There are not the droids you're looking for, move along */
575 if (skipFlag == TRUE) {
576 if ( header.type==REGTYPE || header.type==REGTYPE0 )
577 tarExtractRegularFile(&header, FALSE, FALSE);
582 if (listFlag == TRUE) {
583 /* Special treatment if the list (-t) flag is on */
584 if (verboseFlag == TRUE) {
587 struct tm *tm = localtime (&(header.mtime));
589 len=printf("%s ", modeString(header.mode));
590 memset(buf, 0, 8*sizeof(char));
591 my_getpwuid(buf, header.uid);
593 len+=printf("%d", header.uid);
595 len+=printf("%s", buf);
596 memset(buf, 0, 8*sizeof(char));
597 my_getgrgid(buf, header.gid);
599 len+=printf("/%-d ", header.gid);
601 len+=printf("/%-s ", buf);
603 if (header.type==CHRTYPE || header.type==BLKTYPE) {
604 len1=snprintf(buf, sizeof(buf), "%ld,%-ld ",
605 header.devmajor, header.devminor);
607 len1=snprintf(buf, sizeof(buf), "%lu ", (long)header.size);
609 /* Jump through some hoops to make the columns match up */
610 for(;(len+len1)<31;len++)
614 /* Use ISO 8610 time format */
616 printf ("%04d-%02d-%02d %02d:%02d:%02d ",
617 tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday,
618 tm->tm_hour, tm->tm_min, tm->tm_sec);
621 printf("%s", header.name);
622 if (verboseFlag == TRUE) {
623 if (header.type==LNKTYPE) /* If this is a link, say so */
624 printf(" link to %s", header.linkname);
625 else if (header.type==SYMTYPE)
626 printf(" -> %s", header.linkname);
631 /* List contents if we are supposed to do that */
632 if (verboseFlag == TRUE && extractFlag == TRUE) {
633 /* Now the normal listing */
635 if (tostdoutFlag == TRUE) // If the archive goes to stdout, verbose to stderr
637 fprintf(vbFd, "%s\n", header.name);
640 /* Remove files if we would overwrite them */
641 if (extractFlag == TRUE && tostdoutFlag == FALSE)
644 /* If we got here, we can be certain we have a legitimate
645 * header to work with. So work with it. */
646 switch ( header.type ) {
649 /* If the name ends in a '/' then assume it is
650 * supposed to be a directory, and fall through */
651 if (header.name[strlen(header.name)-1] != '/') {
652 if (tarExtractRegularFile(&header, extractFlag, tostdoutFlag)==FALSE)
657 if (tarExtractDirectory( &header, extractFlag, tostdoutFlag)==FALSE)
661 if (tarExtractHardLink( &header, extractFlag, tostdoutFlag)==FALSE)
665 if (tarExtractSymLink( &header, extractFlag, tostdoutFlag)==FALSE)
671 if (tarExtractSpecial( &header, extractFlag, tostdoutFlag)==FALSE)
681 /* Bummer - we read a partial header */
682 errorMsg( "Error reading '%s': %s\n", tarName, strerror(errno));
685 else if (errorFlag==TRUE) {
686 errorMsg( "Error exit delayed from previous errors\n");
691 /* Stuff to do when we are done */
694 if ( *(header.name) == '\0' ) {
696 errorMsg( "Error exit delayed from previous errors\n");
704 #ifdef BB_FEATURE_TAR_CREATE
706 /* Some info to be carried along when creating a new tarball */
709 char* fileName; /* File name of the tarball */
710 int tarFd; /* Open-for-write file descriptor
712 struct stat statBuf; /* Stat info for the tarball, letting
713 us know the inode and device that the
714 tarball lives, so we can avoid trying
715 to include the tarball into itself */
716 int verboseFlag; /* Whether to print extra stuff or not */
717 char** excludeList; /* List of files to not include */
719 typedef struct TarBallInfo TarBallInfo;
722 /* Put an octal string into the specified buffer.
723 * The number is zero and space padded and possibly null padded.
724 * Returns TRUE if successful. */
725 static int putOctal (char *cp, int len, long value)
729 char *tempString = tempBuffer;
731 /* Create a string of the specified length with an initial space,
732 * leading zeroes and the octal number, and a trailing null. */
733 sprintf (tempString, "%0*lo", len - 1, value);
735 /* If the string is too large, suppress the leading space. */
736 tempLength = strlen (tempString) + 1;
737 if (tempLength > len) {
742 /* If the string is still too large, suppress the trailing null. */
743 if (tempLength > len)
746 /* If the string is still too large, fail. */
747 if (tempLength > len)
750 /* Copy the string to the field. */
751 memcpy (cp, tempString, len);
756 /* Write out a tar header for the specified file/directory/whatever */
758 writeTarHeader(struct TarBallInfo *tbInfo, const char *fileName, struct stat *statbuf)
761 struct TarHeader header;
762 #if defined BB_FEATURE_TAR_EXCLUDE
765 const unsigned char *cp = (const unsigned char *) &header;
766 ssize_t size = sizeof(struct TarHeader);
768 memset( &header, 0, size);
770 if (*fileName=='/') {
771 static int alreadyWarned=FALSE;
772 if (alreadyWarned==FALSE) {
773 errorMsg("Removing leading '/' from member names\n");
776 strncpy(header.name, fileName+1, sizeof(header.name));
779 strncpy(header.name, fileName, sizeof(header.name));
782 #if defined BB_FEATURE_TAR_EXCLUDE
783 /* Check for excluded files.... */
784 for (tmpList=tbInfo->excludeList; tmpList && *tmpList; tmpList++) {
785 /* Do some extra hoop jumping for when directory names
786 * end in '/' but the entry in tmpList doesn't */
787 if (strncmp( *tmpList, header.name, strlen(*tmpList))==0 || (
788 header.name[strlen(header.name)-1]=='/'
789 && strncmp( *tmpList, header.name,
790 MIN(strlen(header.name)-1, strlen(*tmpList)))==0)) {
791 /* Set the mode to something that is not a regular file, thereby
792 * faking out writeTarFile into thinking that nothing further need
793 * be done for this file. Yes, I know this is ugly, but it works. */
794 statbuf->st_mode = 0;
800 putOctal(header.mode, sizeof(header.mode), statbuf->st_mode);
801 putOctal(header.uid, sizeof(header.uid), statbuf->st_uid);
802 putOctal(header.gid, sizeof(header.gid), statbuf->st_gid);
803 putOctal(header.size, sizeof(header.size), 0); /* Regular file size is handled later */
804 putOctal(header.mtime, sizeof(header.mtime), statbuf->st_mtime);
805 strncpy(header.magic, TAR_MAGIC TAR_VERSION,
806 TAR_MAGIC_LEN + TAR_VERSION_LEN );
808 /* Enter the user and group names (default to root if it fails) */
809 my_getpwuid(header.uname, statbuf->st_uid);
811 strcpy(header.uname, "root");
812 my_getgrgid(header.gname, statbuf->st_gid);
814 strcpy(header.uname, "root");
816 /* WARNING/NOTICE: I break Hard Links */
817 if (S_ISLNK(statbuf->st_mode)) {
820 header.typeflag = SYMTYPE;
821 link_size = readlink(fileName, buffer, sizeof(buffer) - 1);
822 if ( link_size < 0) {
823 errorMsg("Error reading symlink '%s': %s\n", header.name, strerror(errno));
826 buffer[link_size] = '\0';
827 strncpy(header.linkname, buffer, sizeof(header.linkname));
828 } else if (S_ISDIR(statbuf->st_mode)) {
829 header.typeflag = DIRTYPE;
830 strncat(header.name, "/", sizeof(header.name));
831 } else if (S_ISCHR(statbuf->st_mode)) {
832 header.typeflag = CHRTYPE;
833 putOctal(header.devmajor, sizeof(header.devmajor), MAJOR(statbuf->st_rdev));
834 putOctal(header.devminor, sizeof(header.devminor), MINOR(statbuf->st_rdev));
835 } else if (S_ISBLK(statbuf->st_mode)) {
836 header.typeflag = BLKTYPE;
837 putOctal(header.devmajor, sizeof(header.devmajor), MAJOR(statbuf->st_rdev));
838 putOctal(header.devminor, sizeof(header.devminor), MINOR(statbuf->st_rdev));
839 } else if (S_ISFIFO(statbuf->st_mode)) {
840 header.typeflag = FIFOTYPE;
841 } else if (S_ISREG(statbuf->st_mode)) {
842 header.typeflag = REGTYPE;
843 putOctal(header.size, sizeof(header.size), statbuf->st_size);
845 errorMsg("%s: Unknown file type\n", fileName);
849 /* Calculate and store the checksum (i.e. the sum of all of the bytes of
850 * the header). The checksum field must be filled with blanks for the
851 * calculation. The checksum field is formatted differently from the
852 * other fields: it has [6] digits, a null, then a space -- rather than
853 * digits, followed by a null like the other fields... */
854 memset(header.chksum, ' ', sizeof(header.chksum));
855 cp = (const unsigned char *) &header;
858 putOctal(header.chksum, 7, chksum);
860 /* Now write the header out to disk */
861 if ((size=fullWrite(tbInfo->tarFd, (char*)&header, sizeof(struct TarHeader))) < 0) {
862 errorMsg(io_error, fileName, strerror(errno));
865 /* Pad the header up to the tar block size */
866 for (; size<TAR_BLOCK_SIZE; size++) {
867 write(tbInfo->tarFd, "\0", 1);
869 /* Now do the verbose thing (or not) */
870 if (tbInfo->verboseFlag==TRUE) {
872 if (tbInfo->tarFd == fileno(stdout)) // If the archive goes to stdout, verbose to stderr
874 fprintf(vbFd, "%s\n", header.name);
881 static int writeFileToTarball(const char *fileName, struct stat *statbuf, void* userData)
883 struct TarBallInfo *tbInfo = (struct TarBallInfo *)userData;
885 /* It is against the rules to archive a socket */
886 if (S_ISSOCK(statbuf->st_mode)) {
887 errorMsg("%s: socket ignored\n", fileName);
891 /* It is a bad idea to store the archive we are in the process of creating,
892 * so check the device and inode to be sure that this particular file isn't
894 if (tbInfo->statBuf.st_dev == statbuf->st_dev &&
895 tbInfo->statBuf.st_ino == statbuf->st_ino) {
896 errorMsg("%s: file is the archive; skipping\n", fileName);
900 if (writeTarHeader(tbInfo, fileName, statbuf)==FALSE) {
904 /* Now, if the file is a regular file, copy it out to the tarball */
905 if (S_ISREG(statbuf->st_mode)) {
908 ssize_t size=0, readSize=0;
910 /* open the file we want to archive, and make sure all is well */
911 if ((inputFileFd = open(fileName, O_RDONLY)) < 0) {
912 errorMsg("%s: Cannot open: %s\n", fileName, strerror(errno));
916 /* write the file to the archive */
917 while ( (size = fullRead(inputFileFd, buffer, sizeof(buffer))) > 0 ) {
918 if (fullWrite(tbInfo->tarFd, buffer, size) != size ) {
919 /* Output file seems to have a problem */
920 errorMsg(io_error, fileName, strerror(errno));
926 errorMsg(io_error, fileName, strerror(errno));
929 /* Pad the file up to the tar block size */
930 for (; (readSize%TAR_BLOCK_SIZE) != 0; readSize++) {
931 write(tbInfo->tarFd, "\0", 1);
939 static int writeTarFile(const char* tarName, int tostdoutFlag,
940 int verboseFlag, int argc, char **argv, char** excludeList)
945 struct TarBallInfo tbInfo;
946 tbInfo.verboseFlag = verboseFlag;
948 /* Make sure there is at least one file to tar up. */
950 fatalError("Cowardly refusing to create an empty archive\n");
952 /* Open the tar file for writing. */
953 if (tostdoutFlag == TRUE)
954 tbInfo.tarFd = fileno(stdout);
956 tbInfo.tarFd = open (tarName, O_WRONLY | O_CREAT | O_TRUNC, 0644);
957 if (tbInfo.tarFd < 0) {
958 errorMsg( "Error opening '%s': %s\n", tarName, strerror(errno));
961 tbInfo.excludeList=excludeList;
962 /* Store the stat info for the tarball's file, so
963 * can avoid including the tarball into itself.... */
964 if (fstat(tbInfo.tarFd, &tbInfo.statBuf) < 0)
965 fatalError(io_error, tarName, strerror(errno));
967 /* Set the umask for this process so it doesn't
968 * screw up permission setting for us later. */
971 /* Read the directory/files and iterate over them one at a time */
973 if (recursiveAction(*argv++, TRUE, FALSE, FALSE,
974 writeFileToTarball, writeFileToTarball,
975 (void*) &tbInfo) == FALSE) {
979 /* Write two empty blocks to the end of the archive */
980 for (size=0; size<(2*TAR_BLOCK_SIZE); size++) {
981 write(tbInfo.tarFd, "\0", 1);
984 /* To be pedantically correct, we would check if the tarball
985 * is smaller then 20 tar blocks, and pad it if it was smaller,
986 * but that isn't necessary for GNU tar interoperability, and
987 * so is considered a waste of space */
989 /* Hang up the tools, close up shop, head home */
991 if (errorFlag == TRUE) {
992 errorMsg("Error exit delayed from previous errors\n");