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\n"
64 "Create, extract, or list files from a tar file. Note that\n"
65 "this version of tar treats hard links as separate files.\n\n"
66 "Main operation mode:\n"
67 #ifdef BB_FEATURE_TAR_CREATE
73 "\tf\t\tname of tarfile or \"-\" for stdin\n"
74 "\tO\t\textract to stdout\n"
75 #if defined BB_FEATURE_TAR_EXCLUDE
76 "\t--exclude\tfile to exclude\n"
78 "\nInformative output:\n"
79 "\tv\t\tverbosely list files processed\n"
82 /* Tar file constants */
84 #define MAJOR(dev) (((dev)>>8)&0xff)
85 #define MINOR(dev) ((dev)&0xff)
89 /* POSIX tar Header Block, from POSIX 1003.1-1990 */
93 char name[100]; /* 0-99 */
94 char mode[8]; /* 100-107 */
95 char uid[8]; /* 108-115 */
96 char gid[8]; /* 116-123 */
97 char size[12]; /* 124-135 */
98 char mtime[12]; /* 136-147 */
99 char chksum[8]; /* 148-155 */
100 char typeflag; /* 156-156 */
101 char linkname[100]; /* 157-256 */
102 char magic[6]; /* 257-262 */
103 char version[2]; /* 263-264 */
104 char uname[32]; /* 265-296 */
105 char gname[32]; /* 297-328 */
106 char devmajor[8]; /* 329-336 */
107 char devminor[8]; /* 337-344 */
108 char prefix[155]; /* 345-499 */
109 char padding[12]; /* 500-512 (pad to exactly the TAR_BLOCK_SIZE) */
111 typedef struct TarHeader TarHeader;
114 /* A few useful constants */
115 #define TAR_MAGIC "ustar" /* ustar and a null */
116 #define TAR_VERSION " " /* Be compatable with GNU tar format */
117 #define TAR_MAGIC_LEN 6
118 #define TAR_VERSION_LEN 2
119 #define TAR_BLOCK_SIZE 512
121 /* A nice enum with all the possible tar file content types */
124 REGTYPE = '0', /* regular file */
125 REGTYPE0 = '\0', /* regular file (ancient bug compat)*/
126 LNKTYPE = '1', /* hard link */
127 SYMTYPE = '2', /* symbolic link */
128 CHRTYPE = '3', /* character special */
129 BLKTYPE = '4', /* block special */
130 DIRTYPE = '5', /* directory */
131 FIFOTYPE = '6', /* FIFO special */
132 CONTTYPE = '7', /* reserved */
134 typedef enum TarFileType TarFileType;
136 /* This struct ignores magic, non-numeric user name,
137 * non-numeric group name, and the checksum, since
138 * these are all ignored by BusyBox tar. */
141 int tarFd; /* An open file descriptor for reading from the tarball */
142 char * name; /* File name */
143 mode_t mode; /* Unix mode, including device bits. */
144 uid_t uid; /* Numeric UID */
145 gid_t gid; /* Numeric GID */
146 size_t size; /* Size of file */
147 time_t mtime; /* Last-modified time */
148 enum TarFileType type; /* Regular, directory, link, etc */
149 char * linkname; /* Name for symbolic and hard links */
150 long devmajor; /* Major number for special device */
151 long devminor; /* Minor number for special device */
153 typedef struct TarInfo TarInfo;
155 /* Local procedures to restore files from a tar file. */
156 static int readTarFile(const char* tarName, int extractFlag, int listFlag,
157 int tostdoutFlag, int verboseFlag, char** excludeList);
161 #ifdef BB_FEATURE_TAR_CREATE
162 /* Local procedures to save files into a tar file. */
163 static int writeTarFile(const char* tarName, int tostdoutFlag,
164 int verboseFlag, int argc, char **argv, char** excludeList);
168 extern int tar_main(int argc, char **argv)
170 char** excludeList=NULL;
171 #if defined BB_FEATURE_TAR_EXCLUDE
172 int excludeListSize=0;
174 const char *tarName=NULL;
175 int listFlag = FALSE;
176 int extractFlag = FALSE;
177 int createFlag = FALSE;
178 int verboseFlag = FALSE;
179 int tostdoutFlag = FALSE;
185 /* Parse any options */
186 while (--argc > 0 && (**(++argv) != '\0')) {
188 while (stopIt==FALSE && *(++(*argv))) {
192 fatalError( "Option requires an argument: No file specified\n");
195 fatalError( "Only one 'f' option allowed\n");
198 fatalError( "Option requires an argument: No file specified\n");
203 if (extractFlag == TRUE || createFlag == TRUE)
209 if (listFlag == TRUE || createFlag == TRUE)
214 if (extractFlag == TRUE || listFlag == TRUE)
228 #if defined BB_FEATURE_TAR_EXCLUDE
229 if (strcmp(*argv, "-exclude")==0) {
231 fatalError( "Option requires an argument: No file specified\n");
233 excludeList=realloc( excludeList, sizeof(char**) * (excludeListSize+2));
234 excludeList[excludeListSize] = *(++argv);
235 /* Remove leading "/"s */
236 if (*excludeList[excludeListSize] =='/') {
237 excludeList[excludeListSize] = (excludeList[excludeListSize])+1;
239 if (excludeList[excludeListSize++] == NULL)
240 fatalError( "Option requires an argument: No file specified\n");
241 /* Tack a NULL onto the end of the list */
242 excludeList[excludeListSize] = NULL;
250 fatalError( "Unknown tar flag '%c'\n"
251 "Try `tar --help' for more information\n", **argv);
257 * Do the correct type of action supplying the rest of the
258 * command line arguments as the list of files to process.
260 if (createFlag == TRUE) {
261 #ifndef BB_FEATURE_TAR_CREATE
262 fatalError( "This version of tar was not compiled with tar creation support.\n");
264 exit(writeTarFile(tarName, tostdoutFlag, verboseFlag, argc, argv, excludeList));
267 exit(readTarFile(tarName, extractFlag, listFlag, tostdoutFlag, verboseFlag, excludeList));
271 fatalError( "Exactly one of 'c', 'x' or 't' must be specified\n");
275 fixUpPermissions(TarInfo *header)
278 /* Now set permissions etc for the new file */
279 chown(header->name, header->uid, header->gid);
280 chmod(header->name, header->mode);
283 t.modtime = header->mtime;
284 utime(header->name, &t);
288 tarExtractRegularFile(TarInfo *header, int extractFlag, int tostdoutFlag)
292 size_t actualWriteSz;
294 size_t size = header->size;
295 int outFd=fileno(stdout);
297 /* Open the file to be written, if a file is supposed to be written */
298 if (extractFlag==TRUE && tostdoutFlag==FALSE) {
299 if ((outFd=open(header->name, O_CREAT|O_TRUNC|O_WRONLY, header->mode & ~S_IFMT)) < 0)
300 errorMsg(io_error, header->name, strerror(errno));
301 /* Create the path to the file, just in case it isn't there...
302 * This should not screw up path permissions or anything. */
303 createPath(header->name, 0777);
306 /* Write out the file, if we are supposed to be doing that */
309 if ( size > sizeof(buffer) )
310 writeSize = readSize = sizeof(buffer);
312 int mod = size % 512;
314 readSize = size + (512 - mod);
319 if ( (readSize = fullRead(header->tarFd, buffer, readSize)) <= 0 ) {
320 /* Tarball seems to have a problem */
321 errorMsg("tar: Unexpected EOF in archive\n");
324 if ( readSize < writeSize )
325 writeSize = readSize;
327 /* Write out the file, if we are supposed to be doing that */
328 if (extractFlag==TRUE) {
330 if ((actualWriteSz=fullWrite(outFd, buffer, writeSize)) != writeSize ) {
331 /* Output file seems to have a problem */
332 errorMsg(io_error, header->name, strerror(errno));
336 actualWriteSz=writeSize;
339 size -= actualWriteSz;
342 /* Now we are done writing the file out, so try
343 * and fix up the permissions and whatnot */
344 if (extractFlag==TRUE && tostdoutFlag==FALSE) {
346 fixUpPermissions(header);
352 tarExtractDirectory(TarInfo *header, int extractFlag, int tostdoutFlag)
355 if (extractFlag==FALSE || tostdoutFlag==TRUE)
358 if (createPath(header->name, header->mode) != TRUE) {
359 errorMsg("tar: %s: Cannot mkdir: %s\n",
360 header->name, strerror(errno));
363 /* make the final component, just in case it was
364 * omitted by createPath() (which will skip the
365 * directory if it doesn't have a terminating '/') */
366 if (mkdir(header->name, header->mode) == 0) {
367 fixUpPermissions(header);
373 tarExtractHardLink(TarInfo *header, int extractFlag, int tostdoutFlag)
375 if (extractFlag==FALSE || tostdoutFlag==TRUE)
378 if (link(header->linkname, header->name) < 0) {
379 errorMsg("tar: %s: Cannot create hard link to '%s': %s\n",
380 header->name, header->linkname, strerror(errno));
384 /* Now set permissions etc for the new directory */
385 fixUpPermissions(header);
390 tarExtractSymLink(TarInfo *header, int extractFlag, int tostdoutFlag)
392 if (extractFlag==FALSE || tostdoutFlag==TRUE)
396 if (symlink(header->linkname, header->name) < 0) {
397 errorMsg("tar: %s: Cannot create symlink to '%s': %s\n",
398 header->name, header->linkname, strerror(errno));
401 /* Try to change ownership of the symlink.
402 * If libs doesn't support that, don't bother.
403 * Changing the pointed-to-file is the Wrong Thing(tm).
405 #if (__GLIBC__ >= 2) && (__GLIBC_MINOR__ >= 1)
406 lchown(header->name, header->uid, header->gid);
409 /* Do not change permissions or date on symlink,
410 * since it changes the pointed to file instead. duh. */
412 errorMsg("tar: %s: Cannot create symlink to '%s': %s\n",
413 header->name, header->linkname,
414 "symlinks not supported");
420 tarExtractSpecial(TarInfo *header, int extractFlag, int tostdoutFlag)
422 if (extractFlag==FALSE || tostdoutFlag==TRUE)
425 if (S_ISCHR(header->mode) || S_ISBLK(header->mode) || S_ISSOCK(header->mode)) {
426 if (mknod(header->name, header->mode, makedev(header->devmajor, header->devminor)) < 0) {
427 errorMsg("tar: %s: Cannot mknod: %s\n",
428 header->name, strerror(errno));
431 } else if (S_ISFIFO(header->mode)) {
432 if (mkfifo(header->name, header->mode) < 0) {
433 errorMsg("tar: %s: Cannot mkfifo: %s\n",
434 header->name, strerror(errno));
439 /* Now set permissions etc for the new directory */
440 fixUpPermissions(header);
444 /* Read an octal value in a field of the specified width, with optional
445 * spaces on both sides of the number and with an optional null character
446 * at the end. Returns -1 on an illegal format. */
447 static long getOctal(const char *cp, int size)
451 for(;(size > 0) && (*cp == ' '); cp++, size--);
452 if ((size == 0) || !isOctal(*cp))
454 for(; (size > 0) && isOctal(*cp); size--) {
455 val = val * 8 + *cp++ - '0';
457 for (;(size > 0) && (*cp == ' '); cp++, size--);
458 if ((size > 0) && *cp)
464 /* Parse the tar header and fill in the nice struct with the details */
466 readTarHeader(struct TarHeader *rawHeader, struct TarInfo *header)
470 unsigned char *s = (unsigned char *)rawHeader;
472 header->name = rawHeader->name;
473 /* Check for and relativify any absolute paths */
474 if ( *(header->name) == '/' ) {
475 static int alreadyWarned=FALSE;
477 while (*(header->name) == '/')
480 if (alreadyWarned == FALSE) {
481 errorMsg("tar: Removing leading '/' from member names\n");
482 alreadyWarned = TRUE;
486 header->mode = getOctal(rawHeader->mode, sizeof(rawHeader->mode));
487 header->uid = getOctal(rawHeader->uid, sizeof(rawHeader->uid));
488 header->gid = getOctal(rawHeader->gid, sizeof(rawHeader->gid));
489 header->size = getOctal(rawHeader->size, sizeof(rawHeader->size));
490 header->mtime = getOctal(rawHeader->mtime, sizeof(rawHeader->mtime));
491 chksum = getOctal(rawHeader->chksum, sizeof(rawHeader->chksum));
492 header->type = rawHeader->typeflag;
493 header->linkname = rawHeader->linkname;
494 header->devmajor = getOctal(rawHeader->devmajor, sizeof(rawHeader->devmajor));
495 header->devminor = getOctal(rawHeader->devminor, sizeof(rawHeader->devminor));
497 /* Check the checksum */
498 for (i = sizeof(*rawHeader); i-- != 0;) {
501 /* Remove the effects of the checksum field (replace
502 * with blanks for the purposes of the checksum) */
503 s = rawHeader->chksum;
504 for (i = sizeof(rawHeader->chksum) ; i-- != 0;) {
507 sum += ' ' * sizeof(rawHeader->chksum);
515 * Read a tar file and extract or list the specified files within it.
516 * If the list is empty than all files are extracted or listed.
518 static int readTarFile(const char* tarName, int extractFlag, int listFlag,
519 int tostdoutFlag, int verboseFlag, char** excludeList)
521 int status, tarFd=-1;
525 #if defined BB_FEATURE_TAR_EXCLUDE
529 /* Open the tar file for reading. */
530 if (!strcmp(tarName, "-"))
531 tarFd = fileno(stdin);
533 tarFd = open(tarName, O_RDONLY);
535 errorMsg( "Error opening '%s': %s\n", tarName, strerror(errno));
539 /* Set the umask for this process so it doesn't
540 * screw up permission setting for us later. */
543 /* Read the tar file, and iterate over it one file at a time */
544 while ( (status = fullRead(tarFd, (char*)&rawHeader, TAR_BLOCK_SIZE)) == TAR_BLOCK_SIZE ) {
546 /* First, try to read the header */
547 if ( readTarHeader(&rawHeader, &header) == FALSE ) {
548 if ( *(header.name) == '\0' ) {
552 errorMsg("Bad tar header, skipping\n");
556 if ( *(header.name) == '\0' )
558 header.tarFd = tarFd;
560 #if defined BB_FEATURE_TAR_EXCLUDE
563 /* Check for excluded files.... */
564 for (tmpList=excludeList; tmpList && *tmpList; tmpList++) {
565 /* Do some extra hoop jumping for when directory names
566 * end in '/' but the entry in tmpList doesn't */
567 if (strncmp( *tmpList, header.name, strlen(*tmpList))==0 || (
568 header.name[strlen(header.name)-1]=='/'
569 && strncmp( *tmpList, header.name,
570 MIN(strlen(header.name)-1, strlen(*tmpList)))==0)) {
571 /* If it is a regular file, pretend to extract it with
572 * the extractFlag set to FALSE, so the junk in the tarball
573 * is properly skipped over */
574 if ( header.type==REGTYPE || header.type==REGTYPE0 ) {
575 tarExtractRegularFile(&header, FALSE, FALSE);
581 /* There are not the droids you're looking for, move along */
586 /* Special treatment if the list (-t) flag is on */
587 if (verboseFlag == TRUE && extractFlag == FALSE) {
590 struct tm *tm = localtime (&(header.mtime));
592 len=printf("%s ", modeString(header.mode));
593 memset(buf, 0, 8*sizeof(char));
594 my_getpwuid(buf, header.uid);
596 len+=printf("%d", header.uid);
598 len+=printf("%s", buf);
599 memset(buf, 0, 8*sizeof(char));
600 my_getgrgid(buf, header.gid);
602 len+=printf("/%-d ", header.gid);
604 len+=printf("/%-s ", buf);
606 if (header.type==CHRTYPE || header.type==BLKTYPE) {
607 len1=snprintf(buf, sizeof(buf), "%ld,%-ld ",
608 header.devmajor, header.devminor);
610 len1=snprintf(buf, sizeof(buf), "%lu ", (long)header.size);
612 /* Jump through some hoops to make the columns match up */
613 for(;(len+len1)<31;len++)
617 /* Use ISO 8610 time format */
619 printf ("%04d-%02d-%02d %02d:%02d:%02d ",
620 tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday,
621 tm->tm_hour, tm->tm_min, tm->tm_sec);
624 /* List contents if we are supposed to do that */
625 if (verboseFlag == TRUE || listFlag == TRUE) {
626 /* Now the normal listing */
627 printf("%s", header.name);
629 if (verboseFlag == TRUE && listFlag == TRUE) {
630 /* If this is a link, say so */
631 if (header.type==LNKTYPE)
632 printf(" link to %s", header.linkname);
633 else if (header.type==SYMTYPE)
634 printf(" -> %s", header.linkname);
636 if (verboseFlag == TRUE || listFlag == TRUE) {
640 /* Remove any clutter lying in our way */
641 unlink( header.name);
643 /* If we got here, we can be certain we have a legitimate
644 * header to work with. So work with it. */
645 switch ( header.type ) {
648 /* If the name ends in a '/' then assume it is
649 * supposed to be a directory, and fall through */
650 if (header.name[strlen(header.name)-1] != '/') {
651 if (tarExtractRegularFile(&header, extractFlag, tostdoutFlag)==FALSE)
656 if (tarExtractDirectory( &header, extractFlag, tostdoutFlag)==FALSE)
660 if (tarExtractHardLink( &header, extractFlag, tostdoutFlag)==FALSE)
664 if (tarExtractSymLink( &header, extractFlag, tostdoutFlag)==FALSE)
670 if (tarExtractSpecial( &header, extractFlag, tostdoutFlag)==FALSE)
680 /* Bummer - we read a partial header */
681 errorMsg( "Error reading '%s': %s\n", tarName, strerror(errno));
684 else if (errorFlag==TRUE) {
685 errorMsg( "tar: Error exit delayed from previous errors\n");
690 /* Stuff to do when we are done */
693 if ( *(header.name) == '\0' ) {
695 errorMsg( "tar: Error exit delayed from previous errors\n");
703 #ifdef BB_FEATURE_TAR_CREATE
705 /* Some info to be carried along when creating a new tarball */
708 char* fileName; /* File name of the tarball */
709 int tarFd; /* Open-for-write file descriptor
711 struct stat statBuf; /* Stat info for the tarball, letting
712 us know the inode and device that the
713 tarball lives, so we can avoid trying
714 to include the tarball into itself */
715 int verboseFlag; /* Whether to print extra stuff or not */
716 char** excludeList; /* List of files to not include */
718 typedef struct TarBallInfo TarBallInfo;
721 /* Put an octal string into the specified buffer.
722 * The number is zero and space padded and possibly null padded.
723 * Returns TRUE if successful. */
724 static int putOctal (char *cp, int len, long value)
728 char *tempString = tempBuffer;
730 /* Create a string of the specified length with an initial space,
731 * leading zeroes and the octal number, and a trailing null. */
732 sprintf (tempString, "%0*lo", len - 1, value);
734 /* If the string is too large, suppress the leading space. */
735 tempLength = strlen (tempString) + 1;
736 if (tempLength > len) {
741 /* If the string is still too large, suppress the trailing null. */
742 if (tempLength > len)
745 /* If the string is still too large, fail. */
746 if (tempLength > len)
749 /* Copy the string to the field. */
750 memcpy (cp, tempString, len);
755 /* Write out a tar header for the specified file/directory/whatever */
757 writeTarHeader(struct TarBallInfo *tbInfo, const char *fileName, struct stat *statbuf)
760 struct TarHeader header;
761 #if defined BB_FEATURE_TAR_EXCLUDE
764 const unsigned char *cp = (const unsigned char *) &header;
765 ssize_t size = sizeof(struct TarHeader);
767 memset( &header, 0, size);
769 if (*fileName=='/') {
770 static int alreadyWarned=FALSE;
771 if (alreadyWarned==FALSE) {
772 errorMsg("tar: Removing leading '/' from member names\n");
775 strncpy(header.name, fileName+1, sizeof(header.name));
778 strncpy(header.name, fileName, sizeof(header.name));
781 #if defined BB_FEATURE_TAR_EXCLUDE
782 /* Check for excluded files.... */
783 for (tmpList=tbInfo->excludeList; tmpList && *tmpList; tmpList++) {
784 /* Do some extra hoop jumping for when directory names
785 * end in '/' but the entry in tmpList doesn't */
786 if (strncmp( *tmpList, header.name, strlen(*tmpList))==0 || (
787 header.name[strlen(header.name)-1]=='/'
788 && strncmp( *tmpList, header.name,
789 MIN(strlen(header.name)-1, strlen(*tmpList)))==0)) {
790 /* Set the mode to something that is not a regular file, thereby
791 * faking out writeTarFile into thinking that nothing further need
792 * be done for this file. Yes, I know this is ugly, but it works. */
793 statbuf->st_mode = 0;
799 putOctal(header.mode, sizeof(header.mode), statbuf->st_mode);
800 putOctal(header.uid, sizeof(header.uid), statbuf->st_uid);
801 putOctal(header.gid, sizeof(header.gid), statbuf->st_gid);
802 putOctal(header.size, sizeof(header.size), 0); /* Regular file size is handled later */
803 putOctal(header.mtime, sizeof(header.mtime), statbuf->st_mtime);
804 strncpy(header.magic, TAR_MAGIC TAR_VERSION,
805 TAR_MAGIC_LEN + TAR_VERSION_LEN );
807 /* Enter the user and group names (default to root if it fails) */
808 my_getpwuid(header.uname, statbuf->st_uid);
810 strcpy(header.uname, "root");
811 my_getgrgid(header.gname, statbuf->st_gid);
813 strcpy(header.uname, "root");
815 /* WARNING/NOTICE: I break Hard Links */
816 if (S_ISLNK(statbuf->st_mode)) {
818 header.typeflag = SYMTYPE;
819 if ( readlink(fileName, buffer, sizeof(buffer) - 1) < 0) {
820 errorMsg("Error reading symlink '%s': %s\n", header.name, strerror(errno));
823 strncpy(header.linkname, buffer, sizeof(header.linkname));
824 } else if (S_ISDIR(statbuf->st_mode)) {
825 header.typeflag = DIRTYPE;
826 strncat(header.name, "/", sizeof(header.name));
827 } else if (S_ISCHR(statbuf->st_mode)) {
828 header.typeflag = CHRTYPE;
829 putOctal(header.devmajor, sizeof(header.devmajor), MAJOR(statbuf->st_rdev));
830 putOctal(header.devminor, sizeof(header.devminor), MINOR(statbuf->st_rdev));
831 } else if (S_ISBLK(statbuf->st_mode)) {
832 header.typeflag = BLKTYPE;
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_ISFIFO(statbuf->st_mode)) {
836 header.typeflag = FIFOTYPE;
837 } else if (S_ISREG(statbuf->st_mode)) {
838 header.typeflag = REGTYPE;
839 putOctal(header.size, sizeof(header.size), statbuf->st_size);
841 errorMsg("tar: %s: Unknown file type\n", fileName);
845 /* Calculate and store the checksum (i.e. the sum of all of the bytes of
846 * the header). The checksum field must be filled with blanks for the
847 * calculation. The checksum field is formatted differently from the
848 * other fields: it has [6] digits, a null, then a space -- rather than
849 * digits, followed by a null like the other fields... */
850 memset(header.chksum, ' ', sizeof(header.chksum));
851 cp = (const unsigned char *) &header;
854 putOctal(header.chksum, 7, chksum);
856 /* Now write the header out to disk */
857 if ((size=fullWrite(tbInfo->tarFd, (char*)&header, sizeof(struct TarHeader))) < 0) {
858 errorMsg(io_error, fileName, strerror(errno));
861 /* Pad the header up to the tar block size */
862 for (; size<TAR_BLOCK_SIZE; size++) {
863 write(tbInfo->tarFd, "\0", 1);
865 /* Now do the verbose thing (or not) */
866 if (tbInfo->verboseFlag==TRUE)
867 fprintf(stdout, "%s\n", header.name);
873 static int writeFileToTarball(const char *fileName, struct stat *statbuf, void* userData)
875 struct TarBallInfo *tbInfo = (struct TarBallInfo *)userData;
877 /* It is against the rules to archive a socket */
878 if (S_ISSOCK(statbuf->st_mode)) {
879 errorMsg("tar: %s: socket ignored\n", fileName);
883 /* It is a bad idea to store the archive we are in the process of creating,
884 * so check the device and inode to be sure that this particular file isn't
886 if (tbInfo->statBuf.st_dev == statbuf->st_dev &&
887 tbInfo->statBuf.st_ino == statbuf->st_ino) {
888 errorMsg("tar: %s: file is the archive; skipping\n", fileName);
892 if (writeTarHeader(tbInfo, fileName, statbuf)==FALSE) {
896 /* Now, if the file is a regular file, copy it out to the tarball */
897 if (S_ISREG(statbuf->st_mode)) {
900 ssize_t size=0, readSize=0;
902 /* open the file we want to archive, and make sure all is well */
903 if ((inputFileFd = open(fileName, O_RDONLY)) < 0) {
904 errorMsg("tar: %s: Cannot open: %s\n", fileName, strerror(errno));
908 /* write the file to the archive */
909 while ( (size = fullRead(inputFileFd, buffer, sizeof(buffer))) > 0 ) {
910 if (fullWrite(tbInfo->tarFd, buffer, size) != size ) {
911 /* Output file seems to have a problem */
912 errorMsg(io_error, fileName, strerror(errno));
918 errorMsg(io_error, fileName, strerror(errno));
921 /* Pad the file up to the tar block size */
922 for (; (readSize%TAR_BLOCK_SIZE) != 0; readSize++) {
923 write(tbInfo->tarFd, "\0", 1);
931 static int writeTarFile(const char* tarName, int tostdoutFlag,
932 int verboseFlag, int argc, char **argv, char** excludeList)
937 struct TarBallInfo tbInfo;
938 tbInfo.verboseFlag = verboseFlag;
940 /* Make sure there is at least one file to tar up. */
942 fatalError("tar: Cowardly refusing to create an empty archive\n");
944 /* Open the tar file for writing. */
945 if (tostdoutFlag == TRUE)
946 tbInfo.tarFd = fileno(stdout);
948 tbInfo.tarFd = open (tarName, O_WRONLY | O_CREAT | O_TRUNC, 0644);
949 if (tbInfo.tarFd < 0) {
950 errorMsg( "tar: Error opening '%s': %s\n", tarName, strerror(errno));
953 tbInfo.excludeList=excludeList;
954 /* Store the stat info for the tarball's file, so
955 * can avoid including the tarball into itself.... */
956 if (fstat(tbInfo.tarFd, &tbInfo.statBuf) < 0)
957 fatalError(io_error, tarName, strerror(errno));
959 /* Set the umask for this process so it doesn't
960 * screw up permission setting for us later. */
963 /* Read the directory/files and iterate over them one at a time */
965 if (recursiveAction(*argv++, TRUE, FALSE, FALSE,
966 writeFileToTarball, writeFileToTarball,
967 (void*) &tbInfo) == FALSE) {
971 /* Write two empty blocks to the end of the archive */
972 for (size=0; size<(2*TAR_BLOCK_SIZE); size++) {
973 write(tbInfo.tarFd, "\0", 1);
976 /* To be pedantically correct, we would check if the tarball
977 * is smaller then 20 tar blocks, and pad it if it was smaller,
978 * but that isn't necessary for GNU tar interoperability, and
979 * so is considered a waste of space */
981 /* Hang up the tools, close up shop, head home */
983 if (errorFlag == TRUE) {
984 errorMsg("tar: Error exit delayed from previous errors\n");