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
42 #define bb_need_name_longer_than_foo
51 #include <sys/types.h>
52 #include <sys/sysmacros.h>
56 #ifdef BB_FEATURE_TAR_GZIP
57 extern int unzip(int in, int out);
58 extern int gunzip_init();
61 /* Tar file constants */
63 #define MAJOR(dev) (((dev)>>8)&0xff)
64 #define MINOR(dev) ((dev)&0xff)
67 enum { NAME_SIZE = 100 }; /* because gcc won't let me use 'static const int' */
69 /* POSIX tar Header Block, from POSIX 1003.1-1990 */
73 char name[NAME_SIZE]; /* 0-99 */
74 char mode[8]; /* 100-107 */
75 char uid[8]; /* 108-115 */
76 char gid[8]; /* 116-123 */
77 char size[12]; /* 124-135 */
78 char mtime[12]; /* 136-147 */
79 char chksum[8]; /* 148-155 */
80 char typeflag; /* 156-156 */
81 char linkname[NAME_SIZE]; /* 157-256 */
82 char magic[6]; /* 257-262 */
83 char version[2]; /* 263-264 */
84 char uname[32]; /* 265-296 */
85 char gname[32]; /* 297-328 */
86 char devmajor[8]; /* 329-336 */
87 char devminor[8]; /* 337-344 */
88 char prefix[155]; /* 345-499 */
89 char padding[12]; /* 500-512 (pad to exactly the TAR_BLOCK_SIZE) */
91 typedef struct TarHeader TarHeader;
94 /* A few useful constants */
95 #define TAR_MAGIC "ustar" /* ustar and a null */
96 #define TAR_VERSION " " /* Be compatable with GNU tar format */
97 static const int TAR_MAGIC_LEN = 6;
98 static const int TAR_VERSION_LEN = 2;
99 static const int TAR_BLOCK_SIZE = 512;
101 /* A nice enum with all the possible tar file content types */
104 REGTYPE = '0', /* regular file */
105 REGTYPE0 = '\0', /* regular file (ancient bug compat)*/
106 LNKTYPE = '1', /* hard link */
107 SYMTYPE = '2', /* symbolic link */
108 CHRTYPE = '3', /* character special */
109 BLKTYPE = '4', /* block special */
110 DIRTYPE = '5', /* directory */
111 FIFOTYPE = '6', /* FIFO special */
112 CONTTYPE = '7', /* reserved */
113 GNULONGLINK = 'K', /* GNU long (>100 chars) link name */
114 GNULONGNAME = 'L', /* GNU long (>100 chars) file name */
116 typedef enum TarFileType TarFileType;
118 /* This struct ignores magic, non-numeric user name,
119 * non-numeric group name, and the checksum, since
120 * these are all ignored by BusyBox tar. */
123 int tarFd; /* An open file descriptor for reading from the tarball */
124 char * name; /* File name */
125 mode_t mode; /* Unix mode, including device bits. */
126 uid_t uid; /* Numeric UID */
127 gid_t gid; /* Numeric GID */
128 size_t size; /* Size of file */
129 time_t mtime; /* Last-modified time */
130 enum TarFileType type; /* Regular, directory, link, etc */
131 char * linkname; /* Name for symbolic and hard links */
132 long devmajor; /* Major number for special device */
133 long devminor; /* Minor number for special device */
135 typedef struct TarInfo TarInfo;
137 /* Local procedures to restore files from a tar file. */
138 extern int readTarFile(int tarFd, int extractFlag, int listFlag,
139 int tostdoutFlag, int verboseFlag, char** extractList,
142 #ifdef BB_FEATURE_TAR_CREATE
143 /* Local procedures to save files into a tar file. */
144 static int writeTarFile(const char* tarName, int verboseFlag, char **argv,
148 #ifdef BB_FEATURE_TAR_GZIP
149 /* Signal handler for when child gzip process dies... */
157 extern int tar_unzip_init(int tarFd)
160 static int unzip_pipe[2];
161 /* Cope if child dies... Otherwise we block forever in read()... */
162 signal(SIGCHLD, child_died);
164 if (pipe(unzip_pipe)!=0)
165 error_msg_and_die("pipe error\n");
167 if ( (child_pid = fork()) == -1)
168 error_msg_and_die("fork failure\n");
172 close(unzip_pipe[0]);
174 unzip(tarFd, unzip_pipe[1]);
178 /* return fd of uncompressed data to parent process */
179 close(unzip_pipe[1]);
180 return(unzip_pipe[0]);
185 #if defined BB_FEATURE_TAR_EXCLUDE
186 struct option longopts[] = {
187 { "exclude", 1, NULL, 'e' },
192 extern int tar_main(int argc, char **argv)
194 char** excludeList=NULL;
195 char** extractList=NULL;
196 const char *tarName="-";
197 #if defined BB_FEATURE_TAR_EXCLUDE
198 int excludeListSize=0;
202 #if defined BB_FEATURE_TAR_GZIP
203 int unzipFlag = FALSE;
205 int listFlag = FALSE;
206 int extractFlag = FALSE;
207 int createFlag = FALSE;
208 int verboseFlag = FALSE;
209 int tostdoutFlag = FALSE;
216 if (argv[1][0] != '-') {
217 char *tmp = xmalloc(strlen(argv[1]) + 2);
219 strcpy(tmp + 1, argv[1]);
224 #ifndef BB_FEATURE_TAR_EXCLUDE
225 (opt = getopt(argc, argv, "cxtzvOf:"))
227 (opt = getopt_long(argc, argv, "cxtzvOf:X:", longopts, NULL))
232 if (extractFlag == TRUE || listFlag == TRUE)
237 if (listFlag == TRUE || createFlag == TRUE)
242 if (extractFlag == TRUE || createFlag == TRUE)
246 #ifdef BB_FEATURE_TAR_GZIP
259 error_msg_and_die( "Only one 'f' option allowed\n");
262 #if defined BB_FEATURE_TAR_EXCLUDE
264 excludeList=xrealloc( excludeList,
265 sizeof(char *) * (excludeListSize+2));
266 excludeList[excludeListSize] = optarg;
267 /* Tack a NULL onto the end of the list */
268 excludeList[++excludeListSize] = NULL;
270 fileList = xfopen(optarg, "r");
271 while (fgets(file, sizeof(file), fileList) != NULL) {
272 excludeList = xrealloc(excludeList,
273 sizeof(char *) * (excludeListSize+2));
274 if (file[strlen(file)-1] == '\n')
275 file[strlen(file)-1] = '\0';
276 excludeList[excludeListSize] = xstrdup(file);
277 /* Tack a NULL onto the end of the list */
278 excludeList[++excludeListSize] = NULL;
289 * Do the correct type of action supplying the rest of the
290 * command line arguments as the list of files to process.
292 if (createFlag == TRUE) {
293 #ifndef BB_FEATURE_TAR_CREATE
294 error_msg_and_die( "This version of tar was not compiled with tar creation support.\n");
296 #ifdef BB_FEATURE_TAR_GZIP
298 error_msg_and_die("Creation of compressed not internally support by tar, pipe to busybox gunzip\n");
300 status = writeTarFile(tarName, verboseFlag, argv + optind, excludeList);
303 if (listFlag == TRUE || extractFlag == TRUE) {
306 extractList = argv + optind;
307 /* Open the tar file for reading. */
308 if (!strcmp(tarName, "-"))
309 tarFd = fileno(stdin);
311 tarFd = open(tarName, O_RDONLY);
313 perror_msg_and_die("Error opening '%s'", tarName);
315 #ifdef BB_FEATURE_TAR_GZIP
316 /* unzip tarFd in a seperate process */
317 if (unzipFlag == TRUE)
318 tarFd = tar_unzip_init(tarFd);
320 status = readTarFile(tarFd, extractFlag, listFlag, tostdoutFlag,
321 verboseFlag, extractList, excludeList);
330 error_msg_and_die( "Exactly one of 'c', 'x' or 't' must be specified\n");
334 fixUpPermissions(TarInfo *header)
337 /* Now set permissions etc for the new file */
338 chown(header->name, header->uid, header->gid);
339 chmod(header->name, header->mode);
342 t.modtime = header->mtime;
343 utime(header->name, &t);
347 tarExtractRegularFile(TarInfo *header, int extractFlag, int tostdoutFlag)
351 size_t actualWriteSz;
353 size_t size = header->size;
354 int outFd=fileno(stdout);
356 /* Open the file to be written, if a file is supposed to be written */
357 if (extractFlag==TRUE && tostdoutFlag==FALSE) {
358 /* Create the path to the file, just in case it isn't there...
359 * This should not screw up path permissions or anything. */
360 create_path(header->name, 0777);
361 if ((outFd=open(header->name, O_CREAT|O_TRUNC|O_WRONLY,
362 header->mode & ~S_IFMT)) < 0) {
363 error_msg(io_error, header->name, strerror(errno));
368 /* Write out the file, if we are supposed to be doing that */
371 if ( size > sizeof(buffer) )
372 writeSize = readSize = sizeof(buffer);
374 int mod = size % 512;
376 readSize = size + (512 - mod);
381 if ( (readSize = full_read(header->tarFd, buffer, readSize)) <= 0 ) {
382 /* Tarball seems to have a problem */
383 error_msg("Unexpected EOF in archive\n");
386 if ( readSize < writeSize )
387 writeSize = readSize;
389 /* Write out the file, if we are supposed to be doing that */
390 if (extractFlag==TRUE) {
392 if ((actualWriteSz=full_write(outFd, buffer, writeSize)) != writeSize ) {
393 /* Output file seems to have a problem */
394 error_msg(io_error, header->name, strerror(errno));
398 actualWriteSz=writeSize;
401 size -= actualWriteSz;
404 /* Now we are done writing the file out, so try
405 * and fix up the permissions and whatnot */
406 if (extractFlag==TRUE && tostdoutFlag==FALSE) {
408 fixUpPermissions(header);
414 tarExtractDirectory(TarInfo *header, int extractFlag, int tostdoutFlag)
417 if (extractFlag==FALSE || tostdoutFlag==TRUE)
420 if (create_path(header->name, header->mode) != TRUE) {
421 perror_msg("%s: Cannot mkdir", header->name);
424 /* make the final component, just in case it was
425 * omitted by create_path() (which will skip the
426 * directory if it doesn't have a terminating '/') */
427 if (mkdir(header->name, header->mode) < 0 && errno != EEXIST) {
428 perror_msg("%s", header->name);
432 fixUpPermissions(header);
437 tarExtractHardLink(TarInfo *header, int extractFlag, int tostdoutFlag)
439 if (extractFlag==FALSE || tostdoutFlag==TRUE)
442 if (link(header->linkname, header->name) < 0) {
443 perror_msg("%s: Cannot create hard link to '%s'", header->name,
448 /* Now set permissions etc for the new directory */
449 fixUpPermissions(header);
454 tarExtractSymLink(TarInfo *header, int extractFlag, int tostdoutFlag)
456 if (extractFlag==FALSE || tostdoutFlag==TRUE)
460 if (symlink(header->linkname, header->name) < 0) {
461 perror_msg("%s: Cannot create symlink to '%s'", header->name,
465 /* Try to change ownership of the symlink.
466 * If libs doesn't support that, don't bother.
467 * Changing the pointed-to-file is the Wrong Thing(tm).
469 #if (__GLIBC__ >= 2) && (__GLIBC_MINOR__ >= 1)
470 lchown(header->name, header->uid, header->gid);
473 /* Do not change permissions or date on symlink,
474 * since it changes the pointed to file instead. duh. */
476 error_msg("%s: Cannot create symlink to '%s': %s\n",
477 header->name, header->linkname,
478 "symlinks not supported");
484 tarExtractSpecial(TarInfo *header, int extractFlag, int tostdoutFlag)
486 if (extractFlag==FALSE || tostdoutFlag==TRUE)
489 if (S_ISCHR(header->mode) || S_ISBLK(header->mode) || S_ISSOCK(header->mode)) {
490 if (mknod(header->name, header->mode, makedev(header->devmajor, header->devminor)) < 0) {
491 perror_msg("%s: Cannot mknod", header->name);
494 } else if (S_ISFIFO(header->mode)) {
495 if (mkfifo(header->name, header->mode) < 0) {
496 perror_msg("%s: Cannot mkfifo", header->name);
501 /* Now set permissions etc for the new directory */
502 fixUpPermissions(header);
506 /* Read an octal value in a field of the specified width, with optional
507 * spaces on both sides of the number and with an optional null character
508 * at the end. Returns -1 on an illegal format. */
509 static long getOctal(const char *cp, int size)
513 for(;(size > 0) && (*cp == ' '); cp++, size--);
514 if ((size == 0) || !is_octal(*cp))
516 for(; (size > 0) && is_octal(*cp); size--) {
517 val = val * 8 + *cp++ - '0';
519 for (;(size > 0) && (*cp == ' '); cp++, size--);
520 if ((size > 0) && *cp)
526 /* Parse the tar header and fill in the nice struct with the details */
528 readTarHeader(struct TarHeader *rawHeader, struct TarInfo *header)
532 unsigned char *s = (unsigned char *)rawHeader;
534 header->name = rawHeader->name;
535 /* Check for and relativify any absolute paths */
536 if ( *(header->name) == '/' ) {
537 static int alreadyWarned=FALSE;
539 while (*(header->name) == '/')
542 if (alreadyWarned == FALSE) {
543 error_msg("Removing leading '/' from member names\n");
544 alreadyWarned = TRUE;
548 header->mode = getOctal(rawHeader->mode, sizeof(rawHeader->mode));
549 header->uid = getOctal(rawHeader->uid, sizeof(rawHeader->uid));
550 header->gid = getOctal(rawHeader->gid, sizeof(rawHeader->gid));
551 header->size = getOctal(rawHeader->size, sizeof(rawHeader->size));
552 header->mtime = getOctal(rawHeader->mtime, sizeof(rawHeader->mtime));
553 chksum = getOctal(rawHeader->chksum, sizeof(rawHeader->chksum));
554 header->type = rawHeader->typeflag;
555 header->linkname = rawHeader->linkname;
556 header->devmajor = getOctal(rawHeader->devmajor, sizeof(rawHeader->devmajor));
557 header->devminor = getOctal(rawHeader->devminor, sizeof(rawHeader->devminor));
559 /* Check the checksum */
560 for (i = sizeof(*rawHeader); i-- != 0;) {
563 /* Remove the effects of the checksum field (replace
564 * with blanks for the purposes of the checksum) */
565 s = rawHeader->chksum;
566 for (i = sizeof(rawHeader->chksum) ; i-- != 0;) {
569 sum += ' ' * sizeof(rawHeader->chksum);
575 int exclude_file(char **excluded_files, const char *file)
579 if (excluded_files == NULL)
582 for (i = 0; excluded_files[i] != NULL; i++) {
583 if (excluded_files[i][0] == '/') {
584 if (fnmatch(excluded_files[i], file,
585 FNM_PATHNAME | FNM_LEADING_DIR) == 0)
590 for (p = file; p[0] != '\0'; p++) {
591 if ((p == file || p[-1] == '/') && p[0] != '/' &&
592 fnmatch(excluded_files[i], p,
593 FNM_PATHNAME | FNM_LEADING_DIR) == 0)
602 int extract_file(char **extract_files, const char *file)
606 if (extract_files == NULL)
609 for (i = 0; extract_files[i] != NULL; i++) {
610 if (fnmatch(extract_files[i], file, FNM_LEADING_DIR) == 0)
618 * Read a tar file and extract or list the specified files within it.
619 * If the list is empty than all files are extracted or listed.
621 extern int readTarFile(int tarFd, int extractFlag, int listFlag,
622 int tostdoutFlag, int verboseFlag, char** extractList,
627 int skipNextHeaderFlag=FALSE;
631 /* Set the umask for this process so it doesn't
632 * screw up permission setting for us later. */
635 /* Read the tar file, and iterate over it one file at a time */
636 while ( (status = full_read(tarFd, (char*)&rawHeader, TAR_BLOCK_SIZE)) == TAR_BLOCK_SIZE ) {
638 /* Try to read the header */
639 if ( readTarHeader(&rawHeader, &header) == FALSE ) {
640 if ( *(header.name) == '\0' ) {
644 error_msg("Bad tar header, skipping\n");
648 if ( *(header.name) == '\0' )
650 header.tarFd = tarFd;
652 /* Skip funky extra GNU headers that precede long files */
653 if ( (header.type == GNULONGNAME) || (header.type == GNULONGLINK) ) {
654 skipNextHeaderFlag=TRUE;
655 if (tarExtractRegularFile(&header, FALSE, FALSE) == FALSE)
659 if ( skipNextHeaderFlag == TRUE ) {
660 skipNextHeaderFlag=FALSE;
661 error_msg(name_longer_than_foo, NAME_SIZE);
662 if (tarExtractRegularFile(&header, FALSE, FALSE) == FALSE)
667 #if defined BB_FEATURE_TAR_EXCLUDE
668 if (exclude_file(excludeList, header.name)) {
669 /* There are not the droids you're looking for, move along */
670 /* If it is a regular file, pretend to extract it with
671 * the extractFlag set to FALSE, so the junk in the tarball
672 * is properly skipped over */
673 if ( header.type==REGTYPE || header.type==REGTYPE0 ) {
674 if (tarExtractRegularFile(&header, FALSE, FALSE) == FALSE)
681 if (!extract_file(extractList, header.name)) {
682 /* There are not the droids you're looking for, move along */
683 /* If it is a regular file, pretend to extract it with
684 * the extractFlag set to FALSE, so the junk in the tarball
685 * is properly skipped over */
686 if ( header.type==REGTYPE || header.type==REGTYPE0 ) {
687 if (tarExtractRegularFile(&header, FALSE, FALSE) == FALSE)
693 if (listFlag == TRUE) {
694 /* Special treatment if the list (-t) flag is on */
695 if (verboseFlag == TRUE) {
698 struct tm *tm = localtime (&(header.mtime));
700 len=printf("%s ", mode_string(header.mode));
701 my_getpwuid(buf, header.uid);
703 len+=printf("%d", header.uid);
705 len+=printf("%s", buf);
706 my_getgrgid(buf, header.gid);
708 len+=printf("/%-d ", header.gid);
710 len+=printf("/%-s ", buf);
712 if (header.type==CHRTYPE || header.type==BLKTYPE) {
713 len1=snprintf(buf, sizeof(buf), "%ld,%-ld ",
714 header.devmajor, header.devminor);
716 len1=snprintf(buf, sizeof(buf), "%lu ", (long)header.size);
718 /* Jump through some hoops to make the columns match up */
719 for(;(len+len1)<31;len++)
723 /* Use ISO 8610 time format */
725 printf ("%04d-%02d-%02d %02d:%02d:%02d ",
726 tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday,
727 tm->tm_hour, tm->tm_min, tm->tm_sec);
730 printf("%s", header.name);
731 if (verboseFlag == TRUE) {
732 if (header.type==LNKTYPE) /* If this is a link, say so */
733 printf(" link to %s", header.linkname);
734 else if (header.type==SYMTYPE)
735 printf(" -> %s", header.linkname);
740 /* List contents if we are supposed to do that */
741 if (verboseFlag == TRUE && extractFlag == TRUE) {
742 /* Now the normal listing */
744 if (tostdoutFlag == TRUE) // If the archive goes to stdout, verbose to stderr
746 fprintf(vbFd, "%s\n", header.name);
749 /* Remove files if we would overwrite them */
750 if (extractFlag == TRUE && tostdoutFlag == FALSE)
753 /* If we got here, we can be certain we have a legitimate
754 * header to work with. So work with it. */
755 switch ( header.type ) {
758 /* If the name ends in a '/' then assume it is
759 * supposed to be a directory, and fall through */
760 if (header.name[strlen(header.name)-1] != '/') {
761 if (tarExtractRegularFile(&header, extractFlag, tostdoutFlag)==FALSE)
766 if (tarExtractDirectory( &header, extractFlag, tostdoutFlag)==FALSE)
770 if (tarExtractHardLink( &header, extractFlag, tostdoutFlag)==FALSE)
774 if (tarExtractSymLink( &header, extractFlag, tostdoutFlag)==FALSE)
780 if (tarExtractSpecial( &header, extractFlag, tostdoutFlag)==FALSE)
784 /* Handled earlier */
787 skipNextHeaderFlag=TRUE;
791 error_msg("Unknown file type '%c' in tar file\n", header.type);
798 /* Bummer - we read a partial header */
799 perror_msg("Error reading tar file");
802 else if (errorFlag==TRUE) {
803 error_msg( "Error exit delayed from previous errors\n");
808 /* Stuff to do when we are done */
811 if ( *(header.name) == '\0' ) {
813 error_msg( "Error exit delayed from previous errors\n");
821 #ifdef BB_FEATURE_TAR_CREATE
824 ** writeTarFile(), writeFileToTarball(), and writeTarHeader() are
825 ** the only functions that deal with the HardLinkInfo structure.
826 ** Even these functions use the xxxHardLinkInfo() functions.
828 typedef struct HardLinkInfo HardLinkInfo;
831 HardLinkInfo *next; /* Next entry in list */
832 dev_t dev; /* Device number */
833 ino_t ino; /* Inode number */
834 short linkCount; /* (Hard) Link Count */
835 char name[1]; /* Start of filename (must be last) */
838 /* Some info to be carried along when creating a new tarball */
841 char* fileName; /* File name of the tarball */
842 int tarFd; /* Open-for-write file descriptor
844 struct stat statBuf; /* Stat info for the tarball, letting
845 us know the inode and device that the
846 tarball lives, so we can avoid trying
847 to include the tarball into itself */
848 int verboseFlag; /* Whether to print extra stuff or not */
849 char** excludeList; /* List of files to not include */
850 HardLinkInfo *hlInfoHead; /* Hard Link Tracking Information */
851 HardLinkInfo *hlInfo; /* Hard Link Info for the current file */
853 typedef struct TarBallInfo TarBallInfo;
856 /* Might be faster (and bigger) if the dev/ino were stored in numeric order;) */
858 addHardLinkInfo (HardLinkInfo **hlInfoHeadPtr, dev_t dev, ino_t ino,
859 short linkCount, const char *name)
861 /* Note: hlInfoHeadPtr can never be NULL! */
862 HardLinkInfo *hlInfo;
864 hlInfo = (HardLinkInfo *)xmalloc(sizeof(HardLinkInfo)+strlen(name)+1);
866 hlInfo->next = *hlInfoHeadPtr;
867 *hlInfoHeadPtr = hlInfo;
870 hlInfo->linkCount = linkCount;
871 strcpy(hlInfo->name, name);
877 freeHardLinkInfo (HardLinkInfo **hlInfoHeadPtr)
879 HardLinkInfo *hlInfo = NULL;
880 HardLinkInfo *hlInfoNext = NULL;
883 hlInfo = *hlInfoHeadPtr;
885 hlInfoNext = hlInfo->next;
889 *hlInfoHeadPtr = NULL;
894 /* Might be faster (and bigger) if the dev/ino were stored in numeric order;) */
895 static HardLinkInfo *
896 findHardLinkInfo (HardLinkInfo *hlInfo, dev_t dev, ino_t ino)
899 if ((ino == hlInfo->ino) && (dev == hlInfo->dev))
901 hlInfo = hlInfo->next;
906 /* Put an octal string into the specified buffer.
907 * The number is zero and space padded and possibly null padded.
908 * Returns TRUE if successful. */
909 static int putOctal (char *cp, int len, long value)
913 char *tempString = tempBuffer;
915 /* Create a string of the specified length with an initial space,
916 * leading zeroes and the octal number, and a trailing null. */
917 sprintf (tempString, "%0*lo", len - 1, value);
919 /* If the string is too large, suppress the leading space. */
920 tempLength = strlen (tempString) + 1;
921 if (tempLength > len) {
926 /* If the string is still too large, suppress the trailing null. */
927 if (tempLength > len)
930 /* If the string is still too large, fail. */
931 if (tempLength > len)
934 /* Copy the string to the field. */
935 memcpy (cp, tempString, len);
940 /* Write out a tar header for the specified file/directory/whatever */
942 writeTarHeader(struct TarBallInfo *tbInfo, const char *header_name,
943 const char *real_name, struct stat *statbuf)
946 struct TarHeader header;
947 const unsigned char *cp = (const unsigned char *) &header;
948 ssize_t size = sizeof(struct TarHeader);
950 memset( &header, 0, size);
952 strncpy(header.name, header_name, sizeof(header.name));
954 putOctal(header.mode, sizeof(header.mode), statbuf->st_mode);
955 putOctal(header.uid, sizeof(header.uid), statbuf->st_uid);
956 putOctal(header.gid, sizeof(header.gid), statbuf->st_gid);
957 putOctal(header.size, sizeof(header.size), 0); /* Regular file size is handled later */
958 putOctal(header.mtime, sizeof(header.mtime), statbuf->st_mtime);
959 strncpy(header.magic, TAR_MAGIC TAR_VERSION,
960 TAR_MAGIC_LEN + TAR_VERSION_LEN );
962 /* Enter the user and group names (default to root if it fails) */
963 my_getpwuid(header.uname, statbuf->st_uid);
965 strcpy(header.uname, "root");
966 my_getgrgid(header.gname, statbuf->st_gid);
968 strcpy(header.uname, "root");
970 if (tbInfo->hlInfo) {
971 /* This is a hard link */
972 header.typeflag = LNKTYPE;
973 strncpy(header.linkname, tbInfo->hlInfo->name, sizeof(header.linkname));
974 } else if (S_ISLNK(statbuf->st_mode)) {
977 header.typeflag = SYMTYPE;
978 link_size = readlink(real_name, buffer, sizeof(buffer) - 1);
979 if ( link_size < 0) {
980 perror_msg("Error reading symlink '%s'", header.name);
983 buffer[link_size] = '\0';
984 strncpy(header.linkname, buffer, sizeof(header.linkname));
985 } else if (S_ISDIR(statbuf->st_mode)) {
986 header.typeflag = DIRTYPE;
987 strncat(header.name, "/", sizeof(header.name));
988 } else if (S_ISCHR(statbuf->st_mode)) {
989 header.typeflag = CHRTYPE;
990 putOctal(header.devmajor, sizeof(header.devmajor), MAJOR(statbuf->st_rdev));
991 putOctal(header.devminor, sizeof(header.devminor), MINOR(statbuf->st_rdev));
992 } else if (S_ISBLK(statbuf->st_mode)) {
993 header.typeflag = BLKTYPE;
994 putOctal(header.devmajor, sizeof(header.devmajor), MAJOR(statbuf->st_rdev));
995 putOctal(header.devminor, sizeof(header.devminor), MINOR(statbuf->st_rdev));
996 } else if (S_ISFIFO(statbuf->st_mode)) {
997 header.typeflag = FIFOTYPE;
998 } else if (S_ISREG(statbuf->st_mode)) {
999 header.typeflag = REGTYPE;
1000 putOctal(header.size, sizeof(header.size), statbuf->st_size);
1002 error_msg("%s: Unknown file type\n", real_name);
1006 /* Calculate and store the checksum (i.e. the sum of all of the bytes of
1007 * the header). The checksum field must be filled with blanks for the
1008 * calculation. The checksum field is formatted differently from the
1009 * other fields: it has [6] digits, a null, then a space -- rather than
1010 * digits, followed by a null like the other fields... */
1011 memset(header.chksum, ' ', sizeof(header.chksum));
1012 cp = (const unsigned char *) &header;
1015 putOctal(header.chksum, 7, chksum);
1017 /* Now write the header out to disk */
1018 if ((size=full_write(tbInfo->tarFd, (char*)&header, sizeof(struct TarHeader))) < 0) {
1019 error_msg(io_error, real_name, strerror(errno));
1022 /* Pad the header up to the tar block size */
1023 for (; size<TAR_BLOCK_SIZE; size++) {
1024 write(tbInfo->tarFd, "\0", 1);
1026 /* Now do the verbose thing (or not) */
1027 if (tbInfo->verboseFlag==TRUE) {
1028 FILE *vbFd = stdout;
1029 if (tbInfo->tarFd == fileno(stdout)) // If the archive goes to stdout, verbose to stderr
1031 fprintf(vbFd, "%s\n", header.name);
1038 static int writeFileToTarball(const char *fileName, struct stat *statbuf, void* userData)
1040 struct TarBallInfo *tbInfo = (struct TarBallInfo *)userData;
1041 const char *header_name;
1044 ** Check to see if we are dealing with a hard link.
1046 ** Treat the first occurance of a given dev/inode as a file while
1047 ** treating any additional occurances as hard links. This is done
1048 ** by adding the file information to the HardLinkInfo linked list.
1050 tbInfo->hlInfo = NULL;
1051 if (statbuf->st_nlink > 1) {
1052 tbInfo->hlInfo = findHardLinkInfo(tbInfo->hlInfoHead, statbuf->st_dev,
1054 if (tbInfo->hlInfo == NULL)
1055 addHardLinkInfo (&tbInfo->hlInfoHead, statbuf->st_dev,
1056 statbuf->st_ino, statbuf->st_nlink, fileName);
1059 /* It is against the rules to archive a socket */
1060 if (S_ISSOCK(statbuf->st_mode)) {
1061 error_msg("%s: socket ignored\n", fileName);
1065 /* It is a bad idea to store the archive we are in the process of creating,
1066 * so check the device and inode to be sure that this particular file isn't
1067 * the new tarball */
1068 if (tbInfo->statBuf.st_dev == statbuf->st_dev &&
1069 tbInfo->statBuf.st_ino == statbuf->st_ino) {
1070 error_msg("%s: file is the archive; skipping\n", fileName);
1074 header_name = fileName;
1075 while (header_name[0] == '/') {
1076 static int alreadyWarned=FALSE;
1077 if (alreadyWarned==FALSE) {
1078 error_msg("Removing leading '/' from member names\n");
1084 if (strlen(fileName) >= NAME_SIZE) {
1085 error_msg(name_longer_than_foo, NAME_SIZE);
1089 if (header_name[0] == '\0')
1092 #if defined BB_FEATURE_TAR_EXCLUDE
1093 if (exclude_file(tbInfo->excludeList, header_name)) {
1098 if (writeTarHeader(tbInfo, header_name, fileName, statbuf)==FALSE) {
1102 /* Now, if the file is a regular file, copy it out to the tarball */
1103 if ((tbInfo->hlInfo == NULL)
1104 && (S_ISREG(statbuf->st_mode))) {
1106 char buffer[BUFSIZ];
1107 ssize_t size=0, readSize=0;
1109 /* open the file we want to archive, and make sure all is well */
1110 if ((inputFileFd = open(fileName, O_RDONLY)) < 0) {
1111 error_msg("%s: Cannot open: %s\n", fileName, strerror(errno));
1115 /* write the file to the archive */
1116 while ( (size = full_read(inputFileFd, buffer, sizeof(buffer))) > 0 ) {
1117 if (full_write(tbInfo->tarFd, buffer, size) != size ) {
1118 /* Output file seems to have a problem */
1119 error_msg(io_error, fileName, strerror(errno));
1125 error_msg(io_error, fileName, strerror(errno));
1128 /* Pad the file up to the tar block size */
1129 for (; (readSize%TAR_BLOCK_SIZE) != 0; readSize++) {
1130 write(tbInfo->tarFd, "\0", 1);
1132 close( inputFileFd);
1138 static int writeTarFile(const char* tarName, int verboseFlag, char **argv,
1142 int errorFlag=FALSE;
1144 struct TarBallInfo tbInfo;
1145 tbInfo.verboseFlag = verboseFlag;
1146 tbInfo.hlInfoHead = NULL;
1148 /* Make sure there is at least one file to tar up. */
1150 error_msg_and_die("Cowardly refusing to create an empty archive\n");
1152 /* Open the tar file for writing. */
1153 if (!strcmp(tarName, "-"))
1154 tbInfo.tarFd = fileno(stdout);
1156 tbInfo.tarFd = open (tarName, O_WRONLY | O_CREAT | O_TRUNC, 0644);
1157 if (tbInfo.tarFd < 0) {
1158 perror_msg( "Error opening '%s'", tarName);
1159 freeHardLinkInfo(&tbInfo.hlInfoHead);
1162 tbInfo.excludeList=excludeList;
1163 /* Store the stat info for the tarball's file, so
1164 * can avoid including the tarball into itself.... */
1165 if (fstat(tbInfo.tarFd, &tbInfo.statBuf) < 0)
1166 error_msg_and_die(io_error, tarName, strerror(errno));
1168 /* Set the umask for this process so it doesn't
1169 * screw up permission setting for us later. */
1172 /* Read the directory/files and iterate over them one at a time */
1173 while (*argv != NULL) {
1174 if (recursive_action(*argv++, TRUE, FALSE, FALSE,
1175 writeFileToTarball, writeFileToTarball,
1176 (void*) &tbInfo) == FALSE) {
1180 /* Write two empty blocks to the end of the archive */
1181 for (size=0; size<(2*TAR_BLOCK_SIZE); size++) {
1182 write(tbInfo.tarFd, "\0", 1);
1185 /* To be pedantically correct, we would check if the tarball
1186 * is smaller than 20 tar blocks, and pad it if it was smaller,
1187 * but that isn't necessary for GNU tar interoperability, and
1188 * so is considered a waste of space */
1190 /* Hang up the tools, close up shop, head home */
1192 if (errorFlag == TRUE) {
1193 error_msg("Error exit delayed from previous errors\n");
1194 freeHardLinkInfo(&tbInfo.hlInfoHead);
1197 freeHardLinkInfo(&tbInfo.hlInfoHead);