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) 1999,2000,2001 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
46 #include <sys/types.h>
47 #include <sys/sysmacros.h>
54 #define BB_DECLARE_EXTERN
55 #define bb_need_io_error
56 #define bb_need_name_longer_than_foo
59 /* Tar file constants */
61 #define MAJOR(dev) (((dev)>>8)&0xff)
62 #define MINOR(dev) ((dev)&0xff)
65 enum { NAME_SIZE = 100 }; /* because gcc won't let me use 'static const int' */
67 /* POSIX tar Header Block, from POSIX 1003.1-1990 */
71 char name[NAME_SIZE]; /* 0-99 */
72 char mode[8]; /* 100-107 */
73 char uid[8]; /* 108-115 */
74 char gid[8]; /* 116-123 */
75 char size[12]; /* 124-135 */
76 char mtime[12]; /* 136-147 */
77 char chksum[8]; /* 148-155 */
78 char typeflag; /* 156-156 */
79 char linkname[NAME_SIZE]; /* 157-256 */
80 char magic[6]; /* 257-262 */
81 char version[2]; /* 263-264 */
82 char uname[32]; /* 265-296 */
83 char gname[32]; /* 297-328 */
84 char devmajor[8]; /* 329-336 */
85 char devminor[8]; /* 337-344 */
86 char prefix[155]; /* 345-499 */
87 char padding[12]; /* 500-512 (pad to exactly the TAR_BLOCK_SIZE) */
89 typedef struct TarHeader TarHeader;
92 /* A few useful constants */
93 #define TAR_MAGIC "ustar" /* ustar and a null */
94 #define TAR_VERSION " " /* Be compatable with GNU tar format */
95 static const int TAR_MAGIC_LEN = 6;
96 static const int TAR_VERSION_LEN = 2;
97 static const int TAR_BLOCK_SIZE = 512;
99 /* A nice enum with all the possible tar file content types */
102 REGTYPE = '0', /* regular file */
103 REGTYPE0 = '\0', /* regular file (ancient bug compat)*/
104 LNKTYPE = '1', /* hard link */
105 SYMTYPE = '2', /* symbolic link */
106 CHRTYPE = '3', /* character special */
107 BLKTYPE = '4', /* block special */
108 DIRTYPE = '5', /* directory */
109 FIFOTYPE = '6', /* FIFO special */
110 CONTTYPE = '7', /* reserved */
111 GNULONGLINK = 'K', /* GNU long (>100 chars) link name */
112 GNULONGNAME = 'L', /* GNU long (>100 chars) file name */
114 typedef enum TarFileType TarFileType;
116 /* This struct ignores magic, non-numeric user name,
117 * non-numeric group name, and the checksum, since
118 * these are all ignored by BusyBox tar. */
121 int tarFd; /* An open file descriptor for reading from the tarball */
122 char * name; /* File name */
123 mode_t mode; /* Unix mode, including device bits. */
124 uid_t uid; /* Numeric UID */
125 gid_t gid; /* Numeric GID */
126 size_t size; /* Size of file */
127 time_t mtime; /* Last-modified time */
128 enum TarFileType type; /* Regular, directory, link, etc */
129 char * linkname; /* Name for symbolic and hard links */
130 long devmajor; /* Major number for special device */
131 long devminor; /* Minor number for special device */
133 typedef struct TarInfo TarInfo;
135 /* Local procedures to restore files from a tar file. */
136 static int readTarFile(int tarFd, int extractFlag, int listFlag,
137 int tostdoutFlag, int verboseFlag, char** extractList,
140 #ifdef BB_FEATURE_TAR_CREATE
141 /* Local procedures to save files into a tar file. */
142 static int writeTarFile(const char* tarName, int verboseFlag, char **argv,
146 #if defined BB_FEATURE_TAR_EXCLUDE
147 static struct option longopts[] = {
148 { "exclude", 1, NULL, 'e' },
153 extern int tar_main(int argc, char **argv)
155 char** excludeList=NULL;
156 char** extractList=NULL;
157 const char *tarName="-";
158 #if defined BB_FEATURE_TAR_EXCLUDE
159 int excludeListSize=0;
163 #if defined BB_FEATURE_TAR_GZIP
164 FILE *comp_file = NULL;
165 int unzipFlag = FALSE;
167 int listFlag = FALSE;
168 int extractFlag = FALSE;
169 int createFlag = FALSE;
170 int verboseFlag = FALSE;
171 int tostdoutFlag = FALSE;
179 if (argv[1][0] != '-') {
180 char *tmp = xmalloc(strlen(argv[1]) + 2);
182 strcpy(tmp + 1, argv[1]);
187 #ifndef BB_FEATURE_TAR_EXCLUDE
188 (opt = getopt(argc, argv, "cxtzvOf:"))
190 (opt = getopt_long(argc, argv, "cxtzvOf:X:", longopts, NULL))
195 if (extractFlag == TRUE || listFlag == TRUE)
200 if (listFlag == TRUE || createFlag == TRUE)
205 if (extractFlag == TRUE || createFlag == TRUE)
209 #ifdef BB_FEATURE_TAR_GZIP
222 error_msg_and_die( "Only one 'f' option allowed");
225 #if defined BB_FEATURE_TAR_EXCLUDE
227 excludeList=xrealloc( excludeList,
228 sizeof(char *) * (excludeListSize+2));
229 excludeList[excludeListSize] = optarg;
230 /* Tack a NULL onto the end of the list */
231 excludeList[++excludeListSize] = NULL;
233 fileList = xfopen(optarg, "r");
234 while (fgets(file, sizeof(file), fileList) != NULL) {
235 excludeList = xrealloc(excludeList,
236 sizeof(char *) * (excludeListSize+2));
238 excludeList[excludeListSize] = xstrdup(file);
239 /* Tack a NULL onto the end of the list */
240 excludeList[++excludeListSize] = NULL;
251 * Do the correct type of action supplying the rest of the
252 * command line arguments as the list of files to process.
254 if (createFlag == TRUE) {
255 #ifndef BB_FEATURE_TAR_CREATE
256 error_msg_and_die( "This version of tar was not compiled with tar creation support.");
258 #ifdef BB_FEATURE_TAR_GZIP
260 error_msg_and_die("Creation of compressed not internally support by tar, pipe to busybox gunzip");
262 status = writeTarFile(tarName, verboseFlag, argv + optind, excludeList);
265 if (listFlag == TRUE || extractFlag == TRUE) {
268 extractList = argv + optind;
269 /* Open the tar file for reading. */
270 if (!strcmp(tarName, "-"))
271 tarFd = fileno(stdin);
273 tarFd = open(tarName, O_RDONLY);
275 perror_msg_and_die("Error opening '%s'", tarName);
277 #ifdef BB_FEATURE_TAR_GZIP
278 /* unzip tarFd in a seperate process */
279 if (unzipFlag == TRUE) {
280 comp_file = fdopen(tarFd, "r");
281 if ((tarFd = gz_open(comp_file, &pid)) == EXIT_FAILURE) {
282 error_msg_and_die("Couldnt unzip file");
286 status = readTarFile(tarFd, extractFlag, listFlag, tostdoutFlag,
287 verboseFlag, extractList, excludeList);
289 #ifdef BB_FEATURE_TAR_GZIP
290 if (unzipFlag == TRUE) {
303 error_msg_and_die( "Exactly one of 'c', 'x' or 't' must be specified");
307 fixUpPermissions(TarInfo *header)
310 /* Now set permissions etc for the new file */
311 chown(header->name, header->uid, header->gid);
312 chmod(header->name, header->mode);
315 t.modtime = header->mtime;
316 utime(header->name, &t);
320 tarExtractRegularFile(TarInfo *header, int extractFlag, int tostdoutFlag)
324 size_t actualWriteSz;
326 size_t size = header->size;
327 int outFd=fileno(stdout);
329 /* Open the file to be written, if a file is supposed to be written */
330 if (extractFlag==TRUE && tostdoutFlag==FALSE) {
331 /* Create the path to the file, just in case it isn't there...
332 * This should not screw up path permissions or anything. */
333 create_path(header->name, 0777);
334 if ((outFd=open(header->name, O_CREAT|O_TRUNC|O_WRONLY,
335 header->mode & ~S_IFMT)) < 0) {
336 error_msg(io_error, header->name, strerror(errno));
341 /* Write out the file, if we are supposed to be doing that */
344 if ( size > sizeof(buffer) )
345 writeSize = readSize = sizeof(buffer);
347 int mod = size % 512;
349 readSize = size + (512 - mod);
354 if ( (readSize = full_read(header->tarFd, buffer, readSize)) <= 0 ) {
355 /* Tarball seems to have a problem */
356 error_msg("Unexpected EOF in archive");
359 if ( readSize < writeSize )
360 writeSize = readSize;
362 /* Write out the file, if we are supposed to be doing that */
363 if (extractFlag==TRUE) {
365 if ((actualWriteSz=full_write(outFd, buffer, writeSize)) != writeSize ) {
366 /* Output file seems to have a problem */
367 error_msg(io_error, header->name, strerror(errno));
371 actualWriteSz=writeSize;
374 size -= actualWriteSz;
377 /* Now we are done writing the file out, so try
378 * and fix up the permissions and whatnot */
379 if (extractFlag==TRUE && tostdoutFlag==FALSE) {
381 fixUpPermissions(header);
387 tarExtractDirectory(TarInfo *header, int extractFlag, int tostdoutFlag)
390 if (extractFlag==FALSE || tostdoutFlag==TRUE)
393 if (create_path(header->name, header->mode) != TRUE) {
394 perror_msg("%s: Cannot mkdir", header->name);
397 /* make the final component, just in case it was
398 * omitted by create_path() (which will skip the
399 * directory if it doesn't have a terminating '/') */
400 if (mkdir(header->name, header->mode) < 0 && errno != EEXIST) {
401 perror_msg("%s", header->name);
405 fixUpPermissions(header);
410 tarExtractHardLink(TarInfo *header, int extractFlag, int tostdoutFlag)
412 if (extractFlag==FALSE || tostdoutFlag==TRUE)
415 if (link(header->linkname, header->name) < 0) {
416 perror_msg("%s: Cannot create hard link to '%s'", header->name,
421 /* Now set permissions etc for the new directory */
422 fixUpPermissions(header);
427 tarExtractSymLink(TarInfo *header, int extractFlag, int tostdoutFlag)
429 if (extractFlag==FALSE || tostdoutFlag==TRUE)
433 if (symlink(header->linkname, header->name) < 0) {
434 perror_msg("%s: Cannot create symlink to '%s'", header->name,
438 /* Try to change ownership of the symlink.
439 * If libs doesn't support that, don't bother.
440 * Changing the pointed-to-file is the Wrong Thing(tm).
442 #if (__GLIBC__ >= 2) && (__GLIBC_MINOR__ >= 1)
443 lchown(header->name, header->uid, header->gid);
446 /* Do not change permissions or date on symlink,
447 * since it changes the pointed to file instead. duh. */
449 error_msg("%s: Cannot create symlink to '%s': %s",
450 header->name, header->linkname,
451 "symlinks not supported");
457 tarExtractSpecial(TarInfo *header, int extractFlag, int tostdoutFlag)
459 if (extractFlag==FALSE || tostdoutFlag==TRUE)
462 if (S_ISCHR(header->mode) || S_ISBLK(header->mode) || S_ISSOCK(header->mode)) {
463 if (mknod(header->name, header->mode, makedev(header->devmajor, header->devminor)) < 0) {
464 perror_msg("%s: Cannot mknod", header->name);
467 } else if (S_ISFIFO(header->mode)) {
468 if (mkfifo(header->name, header->mode) < 0) {
469 perror_msg("%s: Cannot mkfifo", header->name);
474 /* Now set permissions etc for the new directory */
475 fixUpPermissions(header);
479 /* Parse the tar header and fill in the nice struct with the details */
481 readTarHeader(struct TarHeader *rawHeader, struct TarInfo *header)
485 unsigned char *s = (unsigned char *)rawHeader;
487 header->name = rawHeader->name;
488 /* Check for and relativify any absolute paths */
489 if ( *(header->name) == '/' ) {
490 static int alreadyWarned=FALSE;
492 while (*(header->name) == '/')
495 if (alreadyWarned == FALSE) {
496 error_msg("Removing leading '/' from member names");
497 alreadyWarned = TRUE;
501 header->mode = strtol(rawHeader->mode, NULL, 8);
502 header->uid = strtol(rawHeader->uid, NULL, 8);
503 header->gid = strtol(rawHeader->gid, NULL, 8);
504 header->size = strtol(rawHeader->size, NULL, 8);
505 header->mtime = strtol(rawHeader->mtime, NULL, 8);
506 chksum = strtol(rawHeader->chksum, NULL, 8);
507 header->type = rawHeader->typeflag;
508 header->linkname = rawHeader->linkname;
509 header->devmajor = strtol(rawHeader->devmajor, NULL, 8);
510 header->devminor = strtol(rawHeader->devminor, NULL, 8);
512 /* Check the checksum */
513 for (i = sizeof(*rawHeader); i-- != 0;) {
516 /* Remove the effects of the checksum field (replace
517 * with blanks for the purposes of the checksum) */
518 s = rawHeader->chksum;
519 for (i = sizeof(rawHeader->chksum) ; i-- != 0;) {
522 sum += ' ' * sizeof(rawHeader->chksum);
528 static int exclude_file(char **excluded_files, const char *file)
532 if (excluded_files == NULL)
535 for (i = 0; excluded_files[i] != NULL; i++) {
536 if (excluded_files[i][0] == '/') {
537 if (fnmatch(excluded_files[i], file,
538 FNM_PATHNAME | FNM_LEADING_DIR) == 0)
543 for (p = file; p[0] != '\0'; p++) {
544 if ((p == file || p[-1] == '/') && p[0] != '/' &&
545 fnmatch(excluded_files[i], p,
546 FNM_PATHNAME | FNM_LEADING_DIR) == 0)
555 static int extract_file(char **extract_files, const char *file)
559 if (extract_files == NULL)
562 for (i = 0; extract_files[i] != NULL; i++) {
563 if (fnmatch(extract_files[i], file, FNM_LEADING_DIR) == 0)
571 * Read a tar file and extract or list the specified files within it.
572 * If the list is empty than all files are extracted or listed.
574 static int readTarFile(int tarFd, int extractFlag, int listFlag,
575 int tostdoutFlag, int verboseFlag, char** extractList,
580 int skipNextHeaderFlag=FALSE;
584 /* Set the umask for this process so it doesn't
585 * screw up permission setting for us later. */
588 /* Read the tar file, and iterate over it one file at a time */
589 while ( (status = full_read(tarFd, (char*)&rawHeader, TAR_BLOCK_SIZE)) == TAR_BLOCK_SIZE ) {
591 /* Try to read the header */
592 if ( readTarHeader(&rawHeader, &header) == FALSE ) {
593 if ( *(header.name) == '\0' ) {
597 error_msg("Bad tar header, skipping");
601 if ( *(header.name) == '\0' )
603 header.tarFd = tarFd;
605 /* Skip funky extra GNU headers that precede long files */
606 if ( (header.type == GNULONGNAME) || (header.type == GNULONGLINK) ) {
607 skipNextHeaderFlag=TRUE;
608 if (tarExtractRegularFile(&header, FALSE, FALSE) == FALSE)
612 if ( skipNextHeaderFlag == TRUE ) {
613 skipNextHeaderFlag=FALSE;
614 error_msg(name_longer_than_foo, NAME_SIZE);
615 if (tarExtractRegularFile(&header, FALSE, FALSE) == FALSE)
620 #if defined BB_FEATURE_TAR_EXCLUDE
621 if (exclude_file(excludeList, header.name)) {
622 /* There are not the droids you're looking for, move along */
623 /* If it is a regular file, pretend to extract it with
624 * the extractFlag set to FALSE, so the junk in the tarball
625 * is properly skipped over */
626 if ( header.type==REGTYPE || header.type==REGTYPE0 ) {
627 if (tarExtractRegularFile(&header, FALSE, FALSE) == FALSE)
634 if (!extract_file(extractList, header.name)) {
635 /* There are not the droids you're looking for, move along */
636 /* If it is a regular file, pretend to extract it with
637 * the extractFlag set to FALSE, so the junk in the tarball
638 * is properly skipped over */
639 if ( header.type==REGTYPE || header.type==REGTYPE0 ) {
640 if (tarExtractRegularFile(&header, FALSE, FALSE) == FALSE)
646 if (listFlag == TRUE) {
647 /* Special treatment if the list (-t) flag is on */
648 if (verboseFlag == TRUE) {
651 struct tm *tm = localtime (&(header.mtime));
653 len=printf("%s ", mode_string(header.mode));
654 my_getpwuid(buf, header.uid);
656 len+=printf("%d", header.uid);
658 len+=printf("%s", buf);
659 my_getgrgid(buf, header.gid);
661 len+=printf("/%-d ", header.gid);
663 len+=printf("/%-s ", buf);
665 if (header.type==CHRTYPE || header.type==BLKTYPE) {
666 len1=snprintf(buf, sizeof(buf), "%ld,%-ld ",
667 header.devmajor, header.devminor);
669 len1=snprintf(buf, sizeof(buf), "%lu ", (long)header.size);
671 /* Jump through some hoops to make the columns match up */
672 for(;(len+len1)<31;len++)
676 /* Use ISO 8610 time format */
678 printf ("%04d-%02d-%02d %02d:%02d:%02d ",
679 tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday,
680 tm->tm_hour, tm->tm_min, tm->tm_sec);
683 printf("%s", header.name);
684 if (verboseFlag == TRUE) {
685 if (header.type==LNKTYPE) /* If this is a link, say so */
686 printf(" link to %s", header.linkname);
687 else if (header.type==SYMTYPE)
688 printf(" -> %s", header.linkname);
693 /* List contents if we are supposed to do that */
694 if (verboseFlag == TRUE && extractFlag == TRUE) {
695 /* Now the normal listing */
697 if (tostdoutFlag == TRUE) // If the archive goes to stdout, verbose to stderr
699 fprintf(vbFd, "%s\n", header.name);
702 /* Remove files if we would overwrite them */
703 if (extractFlag == TRUE && tostdoutFlag == FALSE)
706 /* If we got here, we can be certain we have a legitimate
707 * header to work with. So work with it. */
708 switch ( header.type ) {
711 /* If the name ends in a '/' then assume it is
712 * supposed to be a directory, and fall through */
713 if (header.name[strlen(header.name)-1] != '/') {
714 if (tarExtractRegularFile(&header, extractFlag, tostdoutFlag)==FALSE)
719 if (tarExtractDirectory( &header, extractFlag, tostdoutFlag)==FALSE)
723 if (tarExtractHardLink( &header, extractFlag, tostdoutFlag)==FALSE)
727 if (tarExtractSymLink( &header, extractFlag, tostdoutFlag)==FALSE)
733 if (tarExtractSpecial( &header, extractFlag, tostdoutFlag)==FALSE)
737 /* Handled earlier */
740 skipNextHeaderFlag=TRUE;
744 error_msg("Unknown file type '%c' in tar file", header.type);
751 /* Bummer - we read a partial header */
752 perror_msg("Error reading tar file");
755 else if (errorFlag==TRUE) {
756 error_msg( "Error exit delayed from previous errors");
761 /* Stuff to do when we are done */
764 if ( *(header.name) == '\0' ) {
766 error_msg( "Error exit delayed from previous errors");
774 #ifdef BB_FEATURE_TAR_CREATE
777 ** writeTarFile(), writeFileToTarball(), and writeTarHeader() are
778 ** the only functions that deal with the HardLinkInfo structure.
779 ** Even these functions use the xxxHardLinkInfo() functions.
781 typedef struct HardLinkInfo HardLinkInfo;
784 HardLinkInfo *next; /* Next entry in list */
785 dev_t dev; /* Device number */
786 ino_t ino; /* Inode number */
787 short linkCount; /* (Hard) Link Count */
788 char name[1]; /* Start of filename (must be last) */
791 /* Some info to be carried along when creating a new tarball */
794 char* fileName; /* File name of the tarball */
795 int tarFd; /* Open-for-write file descriptor
797 struct stat statBuf; /* Stat info for the tarball, letting
798 us know the inode and device that the
799 tarball lives, so we can avoid trying
800 to include the tarball into itself */
801 int verboseFlag; /* Whether to print extra stuff or not */
802 char** excludeList; /* List of files to not include */
803 HardLinkInfo *hlInfoHead; /* Hard Link Tracking Information */
804 HardLinkInfo *hlInfo; /* Hard Link Info for the current file */
806 typedef struct TarBallInfo TarBallInfo;
809 /* Might be faster (and bigger) if the dev/ino were stored in numeric order;) */
811 addHardLinkInfo (HardLinkInfo **hlInfoHeadPtr, dev_t dev, ino_t ino,
812 short linkCount, const char *name)
814 /* Note: hlInfoHeadPtr can never be NULL! */
815 HardLinkInfo *hlInfo;
817 hlInfo = (HardLinkInfo *)xmalloc(sizeof(HardLinkInfo)+strlen(name)+1);
819 hlInfo->next = *hlInfoHeadPtr;
820 *hlInfoHeadPtr = hlInfo;
823 hlInfo->linkCount = linkCount;
824 strcpy(hlInfo->name, name);
830 freeHardLinkInfo (HardLinkInfo **hlInfoHeadPtr)
832 HardLinkInfo *hlInfo = NULL;
833 HardLinkInfo *hlInfoNext = NULL;
836 hlInfo = *hlInfoHeadPtr;
838 hlInfoNext = hlInfo->next;
842 *hlInfoHeadPtr = NULL;
847 /* Might be faster (and bigger) if the dev/ino were stored in numeric order;) */
848 static HardLinkInfo *
849 findHardLinkInfo (HardLinkInfo *hlInfo, dev_t dev, ino_t ino)
852 if ((ino == hlInfo->ino) && (dev == hlInfo->dev))
854 hlInfo = hlInfo->next;
859 /* Put an octal string into the specified buffer.
860 * The number is zero and space padded and possibly null padded.
861 * Returns TRUE if successful. */
862 static int putOctal (char *cp, int len, long value)
866 char *tempString = tempBuffer;
868 /* Create a string of the specified length with an initial space,
869 * leading zeroes and the octal number, and a trailing null. */
870 sprintf (tempString, "%0*lo", len - 1, value);
872 /* If the string is too large, suppress the leading space. */
873 tempLength = strlen (tempString) + 1;
874 if (tempLength > len) {
879 /* If the string is still too large, suppress the trailing null. */
880 if (tempLength > len)
883 /* If the string is still too large, fail. */
884 if (tempLength > len)
887 /* Copy the string to the field. */
888 memcpy (cp, tempString, len);
893 /* Write out a tar header for the specified file/directory/whatever */
895 writeTarHeader(struct TarBallInfo *tbInfo, const char *header_name,
896 const char *real_name, struct stat *statbuf)
899 struct TarHeader header;
900 const unsigned char *cp = (const unsigned char *) &header;
901 ssize_t size = sizeof(struct TarHeader);
903 memset( &header, 0, size);
905 strncpy(header.name, header_name, sizeof(header.name));
907 putOctal(header.mode, sizeof(header.mode), statbuf->st_mode);
908 putOctal(header.uid, sizeof(header.uid), statbuf->st_uid);
909 putOctal(header.gid, sizeof(header.gid), statbuf->st_gid);
910 putOctal(header.size, sizeof(header.size), 0); /* Regular file size is handled later */
911 putOctal(header.mtime, sizeof(header.mtime), statbuf->st_mtime);
912 strncpy(header.magic, TAR_MAGIC TAR_VERSION,
913 TAR_MAGIC_LEN + TAR_VERSION_LEN );
915 /* Enter the user and group names (default to root if it fails) */
916 my_getpwuid(header.uname, statbuf->st_uid);
918 strcpy(header.uname, "root");
919 my_getgrgid(header.gname, statbuf->st_gid);
921 strcpy(header.uname, "root");
923 if (tbInfo->hlInfo) {
924 /* This is a hard link */
925 header.typeflag = LNKTYPE;
926 strncpy(header.linkname, tbInfo->hlInfo->name, sizeof(header.linkname));
927 } else if (S_ISLNK(statbuf->st_mode)) {
930 header.typeflag = SYMTYPE;
931 link_size = readlink(real_name, buffer, sizeof(buffer) - 1);
932 if ( link_size < 0) {
933 perror_msg("Error reading symlink '%s'", header.name);
936 buffer[link_size] = '\0';
937 strncpy(header.linkname, buffer, sizeof(header.linkname));
938 } else if (S_ISDIR(statbuf->st_mode)) {
939 header.typeflag = DIRTYPE;
940 strncat(header.name, "/", sizeof(header.name));
941 } else if (S_ISCHR(statbuf->st_mode)) {
942 header.typeflag = CHRTYPE;
943 putOctal(header.devmajor, sizeof(header.devmajor), MAJOR(statbuf->st_rdev));
944 putOctal(header.devminor, sizeof(header.devminor), MINOR(statbuf->st_rdev));
945 } else if (S_ISBLK(statbuf->st_mode)) {
946 header.typeflag = BLKTYPE;
947 putOctal(header.devmajor, sizeof(header.devmajor), MAJOR(statbuf->st_rdev));
948 putOctal(header.devminor, sizeof(header.devminor), MINOR(statbuf->st_rdev));
949 } else if (S_ISFIFO(statbuf->st_mode)) {
950 header.typeflag = FIFOTYPE;
951 } else if (S_ISREG(statbuf->st_mode)) {
952 header.typeflag = REGTYPE;
953 putOctal(header.size, sizeof(header.size), statbuf->st_size);
955 error_msg("%s: Unknown file type", real_name);
959 /* Calculate and store the checksum (i.e. the sum of all of the bytes of
960 * the header). The checksum field must be filled with blanks for the
961 * calculation. The checksum field is formatted differently from the
962 * other fields: it has [6] digits, a null, then a space -- rather than
963 * digits, followed by a null like the other fields... */
964 memset(header.chksum, ' ', sizeof(header.chksum));
965 cp = (const unsigned char *) &header;
968 putOctal(header.chksum, 7, chksum);
970 /* Now write the header out to disk */
971 if ((size=full_write(tbInfo->tarFd, (char*)&header, sizeof(struct TarHeader))) < 0) {
972 error_msg(io_error, real_name, strerror(errno));
975 /* Pad the header up to the tar block size */
976 for (; size<TAR_BLOCK_SIZE; size++) {
977 write(tbInfo->tarFd, "\0", 1);
979 /* Now do the verbose thing (or not) */
980 if (tbInfo->verboseFlag==TRUE) {
982 if (tbInfo->tarFd == fileno(stdout)) // If the archive goes to stdout, verbose to stderr
984 fprintf(vbFd, "%s\n", header.name);
991 static int writeFileToTarball(const char *fileName, struct stat *statbuf, void* userData)
993 struct TarBallInfo *tbInfo = (struct TarBallInfo *)userData;
994 const char *header_name;
997 ** Check to see if we are dealing with a hard link.
999 ** Treat the first occurance of a given dev/inode as a file while
1000 ** treating any additional occurances as hard links. This is done
1001 ** by adding the file information to the HardLinkInfo linked list.
1003 tbInfo->hlInfo = NULL;
1004 if (statbuf->st_nlink > 1) {
1005 tbInfo->hlInfo = findHardLinkInfo(tbInfo->hlInfoHead, statbuf->st_dev,
1007 if (tbInfo->hlInfo == NULL)
1008 addHardLinkInfo (&tbInfo->hlInfoHead, statbuf->st_dev,
1009 statbuf->st_ino, statbuf->st_nlink, fileName);
1012 /* It is against the rules to archive a socket */
1013 if (S_ISSOCK(statbuf->st_mode)) {
1014 error_msg("%s: socket ignored", fileName);
1018 /* It is a bad idea to store the archive we are in the process of creating,
1019 * so check the device and inode to be sure that this particular file isn't
1020 * the new tarball */
1021 if (tbInfo->statBuf.st_dev == statbuf->st_dev &&
1022 tbInfo->statBuf.st_ino == statbuf->st_ino) {
1023 error_msg("%s: file is the archive; skipping", fileName);
1027 header_name = fileName;
1028 while (header_name[0] == '/') {
1029 static int alreadyWarned=FALSE;
1030 if (alreadyWarned==FALSE) {
1031 error_msg("Removing leading '/' from member names");
1037 if (strlen(fileName) >= NAME_SIZE) {
1038 error_msg(name_longer_than_foo, NAME_SIZE);
1042 if (header_name[0] == '\0')
1045 #if defined BB_FEATURE_TAR_EXCLUDE
1046 if (exclude_file(tbInfo->excludeList, header_name)) {
1051 if (writeTarHeader(tbInfo, header_name, fileName, statbuf)==FALSE) {
1055 /* Now, if the file is a regular file, copy it out to the tarball */
1056 if ((tbInfo->hlInfo == NULL)
1057 && (S_ISREG(statbuf->st_mode))) {
1059 char buffer[BUFSIZ];
1060 ssize_t size=0, readSize=0;
1062 /* open the file we want to archive, and make sure all is well */
1063 if ((inputFileFd = open(fileName, O_RDONLY)) < 0) {
1064 error_msg("%s: Cannot open: %s", fileName, strerror(errno));
1068 /* write the file to the archive */
1069 while ( (size = full_read(inputFileFd, buffer, sizeof(buffer))) > 0 ) {
1070 if (full_write(tbInfo->tarFd, buffer, size) != size ) {
1071 /* Output file seems to have a problem */
1072 error_msg(io_error, fileName, strerror(errno));
1078 error_msg(io_error, fileName, strerror(errno));
1081 /* Pad the file up to the tar block size */
1082 for (; (readSize%TAR_BLOCK_SIZE) != 0; readSize++) {
1083 write(tbInfo->tarFd, "\0", 1);
1085 close( inputFileFd);
1091 static int writeTarFile(const char* tarName, int verboseFlag, char **argv,
1095 int errorFlag=FALSE;
1097 struct TarBallInfo tbInfo;
1098 tbInfo.verboseFlag = verboseFlag;
1099 tbInfo.hlInfoHead = NULL;
1101 /* Make sure there is at least one file to tar up. */
1103 error_msg_and_die("Cowardly refusing to create an empty archive");
1105 /* Open the tar file for writing. */
1106 if (!strcmp(tarName, "-"))
1107 tbInfo.tarFd = fileno(stdout);
1109 tbInfo.tarFd = open (tarName, O_WRONLY | O_CREAT | O_TRUNC, 0644);
1110 if (tbInfo.tarFd < 0) {
1111 perror_msg( "Error opening '%s'", tarName);
1112 freeHardLinkInfo(&tbInfo.hlInfoHead);
1115 tbInfo.excludeList=excludeList;
1116 /* Store the stat info for the tarball's file, so
1117 * can avoid including the tarball into itself.... */
1118 if (fstat(tbInfo.tarFd, &tbInfo.statBuf) < 0)
1119 error_msg_and_die(io_error, tarName, strerror(errno));
1121 /* Set the umask for this process so it doesn't
1122 * screw up permission setting for us later. */
1125 /* Read the directory/files and iterate over them one at a time */
1126 while (*argv != NULL) {
1127 if (recursive_action(*argv++, TRUE, FALSE, FALSE,
1128 writeFileToTarball, writeFileToTarball,
1129 (void*) &tbInfo) == FALSE) {
1133 /* Write two empty blocks to the end of the archive */
1134 for (size=0; size<(2*TAR_BLOCK_SIZE); size++) {
1135 write(tbInfo.tarFd, "\0", 1);
1138 /* To be pedantically correct, we would check if the tarball
1139 * is smaller than 20 tar blocks, and pad it if it was smaller,
1140 * but that isn't necessary for GNU tar interoperability, and
1141 * so is considered a waste of space */
1143 /* Hang up the tools, close up shop, head home */
1145 if (errorFlag == TRUE) {
1146 error_msg("Error exit delayed from previous errors");
1147 freeHardLinkInfo(&tbInfo.hlInfoHead);
1150 freeHardLinkInfo(&tbInfo.hlInfoHead);