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 extern 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 /* Read an octal value in a field of the specified width, with optional
480 * spaces on both sides of the number and with an optional null character
481 * at the end. Returns -1 on an illegal format. */
482 static long getOctal(const char *cp, int size)
486 for(;(size > 0) && (*cp == ' '); cp++, size--);
487 if ((size == 0) || !is_octal(*cp))
489 for(; (size > 0) && is_octal(*cp); size--) {
490 val = val * 8 + *cp++ - '0';
492 for (;(size > 0) && (*cp == ' '); cp++, size--);
493 if ((size > 0) && *cp)
499 /* Parse the tar header and fill in the nice struct with the details */
501 readTarHeader(struct TarHeader *rawHeader, struct TarInfo *header)
505 unsigned char *s = (unsigned char *)rawHeader;
507 header->name = rawHeader->name;
508 /* Check for and relativify any absolute paths */
509 if ( *(header->name) == '/' ) {
510 static int alreadyWarned=FALSE;
512 while (*(header->name) == '/')
515 if (alreadyWarned == FALSE) {
516 error_msg("Removing leading '/' from member names");
517 alreadyWarned = TRUE;
521 header->mode = getOctal(rawHeader->mode, sizeof(rawHeader->mode));
522 header->uid = getOctal(rawHeader->uid, sizeof(rawHeader->uid));
523 header->gid = getOctal(rawHeader->gid, sizeof(rawHeader->gid));
524 header->size = getOctal(rawHeader->size, sizeof(rawHeader->size));
525 header->mtime = getOctal(rawHeader->mtime, sizeof(rawHeader->mtime));
526 chksum = getOctal(rawHeader->chksum, sizeof(rawHeader->chksum));
527 header->type = rawHeader->typeflag;
528 header->linkname = rawHeader->linkname;
529 header->devmajor = getOctal(rawHeader->devmajor, sizeof(rawHeader->devmajor));
530 header->devminor = getOctal(rawHeader->devminor, sizeof(rawHeader->devminor));
532 /* Check the checksum */
533 for (i = sizeof(*rawHeader); i-- != 0;) {
536 /* Remove the effects of the checksum field (replace
537 * with blanks for the purposes of the checksum) */
538 s = rawHeader->chksum;
539 for (i = sizeof(rawHeader->chksum) ; i-- != 0;) {
542 sum += ' ' * sizeof(rawHeader->chksum);
548 static int exclude_file(char **excluded_files, const char *file)
552 if (excluded_files == NULL)
555 for (i = 0; excluded_files[i] != NULL; i++) {
556 if (excluded_files[i][0] == '/') {
557 if (fnmatch(excluded_files[i], file,
558 FNM_PATHNAME | FNM_LEADING_DIR) == 0)
563 for (p = file; p[0] != '\0'; p++) {
564 if ((p == file || p[-1] == '/') && p[0] != '/' &&
565 fnmatch(excluded_files[i], p,
566 FNM_PATHNAME | FNM_LEADING_DIR) == 0)
575 static int extract_file(char **extract_files, const char *file)
579 if (extract_files == NULL)
582 for (i = 0; extract_files[i] != NULL; i++) {
583 if (fnmatch(extract_files[i], file, FNM_LEADING_DIR) == 0)
591 * Read a tar file and extract or list the specified files within it.
592 * If the list is empty than all files are extracted or listed.
594 extern int readTarFile(int tarFd, int extractFlag, int listFlag,
595 int tostdoutFlag, int verboseFlag, char** extractList,
600 int skipNextHeaderFlag=FALSE;
604 /* Set the umask for this process so it doesn't
605 * screw up permission setting for us later. */
608 /* Read the tar file, and iterate over it one file at a time */
609 while ( (status = full_read(tarFd, (char*)&rawHeader, TAR_BLOCK_SIZE)) == TAR_BLOCK_SIZE ) {
611 /* Try to read the header */
612 if ( readTarHeader(&rawHeader, &header) == FALSE ) {
613 if ( *(header.name) == '\0' ) {
617 error_msg("Bad tar header, skipping");
621 if ( *(header.name) == '\0' )
623 header.tarFd = tarFd;
625 /* Skip funky extra GNU headers that precede long files */
626 if ( (header.type == GNULONGNAME) || (header.type == GNULONGLINK) ) {
627 skipNextHeaderFlag=TRUE;
628 if (tarExtractRegularFile(&header, FALSE, FALSE) == FALSE)
632 if ( skipNextHeaderFlag == TRUE ) {
633 skipNextHeaderFlag=FALSE;
634 error_msg(name_longer_than_foo, NAME_SIZE);
635 if (tarExtractRegularFile(&header, FALSE, FALSE) == FALSE)
640 #if defined BB_FEATURE_TAR_EXCLUDE
641 if (exclude_file(excludeList, header.name)) {
642 /* There are not the droids you're looking for, move along */
643 /* If it is a regular file, pretend to extract it with
644 * the extractFlag set to FALSE, so the junk in the tarball
645 * is properly skipped over */
646 if ( header.type==REGTYPE || header.type==REGTYPE0 ) {
647 if (tarExtractRegularFile(&header, FALSE, FALSE) == FALSE)
654 if (!extract_file(extractList, header.name)) {
655 /* There are not the droids you're looking for, move along */
656 /* If it is a regular file, pretend to extract it with
657 * the extractFlag set to FALSE, so the junk in the tarball
658 * is properly skipped over */
659 if ( header.type==REGTYPE || header.type==REGTYPE0 ) {
660 if (tarExtractRegularFile(&header, FALSE, FALSE) == FALSE)
666 if (listFlag == TRUE) {
667 /* Special treatment if the list (-t) flag is on */
668 if (verboseFlag == TRUE) {
671 struct tm *tm = localtime (&(header.mtime));
673 len=printf("%s ", mode_string(header.mode));
674 my_getpwuid(buf, header.uid);
676 len+=printf("%d", header.uid);
678 len+=printf("%s", buf);
679 my_getgrgid(buf, header.gid);
681 len+=printf("/%-d ", header.gid);
683 len+=printf("/%-s ", buf);
685 if (header.type==CHRTYPE || header.type==BLKTYPE) {
686 len1=snprintf(buf, sizeof(buf), "%ld,%-ld ",
687 header.devmajor, header.devminor);
689 len1=snprintf(buf, sizeof(buf), "%lu ", (long)header.size);
691 /* Jump through some hoops to make the columns match up */
692 for(;(len+len1)<31;len++)
696 /* Use ISO 8610 time format */
698 printf ("%04d-%02d-%02d %02d:%02d:%02d ",
699 tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday,
700 tm->tm_hour, tm->tm_min, tm->tm_sec);
703 printf("%s", header.name);
704 if (verboseFlag == TRUE) {
705 if (header.type==LNKTYPE) /* If this is a link, say so */
706 printf(" link to %s", header.linkname);
707 else if (header.type==SYMTYPE)
708 printf(" -> %s", header.linkname);
713 /* List contents if we are supposed to do that */
714 if (verboseFlag == TRUE && extractFlag == TRUE) {
715 /* Now the normal listing */
717 if (tostdoutFlag == TRUE) // If the archive goes to stdout, verbose to stderr
719 fprintf(vbFd, "%s\n", header.name);
722 /* Remove files if we would overwrite them */
723 if (extractFlag == TRUE && tostdoutFlag == FALSE)
726 /* If we got here, we can be certain we have a legitimate
727 * header to work with. So work with it. */
728 switch ( header.type ) {
731 /* If the name ends in a '/' then assume it is
732 * supposed to be a directory, and fall through */
733 if (header.name[strlen(header.name)-1] != '/') {
734 if (tarExtractRegularFile(&header, extractFlag, tostdoutFlag)==FALSE)
739 if (tarExtractDirectory( &header, extractFlag, tostdoutFlag)==FALSE)
743 if (tarExtractHardLink( &header, extractFlag, tostdoutFlag)==FALSE)
747 if (tarExtractSymLink( &header, extractFlag, tostdoutFlag)==FALSE)
753 if (tarExtractSpecial( &header, extractFlag, tostdoutFlag)==FALSE)
757 /* Handled earlier */
760 skipNextHeaderFlag=TRUE;
764 error_msg("Unknown file type '%c' in tar file", header.type);
771 /* Bummer - we read a partial header */
772 perror_msg("Error reading tar file");
775 else if (errorFlag==TRUE) {
776 error_msg( "Error exit delayed from previous errors");
781 /* Stuff to do when we are done */
784 if ( *(header.name) == '\0' ) {
786 error_msg( "Error exit delayed from previous errors");
794 #ifdef BB_FEATURE_TAR_CREATE
797 ** writeTarFile(), writeFileToTarball(), and writeTarHeader() are
798 ** the only functions that deal with the HardLinkInfo structure.
799 ** Even these functions use the xxxHardLinkInfo() functions.
801 typedef struct HardLinkInfo HardLinkInfo;
804 HardLinkInfo *next; /* Next entry in list */
805 dev_t dev; /* Device number */
806 ino_t ino; /* Inode number */
807 short linkCount; /* (Hard) Link Count */
808 char name[1]; /* Start of filename (must be last) */
811 /* Some info to be carried along when creating a new tarball */
814 char* fileName; /* File name of the tarball */
815 int tarFd; /* Open-for-write file descriptor
817 struct stat statBuf; /* Stat info for the tarball, letting
818 us know the inode and device that the
819 tarball lives, so we can avoid trying
820 to include the tarball into itself */
821 int verboseFlag; /* Whether to print extra stuff or not */
822 char** excludeList; /* List of files to not include */
823 HardLinkInfo *hlInfoHead; /* Hard Link Tracking Information */
824 HardLinkInfo *hlInfo; /* Hard Link Info for the current file */
826 typedef struct TarBallInfo TarBallInfo;
829 /* Might be faster (and bigger) if the dev/ino were stored in numeric order;) */
831 addHardLinkInfo (HardLinkInfo **hlInfoHeadPtr, dev_t dev, ino_t ino,
832 short linkCount, const char *name)
834 /* Note: hlInfoHeadPtr can never be NULL! */
835 HardLinkInfo *hlInfo;
837 hlInfo = (HardLinkInfo *)xmalloc(sizeof(HardLinkInfo)+strlen(name)+1);
839 hlInfo->next = *hlInfoHeadPtr;
840 *hlInfoHeadPtr = hlInfo;
843 hlInfo->linkCount = linkCount;
844 strcpy(hlInfo->name, name);
850 freeHardLinkInfo (HardLinkInfo **hlInfoHeadPtr)
852 HardLinkInfo *hlInfo = NULL;
853 HardLinkInfo *hlInfoNext = NULL;
856 hlInfo = *hlInfoHeadPtr;
858 hlInfoNext = hlInfo->next;
862 *hlInfoHeadPtr = NULL;
867 /* Might be faster (and bigger) if the dev/ino were stored in numeric order;) */
868 static HardLinkInfo *
869 findHardLinkInfo (HardLinkInfo *hlInfo, dev_t dev, ino_t ino)
872 if ((ino == hlInfo->ino) && (dev == hlInfo->dev))
874 hlInfo = hlInfo->next;
879 /* Put an octal string into the specified buffer.
880 * The number is zero and space padded and possibly null padded.
881 * Returns TRUE if successful. */
882 static int putOctal (char *cp, int len, long value)
886 char *tempString = tempBuffer;
888 /* Create a string of the specified length with an initial space,
889 * leading zeroes and the octal number, and a trailing null. */
890 sprintf (tempString, "%0*lo", len - 1, value);
892 /* If the string is too large, suppress the leading space. */
893 tempLength = strlen (tempString) + 1;
894 if (tempLength > len) {
899 /* If the string is still too large, suppress the trailing null. */
900 if (tempLength > len)
903 /* If the string is still too large, fail. */
904 if (tempLength > len)
907 /* Copy the string to the field. */
908 memcpy (cp, tempString, len);
913 /* Write out a tar header for the specified file/directory/whatever */
915 writeTarHeader(struct TarBallInfo *tbInfo, const char *header_name,
916 const char *real_name, struct stat *statbuf)
919 struct TarHeader header;
920 const unsigned char *cp = (const unsigned char *) &header;
921 ssize_t size = sizeof(struct TarHeader);
923 memset( &header, 0, size);
925 strncpy(header.name, header_name, sizeof(header.name));
927 putOctal(header.mode, sizeof(header.mode), statbuf->st_mode);
928 putOctal(header.uid, sizeof(header.uid), statbuf->st_uid);
929 putOctal(header.gid, sizeof(header.gid), statbuf->st_gid);
930 putOctal(header.size, sizeof(header.size), 0); /* Regular file size is handled later */
931 putOctal(header.mtime, sizeof(header.mtime), statbuf->st_mtime);
932 strncpy(header.magic, TAR_MAGIC TAR_VERSION,
933 TAR_MAGIC_LEN + TAR_VERSION_LEN );
935 /* Enter the user and group names (default to root if it fails) */
936 my_getpwuid(header.uname, statbuf->st_uid);
938 strcpy(header.uname, "root");
939 my_getgrgid(header.gname, statbuf->st_gid);
941 strcpy(header.uname, "root");
943 if (tbInfo->hlInfo) {
944 /* This is a hard link */
945 header.typeflag = LNKTYPE;
946 strncpy(header.linkname, tbInfo->hlInfo->name, sizeof(header.linkname));
947 } else if (S_ISLNK(statbuf->st_mode)) {
950 header.typeflag = SYMTYPE;
951 link_size = readlink(real_name, buffer, sizeof(buffer) - 1);
952 if ( link_size < 0) {
953 perror_msg("Error reading symlink '%s'", header.name);
956 buffer[link_size] = '\0';
957 strncpy(header.linkname, buffer, sizeof(header.linkname));
958 } else if (S_ISDIR(statbuf->st_mode)) {
959 header.typeflag = DIRTYPE;
960 strncat(header.name, "/", sizeof(header.name));
961 } else if (S_ISCHR(statbuf->st_mode)) {
962 header.typeflag = CHRTYPE;
963 putOctal(header.devmajor, sizeof(header.devmajor), MAJOR(statbuf->st_rdev));
964 putOctal(header.devminor, sizeof(header.devminor), MINOR(statbuf->st_rdev));
965 } else if (S_ISBLK(statbuf->st_mode)) {
966 header.typeflag = BLKTYPE;
967 putOctal(header.devmajor, sizeof(header.devmajor), MAJOR(statbuf->st_rdev));
968 putOctal(header.devminor, sizeof(header.devminor), MINOR(statbuf->st_rdev));
969 } else if (S_ISFIFO(statbuf->st_mode)) {
970 header.typeflag = FIFOTYPE;
971 } else if (S_ISREG(statbuf->st_mode)) {
972 header.typeflag = REGTYPE;
973 putOctal(header.size, sizeof(header.size), statbuf->st_size);
975 error_msg("%s: Unknown file type", real_name);
979 /* Calculate and store the checksum (i.e. the sum of all of the bytes of
980 * the header). The checksum field must be filled with blanks for the
981 * calculation. The checksum field is formatted differently from the
982 * other fields: it has [6] digits, a null, then a space -- rather than
983 * digits, followed by a null like the other fields... */
984 memset(header.chksum, ' ', sizeof(header.chksum));
985 cp = (const unsigned char *) &header;
988 putOctal(header.chksum, 7, chksum);
990 /* Now write the header out to disk */
991 if ((size=full_write(tbInfo->tarFd, (char*)&header, sizeof(struct TarHeader))) < 0) {
992 error_msg(io_error, real_name, strerror(errno));
995 /* Pad the header up to the tar block size */
996 for (; size<TAR_BLOCK_SIZE; size++) {
997 write(tbInfo->tarFd, "\0", 1);
999 /* Now do the verbose thing (or not) */
1000 if (tbInfo->verboseFlag==TRUE) {
1001 FILE *vbFd = stdout;
1002 if (tbInfo->tarFd == fileno(stdout)) // If the archive goes to stdout, verbose to stderr
1004 fprintf(vbFd, "%s\n", header.name);
1011 static int writeFileToTarball(const char *fileName, struct stat *statbuf, void* userData)
1013 struct TarBallInfo *tbInfo = (struct TarBallInfo *)userData;
1014 const char *header_name;
1017 ** Check to see if we are dealing with a hard link.
1019 ** Treat the first occurance of a given dev/inode as a file while
1020 ** treating any additional occurances as hard links. This is done
1021 ** by adding the file information to the HardLinkInfo linked list.
1023 tbInfo->hlInfo = NULL;
1024 if (statbuf->st_nlink > 1) {
1025 tbInfo->hlInfo = findHardLinkInfo(tbInfo->hlInfoHead, statbuf->st_dev,
1027 if (tbInfo->hlInfo == NULL)
1028 addHardLinkInfo (&tbInfo->hlInfoHead, statbuf->st_dev,
1029 statbuf->st_ino, statbuf->st_nlink, fileName);
1032 /* It is against the rules to archive a socket */
1033 if (S_ISSOCK(statbuf->st_mode)) {
1034 error_msg("%s: socket ignored", fileName);
1038 /* It is a bad idea to store the archive we are in the process of creating,
1039 * so check the device and inode to be sure that this particular file isn't
1040 * the new tarball */
1041 if (tbInfo->statBuf.st_dev == statbuf->st_dev &&
1042 tbInfo->statBuf.st_ino == statbuf->st_ino) {
1043 error_msg("%s: file is the archive; skipping", fileName);
1047 header_name = fileName;
1048 while (header_name[0] == '/') {
1049 static int alreadyWarned=FALSE;
1050 if (alreadyWarned==FALSE) {
1051 error_msg("Removing leading '/' from member names");
1057 if (strlen(fileName) >= NAME_SIZE) {
1058 error_msg(name_longer_than_foo, NAME_SIZE);
1062 if (header_name[0] == '\0')
1065 #if defined BB_FEATURE_TAR_EXCLUDE
1066 if (exclude_file(tbInfo->excludeList, header_name)) {
1071 if (writeTarHeader(tbInfo, header_name, fileName, statbuf)==FALSE) {
1075 /* Now, if the file is a regular file, copy it out to the tarball */
1076 if ((tbInfo->hlInfo == NULL)
1077 && (S_ISREG(statbuf->st_mode))) {
1079 char buffer[BUFSIZ];
1080 ssize_t size=0, readSize=0;
1082 /* open the file we want to archive, and make sure all is well */
1083 if ((inputFileFd = open(fileName, O_RDONLY)) < 0) {
1084 error_msg("%s: Cannot open: %s", fileName, strerror(errno));
1088 /* write the file to the archive */
1089 while ( (size = full_read(inputFileFd, buffer, sizeof(buffer))) > 0 ) {
1090 if (full_write(tbInfo->tarFd, buffer, size) != size ) {
1091 /* Output file seems to have a problem */
1092 error_msg(io_error, fileName, strerror(errno));
1098 error_msg(io_error, fileName, strerror(errno));
1101 /* Pad the file up to the tar block size */
1102 for (; (readSize%TAR_BLOCK_SIZE) != 0; readSize++) {
1103 write(tbInfo->tarFd, "\0", 1);
1105 close( inputFileFd);
1111 static int writeTarFile(const char* tarName, int verboseFlag, char **argv,
1115 int errorFlag=FALSE;
1117 struct TarBallInfo tbInfo;
1118 tbInfo.verboseFlag = verboseFlag;
1119 tbInfo.hlInfoHead = NULL;
1121 /* Make sure there is at least one file to tar up. */
1123 error_msg_and_die("Cowardly refusing to create an empty archive");
1125 /* Open the tar file for writing. */
1126 if (!strcmp(tarName, "-"))
1127 tbInfo.tarFd = fileno(stdout);
1129 tbInfo.tarFd = open (tarName, O_WRONLY | O_CREAT | O_TRUNC, 0644);
1130 if (tbInfo.tarFd < 0) {
1131 perror_msg( "Error opening '%s'", tarName);
1132 freeHardLinkInfo(&tbInfo.hlInfoHead);
1135 tbInfo.excludeList=excludeList;
1136 /* Store the stat info for the tarball's file, so
1137 * can avoid including the tarball into itself.... */
1138 if (fstat(tbInfo.tarFd, &tbInfo.statBuf) < 0)
1139 error_msg_and_die(io_error, tarName, strerror(errno));
1141 /* Set the umask for this process so it doesn't
1142 * screw up permission setting for us later. */
1145 /* Read the directory/files and iterate over them one at a time */
1146 while (*argv != NULL) {
1147 if (recursive_action(*argv++, TRUE, FALSE, FALSE,
1148 writeFileToTarball, writeFileToTarball,
1149 (void*) &tbInfo) == FALSE) {
1153 /* Write two empty blocks to the end of the archive */
1154 for (size=0; size<(2*TAR_BLOCK_SIZE); size++) {
1155 write(tbInfo.tarFd, "\0", 1);
1158 /* To be pedantically correct, we would check if the tarball
1159 * is smaller than 20 tar blocks, and pad it if it was smaller,
1160 * but that isn't necessary for GNU tar interoperability, and
1161 * so is considered a waste of space */
1163 /* Hang up the tools, close up shop, head home */
1165 if (errorFlag == TRUE) {
1166 error_msg("Error exit delayed from previous errors");
1167 freeHardLinkInfo(&tbInfo.hlInfoHead);
1170 freeHardLinkInfo(&tbInfo.hlInfoHead);