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 #ifdef BB_FEATURE_TAR_GZIP
60 extern int unzip(int in, int out);
63 /* Tar file constants */
65 #define MAJOR(dev) (((dev)>>8)&0xff)
66 #define MINOR(dev) ((dev)&0xff)
69 enum { NAME_SIZE = 100 }; /* because gcc won't let me use 'static const int' */
71 /* POSIX tar Header Block, from POSIX 1003.1-1990 */
75 char name[NAME_SIZE]; /* 0-99 */
76 char mode[8]; /* 100-107 */
77 char uid[8]; /* 108-115 */
78 char gid[8]; /* 116-123 */
79 char size[12]; /* 124-135 */
80 char mtime[12]; /* 136-147 */
81 char chksum[8]; /* 148-155 */
82 char typeflag; /* 156-156 */
83 char linkname[NAME_SIZE]; /* 157-256 */
84 char magic[6]; /* 257-262 */
85 char version[2]; /* 263-264 */
86 char uname[32]; /* 265-296 */
87 char gname[32]; /* 297-328 */
88 char devmajor[8]; /* 329-336 */
89 char devminor[8]; /* 337-344 */
90 char prefix[155]; /* 345-499 */
91 char padding[12]; /* 500-512 (pad to exactly the TAR_BLOCK_SIZE) */
93 typedef struct TarHeader TarHeader;
96 /* A few useful constants */
97 #define TAR_MAGIC "ustar" /* ustar and a null */
98 #define TAR_VERSION " " /* Be compatable with GNU tar format */
99 static const int TAR_MAGIC_LEN = 6;
100 static const int TAR_VERSION_LEN = 2;
101 static const int TAR_BLOCK_SIZE = 512;
103 /* A nice enum with all the possible tar file content types */
106 REGTYPE = '0', /* regular file */
107 REGTYPE0 = '\0', /* regular file (ancient bug compat)*/
108 LNKTYPE = '1', /* hard link */
109 SYMTYPE = '2', /* symbolic link */
110 CHRTYPE = '3', /* character special */
111 BLKTYPE = '4', /* block special */
112 DIRTYPE = '5', /* directory */
113 FIFOTYPE = '6', /* FIFO special */
114 CONTTYPE = '7', /* reserved */
115 GNULONGLINK = 'K', /* GNU long (>100 chars) link name */
116 GNULONGNAME = 'L', /* GNU long (>100 chars) file name */
118 typedef enum TarFileType TarFileType;
120 /* This struct ignores magic, non-numeric user name,
121 * non-numeric group name, and the checksum, since
122 * these are all ignored by BusyBox tar. */
125 int tarFd; /* An open file descriptor for reading from the tarball */
126 char * name; /* File name */
127 mode_t mode; /* Unix mode, including device bits. */
128 uid_t uid; /* Numeric UID */
129 gid_t gid; /* Numeric GID */
130 size_t size; /* Size of file */
131 time_t mtime; /* Last-modified time */
132 enum TarFileType type; /* Regular, directory, link, etc */
133 char * linkname; /* Name for symbolic and hard links */
134 long devmajor; /* Major number for special device */
135 long devminor; /* Minor number for special device */
137 typedef struct TarInfo TarInfo;
139 /* Local procedures to restore files from a tar file. */
140 extern int readTarFile(int tarFd, int extractFlag, int listFlag,
141 int tostdoutFlag, int verboseFlag, char** extractList,
144 #ifdef BB_FEATURE_TAR_CREATE
145 /* Local procedures to save files into a tar file. */
146 static int writeTarFile(const char* tarName, int verboseFlag, char **argv,
150 #ifdef BB_FEATURE_TAR_GZIP
151 /* Signal handler for when child gzip process dies... */
152 static void child_died()
159 extern int tar_unzip_init(int tarFd)
162 static int unzip_pipe[2];
163 /* Cope if child dies... Otherwise we block forever in read()... */
164 signal(SIGCHLD, child_died);
166 if (pipe(unzip_pipe)!=0)
167 error_msg_and_die("pipe error");
169 if ( (child_pid = fork()) == -1)
170 error_msg_and_die("fork failure");
174 close(unzip_pipe[0]);
176 unzip(tarFd, unzip_pipe[1]);
180 /* return fd of uncompressed data to parent process */
181 close(unzip_pipe[1]);
182 return(unzip_pipe[0]);
187 #if defined BB_FEATURE_TAR_EXCLUDE
188 static struct option longopts[] = {
189 { "exclude", 1, NULL, 'e' },
194 extern int tar_main(int argc, char **argv)
196 char** excludeList=NULL;
197 char** extractList=NULL;
198 const char *tarName="-";
199 #if defined BB_FEATURE_TAR_EXCLUDE
200 int excludeListSize=0;
204 #if defined BB_FEATURE_TAR_GZIP
205 int unzipFlag = FALSE;
207 int listFlag = FALSE;
208 int extractFlag = FALSE;
209 int createFlag = FALSE;
210 int verboseFlag = FALSE;
211 int tostdoutFlag = FALSE;
218 if (argv[1][0] != '-') {
219 char *tmp = xmalloc(strlen(argv[1]) + 2);
221 strcpy(tmp + 1, argv[1]);
226 #ifndef BB_FEATURE_TAR_EXCLUDE
227 (opt = getopt(argc, argv, "cxtzvOf:"))
229 (opt = getopt_long(argc, argv, "cxtzvOf:X:", longopts, NULL))
234 if (extractFlag == TRUE || listFlag == TRUE)
239 if (listFlag == TRUE || createFlag == TRUE)
244 if (extractFlag == TRUE || createFlag == TRUE)
248 #ifdef BB_FEATURE_TAR_GZIP
261 error_msg_and_die( "Only one 'f' option allowed");
264 #if defined BB_FEATURE_TAR_EXCLUDE
266 excludeList=xrealloc( excludeList,
267 sizeof(char *) * (excludeListSize+2));
268 excludeList[excludeListSize] = optarg;
269 /* Tack a NULL onto the end of the list */
270 excludeList[++excludeListSize] = NULL;
272 fileList = xfopen(optarg, "r");
273 while (fgets(file, sizeof(file), fileList) != NULL) {
274 excludeList = xrealloc(excludeList,
275 sizeof(char *) * (excludeListSize+2));
277 excludeList[excludeListSize] = xstrdup(file);
278 /* Tack a NULL onto the end of the list */
279 excludeList[++excludeListSize] = NULL;
290 * Do the correct type of action supplying the rest of the
291 * command line arguments as the list of files to process.
293 if (createFlag == TRUE) {
294 #ifndef BB_FEATURE_TAR_CREATE
295 error_msg_and_die( "This version of tar was not compiled with tar creation support.");
297 #ifdef BB_FEATURE_TAR_GZIP
299 error_msg_and_die("Creation of compressed not internally support by tar, pipe to busybox gunzip");
301 status = writeTarFile(tarName, verboseFlag, argv + optind, excludeList);
304 if (listFlag == TRUE || extractFlag == TRUE) {
307 extractList = argv + optind;
308 /* Open the tar file for reading. */
309 if (!strcmp(tarName, "-"))
310 tarFd = fileno(stdin);
312 tarFd = open(tarName, O_RDONLY);
314 perror_msg_and_die("Error opening '%s'", tarName);
316 #ifdef BB_FEATURE_TAR_GZIP
317 /* unzip tarFd in a seperate process */
318 if (unzipFlag == TRUE)
319 tarFd = tar_unzip_init(tarFd);
321 status = readTarFile(tarFd, extractFlag, listFlag, tostdoutFlag,
322 verboseFlag, extractList, excludeList);
331 error_msg_and_die( "Exactly one of 'c', 'x' or 't' must be specified");
335 fixUpPermissions(TarInfo *header)
338 /* Now set permissions etc for the new file */
339 chown(header->name, header->uid, header->gid);
340 chmod(header->name, header->mode);
343 t.modtime = header->mtime;
344 utime(header->name, &t);
348 tarExtractRegularFile(TarInfo *header, int extractFlag, int tostdoutFlag)
352 size_t actualWriteSz;
354 size_t size = header->size;
355 int outFd=fileno(stdout);
357 /* Open the file to be written, if a file is supposed to be written */
358 if (extractFlag==TRUE && tostdoutFlag==FALSE) {
359 /* Create the path to the file, just in case it isn't there...
360 * This should not screw up path permissions or anything. */
361 create_path(header->name, 0777);
362 if ((outFd=open(header->name, O_CREAT|O_TRUNC|O_WRONLY,
363 header->mode & ~S_IFMT)) < 0) {
364 error_msg(io_error, header->name, strerror(errno));
369 /* Write out the file, if we are supposed to be doing that */
372 if ( size > sizeof(buffer) )
373 writeSize = readSize = sizeof(buffer);
375 int mod = size % 512;
377 readSize = size + (512 - mod);
382 if ( (readSize = full_read(header->tarFd, buffer, readSize)) <= 0 ) {
383 /* Tarball seems to have a problem */
384 error_msg("Unexpected EOF in archive");
387 if ( readSize < writeSize )
388 writeSize = readSize;
390 /* Write out the file, if we are supposed to be doing that */
391 if (extractFlag==TRUE) {
393 if ((actualWriteSz=full_write(outFd, buffer, writeSize)) != writeSize ) {
394 /* Output file seems to have a problem */
395 error_msg(io_error, header->name, strerror(errno));
399 actualWriteSz=writeSize;
402 size -= actualWriteSz;
405 /* Now we are done writing the file out, so try
406 * and fix up the permissions and whatnot */
407 if (extractFlag==TRUE && tostdoutFlag==FALSE) {
409 fixUpPermissions(header);
415 tarExtractDirectory(TarInfo *header, int extractFlag, int tostdoutFlag)
418 if (extractFlag==FALSE || tostdoutFlag==TRUE)
421 if (create_path(header->name, header->mode) != TRUE) {
422 perror_msg("%s: Cannot mkdir", header->name);
425 /* make the final component, just in case it was
426 * omitted by create_path() (which will skip the
427 * directory if it doesn't have a terminating '/') */
428 if (mkdir(header->name, header->mode) < 0 && errno != EEXIST) {
429 perror_msg("%s", header->name);
433 fixUpPermissions(header);
438 tarExtractHardLink(TarInfo *header, int extractFlag, int tostdoutFlag)
440 if (extractFlag==FALSE || tostdoutFlag==TRUE)
443 if (link(header->linkname, header->name) < 0) {
444 perror_msg("%s: Cannot create hard link to '%s'", header->name,
449 /* Now set permissions etc for the new directory */
450 fixUpPermissions(header);
455 tarExtractSymLink(TarInfo *header, int extractFlag, int tostdoutFlag)
457 if (extractFlag==FALSE || tostdoutFlag==TRUE)
461 if (symlink(header->linkname, header->name) < 0) {
462 perror_msg("%s: Cannot create symlink to '%s'", header->name,
466 /* Try to change ownership of the symlink.
467 * If libs doesn't support that, don't bother.
468 * Changing the pointed-to-file is the Wrong Thing(tm).
470 #if (__GLIBC__ >= 2) && (__GLIBC_MINOR__ >= 1)
471 lchown(header->name, header->uid, header->gid);
474 /* Do not change permissions or date on symlink,
475 * since it changes the pointed to file instead. duh. */
477 error_msg("%s: Cannot create symlink to '%s': %s",
478 header->name, header->linkname,
479 "symlinks not supported");
485 tarExtractSpecial(TarInfo *header, int extractFlag, int tostdoutFlag)
487 if (extractFlag==FALSE || tostdoutFlag==TRUE)
490 if (S_ISCHR(header->mode) || S_ISBLK(header->mode) || S_ISSOCK(header->mode)) {
491 if (mknod(header->name, header->mode, makedev(header->devmajor, header->devminor)) < 0) {
492 perror_msg("%s: Cannot mknod", header->name);
495 } else if (S_ISFIFO(header->mode)) {
496 if (mkfifo(header->name, header->mode) < 0) {
497 perror_msg("%s: Cannot mkfifo", header->name);
502 /* Now set permissions etc for the new directory */
503 fixUpPermissions(header);
507 /* Read an octal value in a field of the specified width, with optional
508 * spaces on both sides of the number and with an optional null character
509 * at the end. Returns -1 on an illegal format. */
510 static long getOctal(const char *cp, int size)
514 for(;(size > 0) && (*cp == ' '); cp++, size--);
515 if ((size == 0) || !is_octal(*cp))
517 for(; (size > 0) && is_octal(*cp); size--) {
518 val = val * 8 + *cp++ - '0';
520 for (;(size > 0) && (*cp == ' '); cp++, size--);
521 if ((size > 0) && *cp)
527 /* Parse the tar header and fill in the nice struct with the details */
529 readTarHeader(struct TarHeader *rawHeader, struct TarInfo *header)
533 unsigned char *s = (unsigned char *)rawHeader;
535 header->name = rawHeader->name;
536 /* Check for and relativify any absolute paths */
537 if ( *(header->name) == '/' ) {
538 static int alreadyWarned=FALSE;
540 while (*(header->name) == '/')
543 if (alreadyWarned == FALSE) {
544 error_msg("Removing leading '/' from member names");
545 alreadyWarned = TRUE;
549 header->mode = getOctal(rawHeader->mode, sizeof(rawHeader->mode));
550 header->uid = getOctal(rawHeader->uid, sizeof(rawHeader->uid));
551 header->gid = getOctal(rawHeader->gid, sizeof(rawHeader->gid));
552 header->size = getOctal(rawHeader->size, sizeof(rawHeader->size));
553 header->mtime = getOctal(rawHeader->mtime, sizeof(rawHeader->mtime));
554 chksum = getOctal(rawHeader->chksum, sizeof(rawHeader->chksum));
555 header->type = rawHeader->typeflag;
556 header->linkname = rawHeader->linkname;
557 header->devmajor = getOctal(rawHeader->devmajor, sizeof(rawHeader->devmajor));
558 header->devminor = getOctal(rawHeader->devminor, sizeof(rawHeader->devminor));
560 /* Check the checksum */
561 for (i = sizeof(*rawHeader); i-- != 0;) {
564 /* Remove the effects of the checksum field (replace
565 * with blanks for the purposes of the checksum) */
566 s = rawHeader->chksum;
567 for (i = sizeof(rawHeader->chksum) ; i-- != 0;) {
570 sum += ' ' * sizeof(rawHeader->chksum);
576 static int exclude_file(char **excluded_files, const char *file)
580 if (excluded_files == NULL)
583 for (i = 0; excluded_files[i] != NULL; i++) {
584 if (excluded_files[i][0] == '/') {
585 if (fnmatch(excluded_files[i], file,
586 FNM_PATHNAME | FNM_LEADING_DIR) == 0)
591 for (p = file; p[0] != '\0'; p++) {
592 if ((p == file || p[-1] == '/') && p[0] != '/' &&
593 fnmatch(excluded_files[i], p,
594 FNM_PATHNAME | FNM_LEADING_DIR) == 0)
603 static int extract_file(char **extract_files, const char *file)
607 if (extract_files == NULL)
610 for (i = 0; extract_files[i] != NULL; i++) {
611 if (fnmatch(extract_files[i], file, FNM_LEADING_DIR) == 0)
619 * Read a tar file and extract or list the specified files within it.
620 * If the list is empty than all files are extracted or listed.
622 extern int readTarFile(int tarFd, int extractFlag, int listFlag,
623 int tostdoutFlag, int verboseFlag, char** extractList,
628 int skipNextHeaderFlag=FALSE;
632 /* Set the umask for this process so it doesn't
633 * screw up permission setting for us later. */
636 /* Read the tar file, and iterate over it one file at a time */
637 while ( (status = full_read(tarFd, (char*)&rawHeader, TAR_BLOCK_SIZE)) == TAR_BLOCK_SIZE ) {
639 /* Try to read the header */
640 if ( readTarHeader(&rawHeader, &header) == FALSE ) {
641 if ( *(header.name) == '\0' ) {
645 error_msg("Bad tar header, skipping");
649 if ( *(header.name) == '\0' )
651 header.tarFd = tarFd;
653 /* Skip funky extra GNU headers that precede long files */
654 if ( (header.type == GNULONGNAME) || (header.type == GNULONGLINK) ) {
655 skipNextHeaderFlag=TRUE;
656 if (tarExtractRegularFile(&header, FALSE, FALSE) == FALSE)
660 if ( skipNextHeaderFlag == TRUE ) {
661 skipNextHeaderFlag=FALSE;
662 error_msg(name_longer_than_foo, NAME_SIZE);
663 if (tarExtractRegularFile(&header, FALSE, FALSE) == FALSE)
668 #if defined BB_FEATURE_TAR_EXCLUDE
669 if (exclude_file(excludeList, header.name)) {
670 /* There are not the droids you're looking for, move along */
671 /* If it is a regular file, pretend to extract it with
672 * the extractFlag set to FALSE, so the junk in the tarball
673 * is properly skipped over */
674 if ( header.type==REGTYPE || header.type==REGTYPE0 ) {
675 if (tarExtractRegularFile(&header, FALSE, FALSE) == FALSE)
682 if (!extract_file(extractList, header.name)) {
683 /* There are not the droids you're looking for, move along */
684 /* If it is a regular file, pretend to extract it with
685 * the extractFlag set to FALSE, so the junk in the tarball
686 * is properly skipped over */
687 if ( header.type==REGTYPE || header.type==REGTYPE0 ) {
688 if (tarExtractRegularFile(&header, FALSE, FALSE) == FALSE)
694 if (listFlag == TRUE) {
695 /* Special treatment if the list (-t) flag is on */
696 if (verboseFlag == TRUE) {
699 struct tm *tm = localtime (&(header.mtime));
701 len=printf("%s ", mode_string(header.mode));
702 my_getpwuid(buf, header.uid);
704 len+=printf("%d", header.uid);
706 len+=printf("%s", buf);
707 my_getgrgid(buf, header.gid);
709 len+=printf("/%-d ", header.gid);
711 len+=printf("/%-s ", buf);
713 if (header.type==CHRTYPE || header.type==BLKTYPE) {
714 len1=snprintf(buf, sizeof(buf), "%ld,%-ld ",
715 header.devmajor, header.devminor);
717 len1=snprintf(buf, sizeof(buf), "%lu ", (long)header.size);
719 /* Jump through some hoops to make the columns match up */
720 for(;(len+len1)<31;len++)
724 /* Use ISO 8610 time format */
726 printf ("%04d-%02d-%02d %02d:%02d:%02d ",
727 tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday,
728 tm->tm_hour, tm->tm_min, tm->tm_sec);
731 printf("%s", header.name);
732 if (verboseFlag == TRUE) {
733 if (header.type==LNKTYPE) /* If this is a link, say so */
734 printf(" link to %s", header.linkname);
735 else if (header.type==SYMTYPE)
736 printf(" -> %s", header.linkname);
741 /* List contents if we are supposed to do that */
742 if (verboseFlag == TRUE && extractFlag == TRUE) {
743 /* Now the normal listing */
745 if (tostdoutFlag == TRUE) // If the archive goes to stdout, verbose to stderr
747 fprintf(vbFd, "%s\n", header.name);
750 /* Remove files if we would overwrite them */
751 if (extractFlag == TRUE && tostdoutFlag == FALSE)
754 /* If we got here, we can be certain we have a legitimate
755 * header to work with. So work with it. */
756 switch ( header.type ) {
759 /* If the name ends in a '/' then assume it is
760 * supposed to be a directory, and fall through */
761 if (header.name[strlen(header.name)-1] != '/') {
762 if (tarExtractRegularFile(&header, extractFlag, tostdoutFlag)==FALSE)
767 if (tarExtractDirectory( &header, extractFlag, tostdoutFlag)==FALSE)
771 if (tarExtractHardLink( &header, extractFlag, tostdoutFlag)==FALSE)
775 if (tarExtractSymLink( &header, extractFlag, tostdoutFlag)==FALSE)
781 if (tarExtractSpecial( &header, extractFlag, tostdoutFlag)==FALSE)
785 /* Handled earlier */
788 skipNextHeaderFlag=TRUE;
792 error_msg("Unknown file type '%c' in tar file", header.type);
799 /* Bummer - we read a partial header */
800 perror_msg("Error reading tar file");
803 else if (errorFlag==TRUE) {
804 error_msg( "Error exit delayed from previous errors");
809 /* Stuff to do when we are done */
812 if ( *(header.name) == '\0' ) {
814 error_msg( "Error exit delayed from previous errors");
822 #ifdef BB_FEATURE_TAR_CREATE
825 ** writeTarFile(), writeFileToTarball(), and writeTarHeader() are
826 ** the only functions that deal with the HardLinkInfo structure.
827 ** Even these functions use the xxxHardLinkInfo() functions.
829 typedef struct HardLinkInfo HardLinkInfo;
832 HardLinkInfo *next; /* Next entry in list */
833 dev_t dev; /* Device number */
834 ino_t ino; /* Inode number */
835 short linkCount; /* (Hard) Link Count */
836 char name[1]; /* Start of filename (must be last) */
839 /* Some info to be carried along when creating a new tarball */
842 char* fileName; /* File name of the tarball */
843 int tarFd; /* Open-for-write file descriptor
845 struct stat statBuf; /* Stat info for the tarball, letting
846 us know the inode and device that the
847 tarball lives, so we can avoid trying
848 to include the tarball into itself */
849 int verboseFlag; /* Whether to print extra stuff or not */
850 char** excludeList; /* List of files to not include */
851 HardLinkInfo *hlInfoHead; /* Hard Link Tracking Information */
852 HardLinkInfo *hlInfo; /* Hard Link Info for the current file */
854 typedef struct TarBallInfo TarBallInfo;
857 /* Might be faster (and bigger) if the dev/ino were stored in numeric order;) */
859 addHardLinkInfo (HardLinkInfo **hlInfoHeadPtr, dev_t dev, ino_t ino,
860 short linkCount, const char *name)
862 /* Note: hlInfoHeadPtr can never be NULL! */
863 HardLinkInfo *hlInfo;
865 hlInfo = (HardLinkInfo *)xmalloc(sizeof(HardLinkInfo)+strlen(name)+1);
867 hlInfo->next = *hlInfoHeadPtr;
868 *hlInfoHeadPtr = hlInfo;
871 hlInfo->linkCount = linkCount;
872 strcpy(hlInfo->name, name);
878 freeHardLinkInfo (HardLinkInfo **hlInfoHeadPtr)
880 HardLinkInfo *hlInfo = NULL;
881 HardLinkInfo *hlInfoNext = NULL;
884 hlInfo = *hlInfoHeadPtr;
886 hlInfoNext = hlInfo->next;
890 *hlInfoHeadPtr = NULL;
895 /* Might be faster (and bigger) if the dev/ino were stored in numeric order;) */
896 static HardLinkInfo *
897 findHardLinkInfo (HardLinkInfo *hlInfo, dev_t dev, ino_t ino)
900 if ((ino == hlInfo->ino) && (dev == hlInfo->dev))
902 hlInfo = hlInfo->next;
907 /* Put an octal string into the specified buffer.
908 * The number is zero and space padded and possibly null padded.
909 * Returns TRUE if successful. */
910 static int putOctal (char *cp, int len, long value)
914 char *tempString = tempBuffer;
916 /* Create a string of the specified length with an initial space,
917 * leading zeroes and the octal number, and a trailing null. */
918 sprintf (tempString, "%0*lo", len - 1, value);
920 /* If the string is too large, suppress the leading space. */
921 tempLength = strlen (tempString) + 1;
922 if (tempLength > len) {
927 /* If the string is still too large, suppress the trailing null. */
928 if (tempLength > len)
931 /* If the string is still too large, fail. */
932 if (tempLength > len)
935 /* Copy the string to the field. */
936 memcpy (cp, tempString, len);
941 /* Write out a tar header for the specified file/directory/whatever */
943 writeTarHeader(struct TarBallInfo *tbInfo, const char *header_name,
944 const char *real_name, struct stat *statbuf)
947 struct TarHeader header;
948 const unsigned char *cp = (const unsigned char *) &header;
949 ssize_t size = sizeof(struct TarHeader);
951 memset( &header, 0, size);
953 strncpy(header.name, header_name, sizeof(header.name));
955 putOctal(header.mode, sizeof(header.mode), statbuf->st_mode);
956 putOctal(header.uid, sizeof(header.uid), statbuf->st_uid);
957 putOctal(header.gid, sizeof(header.gid), statbuf->st_gid);
958 putOctal(header.size, sizeof(header.size), 0); /* Regular file size is handled later */
959 putOctal(header.mtime, sizeof(header.mtime), statbuf->st_mtime);
960 strncpy(header.magic, TAR_MAGIC TAR_VERSION,
961 TAR_MAGIC_LEN + TAR_VERSION_LEN );
963 /* Enter the user and group names (default to root if it fails) */
964 my_getpwuid(header.uname, statbuf->st_uid);
966 strcpy(header.uname, "root");
967 my_getgrgid(header.gname, statbuf->st_gid);
969 strcpy(header.uname, "root");
971 if (tbInfo->hlInfo) {
972 /* This is a hard link */
973 header.typeflag = LNKTYPE;
974 strncpy(header.linkname, tbInfo->hlInfo->name, sizeof(header.linkname));
975 } else if (S_ISLNK(statbuf->st_mode)) {
978 header.typeflag = SYMTYPE;
979 link_size = readlink(real_name, buffer, sizeof(buffer) - 1);
980 if ( link_size < 0) {
981 perror_msg("Error reading symlink '%s'", header.name);
984 buffer[link_size] = '\0';
985 strncpy(header.linkname, buffer, sizeof(header.linkname));
986 } else if (S_ISDIR(statbuf->st_mode)) {
987 header.typeflag = DIRTYPE;
988 strncat(header.name, "/", sizeof(header.name));
989 } else if (S_ISCHR(statbuf->st_mode)) {
990 header.typeflag = CHRTYPE;
991 putOctal(header.devmajor, sizeof(header.devmajor), MAJOR(statbuf->st_rdev));
992 putOctal(header.devminor, sizeof(header.devminor), MINOR(statbuf->st_rdev));
993 } else if (S_ISBLK(statbuf->st_mode)) {
994 header.typeflag = BLKTYPE;
995 putOctal(header.devmajor, sizeof(header.devmajor), MAJOR(statbuf->st_rdev));
996 putOctal(header.devminor, sizeof(header.devminor), MINOR(statbuf->st_rdev));
997 } else if (S_ISFIFO(statbuf->st_mode)) {
998 header.typeflag = FIFOTYPE;
999 } else if (S_ISREG(statbuf->st_mode)) {
1000 header.typeflag = REGTYPE;
1001 putOctal(header.size, sizeof(header.size), statbuf->st_size);
1003 error_msg("%s: Unknown file type", real_name);
1007 /* Calculate and store the checksum (i.e. the sum of all of the bytes of
1008 * the header). The checksum field must be filled with blanks for the
1009 * calculation. The checksum field is formatted differently from the
1010 * other fields: it has [6] digits, a null, then a space -- rather than
1011 * digits, followed by a null like the other fields... */
1012 memset(header.chksum, ' ', sizeof(header.chksum));
1013 cp = (const unsigned char *) &header;
1016 putOctal(header.chksum, 7, chksum);
1018 /* Now write the header out to disk */
1019 if ((size=full_write(tbInfo->tarFd, (char*)&header, sizeof(struct TarHeader))) < 0) {
1020 error_msg(io_error, real_name, strerror(errno));
1023 /* Pad the header up to the tar block size */
1024 for (; size<TAR_BLOCK_SIZE; size++) {
1025 write(tbInfo->tarFd, "\0", 1);
1027 /* Now do the verbose thing (or not) */
1028 if (tbInfo->verboseFlag==TRUE) {
1029 FILE *vbFd = stdout;
1030 if (tbInfo->tarFd == fileno(stdout)) // If the archive goes to stdout, verbose to stderr
1032 fprintf(vbFd, "%s\n", header.name);
1039 static int writeFileToTarball(const char *fileName, struct stat *statbuf, void* userData)
1041 struct TarBallInfo *tbInfo = (struct TarBallInfo *)userData;
1042 const char *header_name;
1045 ** Check to see if we are dealing with a hard link.
1047 ** Treat the first occurance of a given dev/inode as a file while
1048 ** treating any additional occurances as hard links. This is done
1049 ** by adding the file information to the HardLinkInfo linked list.
1051 tbInfo->hlInfo = NULL;
1052 if (statbuf->st_nlink > 1) {
1053 tbInfo->hlInfo = findHardLinkInfo(tbInfo->hlInfoHead, statbuf->st_dev,
1055 if (tbInfo->hlInfo == NULL)
1056 addHardLinkInfo (&tbInfo->hlInfoHead, statbuf->st_dev,
1057 statbuf->st_ino, statbuf->st_nlink, fileName);
1060 /* It is against the rules to archive a socket */
1061 if (S_ISSOCK(statbuf->st_mode)) {
1062 error_msg("%s: socket ignored", fileName);
1066 /* It is a bad idea to store the archive we are in the process of creating,
1067 * so check the device and inode to be sure that this particular file isn't
1068 * the new tarball */
1069 if (tbInfo->statBuf.st_dev == statbuf->st_dev &&
1070 tbInfo->statBuf.st_ino == statbuf->st_ino) {
1071 error_msg("%s: file is the archive; skipping", fileName);
1075 header_name = fileName;
1076 while (header_name[0] == '/') {
1077 static int alreadyWarned=FALSE;
1078 if (alreadyWarned==FALSE) {
1079 error_msg("Removing leading '/' from member names");
1085 if (strlen(fileName) >= NAME_SIZE) {
1086 error_msg(name_longer_than_foo, NAME_SIZE);
1090 if (header_name[0] == '\0')
1093 #if defined BB_FEATURE_TAR_EXCLUDE
1094 if (exclude_file(tbInfo->excludeList, header_name)) {
1099 if (writeTarHeader(tbInfo, header_name, fileName, statbuf)==FALSE) {
1103 /* Now, if the file is a regular file, copy it out to the tarball */
1104 if ((tbInfo->hlInfo == NULL)
1105 && (S_ISREG(statbuf->st_mode))) {
1107 char buffer[BUFSIZ];
1108 ssize_t size=0, readSize=0;
1110 /* open the file we want to archive, and make sure all is well */
1111 if ((inputFileFd = open(fileName, O_RDONLY)) < 0) {
1112 error_msg("%s: Cannot open: %s", fileName, strerror(errno));
1116 /* write the file to the archive */
1117 while ( (size = full_read(inputFileFd, buffer, sizeof(buffer))) > 0 ) {
1118 if (full_write(tbInfo->tarFd, buffer, size) != size ) {
1119 /* Output file seems to have a problem */
1120 error_msg(io_error, fileName, strerror(errno));
1126 error_msg(io_error, fileName, strerror(errno));
1129 /* Pad the file up to the tar block size */
1130 for (; (readSize%TAR_BLOCK_SIZE) != 0; readSize++) {
1131 write(tbInfo->tarFd, "\0", 1);
1133 close( inputFileFd);
1139 static int writeTarFile(const char* tarName, int verboseFlag, char **argv,
1143 int errorFlag=FALSE;
1145 struct TarBallInfo tbInfo;
1146 tbInfo.verboseFlag = verboseFlag;
1147 tbInfo.hlInfoHead = NULL;
1149 /* Make sure there is at least one file to tar up. */
1151 error_msg_and_die("Cowardly refusing to create an empty archive");
1153 /* Open the tar file for writing. */
1154 if (!strcmp(tarName, "-"))
1155 tbInfo.tarFd = fileno(stdout);
1157 tbInfo.tarFd = open (tarName, O_WRONLY | O_CREAT | O_TRUNC, 0644);
1158 if (tbInfo.tarFd < 0) {
1159 perror_msg( "Error opening '%s'", tarName);
1160 freeHardLinkInfo(&tbInfo.hlInfoHead);
1163 tbInfo.excludeList=excludeList;
1164 /* Store the stat info for the tarball's file, so
1165 * can avoid including the tarball into itself.... */
1166 if (fstat(tbInfo.tarFd, &tbInfo.statBuf) < 0)
1167 error_msg_and_die(io_error, tarName, strerror(errno));
1169 /* Set the umask for this process so it doesn't
1170 * screw up permission setting for us later. */
1173 /* Read the directory/files and iterate over them one at a time */
1174 while (*argv != NULL) {
1175 if (recursive_action(*argv++, TRUE, FALSE, FALSE,
1176 writeFileToTarball, writeFileToTarball,
1177 (void*) &tbInfo) == FALSE) {
1181 /* Write two empty blocks to the end of the archive */
1182 for (size=0; size<(2*TAR_BLOCK_SIZE); size++) {
1183 write(tbInfo.tarFd, "\0", 1);
1186 /* To be pedantically correct, we would check if the tarball
1187 * is smaller than 20 tar blocks, and pad it if it was smaller,
1188 * but that isn't necessary for GNU tar interoperability, and
1189 * so is considered a waste of space */
1191 /* Hang up the tools, close up shop, head home */
1193 if (errorFlag == TRUE) {
1194 error_msg("Error exit delayed from previous errors");
1195 freeHardLinkInfo(&tbInfo.hlInfoHead);
1198 freeHardLinkInfo(&tbInfo.hlInfoHead);