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)
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 #define TAR_MAGIC_LEN 6
98 #define TAR_VERSION_LEN 2
99 #define 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");
173 unzip(tarFd, unzip_pipe[1]);
177 /* return fd of uncompressed data to parent process */
178 return(unzip_pipe[0]);
182 extern int tar_main(int argc, char **argv)
184 char** excludeList=NULL;
185 char** extractList=NULL;
186 const char *tarName="-";
187 #if defined BB_FEATURE_TAR_EXCLUDE
188 int excludeListSize=0;
189 char *excludeFileName ="-";
193 #if defined BB_FEATURE_TAR_GZIP
194 int unzipFlag = FALSE;
196 int listFlag = FALSE;
197 int extractFlag = FALSE;
198 int createFlag = FALSE;
199 int verboseFlag = FALSE;
200 int tostdoutFlag = FALSE;
208 while (*(++argv) && (**argv == '-' || firstOpt == TRUE)) {
211 while (stopIt==FALSE && **argv) {
212 switch (*((*argv)++)) {
214 if (extractFlag == TRUE || listFlag == TRUE)
219 if (listFlag == TRUE || createFlag == TRUE)
224 if (extractFlag == TRUE || createFlag == TRUE)
228 #ifdef BB_FEATURE_TAR_GZIP
241 error_msg_and_die( "Only one 'f' option allowed\n");
244 error_msg_and_die( "Option requires an argument: No file specified\n");
247 #if defined BB_FEATURE_TAR_EXCLUDE
249 if (strcmp(*argv, "xclude")==0) {
250 excludeList=xrealloc( excludeList,
251 sizeof(char *) * (excludeListSize+2));
252 excludeList[excludeListSize] = *(++argv);
253 if (excludeList[excludeListSize] == NULL)
254 error_msg_and_die( "Option requires an argument: No file specified\n");
255 /* Tack a NULL onto the end of the list */
256 excludeList[++excludeListSize] = NULL;
261 if (*excludeFileName != '-')
262 error_msg_and_die("Only one 'X' option allowed\n");
263 excludeFileName = *(++argv);
264 if (excludeFileName == NULL)
265 error_msg_and_die("Option requires an argument: No file specified\n");
266 fileList = fopen (excludeFileName, "r");
268 error_msg_and_die("Exclude file: file not found\n");
269 while (fgets(file, sizeof(file), fileList) != NULL) {
270 excludeList = xrealloc(excludeList,
271 sizeof(char *) * (excludeListSize+2));
272 if (file[strlen(file)-1] == '\n')
273 file[strlen(file)-1] = '\0';
274 excludeList[excludeListSize] = xstrdup(file);
275 /* Tack a NULL onto the end of the list */
276 excludeList[++excludeListSize] = NULL;
291 * Do the correct type of action supplying the rest of the
292 * command line arguments as the list of files to process.
294 if (createFlag == TRUE) {
295 #ifndef BB_FEATURE_TAR_CREATE
296 error_msg_and_die( "This version of tar was not compiled with tar creation support.\n");
298 #ifdef BB_FEATURE_TAR_GZIP
300 error_msg_and_die("Creation of compressed not internally support by tar, pipe to busybox gunzip\n");
302 status = writeTarFile(tarName, verboseFlag, argv, excludeList);
305 if (listFlag == TRUE || extractFlag == TRUE) {
309 /* Open the tar file for reading. */
310 if (!strcmp(tarName, "-"))
311 tarFd = fileno(stdin);
313 tarFd = open(tarName, O_RDONLY);
315 perror_msg_and_die("Error opening '%s'", tarName);
317 #ifdef BB_FEATURE_TAR_GZIP
318 /* unzip tarFd in a seperate process */
319 if (unzipFlag == TRUE)
320 tarFd = tar_unzip_init(tarFd);
322 status = readTarFile(tarFd, extractFlag, listFlag, tostdoutFlag,
323 verboseFlag, extractList, excludeList);
332 error_msg_and_die( "Exactly one of 'c', 'x' or 't' must be specified\n");
336 fixUpPermissions(TarInfo *header)
339 /* Now set permissions etc for the new file */
340 chown(header->name, header->uid, header->gid);
341 chmod(header->name, header->mode);
344 t.modtime = header->mtime;
345 utime(header->name, &t);
349 tarExtractRegularFile(TarInfo *header, int extractFlag, int tostdoutFlag)
353 size_t actualWriteSz;
355 size_t size = header->size;
356 int outFd=fileno(stdout);
358 /* Open the file to be written, if a file is supposed to be written */
359 if (extractFlag==TRUE && tostdoutFlag==FALSE) {
360 /* Create the path to the file, just in case it isn't there...
361 * This should not screw up path permissions or anything. */
362 create_path(header->name, 0777);
363 if ((outFd=open(header->name, O_CREAT|O_TRUNC|O_WRONLY,
364 header->mode & ~S_IFMT)) < 0) {
365 error_msg(io_error, header->name, strerror(errno));
370 /* Write out the file, if we are supposed to be doing that */
373 if ( size > sizeof(buffer) )
374 writeSize = readSize = sizeof(buffer);
376 int mod = size % 512;
378 readSize = size + (512 - mod);
383 if ( (readSize = full_read(header->tarFd, buffer, readSize)) <= 0 ) {
384 /* Tarball seems to have a problem */
385 error_msg("Unexpected EOF in archive\n");
388 if ( readSize < writeSize )
389 writeSize = readSize;
391 /* Write out the file, if we are supposed to be doing that */
392 if (extractFlag==TRUE) {
394 if ((actualWriteSz=full_write(outFd, buffer, writeSize)) != writeSize ) {
395 /* Output file seems to have a problem */
396 error_msg(io_error, header->name, strerror(errno));
400 actualWriteSz=writeSize;
403 size -= actualWriteSz;
406 /* Now we are done writing the file out, so try
407 * and fix up the permissions and whatnot */
408 if (extractFlag==TRUE && tostdoutFlag==FALSE) {
410 fixUpPermissions(header);
416 tarExtractDirectory(TarInfo *header, int extractFlag, int tostdoutFlag)
419 if (extractFlag==FALSE || tostdoutFlag==TRUE)
422 if (create_path(header->name, header->mode) != TRUE) {
423 perror_msg("%s: Cannot mkdir", header->name);
426 /* make the final component, just in case it was
427 * omitted by create_path() (which will skip the
428 * directory if it doesn't have a terminating '/') */
429 if (mkdir(header->name, header->mode) < 0 && errno != EEXIST) {
430 perror_msg("%s", header->name);
434 fixUpPermissions(header);
439 tarExtractHardLink(TarInfo *header, int extractFlag, int tostdoutFlag)
441 if (extractFlag==FALSE || tostdoutFlag==TRUE)
444 if (link(header->linkname, header->name) < 0) {
445 perror_msg("%s: Cannot create hard link to '%s'", header->name,
450 /* Now set permissions etc for the new directory */
451 fixUpPermissions(header);
456 tarExtractSymLink(TarInfo *header, int extractFlag, int tostdoutFlag)
458 if (extractFlag==FALSE || tostdoutFlag==TRUE)
462 if (symlink(header->linkname, header->name) < 0) {
463 perror_msg("%s: Cannot create symlink to '%s'", header->name,
467 /* Try to change ownership of the symlink.
468 * If libs doesn't support that, don't bother.
469 * Changing the pointed-to-file is the Wrong Thing(tm).
471 #if (__GLIBC__ >= 2) && (__GLIBC_MINOR__ >= 1)
472 lchown(header->name, header->uid, header->gid);
475 /* Do not change permissions or date on symlink,
476 * since it changes the pointed to file instead. duh. */
478 error_msg("%s: Cannot create symlink to '%s': %s\n",
479 header->name, header->linkname,
480 "symlinks not supported");
486 tarExtractSpecial(TarInfo *header, int extractFlag, int tostdoutFlag)
488 if (extractFlag==FALSE || tostdoutFlag==TRUE)
491 if (S_ISCHR(header->mode) || S_ISBLK(header->mode) || S_ISSOCK(header->mode)) {
492 if (mknod(header->name, header->mode, makedev(header->devmajor, header->devminor)) < 0) {
493 perror_msg("%s: Cannot mknod", header->name);
496 } else if (S_ISFIFO(header->mode)) {
497 if (mkfifo(header->name, header->mode) < 0) {
498 perror_msg("%s: Cannot mkfifo", header->name);
503 /* Now set permissions etc for the new directory */
504 fixUpPermissions(header);
508 /* Read an octal value in a field of the specified width, with optional
509 * spaces on both sides of the number and with an optional null character
510 * at the end. Returns -1 on an illegal format. */
511 static long getOctal(const char *cp, int size)
515 for(;(size > 0) && (*cp == ' '); cp++, size--);
516 if ((size == 0) || !is_octal(*cp))
518 for(; (size > 0) && is_octal(*cp); size--) {
519 val = val * 8 + *cp++ - '0';
521 for (;(size > 0) && (*cp == ' '); cp++, size--);
522 if ((size > 0) && *cp)
528 /* Parse the tar header and fill in the nice struct with the details */
530 readTarHeader(struct TarHeader *rawHeader, struct TarInfo *header)
534 unsigned char *s = (unsigned char *)rawHeader;
536 header->name = rawHeader->name;
537 /* Check for and relativify any absolute paths */
538 if ( *(header->name) == '/' ) {
539 static int alreadyWarned=FALSE;
541 while (*(header->name) == '/')
544 if (alreadyWarned == FALSE) {
545 error_msg("Removing leading '/' from member names\n");
546 alreadyWarned = TRUE;
550 header->mode = getOctal(rawHeader->mode, sizeof(rawHeader->mode));
551 header->uid = getOctal(rawHeader->uid, sizeof(rawHeader->uid));
552 header->gid = getOctal(rawHeader->gid, sizeof(rawHeader->gid));
553 header->size = getOctal(rawHeader->size, sizeof(rawHeader->size));
554 header->mtime = getOctal(rawHeader->mtime, sizeof(rawHeader->mtime));
555 chksum = getOctal(rawHeader->chksum, sizeof(rawHeader->chksum));
556 header->type = rawHeader->typeflag;
557 header->linkname = rawHeader->linkname;
558 header->devmajor = getOctal(rawHeader->devmajor, sizeof(rawHeader->devmajor));
559 header->devminor = getOctal(rawHeader->devminor, sizeof(rawHeader->devminor));
561 /* Check the checksum */
562 for (i = sizeof(*rawHeader); i-- != 0;) {
565 /* Remove the effects of the checksum field (replace
566 * with blanks for the purposes of the checksum) */
567 s = rawHeader->chksum;
568 for (i = sizeof(rawHeader->chksum) ; i-- != 0;) {
571 sum += ' ' * sizeof(rawHeader->chksum);
577 int exclude_file(char **excluded_files, const char *file)
581 if (excluded_files == NULL)
584 for (i = 0; excluded_files[i] != NULL; i++) {
585 if (excluded_files[i][0] == '/') {
586 if (fnmatch(excluded_files[i], file,
587 FNM_PATHNAME | FNM_LEADING_DIR) == 0)
592 for (p = file; p[0] != '\0'; p++) {
593 if ((p == file || p[-1] == '/') && p[0] != '/' &&
594 fnmatch(excluded_files[i], p,
595 FNM_PATHNAME | FNM_LEADING_DIR) == 0)
605 * Read a tar file and extract or list the specified files within it.
606 * If the list is empty than all files are extracted or listed.
608 extern int readTarFile(int tarFd, int extractFlag, int listFlag,
609 int tostdoutFlag, int verboseFlag, char** extractList,
614 int skipNextHeaderFlag=FALSE;
619 /* Set the umask for this process so it doesn't
620 * screw up permission setting for us later. */
623 /* Read the tar file, and iterate over it one file at a time */
624 while ( (status = full_read(tarFd, (char*)&rawHeader, TAR_BLOCK_SIZE)) == TAR_BLOCK_SIZE ) {
626 /* Try to read the header */
627 if ( readTarHeader(&rawHeader, &header) == FALSE ) {
628 if ( *(header.name) == '\0' ) {
632 error_msg("Bad tar header, skipping\n");
636 if ( *(header.name) == '\0' )
638 header.tarFd = tarFd;
640 /* Skip funky extra GNU headers that precede long files */
641 if ( (header.type == GNULONGNAME) || (header.type == GNULONGLINK) ) {
642 skipNextHeaderFlag=TRUE;
643 if (tarExtractRegularFile(&header, FALSE, FALSE) == FALSE)
647 if ( skipNextHeaderFlag == TRUE ) {
648 skipNextHeaderFlag=FALSE;
649 error_msg(name_longer_than_foo, NAME_SIZE);
650 if (tarExtractRegularFile(&header, FALSE, FALSE) == FALSE)
655 #if defined BB_FEATURE_TAR_EXCLUDE
656 if (exclude_file(excludeList, header.name)) {
657 /* There are not the droids you're looking for, move along */
658 /* If it is a regular file, pretend to extract it with
659 * the extractFlag set to FALSE, so the junk in the tarball
660 * is properly skipped over */
661 if ( header.type==REGTYPE || header.type==REGTYPE0 ) {
662 if (tarExtractRegularFile(&header, FALSE, FALSE) == FALSE)
669 if (extractList != NULL) {
671 for (tmpList = extractList; *tmpList != NULL; tmpList++) {
672 if (strncmp( *tmpList, header.name, strlen(*tmpList))==0 || (
673 header.name[strlen(header.name)-1]=='/'
674 && strncmp( *tmpList, header.name,
675 MIN(strlen(header.name)-1, strlen(*tmpList)))==0)) {
676 /* If it is a regular file, pretend to extract it with
677 * the extractFlag set to FALSE, so the junk in the tarball
678 * is properly skipped over */
680 memmove(extractList+1, extractList,
681 sizeof(*extractList)*(tmpList-extractList));
686 /* There are not the droids you're looking for, move along */
687 if (skipFlag == TRUE) {
688 if ( header.type==REGTYPE || header.type==REGTYPE0 )
689 if (tarExtractRegularFile(&header, FALSE, FALSE) == FALSE)
695 if (listFlag == TRUE) {
696 /* Special treatment if the list (-t) flag is on */
697 if (verboseFlag == TRUE) {
700 struct tm *tm = localtime (&(header.mtime));
702 len=printf("%s ", mode_string(header.mode));
703 my_getpwuid(buf, header.uid);
705 len+=printf("%d", header.uid);
707 len+=printf("%s", buf);
708 my_getgrgid(buf, header.gid);
710 len+=printf("/%-d ", header.gid);
712 len+=printf("/%-s ", buf);
714 if (header.type==CHRTYPE || header.type==BLKTYPE) {
715 len1=snprintf(buf, sizeof(buf), "%ld,%-ld ",
716 header.devmajor, header.devminor);
718 len1=snprintf(buf, sizeof(buf), "%lu ", (long)header.size);
720 /* Jump through some hoops to make the columns match up */
721 for(;(len+len1)<31;len++)
725 /* Use ISO 8610 time format */
727 printf ("%04d-%02d-%02d %02d:%02d:%02d ",
728 tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday,
729 tm->tm_hour, tm->tm_min, tm->tm_sec);
732 printf("%s", header.name);
733 if (verboseFlag == TRUE) {
734 if (header.type==LNKTYPE) /* If this is a link, say so */
735 printf(" link to %s", header.linkname);
736 else if (header.type==SYMTYPE)
737 printf(" -> %s", header.linkname);
742 /* List contents if we are supposed to do that */
743 if (verboseFlag == TRUE && extractFlag == TRUE) {
744 /* Now the normal listing */
746 if (tostdoutFlag == TRUE) // If the archive goes to stdout, verbose to stderr
748 fprintf(vbFd, "%s\n", header.name);
751 /* Remove files if we would overwrite them */
752 if (extractFlag == TRUE && tostdoutFlag == FALSE)
755 /* If we got here, we can be certain we have a legitimate
756 * header to work with. So work with it. */
757 switch ( header.type ) {
760 /* If the name ends in a '/' then assume it is
761 * supposed to be a directory, and fall through */
762 if (header.name[strlen(header.name)-1] != '/') {
763 if (tarExtractRegularFile(&header, extractFlag, tostdoutFlag)==FALSE)
768 if (tarExtractDirectory( &header, extractFlag, tostdoutFlag)==FALSE)
772 if (tarExtractHardLink( &header, extractFlag, tostdoutFlag)==FALSE)
776 if (tarExtractSymLink( &header, extractFlag, tostdoutFlag)==FALSE)
782 if (tarExtractSpecial( &header, extractFlag, tostdoutFlag)==FALSE)
786 /* Handled earlier */
789 skipNextHeaderFlag=TRUE;
793 error_msg("Unknown file type '%c' in tar file\n", header.type);
800 /* Bummer - we read a partial header */
801 perror_msg("Error reading tar file");
804 else if (errorFlag==TRUE) {
805 error_msg( "Error exit delayed from previous errors\n");
810 /* Stuff to do when we are done */
813 if (extractList != NULL) {
814 for (; *extractList != NULL; extractList++) {
815 error_msg("%s: Not found in archive\n", *extractList);
819 if ( *(header.name) == '\0' ) {
821 error_msg( "Error exit delayed from previous errors\n");
829 #ifdef BB_FEATURE_TAR_CREATE
832 ** writeTarFile(), writeFileToTarball(), and writeTarHeader() are
833 ** the only functions that deal with the HardLinkInfo structure.
834 ** Even these functions use the xxxHardLinkInfo() functions.
836 typedef struct HardLinkInfo HardLinkInfo;
839 HardLinkInfo *next; /* Next entry in list */
840 dev_t dev; /* Device number */
841 ino_t ino; /* Inode number */
842 short linkCount; /* (Hard) Link Count */
843 char name[1]; /* Start of filename (must be last) */
846 /* Some info to be carried along when creating a new tarball */
849 char* fileName; /* File name of the tarball */
850 int tarFd; /* Open-for-write file descriptor
852 struct stat statBuf; /* Stat info for the tarball, letting
853 us know the inode and device that the
854 tarball lives, so we can avoid trying
855 to include the tarball into itself */
856 int verboseFlag; /* Whether to print extra stuff or not */
857 char** excludeList; /* List of files to not include */
858 HardLinkInfo *hlInfoHead; /* Hard Link Tracking Information */
859 HardLinkInfo *hlInfo; /* Hard Link Info for the current file */
861 typedef struct TarBallInfo TarBallInfo;
864 /* Might be faster (and bigger) if the dev/ino were stored in numeric order;) */
866 addHardLinkInfo (HardLinkInfo **hlInfoHeadPtr, dev_t dev, ino_t ino,
867 short linkCount, const char *name)
869 /* Note: hlInfoHeadPtr can never be NULL! */
870 HardLinkInfo *hlInfo;
872 hlInfo = (HardLinkInfo *)xmalloc(sizeof(HardLinkInfo)+strlen(name)+1);
874 hlInfo->next = *hlInfoHeadPtr;
875 *hlInfoHeadPtr = hlInfo;
878 hlInfo->linkCount = linkCount;
879 strcpy(hlInfo->name, name);
885 freeHardLinkInfo (HardLinkInfo **hlInfoHeadPtr)
887 HardLinkInfo *hlInfo = NULL;
888 HardLinkInfo *hlInfoNext = NULL;
891 hlInfo = *hlInfoHeadPtr;
893 hlInfoNext = hlInfo->next;
897 *hlInfoHeadPtr = NULL;
902 /* Might be faster (and bigger) if the dev/ino were stored in numeric order;) */
903 static HardLinkInfo *
904 findHardLinkInfo (HardLinkInfo *hlInfo, dev_t dev, ino_t ino)
907 if ((ino == hlInfo->ino) && (dev == hlInfo->dev))
909 hlInfo = hlInfo->next;
914 /* Put an octal string into the specified buffer.
915 * The number is zero and space padded and possibly null padded.
916 * Returns TRUE if successful. */
917 static int putOctal (char *cp, int len, long value)
921 char *tempString = tempBuffer;
923 /* Create a string of the specified length with an initial space,
924 * leading zeroes and the octal number, and a trailing null. */
925 sprintf (tempString, "%0*lo", len - 1, value);
927 /* If the string is too large, suppress the leading space. */
928 tempLength = strlen (tempString) + 1;
929 if (tempLength > len) {
934 /* If the string is still too large, suppress the trailing null. */
935 if (tempLength > len)
938 /* If the string is still too large, fail. */
939 if (tempLength > len)
942 /* Copy the string to the field. */
943 memcpy (cp, tempString, len);
948 /* Write out a tar header for the specified file/directory/whatever */
950 writeTarHeader(struct TarBallInfo *tbInfo, const char *header_name,
951 const char *real_name, struct stat *statbuf)
954 struct TarHeader header;
955 const unsigned char *cp = (const unsigned char *) &header;
956 ssize_t size = sizeof(struct TarHeader);
958 memset( &header, 0, size);
960 strncpy(header.name, header_name, sizeof(header.name));
962 putOctal(header.mode, sizeof(header.mode), statbuf->st_mode);
963 putOctal(header.uid, sizeof(header.uid), statbuf->st_uid);
964 putOctal(header.gid, sizeof(header.gid), statbuf->st_gid);
965 putOctal(header.size, sizeof(header.size), 0); /* Regular file size is handled later */
966 putOctal(header.mtime, sizeof(header.mtime), statbuf->st_mtime);
967 strncpy(header.magic, TAR_MAGIC TAR_VERSION,
968 TAR_MAGIC_LEN + TAR_VERSION_LEN );
970 /* Enter the user and group names (default to root if it fails) */
971 my_getpwuid(header.uname, statbuf->st_uid);
973 strcpy(header.uname, "root");
974 my_getgrgid(header.gname, statbuf->st_gid);
976 strcpy(header.uname, "root");
978 if (tbInfo->hlInfo) {
979 /* This is a hard link */
980 header.typeflag = LNKTYPE;
981 strncpy(header.linkname, tbInfo->hlInfo->name, sizeof(header.linkname));
982 } else if (S_ISLNK(statbuf->st_mode)) {
985 header.typeflag = SYMTYPE;
986 link_size = readlink(real_name, buffer, sizeof(buffer) - 1);
987 if ( link_size < 0) {
988 perror_msg("Error reading symlink '%s'", header.name);
991 buffer[link_size] = '\0';
992 strncpy(header.linkname, buffer, sizeof(header.linkname));
993 } else if (S_ISDIR(statbuf->st_mode)) {
994 header.typeflag = DIRTYPE;
995 strncat(header.name, "/", sizeof(header.name));
996 } else if (S_ISCHR(statbuf->st_mode)) {
997 header.typeflag = CHRTYPE;
998 putOctal(header.devmajor, sizeof(header.devmajor), MAJOR(statbuf->st_rdev));
999 putOctal(header.devminor, sizeof(header.devminor), MINOR(statbuf->st_rdev));
1000 } else if (S_ISBLK(statbuf->st_mode)) {
1001 header.typeflag = BLKTYPE;
1002 putOctal(header.devmajor, sizeof(header.devmajor), MAJOR(statbuf->st_rdev));
1003 putOctal(header.devminor, sizeof(header.devminor), MINOR(statbuf->st_rdev));
1004 } else if (S_ISFIFO(statbuf->st_mode)) {
1005 header.typeflag = FIFOTYPE;
1006 } else if (S_ISREG(statbuf->st_mode)) {
1007 header.typeflag = REGTYPE;
1008 putOctal(header.size, sizeof(header.size), statbuf->st_size);
1010 error_msg("%s: Unknown file type\n", real_name);
1014 /* Calculate and store the checksum (i.e. the sum of all of the bytes of
1015 * the header). The checksum field must be filled with blanks for the
1016 * calculation. The checksum field is formatted differently from the
1017 * other fields: it has [6] digits, a null, then a space -- rather than
1018 * digits, followed by a null like the other fields... */
1019 memset(header.chksum, ' ', sizeof(header.chksum));
1020 cp = (const unsigned char *) &header;
1023 putOctal(header.chksum, 7, chksum);
1025 /* Now write the header out to disk */
1026 if ((size=full_write(tbInfo->tarFd, (char*)&header, sizeof(struct TarHeader))) < 0) {
1027 error_msg(io_error, real_name, strerror(errno));
1030 /* Pad the header up to the tar block size */
1031 for (; size<TAR_BLOCK_SIZE; size++) {
1032 write(tbInfo->tarFd, "\0", 1);
1034 /* Now do the verbose thing (or not) */
1035 if (tbInfo->verboseFlag==TRUE) {
1036 FILE *vbFd = stdout;
1037 if (tbInfo->tarFd == fileno(stdout)) // If the archive goes to stdout, verbose to stderr
1039 fprintf(vbFd, "%s\n", header.name);
1046 static int writeFileToTarball(const char *fileName, struct stat *statbuf, void* userData)
1048 struct TarBallInfo *tbInfo = (struct TarBallInfo *)userData;
1049 const char *header_name;
1052 ** Check to see if we are dealing with a hard link.
1054 ** Treat the first occurance of a given dev/inode as a file while
1055 ** treating any additional occurances as hard links. This is done
1056 ** by adding the file information to the HardLinkInfo linked list.
1058 tbInfo->hlInfo = NULL;
1059 if (statbuf->st_nlink > 1) {
1060 tbInfo->hlInfo = findHardLinkInfo(tbInfo->hlInfoHead, statbuf->st_dev,
1062 if (tbInfo->hlInfo == NULL)
1063 addHardLinkInfo (&tbInfo->hlInfoHead, statbuf->st_dev,
1064 statbuf->st_ino, statbuf->st_nlink, fileName);
1067 /* It is against the rules to archive a socket */
1068 if (S_ISSOCK(statbuf->st_mode)) {
1069 error_msg("%s: socket ignored\n", fileName);
1073 /* It is a bad idea to store the archive we are in the process of creating,
1074 * so check the device and inode to be sure that this particular file isn't
1075 * the new tarball */
1076 if (tbInfo->statBuf.st_dev == statbuf->st_dev &&
1077 tbInfo->statBuf.st_ino == statbuf->st_ino) {
1078 error_msg("%s: file is the archive; skipping\n", fileName);
1082 header_name = fileName;
1083 while (header_name[0] == '/') {
1084 static int alreadyWarned=FALSE;
1085 if (alreadyWarned==FALSE) {
1086 error_msg("Removing leading '/' from member names\n");
1092 if (strlen(fileName) >= NAME_SIZE) {
1093 error_msg(name_longer_than_foo, NAME_SIZE);
1097 if (header_name[0] == '\0')
1100 #if defined BB_FEATURE_TAR_EXCLUDE
1101 if (exclude_file(tbInfo->excludeList, header_name)) {
1106 if (writeTarHeader(tbInfo, header_name, fileName, statbuf)==FALSE) {
1110 /* Now, if the file is a regular file, copy it out to the tarball */
1111 if ((tbInfo->hlInfo == NULL)
1112 && (S_ISREG(statbuf->st_mode))) {
1114 char buffer[BUFSIZ];
1115 ssize_t size=0, readSize=0;
1117 /* open the file we want to archive, and make sure all is well */
1118 if ((inputFileFd = open(fileName, O_RDONLY)) < 0) {
1119 error_msg("%s: Cannot open: %s\n", fileName, strerror(errno));
1123 /* write the file to the archive */
1124 while ( (size = full_read(inputFileFd, buffer, sizeof(buffer))) > 0 ) {
1125 if (full_write(tbInfo->tarFd, buffer, size) != size ) {
1126 /* Output file seems to have a problem */
1127 error_msg(io_error, fileName, strerror(errno));
1133 error_msg(io_error, fileName, strerror(errno));
1136 /* Pad the file up to the tar block size */
1137 for (; (readSize%TAR_BLOCK_SIZE) != 0; readSize++) {
1138 write(tbInfo->tarFd, "\0", 1);
1140 close( inputFileFd);
1146 static int writeTarFile(const char* tarName, int verboseFlag, char **argv,
1150 int errorFlag=FALSE;
1152 struct TarBallInfo tbInfo;
1153 tbInfo.verboseFlag = verboseFlag;
1154 tbInfo.hlInfoHead = NULL;
1156 /* Make sure there is at least one file to tar up. */
1158 error_msg_and_die("Cowardly refusing to create an empty archive\n");
1160 /* Open the tar file for writing. */
1161 if (!strcmp(tarName, "-"))
1162 tbInfo.tarFd = fileno(stdout);
1164 tbInfo.tarFd = open (tarName, O_WRONLY | O_CREAT | O_TRUNC, 0644);
1165 if (tbInfo.tarFd < 0) {
1166 perror_msg( "Error opening '%s'", tarName);
1167 freeHardLinkInfo(&tbInfo.hlInfoHead);
1170 tbInfo.excludeList=excludeList;
1171 /* Store the stat info for the tarball's file, so
1172 * can avoid including the tarball into itself.... */
1173 if (fstat(tbInfo.tarFd, &tbInfo.statBuf) < 0)
1174 error_msg_and_die(io_error, tarName, strerror(errno));
1176 /* Set the umask for this process so it doesn't
1177 * screw up permission setting for us later. */
1180 /* Read the directory/files and iterate over them one at a time */
1181 while (*argv != NULL) {
1182 if (recursive_action(*argv++, TRUE, FALSE, FALSE,
1183 writeFileToTarball, writeFileToTarball,
1184 (void*) &tbInfo) == FALSE) {
1188 /* Write two empty blocks to the end of the archive */
1189 for (size=0; size<(2*TAR_BLOCK_SIZE); size++) {
1190 write(tbInfo.tarFd, "\0", 1);
1193 /* To be pedantically correct, we would check if the tarball
1194 * is smaller than 20 tar blocks, and pad it if it was smaller,
1195 * but that isn't necessary for GNU tar interoperability, and
1196 * so is considered a waste of space */
1198 /* Hang up the tools, close up shop, head home */
1200 if (errorFlag == TRUE) {
1201 error_msg("Error exit delayed from previous errors\n");
1202 freeHardLinkInfo(&tbInfo.hlInfoHead);
1205 freeHardLinkInfo(&tbInfo.hlInfoHead);