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>
53 /* Tar file constants */
55 #define MAJOR(dev) (((dev)>>8)&0xff)
56 #define MINOR(dev) ((dev)&0xff)
60 /* POSIX tar Header Block, from POSIX 1003.1-1990 */
64 char name[100]; /* 0-99 */
65 char mode[8]; /* 100-107 */
66 char uid[8]; /* 108-115 */
67 char gid[8]; /* 116-123 */
68 char size[12]; /* 124-135 */
69 char mtime[12]; /* 136-147 */
70 char chksum[8]; /* 148-155 */
71 char typeflag; /* 156-156 */
72 char linkname[100]; /* 157-256 */
73 char magic[6]; /* 257-262 */
74 char version[2]; /* 263-264 */
75 char uname[32]; /* 265-296 */
76 char gname[32]; /* 297-328 */
77 char devmajor[8]; /* 329-336 */
78 char devminor[8]; /* 337-344 */
79 char prefix[155]; /* 345-499 */
80 char padding[12]; /* 500-512 (pad to exactly the TAR_BLOCK_SIZE) */
82 typedef struct TarHeader TarHeader;
85 /* A few useful constants */
86 #define TAR_MAGIC "ustar" /* ustar and a null */
87 #define TAR_VERSION " " /* Be compatable with GNU tar format */
88 #define TAR_MAGIC_LEN 6
89 #define TAR_VERSION_LEN 2
90 #define TAR_BLOCK_SIZE 512
92 /* A nice enum with all the possible tar file content types */
95 REGTYPE = '0', /* regular file */
96 REGTYPE0 = '\0', /* regular file (ancient bug compat)*/
97 LNKTYPE = '1', /* hard link */
98 SYMTYPE = '2', /* symbolic link */
99 CHRTYPE = '3', /* character special */
100 BLKTYPE = '4', /* block special */
101 DIRTYPE = '5', /* directory */
102 FIFOTYPE = '6', /* FIFO special */
103 CONTTYPE = '7', /* reserved */
105 typedef enum TarFileType TarFileType;
107 /* This struct ignores magic, non-numeric user name,
108 * non-numeric group name, and the checksum, since
109 * these are all ignored by BusyBox tar. */
112 int tarFd; /* An open file descriptor for reading from the tarball */
113 char * name; /* File name */
114 mode_t mode; /* Unix mode, including device bits. */
115 uid_t uid; /* Numeric UID */
116 gid_t gid; /* Numeric GID */
117 size_t size; /* Size of file */
118 time_t mtime; /* Last-modified time */
119 enum TarFileType type; /* Regular, directory, link, etc */
120 char * linkname; /* Name for symbolic and hard links */
121 long devmajor; /* Major number for special device */
122 long devminor; /* Minor number for special device */
124 typedef struct TarInfo TarInfo;
126 /* Local procedures to restore files from a tar file. */
127 static int readTarFile(const char* tarName, int extractFlag, int listFlag,
128 int tostdoutFlag, int verboseFlag, char** extractList,
133 #ifdef BB_FEATURE_TAR_CREATE
134 /* Local procedures to save files into a tar file. */
135 static int writeTarFile(const char* tarName, int tostdoutFlag,
136 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;
157 /* do normal option parsing */
158 while ((opt = getopt(argc, argv, "cxtvOf:-:")) > 0) {
161 if (extractFlag == TRUE || listFlag == TRUE)
166 if (listFlag == TRUE || createFlag == TRUE)
171 if (extractFlag == TRUE || createFlag == TRUE)
184 fatalError( "Only one 'f' option allowed\n");
186 if (!strcmp(tarName, "-") && createFlag == TRUE)
190 #if defined BB_FEATURE_TAR_EXCLUDE
191 if (strcmp(optarg, "exclude")==0) {
192 if (argv[optind]==NULL)
193 fatalError( "option `--exclude' requires an argument\n");
194 excludeList=xrealloc( excludeList, sizeof(char**) * (excludeListSize+2));
195 excludeList[excludeListSize] = argv[optind];
196 /* Remove leading "/"s */
197 if (*excludeList[excludeListSize] =='/') {
198 excludeList[excludeListSize] = (excludeList[excludeListSize])+1;
200 /* Tack a NULL onto the end of the list */
201 excludeList[excludeListSize] = NULL;
206 fatalError( "Unknown tar flag '%s'\n"
207 "Try `tar --help' for more information\n", optarg);
209 fatalError( "Unknown tar flag '%c'\n"
210 "Try `tar --help' for more information\n", **argv);
215 * Do the correct type of action supplying the rest of the
216 * command line arguments as the list of files to process.
218 if (createFlag == TRUE) {
219 #ifndef BB_FEATURE_TAR_CREATE
220 fatalError( "This version of tar was not compiled with tar creation support.\n");
222 exit(writeTarFile(tarName, tostdoutFlag, verboseFlag, argc-optind, &argv[optind], excludeList));
225 if (listFlag == TRUE || extractFlag == TRUE) {
226 exit(readTarFile(tarName, extractFlag, listFlag, tostdoutFlag, verboseFlag, &argv[optind], excludeList));
230 fatalError( "Exactly one of 'c', 'x' or 't' must be specified\n");
234 fixUpPermissions(TarInfo *header)
237 /* Now set permissions etc for the new file */
238 chown(header->name, header->uid, header->gid);
239 chmod(header->name, header->mode);
242 t.modtime = header->mtime;
243 utime(header->name, &t);
247 tarExtractRegularFile(TarInfo *header, int extractFlag, int tostdoutFlag)
251 size_t actualWriteSz;
253 size_t size = header->size;
254 int outFd=fileno(stdout);
256 /* Open the file to be written, if a file is supposed to be written */
257 if (extractFlag==TRUE && tostdoutFlag==FALSE) {
258 /* Create the path to the file, just in case it isn't there...
259 * This should not screw up path permissions or anything. */
260 createPath(header->name, 0777);
261 if ((outFd=open(header->name, O_CREAT|O_TRUNC|O_WRONLY,
262 header->mode & ~S_IFMT)) < 0) {
263 errorMsg(io_error, header->name, strerror(errno));
268 /* Write out the file, if we are supposed to be doing that */
271 if ( size > sizeof(buffer) )
272 writeSize = readSize = sizeof(buffer);
274 int mod = size % 512;
276 readSize = size + (512 - mod);
281 if ( (readSize = fullRead(header->tarFd, buffer, readSize)) <= 0 ) {
282 /* Tarball seems to have a problem */
283 errorMsg("Unexpected EOF in archive\n");
286 if ( readSize < writeSize )
287 writeSize = readSize;
289 /* Write out the file, if we are supposed to be doing that */
290 if (extractFlag==TRUE) {
292 if ((actualWriteSz=fullWrite(outFd, buffer, writeSize)) != writeSize ) {
293 /* Output file seems to have a problem */
294 errorMsg(io_error, header->name, strerror(errno));
298 actualWriteSz=writeSize;
301 size -= actualWriteSz;
304 /* Now we are done writing the file out, so try
305 * and fix up the permissions and whatnot */
306 if (extractFlag==TRUE && tostdoutFlag==FALSE) {
308 fixUpPermissions(header);
314 tarExtractDirectory(TarInfo *header, int extractFlag, int tostdoutFlag)
317 if (extractFlag==FALSE || tostdoutFlag==TRUE)
320 if (createPath(header->name, header->mode) != TRUE) {
321 errorMsg("%s: Cannot mkdir: %s\n",
322 header->name, strerror(errno));
325 /* make the final component, just in case it was
326 * omitted by createPath() (which will skip the
327 * directory if it doesn't have a terminating '/') */
328 if (mkdir(header->name, header->mode) == 0) {
329 fixUpPermissions(header);
335 tarExtractHardLink(TarInfo *header, int extractFlag, int tostdoutFlag)
337 if (extractFlag==FALSE || tostdoutFlag==TRUE)
340 if (link(header->linkname, header->name) < 0) {
341 errorMsg("%s: Cannot create hard link to '%s': %s\n",
342 header->name, header->linkname, strerror(errno));
346 /* Now set permissions etc for the new directory */
347 fixUpPermissions(header);
352 tarExtractSymLink(TarInfo *header, int extractFlag, int tostdoutFlag)
354 if (extractFlag==FALSE || tostdoutFlag==TRUE)
358 if (symlink(header->linkname, header->name) < 0) {
359 errorMsg("%s: Cannot create symlink to '%s': %s\n",
360 header->name, header->linkname, strerror(errno));
363 /* Try to change ownership of the symlink.
364 * If libs doesn't support that, don't bother.
365 * Changing the pointed-to-file is the Wrong Thing(tm).
367 #if (__GLIBC__ >= 2) && (__GLIBC_MINOR__ >= 1)
368 lchown(header->name, header->uid, header->gid);
371 /* Do not change permissions or date on symlink,
372 * since it changes the pointed to file instead. duh. */
374 errorMsg("%s: Cannot create symlink to '%s': %s\n",
375 header->name, header->linkname,
376 "symlinks not supported");
382 tarExtractSpecial(TarInfo *header, int extractFlag, int tostdoutFlag)
384 if (extractFlag==FALSE || tostdoutFlag==TRUE)
387 if (S_ISCHR(header->mode) || S_ISBLK(header->mode) || S_ISSOCK(header->mode)) {
388 if (mknod(header->name, header->mode, makedev(header->devmajor, header->devminor)) < 0) {
389 errorMsg("%s: Cannot mknod: %s\n",
390 header->name, strerror(errno));
393 } else if (S_ISFIFO(header->mode)) {
394 if (mkfifo(header->name, header->mode) < 0) {
395 errorMsg("%s: Cannot mkfifo: %s\n",
396 header->name, strerror(errno));
401 /* Now set permissions etc for the new directory */
402 fixUpPermissions(header);
406 /* Read an octal value in a field of the specified width, with optional
407 * spaces on both sides of the number and with an optional null character
408 * at the end. Returns -1 on an illegal format. */
409 static long getOctal(const char *cp, int size)
413 for(;(size > 0) && (*cp == ' '); cp++, size--);
414 if ((size == 0) || !isOctal(*cp))
416 for(; (size > 0) && isOctal(*cp); size--) {
417 val = val * 8 + *cp++ - '0';
419 for (;(size > 0) && (*cp == ' '); cp++, size--);
420 if ((size > 0) && *cp)
426 /* Parse the tar header and fill in the nice struct with the details */
428 readTarHeader(struct TarHeader *rawHeader, struct TarInfo *header)
432 unsigned char *s = (unsigned char *)rawHeader;
434 header->name = rawHeader->name;
435 /* Check for and relativify any absolute paths */
436 if ( *(header->name) == '/' ) {
437 static int alreadyWarned=FALSE;
439 while (*(header->name) == '/')
442 if (alreadyWarned == FALSE) {
443 errorMsg("Removing leading '/' from member names\n");
444 alreadyWarned = TRUE;
448 header->mode = getOctal(rawHeader->mode, sizeof(rawHeader->mode));
449 header->uid = getOctal(rawHeader->uid, sizeof(rawHeader->uid));
450 header->gid = getOctal(rawHeader->gid, sizeof(rawHeader->gid));
451 header->size = getOctal(rawHeader->size, sizeof(rawHeader->size));
452 header->mtime = getOctal(rawHeader->mtime, sizeof(rawHeader->mtime));
453 chksum = getOctal(rawHeader->chksum, sizeof(rawHeader->chksum));
454 header->type = rawHeader->typeflag;
455 header->linkname = rawHeader->linkname;
456 header->devmajor = getOctal(rawHeader->devmajor, sizeof(rawHeader->devmajor));
457 header->devminor = getOctal(rawHeader->devminor, sizeof(rawHeader->devminor));
459 /* Check the checksum */
460 for (i = sizeof(*rawHeader); i-- != 0;) {
463 /* Remove the effects of the checksum field (replace
464 * with blanks for the purposes of the checksum) */
465 s = rawHeader->chksum;
466 for (i = sizeof(rawHeader->chksum) ; i-- != 0;) {
469 sum += ' ' * sizeof(rawHeader->chksum);
477 * Read a tar file and extract or list the specified files within it.
478 * If the list is empty than all files are extracted or listed.
480 static int readTarFile(const char* tarName, int extractFlag, int listFlag,
481 int tostdoutFlag, int verboseFlag, char** extractList,
484 int status, tarFd=-1;
488 #if defined BB_FEATURE_TAR_EXCLUDE
492 /* Open the tar file for reading. */
493 if (!strcmp(tarName, "-"))
494 tarFd = fileno(stdin);
496 tarFd = open(tarName, O_RDONLY);
498 errorMsg( "Error opening '%s': %s\n", tarName, strerror(errno));
502 /* Set the umask for this process so it doesn't
503 * screw up permission setting for us later. */
506 /* Read the tar file, and iterate over it one file at a time */
507 while ( (status = fullRead(tarFd, (char*)&rawHeader, TAR_BLOCK_SIZE)) == TAR_BLOCK_SIZE ) {
509 /* First, try to read the header */
510 if ( readTarHeader(&rawHeader, &header) == FALSE ) {
511 if ( *(header.name) == '\0' ) {
515 errorMsg("Bad tar header, skipping\n");
519 if ( *(header.name) == '\0' )
521 header.tarFd = tarFd;
523 #if defined BB_FEATURE_TAR_EXCLUDE
526 /* Check for excluded files.... */
527 for (tmpList=excludeList; tmpList && *tmpList; tmpList++) {
528 /* Do some extra hoop jumping for when directory names
529 * end in '/' but the entry in tmpList doesn't */
530 if (strncmp( *tmpList, header.name, strlen(*tmpList))==0 || (
531 header.name[strlen(header.name)-1]=='/'
532 && strncmp( *tmpList, header.name,
533 MIN(strlen(header.name)-1, strlen(*tmpList)))==0)) {
534 /* If it is a regular file, pretend to extract it with
535 * the extractFlag set to FALSE, so the junk in the tarball
536 * is properly skipped over */
537 if ( header.type==REGTYPE || header.type==REGTYPE0 ) {
538 tarExtractRegularFile(&header, FALSE, FALSE);
544 /* There are not the droids you're looking for, move along */
549 if (*extractList != NULL) {
551 for (tmpList = extractList; *tmpList != NULL; tmpList++) {
552 if (strncmp( *tmpList, header.name, strlen(*tmpList))==0 || (
553 header.name[strlen(header.name)-1]=='/'
554 && strncmp( *tmpList, header.name,
555 MIN(strlen(header.name)-1, strlen(*tmpList)))==0)) {
556 /* If it is a regular file, pretend to extract it with
557 * the extractFlag set to FALSE, so the junk in the tarball
558 * is properly skipped over */
563 /* There are not the droids you're looking for, move along */
564 if (skipFlag == TRUE) {
565 if ( header.type==REGTYPE || header.type==REGTYPE0 )
566 tarExtractRegularFile(&header, FALSE, FALSE);
570 /* Special treatment if the list (-t) flag is on */
571 if (verboseFlag == TRUE && extractFlag == FALSE) {
574 struct tm *tm = localtime (&(header.mtime));
576 len=printf("%s ", modeString(header.mode));
577 memset(buf, 0, 8*sizeof(char));
578 my_getpwuid(buf, header.uid);
580 len+=printf("%d", header.uid);
582 len+=printf("%s", buf);
583 memset(buf, 0, 8*sizeof(char));
584 my_getgrgid(buf, header.gid);
586 len+=printf("/%-d ", header.gid);
588 len+=printf("/%-s ", buf);
590 if (header.type==CHRTYPE || header.type==BLKTYPE) {
591 len1=snprintf(buf, sizeof(buf), "%ld,%-ld ",
592 header.devmajor, header.devminor);
594 len1=snprintf(buf, sizeof(buf), "%lu ", (long)header.size);
596 /* Jump through some hoops to make the columns match up */
597 for(;(len+len1)<31;len++)
601 /* Use ISO 8610 time format */
603 printf ("%04d-%02d-%02d %02d:%02d:%02d ",
604 tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday,
605 tm->tm_hour, tm->tm_min, tm->tm_sec);
608 /* List contents if we are supposed to do that */
609 if (verboseFlag == TRUE && listFlag != TRUE) {
610 /* Now the normal listing */
612 if (tostdoutFlag == TRUE) // If the archive goes to stdout, verbose to stderr
614 fprintf(vbFd, "%s\n", header.name);
617 if (verboseFlag == TRUE && listFlag == TRUE) {
618 printf("%s", header.name);
619 if (header.type==LNKTYPE) /* If this is a link, say so */
620 printf(" link to %s", header.linkname);
621 else if (header.type==SYMTYPE)
622 printf(" -> %s", header.linkname);
626 /* Remove files if we would overwrite them */
627 if (extractFlag == TRUE && tostdoutFlag == FALSE)
630 /* If we got here, we can be certain we have a legitimate
631 * header to work with. So work with it. */
632 switch ( header.type ) {
635 /* If the name ends in a '/' then assume it is
636 * supposed to be a directory, and fall through */
637 if (header.name[strlen(header.name)-1] != '/') {
638 if (tarExtractRegularFile(&header, extractFlag, tostdoutFlag)==FALSE)
643 if (tarExtractDirectory( &header, extractFlag, tostdoutFlag)==FALSE)
647 if (tarExtractHardLink( &header, extractFlag, tostdoutFlag)==FALSE)
651 if (tarExtractSymLink( &header, extractFlag, tostdoutFlag)==FALSE)
657 if (tarExtractSpecial( &header, extractFlag, tostdoutFlag)==FALSE)
667 /* Bummer - we read a partial header */
668 errorMsg( "Error reading '%s': %s\n", tarName, strerror(errno));
671 else if (errorFlag==TRUE) {
672 errorMsg( "Error exit delayed from previous errors\n");
677 /* Stuff to do when we are done */
680 if ( *(header.name) == '\0' ) {
682 errorMsg( "Error exit delayed from previous errors\n");
690 #ifdef BB_FEATURE_TAR_CREATE
692 /* Some info to be carried along when creating a new tarball */
695 char* fileName; /* File name of the tarball */
696 int tarFd; /* Open-for-write file descriptor
698 struct stat statBuf; /* Stat info for the tarball, letting
699 us know the inode and device that the
700 tarball lives, so we can avoid trying
701 to include the tarball into itself */
702 int verboseFlag; /* Whether to print extra stuff or not */
703 char** excludeList; /* List of files to not include */
705 typedef struct TarBallInfo TarBallInfo;
708 /* Put an octal string into the specified buffer.
709 * The number is zero and space padded and possibly null padded.
710 * Returns TRUE if successful. */
711 static int putOctal (char *cp, int len, long value)
715 char *tempString = tempBuffer;
717 /* Create a string of the specified length with an initial space,
718 * leading zeroes and the octal number, and a trailing null. */
719 sprintf (tempString, "%0*lo", len - 1, value);
721 /* If the string is too large, suppress the leading space. */
722 tempLength = strlen (tempString) + 1;
723 if (tempLength > len) {
728 /* If the string is still too large, suppress the trailing null. */
729 if (tempLength > len)
732 /* If the string is still too large, fail. */
733 if (tempLength > len)
736 /* Copy the string to the field. */
737 memcpy (cp, tempString, len);
742 /* Write out a tar header for the specified file/directory/whatever */
744 writeTarHeader(struct TarBallInfo *tbInfo, const char *fileName, struct stat *statbuf)
747 struct TarHeader header;
748 #if defined BB_FEATURE_TAR_EXCLUDE
751 const unsigned char *cp = (const unsigned char *) &header;
752 ssize_t size = sizeof(struct TarHeader);
754 memset( &header, 0, size);
756 if (*fileName=='/') {
757 static int alreadyWarned=FALSE;
758 if (alreadyWarned==FALSE) {
759 errorMsg("Removing leading '/' from member names\n");
762 strncpy(header.name, fileName+1, sizeof(header.name));
765 strncpy(header.name, fileName, sizeof(header.name));
768 #if defined BB_FEATURE_TAR_EXCLUDE
769 /* Check for excluded files.... */
770 for (tmpList=tbInfo->excludeList; tmpList && *tmpList; tmpList++) {
771 /* Do some extra hoop jumping for when directory names
772 * end in '/' but the entry in tmpList doesn't */
773 if (strncmp( *tmpList, header.name, strlen(*tmpList))==0 || (
774 header.name[strlen(header.name)-1]=='/'
775 && strncmp( *tmpList, header.name,
776 MIN(strlen(header.name)-1, strlen(*tmpList)))==0)) {
777 /* Set the mode to something that is not a regular file, thereby
778 * faking out writeTarFile into thinking that nothing further need
779 * be done for this file. Yes, I know this is ugly, but it works. */
780 statbuf->st_mode = 0;
786 putOctal(header.mode, sizeof(header.mode), statbuf->st_mode);
787 putOctal(header.uid, sizeof(header.uid), statbuf->st_uid);
788 putOctal(header.gid, sizeof(header.gid), statbuf->st_gid);
789 putOctal(header.size, sizeof(header.size), 0); /* Regular file size is handled later */
790 putOctal(header.mtime, sizeof(header.mtime), statbuf->st_mtime);
791 strncpy(header.magic, TAR_MAGIC TAR_VERSION,
792 TAR_MAGIC_LEN + TAR_VERSION_LEN );
794 /* Enter the user and group names (default to root if it fails) */
795 my_getpwuid(header.uname, statbuf->st_uid);
797 strcpy(header.uname, "root");
798 my_getgrgid(header.gname, statbuf->st_gid);
800 strcpy(header.uname, "root");
802 /* WARNING/NOTICE: I break Hard Links */
803 if (S_ISLNK(statbuf->st_mode)) {
806 header.typeflag = SYMTYPE;
807 link_size = readlink(fileName, buffer, sizeof(buffer) - 1);
808 if ( link_size < 0) {
809 errorMsg("Error reading symlink '%s': %s\n", header.name, strerror(errno));
812 buffer[link_size] = '\0';
813 strncpy(header.linkname, buffer, sizeof(header.linkname));
814 } else if (S_ISDIR(statbuf->st_mode)) {
815 header.typeflag = DIRTYPE;
816 strncat(header.name, "/", sizeof(header.name));
817 } else if (S_ISCHR(statbuf->st_mode)) {
818 header.typeflag = CHRTYPE;
819 putOctal(header.devmajor, sizeof(header.devmajor), MAJOR(statbuf->st_rdev));
820 putOctal(header.devminor, sizeof(header.devminor), MINOR(statbuf->st_rdev));
821 } else if (S_ISBLK(statbuf->st_mode)) {
822 header.typeflag = BLKTYPE;
823 putOctal(header.devmajor, sizeof(header.devmajor), MAJOR(statbuf->st_rdev));
824 putOctal(header.devminor, sizeof(header.devminor), MINOR(statbuf->st_rdev));
825 } else if (S_ISFIFO(statbuf->st_mode)) {
826 header.typeflag = FIFOTYPE;
827 } else if (S_ISREG(statbuf->st_mode)) {
828 header.typeflag = REGTYPE;
829 putOctal(header.size, sizeof(header.size), statbuf->st_size);
831 errorMsg("%s: Unknown file type\n", fileName);
835 /* Calculate and store the checksum (i.e. the sum of all of the bytes of
836 * the header). The checksum field must be filled with blanks for the
837 * calculation. The checksum field is formatted differently from the
838 * other fields: it has [6] digits, a null, then a space -- rather than
839 * digits, followed by a null like the other fields... */
840 memset(header.chksum, ' ', sizeof(header.chksum));
841 cp = (const unsigned char *) &header;
844 putOctal(header.chksum, 7, chksum);
846 /* Now write the header out to disk */
847 if ((size=fullWrite(tbInfo->tarFd, (char*)&header, sizeof(struct TarHeader))) < 0) {
848 errorMsg(io_error, fileName, strerror(errno));
851 /* Pad the header up to the tar block size */
852 for (; size<TAR_BLOCK_SIZE; size++) {
853 write(tbInfo->tarFd, "\0", 1);
855 /* Now do the verbose thing (or not) */
856 if (tbInfo->verboseFlag==TRUE) {
858 if (tbInfo->tarFd == fileno(stdout)) // If the archive goes to stdout, verbose to stderr
860 fprintf(vbFd, "%s\n", header.name);
867 static int writeFileToTarball(const char *fileName, struct stat *statbuf, void* userData)
869 struct TarBallInfo *tbInfo = (struct TarBallInfo *)userData;
871 /* It is against the rules to archive a socket */
872 if (S_ISSOCK(statbuf->st_mode)) {
873 errorMsg("%s: socket ignored\n", fileName);
877 /* It is a bad idea to store the archive we are in the process of creating,
878 * so check the device and inode to be sure that this particular file isn't
880 if (tbInfo->statBuf.st_dev == statbuf->st_dev &&
881 tbInfo->statBuf.st_ino == statbuf->st_ino) {
882 errorMsg("%s: file is the archive; skipping\n", fileName);
886 if (writeTarHeader(tbInfo, fileName, statbuf)==FALSE) {
890 /* Now, if the file is a regular file, copy it out to the tarball */
891 if (S_ISREG(statbuf->st_mode)) {
894 ssize_t size=0, readSize=0;
896 /* open the file we want to archive, and make sure all is well */
897 if ((inputFileFd = open(fileName, O_RDONLY)) < 0) {
898 errorMsg("%s: Cannot open: %s\n", fileName, strerror(errno));
902 /* write the file to the archive */
903 while ( (size = fullRead(inputFileFd, buffer, sizeof(buffer))) > 0 ) {
904 if (fullWrite(tbInfo->tarFd, buffer, size) != size ) {
905 /* Output file seems to have a problem */
906 errorMsg(io_error, fileName, strerror(errno));
912 errorMsg(io_error, fileName, strerror(errno));
915 /* Pad the file up to the tar block size */
916 for (; (readSize%TAR_BLOCK_SIZE) != 0; readSize++) {
917 write(tbInfo->tarFd, "\0", 1);
925 static int writeTarFile(const char* tarName, int tostdoutFlag,
926 int verboseFlag, int argc, char **argv, char** excludeList)
931 struct TarBallInfo tbInfo;
932 tbInfo.verboseFlag = verboseFlag;
934 /* Make sure there is at least one file to tar up. */
936 fatalError("Cowardly refusing to create an empty archive\n");
938 /* Open the tar file for writing. */
939 if (tostdoutFlag == TRUE)
940 tbInfo.tarFd = fileno(stdout);
942 tbInfo.tarFd = open (tarName, O_WRONLY | O_CREAT | O_TRUNC, 0644);
943 if (tbInfo.tarFd < 0) {
944 errorMsg( "Error opening '%s': %s\n", tarName, strerror(errno));
947 tbInfo.excludeList=excludeList;
948 /* Store the stat info for the tarball's file, so
949 * can avoid including the tarball into itself.... */
950 if (fstat(tbInfo.tarFd, &tbInfo.statBuf) < 0)
951 fatalError(io_error, tarName, strerror(errno));
953 /* Set the umask for this process so it doesn't
954 * screw up permission setting for us later. */
957 /* Read the directory/files and iterate over them one at a time */
959 if (recursiveAction(*argv++, TRUE, FALSE, FALSE,
960 writeFileToTarball, writeFileToTarball,
961 (void*) &tbInfo) == FALSE) {
965 /* Write two empty blocks to the end of the archive */
966 for (size=0; size<(2*TAR_BLOCK_SIZE); size++) {
967 write(tbInfo.tarFd, "\0", 1);
970 /* To be pedantically correct, we would check if the tarball
971 * is smaller then 20 tar blocks, and pad it if it was smaller,
972 * but that isn't necessary for GNU tar interoperability, and
973 * so is considered a waste of space */
975 /* Hang up the tools, close up shop, head home */
977 if (errorFlag == TRUE) {
978 errorMsg("Error exit delayed from previous errors\n");