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
42 #define bb_need_name_longer_than_foo
51 #include <sys/types.h>
52 #include <sys/sysmacros.h>
55 /* Tar file constants */
57 #define MAJOR(dev) (((dev)>>8)&0xff)
58 #define MINOR(dev) ((dev)&0xff)
63 /* POSIX tar Header Block, from POSIX 1003.1-1990 */
67 char name[NAME_SIZE]; /* 0-99 */
68 char mode[8]; /* 100-107 */
69 char uid[8]; /* 108-115 */
70 char gid[8]; /* 116-123 */
71 char size[12]; /* 124-135 */
72 char mtime[12]; /* 136-147 */
73 char chksum[8]; /* 148-155 */
74 char typeflag; /* 156-156 */
75 char linkname[NAME_SIZE]; /* 157-256 */
76 char magic[6]; /* 257-262 */
77 char version[2]; /* 263-264 */
78 char uname[32]; /* 265-296 */
79 char gname[32]; /* 297-328 */
80 char devmajor[8]; /* 329-336 */
81 char devminor[8]; /* 337-344 */
82 char prefix[155]; /* 345-499 */
83 char padding[12]; /* 500-512 (pad to exactly the TAR_BLOCK_SIZE) */
85 typedef struct TarHeader TarHeader;
88 /* A few useful constants */
89 #define TAR_MAGIC "ustar" /* ustar and a null */
90 #define TAR_VERSION " " /* Be compatable with GNU tar format */
91 #define TAR_MAGIC_LEN 6
92 #define TAR_VERSION_LEN 2
93 #define TAR_BLOCK_SIZE 512
95 /* A nice enum with all the possible tar file content types */
98 REGTYPE = '0', /* regular file */
99 REGTYPE0 = '\0', /* regular file (ancient bug compat)*/
100 LNKTYPE = '1', /* hard link */
101 SYMTYPE = '2', /* symbolic link */
102 CHRTYPE = '3', /* character special */
103 BLKTYPE = '4', /* block special */
104 DIRTYPE = '5', /* directory */
105 FIFOTYPE = '6', /* FIFO special */
106 CONTTYPE = '7', /* reserved */
107 GNULONGLINK = 'K', /* GNU long (>100 chars) link name */
108 GNULONGNAME = 'L', /* GNU long (>100 chars) file name */
110 typedef enum TarFileType TarFileType;
112 /* This struct ignores magic, non-numeric user name,
113 * non-numeric group name, and the checksum, since
114 * these are all ignored by BusyBox tar. */
117 int tarFd; /* An open file descriptor for reading from the tarball */
118 char * name; /* File name */
119 mode_t mode; /* Unix mode, including device bits. */
120 uid_t uid; /* Numeric UID */
121 gid_t gid; /* Numeric GID */
122 size_t size; /* Size of file */
123 time_t mtime; /* Last-modified time */
124 enum TarFileType type; /* Regular, directory, link, etc */
125 char * linkname; /* Name for symbolic and hard links */
126 long devmajor; /* Major number for special device */
127 long devminor; /* Minor number for special device */
129 typedef struct TarInfo TarInfo;
131 /* Local procedures to restore files from a tar file. */
132 static int readTarFile(const char* tarName, int extractFlag, int listFlag,
133 int tostdoutFlag, int verboseFlag, char** extractList,
138 #ifdef BB_FEATURE_TAR_CREATE
139 /* Local procedures to save files into a tar file. */
140 static int writeTarFile(const char* tarName, int verboseFlag, char **argv,
144 extern int tar_main(int argc, char **argv)
146 char** excludeList=NULL;
147 #if defined BB_FEATURE_TAR_EXCLUDE
148 int excludeListSize=0;
150 const char *tarName="-";
151 int listFlag = FALSE;
152 int extractFlag = FALSE;
153 int createFlag = FALSE;
154 int verboseFlag = FALSE;
155 int tostdoutFlag = FALSE;
163 while (*(++argv) && (**argv == '-' || firstOpt == TRUE)) {
166 while (stopIt==FALSE && **argv) {
167 switch (*((*argv)++)) {
169 if (extractFlag == TRUE || listFlag == TRUE)
174 if (listFlag == TRUE || createFlag == TRUE)
179 if (extractFlag == TRUE || createFlag == TRUE)
191 fatalError( "Only one 'f' option allowed\n");
194 fatalError( "Option requires an argument: No file specified\n");
197 #if defined BB_FEATURE_TAR_EXCLUDE
199 if (strcmp(*argv, "exclude")==0) {
200 excludeList=xrealloc( excludeList, sizeof(char**) * (excludeListSize+2));
201 excludeList[excludeListSize] = *(++argv);
202 if (excludeList[excludeListSize] == NULL)
203 fatalError( "Option requires an argument: No file specified\n");
204 /* Remove leading "/"s */
205 if (*excludeList[excludeListSize] =='/')
206 excludeList[excludeListSize] = (excludeList[excludeListSize])+1;
207 /* Tack a NULL onto the end of the list */
208 excludeList[++excludeListSize] = NULL;
222 * Do the correct type of action supplying the rest of the
223 * command line arguments as the list of files to process.
225 if (createFlag == TRUE) {
226 #ifndef BB_FEATURE_TAR_CREATE
227 fatalError( "This version of tar was not compiled with tar creation support.\n");
229 exit(writeTarFile(tarName, verboseFlag, argv, excludeList));
232 if (listFlag == TRUE || extractFlag == TRUE) {
233 exit(readTarFile(tarName, extractFlag, listFlag, tostdoutFlag,
234 verboseFlag, argv, excludeList));
238 fatalError( "Exactly one of 'c', 'x' or 't' must be specified\n");
242 fixUpPermissions(TarInfo *header)
245 /* Now set permissions etc for the new file */
246 chown(header->name, header->uid, header->gid);
247 chmod(header->name, header->mode);
250 t.modtime = header->mtime;
251 utime(header->name, &t);
255 tarExtractRegularFile(TarInfo *header, int extractFlag, int tostdoutFlag)
259 size_t actualWriteSz;
261 size_t size = header->size;
262 int outFd=fileno(stdout);
264 /* Open the file to be written, if a file is supposed to be written */
265 if (extractFlag==TRUE && tostdoutFlag==FALSE) {
266 /* Create the path to the file, just in case it isn't there...
267 * This should not screw up path permissions or anything. */
268 createPath(header->name, 0777);
269 if ((outFd=open(header->name, O_CREAT|O_TRUNC|O_WRONLY,
270 header->mode & ~S_IFMT)) < 0) {
271 errorMsg(io_error, header->name, strerror(errno));
276 /* Write out the file, if we are supposed to be doing that */
279 if ( size > sizeof(buffer) )
280 writeSize = readSize = sizeof(buffer);
282 int mod = size % 512;
284 readSize = size + (512 - mod);
289 if ( (readSize = fullRead(header->tarFd, buffer, readSize)) <= 0 ) {
290 /* Tarball seems to have a problem */
291 errorMsg("Unexpected EOF in archive\n");
294 if ( readSize < writeSize )
295 writeSize = readSize;
297 /* Write out the file, if we are supposed to be doing that */
298 if (extractFlag==TRUE) {
300 if ((actualWriteSz=fullWrite(outFd, buffer, writeSize)) != writeSize ) {
301 /* Output file seems to have a problem */
302 errorMsg(io_error, header->name, strerror(errno));
306 actualWriteSz=writeSize;
309 size -= actualWriteSz;
312 /* Now we are done writing the file out, so try
313 * and fix up the permissions and whatnot */
314 if (extractFlag==TRUE && tostdoutFlag==FALSE) {
316 fixUpPermissions(header);
322 tarExtractDirectory(TarInfo *header, int extractFlag, int tostdoutFlag)
325 if (extractFlag==FALSE || tostdoutFlag==TRUE)
328 if (createPath(header->name, header->mode) != TRUE) {
329 errorMsg("%s: Cannot mkdir: %s\n",
330 header->name, strerror(errno));
333 /* make the final component, just in case it was
334 * omitted by createPath() (which will skip the
335 * directory if it doesn't have a terminating '/') */
336 if (mkdir(header->name, header->mode) == 0) {
337 fixUpPermissions(header);
343 tarExtractHardLink(TarInfo *header, int extractFlag, int tostdoutFlag)
345 if (extractFlag==FALSE || tostdoutFlag==TRUE)
348 if (link(header->linkname, header->name) < 0) {
349 errorMsg("%s: Cannot create hard link to '%s': %s\n",
350 header->name, header->linkname, strerror(errno));
354 /* Now set permissions etc for the new directory */
355 fixUpPermissions(header);
360 tarExtractSymLink(TarInfo *header, int extractFlag, int tostdoutFlag)
362 if (extractFlag==FALSE || tostdoutFlag==TRUE)
366 if (symlink(header->linkname, header->name) < 0) {
367 errorMsg("%s: Cannot create symlink to '%s': %s\n",
368 header->name, header->linkname, strerror(errno));
371 /* Try to change ownership of the symlink.
372 * If libs doesn't support that, don't bother.
373 * Changing the pointed-to-file is the Wrong Thing(tm).
375 #if (__GLIBC__ >= 2) && (__GLIBC_MINOR__ >= 1)
376 lchown(header->name, header->uid, header->gid);
379 /* Do not change permissions or date on symlink,
380 * since it changes the pointed to file instead. duh. */
382 errorMsg("%s: Cannot create symlink to '%s': %s\n",
383 header->name, header->linkname,
384 "symlinks not supported");
390 tarExtractSpecial(TarInfo *header, int extractFlag, int tostdoutFlag)
392 if (extractFlag==FALSE || tostdoutFlag==TRUE)
395 if (S_ISCHR(header->mode) || S_ISBLK(header->mode) || S_ISSOCK(header->mode)) {
396 if (mknod(header->name, header->mode, makedev(header->devmajor, header->devminor)) < 0) {
397 errorMsg("%s: Cannot mknod: %s\n",
398 header->name, strerror(errno));
401 } else if (S_ISFIFO(header->mode)) {
402 if (mkfifo(header->name, header->mode) < 0) {
403 errorMsg("%s: Cannot mkfifo: %s\n",
404 header->name, strerror(errno));
409 /* Now set permissions etc for the new directory */
410 fixUpPermissions(header);
414 /* Read an octal value in a field of the specified width, with optional
415 * spaces on both sides of the number and with an optional null character
416 * at the end. Returns -1 on an illegal format. */
417 static long getOctal(const char *cp, int size)
421 for(;(size > 0) && (*cp == ' '); cp++, size--);
422 if ((size == 0) || !isOctal(*cp))
424 for(; (size > 0) && isOctal(*cp); size--) {
425 val = val * 8 + *cp++ - '0';
427 for (;(size > 0) && (*cp == ' '); cp++, size--);
428 if ((size > 0) && *cp)
434 /* Parse the tar header and fill in the nice struct with the details */
436 readTarHeader(struct TarHeader *rawHeader, struct TarInfo *header)
440 unsigned char *s = (unsigned char *)rawHeader;
442 header->name = rawHeader->name;
443 /* Check for and relativify any absolute paths */
444 if ( *(header->name) == '/' ) {
445 static int alreadyWarned=FALSE;
447 while (*(header->name) == '/')
450 if (alreadyWarned == FALSE) {
451 errorMsg("Removing leading '/' from member names\n");
452 alreadyWarned = TRUE;
456 header->mode = getOctal(rawHeader->mode, sizeof(rawHeader->mode));
457 header->uid = getOctal(rawHeader->uid, sizeof(rawHeader->uid));
458 header->gid = getOctal(rawHeader->gid, sizeof(rawHeader->gid));
459 header->size = getOctal(rawHeader->size, sizeof(rawHeader->size));
460 header->mtime = getOctal(rawHeader->mtime, sizeof(rawHeader->mtime));
461 chksum = getOctal(rawHeader->chksum, sizeof(rawHeader->chksum));
462 header->type = rawHeader->typeflag;
463 header->linkname = rawHeader->linkname;
464 header->devmajor = getOctal(rawHeader->devmajor, sizeof(rawHeader->devmajor));
465 header->devminor = getOctal(rawHeader->devminor, sizeof(rawHeader->devminor));
467 /* Check the checksum */
468 for (i = sizeof(*rawHeader); i-- != 0;) {
471 /* Remove the effects of the checksum field (replace
472 * with blanks for the purposes of the checksum) */
473 s = rawHeader->chksum;
474 for (i = sizeof(rawHeader->chksum) ; i-- != 0;) {
477 sum += ' ' * sizeof(rawHeader->chksum);
485 * Read a tar file and extract or list the specified files within it.
486 * If the list is empty than all files are extracted or listed.
488 static int readTarFile(const char* tarName, int extractFlag, int listFlag,
489 int tostdoutFlag, int verboseFlag, char** extractList,
492 int status, tarFd=-1;
494 int skipNextHeaderFlag=FALSE;
499 /* Open the tar file for reading. */
500 if (!strcmp(tarName, "-"))
501 tarFd = fileno(stdin);
503 tarFd = open(tarName, O_RDONLY);
505 errorMsg( "Error opening '%s': %s\n", tarName, strerror(errno));
509 /* Set the umask for this process so it doesn't
510 * screw up permission setting for us later. */
513 /* Read the tar file, and iterate over it one file at a time */
514 while ( (status = fullRead(tarFd, (char*)&rawHeader, TAR_BLOCK_SIZE)) == TAR_BLOCK_SIZE ) {
516 /* Try to read the header */
517 if ( readTarHeader(&rawHeader, &header) == FALSE ) {
518 if ( *(header.name) == '\0' ) {
522 errorMsg("Bad tar header, skipping\n");
526 if ( *(header.name) == '\0' )
528 header.tarFd = tarFd;
530 /* Skip funky extra GNU headers that precede long files */
531 if ( (header.type == GNULONGNAME) || (header.type == GNULONGLINK) ) {
532 skipNextHeaderFlag=TRUE;
533 tarExtractRegularFile(&header, FALSE, FALSE);
536 if ( skipNextHeaderFlag == TRUE ) {
537 skipNextHeaderFlag=FALSE;
538 errorMsg(name_longer_than_foo, NAME_SIZE);
539 tarExtractRegularFile(&header, FALSE, FALSE);
543 #if defined BB_FEATURE_TAR_EXCLUDE
546 /* Check for excluded files.... */
547 for (tmpList=excludeList; tmpList && *tmpList; tmpList++) {
548 /* Do some extra hoop jumping for when directory names
549 * end in '/' but the entry in tmpList doesn't */
550 if (strncmp( *tmpList, header.name, strlen(*tmpList))==0 || (
551 header.name[strlen(header.name)-1]=='/'
552 && strncmp( *tmpList, header.name,
553 MIN(strlen(header.name)-1, strlen(*tmpList)))==0)) {
554 /* If it is a regular file, pretend to extract it with
555 * the extractFlag set to FALSE, so the junk in the tarball
556 * is properly skipped over */
557 if ( header.type==REGTYPE || header.type==REGTYPE0 ) {
558 tarExtractRegularFile(&header, FALSE, FALSE);
564 /* There are not the droids you're looking for, move along */
569 if (*extractList != NULL) {
571 for (tmpList = extractList; *tmpList != NULL; tmpList++) {
572 if (strncmp( *tmpList, header.name, strlen(*tmpList))==0 || (
573 header.name[strlen(header.name)-1]=='/'
574 && strncmp( *tmpList, header.name,
575 MIN(strlen(header.name)-1, strlen(*tmpList)))==0)) {
576 /* If it is a regular file, pretend to extract it with
577 * the extractFlag set to FALSE, so the junk in the tarball
578 * is properly skipped over */
583 /* There are not the droids you're looking for, move along */
584 if (skipFlag == TRUE) {
585 if ( header.type==REGTYPE || header.type==REGTYPE0 )
586 tarExtractRegularFile(&header, FALSE, FALSE);
591 if (listFlag == TRUE) {
592 /* Special treatment if the list (-t) flag is on */
593 if (verboseFlag == TRUE) {
596 struct tm *tm = localtime (&(header.mtime));
598 len=printf("%s ", modeString(header.mode));
599 memset(buf, 0, 8*sizeof(char));
600 my_getpwuid(buf, header.uid);
602 len+=printf("%d", header.uid);
604 len+=printf("%s", buf);
605 memset(buf, 0, 8*sizeof(char));
606 my_getgrgid(buf, header.gid);
608 len+=printf("/%-d ", header.gid);
610 len+=printf("/%-s ", buf);
612 if (header.type==CHRTYPE || header.type==BLKTYPE) {
613 len1=snprintf(buf, sizeof(buf), "%ld,%-ld ",
614 header.devmajor, header.devminor);
616 len1=snprintf(buf, sizeof(buf), "%lu ", (long)header.size);
618 /* Jump through some hoops to make the columns match up */
619 for(;(len+len1)<31;len++)
623 /* Use ISO 8610 time format */
625 printf ("%04d-%02d-%02d %02d:%02d:%02d ",
626 tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday,
627 tm->tm_hour, tm->tm_min, tm->tm_sec);
630 printf("%s", header.name);
631 if (verboseFlag == TRUE) {
632 if (header.type==LNKTYPE) /* If this is a link, say so */
633 printf(" link to %s", header.linkname);
634 else if (header.type==SYMTYPE)
635 printf(" -> %s", header.linkname);
640 /* List contents if we are supposed to do that */
641 if (verboseFlag == TRUE && extractFlag == TRUE) {
642 /* Now the normal listing */
644 if (tostdoutFlag == TRUE) // If the archive goes to stdout, verbose to stderr
646 fprintf(vbFd, "%s\n", header.name);
649 /* Remove files if we would overwrite them */
650 if (extractFlag == TRUE && tostdoutFlag == FALSE)
653 /* If we got here, we can be certain we have a legitimate
654 * header to work with. So work with it. */
655 switch ( header.type ) {
658 /* If the name ends in a '/' then assume it is
659 * supposed to be a directory, and fall through */
660 if (header.name[strlen(header.name)-1] != '/') {
661 if (tarExtractRegularFile(&header, extractFlag, tostdoutFlag)==FALSE)
666 if (tarExtractDirectory( &header, extractFlag, tostdoutFlag)==FALSE)
670 if (tarExtractHardLink( &header, extractFlag, tostdoutFlag)==FALSE)
674 if (tarExtractSymLink( &header, extractFlag, tostdoutFlag)==FALSE)
680 if (tarExtractSpecial( &header, extractFlag, tostdoutFlag)==FALSE)
684 /* Handled earlier */
687 skipNextHeaderFlag=TRUE;
691 errorMsg("Unknown file type '%c' in tar file\n", header.type);
698 /* Bummer - we read a partial header */
699 errorMsg( "Error reading '%s': %s\n", tarName, strerror(errno));
702 else if (errorFlag==TRUE) {
703 errorMsg( "Error exit delayed from previous errors\n");
708 /* Stuff to do when we are done */
711 if ( *(header.name) == '\0' ) {
713 errorMsg( "Error exit delayed from previous errors\n");
721 #ifdef BB_FEATURE_TAR_CREATE
723 /* Some info to be carried along when creating a new tarball */
726 char* fileName; /* File name of the tarball */
727 int tarFd; /* Open-for-write file descriptor
729 struct stat statBuf; /* Stat info for the tarball, letting
730 us know the inode and device that the
731 tarball lives, so we can avoid trying
732 to include the tarball into itself */
733 int verboseFlag; /* Whether to print extra stuff or not */
734 char** excludeList; /* List of files to not include */
736 typedef struct TarBallInfo TarBallInfo;
739 /* Put an octal string into the specified buffer.
740 * The number is zero and space padded and possibly null padded.
741 * Returns TRUE if successful. */
742 static int putOctal (char *cp, int len, long value)
746 char *tempString = tempBuffer;
748 /* Create a string of the specified length with an initial space,
749 * leading zeroes and the octal number, and a trailing null. */
750 sprintf (tempString, "%0*lo", len - 1, value);
752 /* If the string is too large, suppress the leading space. */
753 tempLength = strlen (tempString) + 1;
754 if (tempLength > len) {
759 /* If the string is still too large, suppress the trailing null. */
760 if (tempLength > len)
763 /* If the string is still too large, fail. */
764 if (tempLength > len)
767 /* Copy the string to the field. */
768 memcpy (cp, tempString, len);
773 /* Write out a tar header for the specified file/directory/whatever */
775 writeTarHeader(struct TarBallInfo *tbInfo, const char *fileName, struct stat *statbuf)
778 struct TarHeader header;
779 #if defined BB_FEATURE_TAR_EXCLUDE
782 const unsigned char *cp = (const unsigned char *) &header;
783 ssize_t size = sizeof(struct TarHeader);
785 memset( &header, 0, size);
787 if (*fileName=='/') {
788 static int alreadyWarned=FALSE;
789 if (alreadyWarned==FALSE) {
790 errorMsg("Removing leading '/' from member names\n");
793 strncpy(header.name, fileName+1, sizeof(header.name));
796 strncpy(header.name, fileName, sizeof(header.name));
799 #if defined BB_FEATURE_TAR_EXCLUDE
800 /* Check for excluded files.... */
801 for (tmpList=tbInfo->excludeList; tmpList && *tmpList; tmpList++) {
802 /* Do some extra hoop jumping for when directory names
803 * end in '/' but the entry in tmpList doesn't */
804 if (strncmp( *tmpList, header.name, strlen(*tmpList))==0 || (
805 header.name[strlen(header.name)-1]=='/'
806 && strncmp( *tmpList, header.name,
807 MIN(strlen(header.name)-1, strlen(*tmpList)))==0)) {
808 /* Set the mode to something that is not a regular file, thereby
809 * faking out writeTarFile into thinking that nothing further need
810 * be done for this file. Yes, I know this is ugly, but it works. */
811 statbuf->st_mode = 0;
817 putOctal(header.mode, sizeof(header.mode), statbuf->st_mode);
818 putOctal(header.uid, sizeof(header.uid), statbuf->st_uid);
819 putOctal(header.gid, sizeof(header.gid), statbuf->st_gid);
820 putOctal(header.size, sizeof(header.size), 0); /* Regular file size is handled later */
821 putOctal(header.mtime, sizeof(header.mtime), statbuf->st_mtime);
822 strncpy(header.magic, TAR_MAGIC TAR_VERSION,
823 TAR_MAGIC_LEN + TAR_VERSION_LEN );
825 /* Enter the user and group names (default to root if it fails) */
826 my_getpwuid(header.uname, statbuf->st_uid);
828 strcpy(header.uname, "root");
829 my_getgrgid(header.gname, statbuf->st_gid);
831 strcpy(header.uname, "root");
833 /* WARNING/NOTICE: I break Hard Links */
834 if (S_ISLNK(statbuf->st_mode)) {
837 header.typeflag = SYMTYPE;
838 link_size = readlink(fileName, buffer, sizeof(buffer) - 1);
839 if ( link_size < 0) {
840 errorMsg("Error reading symlink '%s': %s\n", header.name, strerror(errno));
843 buffer[link_size] = '\0';
844 strncpy(header.linkname, buffer, sizeof(header.linkname));
845 } else if (S_ISDIR(statbuf->st_mode)) {
846 header.typeflag = DIRTYPE;
847 strncat(header.name, "/", sizeof(header.name));
848 } else if (S_ISCHR(statbuf->st_mode)) {
849 header.typeflag = CHRTYPE;
850 putOctal(header.devmajor, sizeof(header.devmajor), MAJOR(statbuf->st_rdev));
851 putOctal(header.devminor, sizeof(header.devminor), MINOR(statbuf->st_rdev));
852 } else if (S_ISBLK(statbuf->st_mode)) {
853 header.typeflag = BLKTYPE;
854 putOctal(header.devmajor, sizeof(header.devmajor), MAJOR(statbuf->st_rdev));
855 putOctal(header.devminor, sizeof(header.devminor), MINOR(statbuf->st_rdev));
856 } else if (S_ISFIFO(statbuf->st_mode)) {
857 header.typeflag = FIFOTYPE;
858 } else if (S_ISREG(statbuf->st_mode)) {
859 header.typeflag = REGTYPE;
860 putOctal(header.size, sizeof(header.size), statbuf->st_size);
862 errorMsg("%s: Unknown file type\n", fileName);
866 /* Calculate and store the checksum (i.e. the sum of all of the bytes of
867 * the header). The checksum field must be filled with blanks for the
868 * calculation. The checksum field is formatted differently from the
869 * other fields: it has [6] digits, a null, then a space -- rather than
870 * digits, followed by a null like the other fields... */
871 memset(header.chksum, ' ', sizeof(header.chksum));
872 cp = (const unsigned char *) &header;
875 putOctal(header.chksum, 7, chksum);
877 /* Now write the header out to disk */
878 if ((size=fullWrite(tbInfo->tarFd, (char*)&header, sizeof(struct TarHeader))) < 0) {
879 errorMsg(io_error, fileName, strerror(errno));
882 /* Pad the header up to the tar block size */
883 for (; size<TAR_BLOCK_SIZE; size++) {
884 write(tbInfo->tarFd, "\0", 1);
886 /* Now do the verbose thing (or not) */
887 if (tbInfo->verboseFlag==TRUE) {
889 if (tbInfo->tarFd == fileno(stdout)) // If the archive goes to stdout, verbose to stderr
891 fprintf(vbFd, "%s\n", header.name);
898 static int writeFileToTarball(const char *fileName, struct stat *statbuf, void* userData)
900 struct TarBallInfo *tbInfo = (struct TarBallInfo *)userData;
902 /* It is against the rules to archive a socket */
903 if (S_ISSOCK(statbuf->st_mode)) {
904 errorMsg("%s: socket ignored\n", fileName);
908 /* It is a bad idea to store the archive we are in the process of creating,
909 * so check the device and inode to be sure that this particular file isn't
911 if (tbInfo->statBuf.st_dev == statbuf->st_dev &&
912 tbInfo->statBuf.st_ino == statbuf->st_ino) {
913 errorMsg("%s: file is the archive; skipping\n", fileName);
917 if (strlen(fileName) >= NAME_SIZE) {
918 errorMsg(name_longer_than_foo, NAME_SIZE);
922 if (writeTarHeader(tbInfo, fileName, statbuf)==FALSE) {
926 /* Now, if the file is a regular file, copy it out to the tarball */
927 if (S_ISREG(statbuf->st_mode)) {
930 ssize_t size=0, readSize=0;
932 /* open the file we want to archive, and make sure all is well */
933 if ((inputFileFd = open(fileName, O_RDONLY)) < 0) {
934 errorMsg("%s: Cannot open: %s\n", fileName, strerror(errno));
938 /* write the file to the archive */
939 while ( (size = fullRead(inputFileFd, buffer, sizeof(buffer))) > 0 ) {
940 if (fullWrite(tbInfo->tarFd, buffer, size) != size ) {
941 /* Output file seems to have a problem */
942 errorMsg(io_error, fileName, strerror(errno));
948 errorMsg(io_error, fileName, strerror(errno));
951 /* Pad the file up to the tar block size */
952 for (; (readSize%TAR_BLOCK_SIZE) != 0; readSize++) {
953 write(tbInfo->tarFd, "\0", 1);
961 static int writeTarFile(const char* tarName, int verboseFlag, char **argv,
967 struct TarBallInfo tbInfo;
968 tbInfo.verboseFlag = verboseFlag;
970 /* Make sure there is at least one file to tar up. */
972 fatalError("Cowardly refusing to create an empty archive\n");
974 /* Open the tar file for writing. */
975 if (!strcmp(tarName, "-"))
976 tbInfo.tarFd = fileno(stdout);
978 tbInfo.tarFd = open (tarName, O_WRONLY | O_CREAT | O_TRUNC, 0644);
979 if (tbInfo.tarFd < 0) {
980 errorMsg( "Error opening '%s': %s\n", tarName, strerror(errno));
983 tbInfo.excludeList=excludeList;
984 /* Store the stat info for the tarball's file, so
985 * can avoid including the tarball into itself.... */
986 if (fstat(tbInfo.tarFd, &tbInfo.statBuf) < 0)
987 fatalError(io_error, tarName, strerror(errno));
989 /* Set the umask for this process so it doesn't
990 * screw up permission setting for us later. */
993 /* Read the directory/files and iterate over them one at a time */
994 while (*argv != NULL) {
995 if (recursiveAction(*argv++, TRUE, FALSE, FALSE,
996 writeFileToTarball, writeFileToTarball,
997 (void*) &tbInfo) == FALSE) {
1001 /* Write two empty blocks to the end of the archive */
1002 for (size=0; size<(2*TAR_BLOCK_SIZE); size++) {
1003 write(tbInfo.tarFd, "\0", 1);
1006 /* To be pedantically correct, we would check if the tarball
1007 * is smaller than 20 tar blocks, and pad it if it was smaller,
1008 * but that isn't necessary for GNU tar interoperability, and
1009 * so is considered a waste of space */
1011 /* Hang up the tools, close up shop, head home */
1013 if (errorFlag == TRUE) {
1014 errorMsg("Error exit delayed from previous errors\n");