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>
55 /* Tar file constants */
57 #define MAJOR(dev) (((dev)>>8)&0xff)
58 #define MINOR(dev) ((dev)&0xff)
61 enum { NAME_SIZE = 100 }; /* because gcc won't let me use 'static const int' */
63 /* POSIX tar Header Block, from POSIX 1003.1-1990 */
67 char name[NAME_SIZE]; /* 0-99 */
68 char mode[8]; /* 100-107 */
69 char uid[8]; /* 108-115 */
70 char gid[8]; /* 116-123 */
71 char size[12]; /* 124-135 */
72 char mtime[12]; /* 136-147 */
73 char chksum[8]; /* 148-155 */
74 char typeflag; /* 156-156 */
75 char linkname[NAME_SIZE]; /* 157-256 */
76 char magic[6]; /* 257-262 */
77 char version[2]; /* 263-264 */
78 char uname[32]; /* 265-296 */
79 char gname[32]; /* 297-328 */
80 char devmajor[8]; /* 329-336 */
81 char devminor[8]; /* 337-344 */
82 char prefix[155]; /* 345-499 */
83 char padding[12]; /* 500-512 (pad to exactly the TAR_BLOCK_SIZE) */
85 typedef struct TarHeader TarHeader;
88 /* A few useful constants */
89 #define TAR_MAGIC "ustar" /* ustar and a null */
90 #define TAR_VERSION " " /* Be compatable with GNU tar format */
91 static const int TAR_MAGIC_LEN = 6;
92 static const int TAR_VERSION_LEN = 2;
93 static const int TAR_BLOCK_SIZE = 512;
95 /* A nice enum with all the possible tar file content types */
98 REGTYPE = '0', /* regular file */
99 REGTYPE0 = '\0', /* regular file (ancient bug compat)*/
100 LNKTYPE = '1', /* hard link */
101 SYMTYPE = '2', /* symbolic link */
102 CHRTYPE = '3', /* character special */
103 BLKTYPE = '4', /* block special */
104 DIRTYPE = '5', /* directory */
105 FIFOTYPE = '6', /* FIFO special */
106 CONTTYPE = '7', /* reserved */
107 GNULONGLINK = 'K', /* GNU long (>100 chars) link name */
108 GNULONGNAME = 'L', /* GNU long (>100 chars) file name */
110 typedef enum TarFileType TarFileType;
112 /* This struct ignores magic, non-numeric user name,
113 * non-numeric group name, and the checksum, since
114 * these are all ignored by BusyBox tar. */
117 int tarFd; /* An open file descriptor for reading from the tarball */
118 char * name; /* File name */
119 mode_t mode; /* Unix mode, including device bits. */
120 uid_t uid; /* Numeric UID */
121 gid_t gid; /* Numeric GID */
122 size_t size; /* Size of file */
123 time_t mtime; /* Last-modified time */
124 enum TarFileType type; /* Regular, directory, link, etc */
125 char * linkname; /* Name for symbolic and hard links */
126 long devmajor; /* Major number for special device */
127 long devminor; /* Minor number for special device */
129 typedef struct TarInfo TarInfo;
131 /* Local procedures to restore files from a tar file. */
132 static int readTarFile(int tarFd, int extractFlag, int listFlag,
133 int tostdoutFlag, int verboseFlag, char** extractList,
136 #ifdef BB_FEATURE_TAR_CREATE
137 /* Local procedures to save files into a tar file. */
138 static int writeTarFile(const char* tarName, int verboseFlag, char **argv,
142 #if defined BB_FEATURE_TAR_EXCLUDE
143 static struct option longopts[] = {
144 { "exclude", 1, NULL, 'e' },
149 extern int tar_main(int argc, char **argv)
151 char** excludeList=NULL;
152 char** extractList=NULL;
153 const char *tarName="-";
154 #if defined BB_FEATURE_TAR_EXCLUDE
155 int excludeListSize=0;
159 #if defined BB_FEATURE_TAR_GZIP
160 FILE *comp_file = NULL;
161 int unzipFlag = FALSE;
163 int listFlag = FALSE;
164 int extractFlag = FALSE;
165 int createFlag = FALSE;
166 int verboseFlag = FALSE;
167 int tostdoutFlag = FALSE;
175 if (argv[1][0] != '-') {
176 char *tmp = xmalloc(strlen(argv[1]) + 2);
178 strcpy(tmp + 1, argv[1]);
183 #ifndef BB_FEATURE_TAR_EXCLUDE
184 (opt = getopt(argc, argv, "cxtzvOf:"))
186 (opt = getopt_long(argc, argv, "cxtzvOf:X:", longopts, NULL))
191 if (extractFlag == TRUE || listFlag == TRUE)
196 if (listFlag == TRUE || createFlag == TRUE)
201 if (extractFlag == TRUE || createFlag == TRUE)
205 #ifdef BB_FEATURE_TAR_GZIP
218 error_msg_and_die( "Only one 'f' option allowed");
221 #if defined BB_FEATURE_TAR_EXCLUDE
223 excludeList=xrealloc( excludeList,
224 sizeof(char *) * (excludeListSize+2));
225 excludeList[excludeListSize] = optarg;
226 /* Tack a NULL onto the end of the list */
227 excludeList[++excludeListSize] = NULL;
229 fileList = xfopen(optarg, "r");
230 while (fgets(file, sizeof(file), fileList) != NULL) {
231 excludeList = xrealloc(excludeList,
232 sizeof(char *) * (excludeListSize+2));
234 excludeList[excludeListSize] = xstrdup(file);
235 /* Tack a NULL onto the end of the list */
236 excludeList[++excludeListSize] = NULL;
247 * Do the correct type of action supplying the rest of the
248 * command line arguments as the list of files to process.
250 if (createFlag == TRUE) {
251 #ifndef BB_FEATURE_TAR_CREATE
252 error_msg_and_die( "This version of tar was not compiled with tar creation support.");
254 #ifdef BB_FEATURE_TAR_GZIP
256 error_msg_and_die("Creation of compressed not internally support by tar, pipe to busybox gunzip");
258 status = writeTarFile(tarName, verboseFlag, argv + optind, excludeList);
261 if (listFlag == TRUE || extractFlag == TRUE) {
264 extractList = argv + optind;
265 /* Open the tar file for reading. */
266 if (!strcmp(tarName, "-"))
267 tarFd = fileno(stdin);
269 tarFd = open(tarName, O_RDONLY);
271 perror_msg_and_die("Error opening '%s'", tarName);
273 #ifdef BB_FEATURE_TAR_GZIP
274 /* unzip tarFd in a seperate process */
275 if (unzipFlag == TRUE) {
276 comp_file = fdopen(tarFd, "r");
277 if ((tarFd = gz_open(comp_file, &pid)) == EXIT_FAILURE) {
278 error_msg_and_die("Couldnt unzip file");
282 status = readTarFile(tarFd, extractFlag, listFlag, tostdoutFlag,
283 verboseFlag, extractList, excludeList);
285 #ifdef BB_FEATURE_TAR_GZIP
286 if (unzipFlag == TRUE) {
299 error_msg_and_die( "Exactly one of 'c', 'x' or 't' must be specified");
303 fixUpPermissions(TarInfo *header)
306 /* Now set permissions etc for the new file */
307 chown(header->name, header->uid, header->gid);
308 chmod(header->name, header->mode);
311 t.modtime = header->mtime;
312 utime(header->name, &t);
316 tarExtractRegularFile(TarInfo *header, int extractFlag, int tostdoutFlag)
320 size_t actualWriteSz;
322 size_t size = header->size;
323 int outFd=fileno(stdout);
325 /* Open the file to be written, if a file is supposed to be written */
326 if (extractFlag==TRUE && tostdoutFlag==FALSE) {
327 /* Create the path to the file, just in case it isn't there...
328 * This should not screw up path permissions or anything. */
329 create_path(header->name, 0777);
330 if ((outFd=open(header->name, O_CREAT|O_TRUNC|O_WRONLY,
331 header->mode & ~S_IFMT)) < 0) {
332 error_msg(io_error, header->name, strerror(errno));
337 /* Write out the file, if we are supposed to be doing that */
340 if ( size > sizeof(buffer) )
341 writeSize = readSize = sizeof(buffer);
343 int mod = size % 512;
345 readSize = size + (512 - mod);
350 if ( (readSize = full_read(header->tarFd, buffer, readSize)) <= 0 ) {
351 /* Tarball seems to have a problem */
352 error_msg("Unexpected EOF in archive");
355 if ( readSize < writeSize )
356 writeSize = readSize;
358 /* Write out the file, if we are supposed to be doing that */
359 if (extractFlag==TRUE) {
361 if ((actualWriteSz=full_write(outFd, buffer, writeSize)) != writeSize ) {
362 /* Output file seems to have a problem */
363 error_msg(io_error, header->name, strerror(errno));
367 actualWriteSz=writeSize;
370 size -= actualWriteSz;
373 /* Now we are done writing the file out, so try
374 * and fix up the permissions and whatnot */
375 if (extractFlag==TRUE && tostdoutFlag==FALSE) {
377 fixUpPermissions(header);
383 tarExtractDirectory(TarInfo *header, int extractFlag, int tostdoutFlag)
386 if (extractFlag==FALSE || tostdoutFlag==TRUE)
389 if (create_path(header->name, header->mode) != TRUE) {
390 perror_msg("%s: Cannot mkdir", header->name);
393 /* make the final component, just in case it was
394 * omitted by create_path() (which will skip the
395 * directory if it doesn't have a terminating '/') */
396 if (mkdir(header->name, header->mode) < 0 && errno != EEXIST) {
397 perror_msg("%s", header->name);
401 fixUpPermissions(header);
406 tarExtractHardLink(TarInfo *header, int extractFlag, int tostdoutFlag)
408 if (extractFlag==FALSE || tostdoutFlag==TRUE)
411 if (link(header->linkname, header->name) < 0) {
412 perror_msg("%s: Cannot create hard link to '%s'", header->name,
417 /* Now set permissions etc for the new directory */
418 fixUpPermissions(header);
423 tarExtractSymLink(TarInfo *header, int extractFlag, int tostdoutFlag)
425 if (extractFlag==FALSE || tostdoutFlag==TRUE)
429 if (symlink(header->linkname, header->name) < 0) {
430 perror_msg("%s: Cannot create symlink to '%s'", header->name,
434 /* Try to change ownership of the symlink.
435 * If libs doesn't support that, don't bother.
436 * Changing the pointed-to-file is the Wrong Thing(tm).
438 #if (__GLIBC__ >= 2) && (__GLIBC_MINOR__ >= 1)
439 lchown(header->name, header->uid, header->gid);
442 /* Do not change permissions or date on symlink,
443 * since it changes the pointed to file instead. duh. */
445 error_msg("%s: Cannot create symlink to '%s': %s",
446 header->name, header->linkname,
447 "symlinks not supported");
453 tarExtractSpecial(TarInfo *header, int extractFlag, int tostdoutFlag)
455 if (extractFlag==FALSE || tostdoutFlag==TRUE)
458 if (S_ISCHR(header->mode) || S_ISBLK(header->mode) || S_ISSOCK(header->mode)) {
459 if (mknod(header->name, header->mode, makedev(header->devmajor, header->devminor)) < 0) {
460 perror_msg("%s: Cannot mknod", header->name);
463 } else if (S_ISFIFO(header->mode)) {
464 if (mkfifo(header->name, header->mode) < 0) {
465 perror_msg("%s: Cannot mkfifo", header->name);
470 /* Now set permissions etc for the new directory */
471 fixUpPermissions(header);
475 /* Parse the tar header and fill in the nice struct with the details */
477 readTarHeader(struct TarHeader *rawHeader, struct TarInfo *header)
481 unsigned char *s = (unsigned char *)rawHeader;
483 header->name = rawHeader->name;
484 /* Check for and relativify any absolute paths */
485 if ( *(header->name) == '/' ) {
486 static int alreadyWarned=FALSE;
488 while (*(header->name) == '/')
491 if (alreadyWarned == FALSE) {
492 error_msg("Removing leading '/' from member names");
493 alreadyWarned = TRUE;
497 header->mode = strtol(rawHeader->mode, NULL, 8);
498 header->uid = strtol(rawHeader->uid, NULL, 8);
499 header->gid = strtol(rawHeader->gid, NULL, 8);
500 header->size = strtol(rawHeader->size, NULL, 8);
501 header->mtime = strtol(rawHeader->mtime, NULL, 8);
502 chksum = strtol(rawHeader->chksum, NULL, 8);
503 header->type = rawHeader->typeflag;
504 header->linkname = rawHeader->linkname;
505 header->devmajor = strtol(rawHeader->devmajor, NULL, 8);
506 header->devminor = strtol(rawHeader->devminor, NULL, 8);
508 /* Check the checksum */
509 for (i = sizeof(*rawHeader); i-- != 0;) {
512 /* Remove the effects of the checksum field (replace
513 * with blanks for the purposes of the checksum) */
514 s = rawHeader->chksum;
515 for (i = sizeof(rawHeader->chksum) ; i-- != 0;) {
518 sum += ' ' * sizeof(rawHeader->chksum);
524 static int exclude_file(char **excluded_files, const char *file)
528 if (excluded_files == NULL)
531 for (i = 0; excluded_files[i] != NULL; i++) {
532 if (excluded_files[i][0] == '/') {
533 if (fnmatch(excluded_files[i], file,
534 FNM_PATHNAME | FNM_LEADING_DIR) == 0)
539 for (p = file; p[0] != '\0'; p++) {
540 if ((p == file || p[-1] == '/') && p[0] != '/' &&
541 fnmatch(excluded_files[i], p,
542 FNM_PATHNAME | FNM_LEADING_DIR) == 0)
551 static int extract_file(char **extract_files, const char *file)
555 if (extract_files == NULL)
558 for (i = 0; extract_files[i] != NULL; i++) {
559 if (fnmatch(extract_files[i], file, FNM_LEADING_DIR) == 0)
567 * Read a tar file and extract or list the specified files within it.
568 * If the list is empty than all files are extracted or listed.
570 static int readTarFile(int tarFd, int extractFlag, int listFlag,
571 int tostdoutFlag, int verboseFlag, char** extractList,
576 int skipNextHeaderFlag=FALSE;
580 /* Set the umask for this process so it doesn't
581 * screw up permission setting for us later. */
584 /* Read the tar file, and iterate over it one file at a time */
585 while ( (status = full_read(tarFd, (char*)&rawHeader, TAR_BLOCK_SIZE)) == TAR_BLOCK_SIZE ) {
587 /* Try to read the header */
588 if ( readTarHeader(&rawHeader, &header) == FALSE ) {
589 if ( *(header.name) == '\0' ) {
593 error_msg("Bad tar header, skipping");
597 if ( *(header.name) == '\0' )
599 header.tarFd = tarFd;
601 /* Skip funky extra GNU headers that precede long files */
602 if ( (header.type == GNULONGNAME) || (header.type == GNULONGLINK) ) {
603 skipNextHeaderFlag=TRUE;
604 if (tarExtractRegularFile(&header, FALSE, FALSE) == FALSE)
608 if ( skipNextHeaderFlag == TRUE ) {
609 skipNextHeaderFlag=FALSE;
610 error_msg(name_longer_than_foo, NAME_SIZE);
611 if (tarExtractRegularFile(&header, FALSE, FALSE) == FALSE)
616 #if defined BB_FEATURE_TAR_EXCLUDE
617 if (exclude_file(excludeList, header.name)) {
618 /* There are not the droids you're looking for, move along */
619 /* If it is a regular file, pretend to extract it with
620 * the extractFlag set to FALSE, so the junk in the tarball
621 * is properly skipped over */
622 if ( header.type==REGTYPE || header.type==REGTYPE0 ) {
623 if (tarExtractRegularFile(&header, FALSE, FALSE) == FALSE)
630 if (!extract_file(extractList, header.name)) {
631 /* There are not the droids you're looking for, move along */
632 /* If it is a regular file, pretend to extract it with
633 * the extractFlag set to FALSE, so the junk in the tarball
634 * is properly skipped over */
635 if ( header.type==REGTYPE || header.type==REGTYPE0 ) {
636 if (tarExtractRegularFile(&header, FALSE, FALSE) == FALSE)
642 if (listFlag == TRUE) {
643 /* Special treatment if the list (-t) flag is on */
644 if (verboseFlag == TRUE) {
647 struct tm *tm = localtime (&(header.mtime));
649 len=printf("%s ", mode_string(header.mode));
650 my_getpwuid(buf, header.uid);
652 len+=printf("%d", header.uid);
654 len+=printf("%s", buf);
655 my_getgrgid(buf, header.gid);
657 len+=printf("/%-d ", header.gid);
659 len+=printf("/%-s ", buf);
661 if (header.type==CHRTYPE || header.type==BLKTYPE) {
662 len1=snprintf(buf, sizeof(buf), "%ld,%-ld ",
663 header.devmajor, header.devminor);
665 len1=snprintf(buf, sizeof(buf), "%lu ", (long)header.size);
667 /* Jump through some hoops to make the columns match up */
668 for(;(len+len1)<31;len++)
672 /* Use ISO 8610 time format */
674 printf ("%04d-%02d-%02d %02d:%02d:%02d ",
675 tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday,
676 tm->tm_hour, tm->tm_min, tm->tm_sec);
679 printf("%s", header.name);
680 if (verboseFlag == TRUE) {
681 if (header.type==LNKTYPE) /* If this is a link, say so */
682 printf(" link to %s", header.linkname);
683 else if (header.type==SYMTYPE)
684 printf(" -> %s", header.linkname);
689 /* List contents if we are supposed to do that */
690 if (verboseFlag == TRUE && extractFlag == TRUE) {
691 /* Now the normal listing */
693 if (tostdoutFlag == TRUE) // If the archive goes to stdout, verbose to stderr
695 fprintf(vbFd, "%s\n", header.name);
698 /* Remove files if we would overwrite them */
699 if (extractFlag == TRUE && tostdoutFlag == FALSE)
702 /* If we got here, we can be certain we have a legitimate
703 * header to work with. So work with it. */
704 switch ( header.type ) {
707 /* If the name ends in a '/' then assume it is
708 * supposed to be a directory, and fall through */
709 if (!last_char_is(header.name,'/')) {
710 if (tarExtractRegularFile(&header, extractFlag, tostdoutFlag)==FALSE)
715 if (tarExtractDirectory( &header, extractFlag, tostdoutFlag)==FALSE)
719 if (tarExtractHardLink( &header, extractFlag, tostdoutFlag)==FALSE)
723 if (tarExtractSymLink( &header, extractFlag, tostdoutFlag)==FALSE)
729 if (tarExtractSpecial( &header, extractFlag, tostdoutFlag)==FALSE)
733 /* Handled earlier */
736 skipNextHeaderFlag=TRUE;
740 error_msg("Unknown file type '%c' in tar file", header.type);
747 /* Bummer - we read a partial header */
748 perror_msg("Error reading tar file");
751 else if (errorFlag==TRUE) {
752 error_msg( "Error exit delayed from previous errors");
757 /* Stuff to do when we are done */
760 if ( *(header.name) == '\0' ) {
762 error_msg( "Error exit delayed from previous errors");
770 #ifdef BB_FEATURE_TAR_CREATE
773 ** writeTarFile(), writeFileToTarball(), and writeTarHeader() are
774 ** the only functions that deal with the HardLinkInfo structure.
775 ** Even these functions use the xxxHardLinkInfo() functions.
777 typedef struct HardLinkInfo HardLinkInfo;
780 HardLinkInfo *next; /* Next entry in list */
781 dev_t dev; /* Device number */
782 ino_t ino; /* Inode number */
783 short linkCount; /* (Hard) Link Count */
784 char name[1]; /* Start of filename (must be last) */
787 /* Some info to be carried along when creating a new tarball */
790 char* fileName; /* File name of the tarball */
791 int tarFd; /* Open-for-write file descriptor
793 struct stat statBuf; /* Stat info for the tarball, letting
794 us know the inode and device that the
795 tarball lives, so we can avoid trying
796 to include the tarball into itself */
797 int verboseFlag; /* Whether to print extra stuff or not */
798 char** excludeList; /* List of files to not include */
799 HardLinkInfo *hlInfoHead; /* Hard Link Tracking Information */
800 HardLinkInfo *hlInfo; /* Hard Link Info for the current file */
802 typedef struct TarBallInfo TarBallInfo;
805 /* Might be faster (and bigger) if the dev/ino were stored in numeric order;) */
807 addHardLinkInfo (HardLinkInfo **hlInfoHeadPtr, dev_t dev, ino_t ino,
808 short linkCount, const char *name)
810 /* Note: hlInfoHeadPtr can never be NULL! */
811 HardLinkInfo *hlInfo;
813 hlInfo = (HardLinkInfo *)xmalloc(sizeof(HardLinkInfo)+strlen(name)+1);
815 hlInfo->next = *hlInfoHeadPtr;
816 *hlInfoHeadPtr = hlInfo;
819 hlInfo->linkCount = linkCount;
820 strcpy(hlInfo->name, name);
826 freeHardLinkInfo (HardLinkInfo **hlInfoHeadPtr)
828 HardLinkInfo *hlInfo = NULL;
829 HardLinkInfo *hlInfoNext = NULL;
832 hlInfo = *hlInfoHeadPtr;
834 hlInfoNext = hlInfo->next;
838 *hlInfoHeadPtr = NULL;
843 /* Might be faster (and bigger) if the dev/ino were stored in numeric order;) */
844 static HardLinkInfo *
845 findHardLinkInfo (HardLinkInfo *hlInfo, dev_t dev, ino_t ino)
848 if ((ino == hlInfo->ino) && (dev == hlInfo->dev))
850 hlInfo = hlInfo->next;
855 /* Put an octal string into the specified buffer.
856 * The number is zero and space padded and possibly null padded.
857 * Returns TRUE if successful. */
858 static int putOctal (char *cp, int len, long value)
862 char *tempString = tempBuffer;
864 /* Create a string of the specified length with an initial space,
865 * leading zeroes and the octal number, and a trailing null. */
866 sprintf (tempString, "%0*lo", len - 1, value);
868 /* If the string is too large, suppress the leading space. */
869 tempLength = strlen (tempString) + 1;
870 if (tempLength > len) {
875 /* If the string is still too large, suppress the trailing null. */
876 if (tempLength > len)
879 /* If the string is still too large, fail. */
880 if (tempLength > len)
883 /* Copy the string to the field. */
884 memcpy (cp, tempString, len);
889 /* Write out a tar header for the specified file/directory/whatever */
891 writeTarHeader(struct TarBallInfo *tbInfo, const char *header_name,
892 const char *real_name, struct stat *statbuf)
895 struct TarHeader header;
896 const unsigned char *cp = (const unsigned char *) &header;
897 ssize_t size = sizeof(struct TarHeader);
899 memset( &header, 0, size);
901 strncpy(header.name, header_name, sizeof(header.name));
903 putOctal(header.mode, sizeof(header.mode), statbuf->st_mode);
904 putOctal(header.uid, sizeof(header.uid), statbuf->st_uid);
905 putOctal(header.gid, sizeof(header.gid), statbuf->st_gid);
906 putOctal(header.size, sizeof(header.size), 0); /* Regular file size is handled later */
907 putOctal(header.mtime, sizeof(header.mtime), statbuf->st_mtime);
908 strncpy(header.magic, TAR_MAGIC TAR_VERSION,
909 TAR_MAGIC_LEN + TAR_VERSION_LEN );
911 /* Enter the user and group names (default to root if it fails) */
912 my_getpwuid(header.uname, statbuf->st_uid);
914 strcpy(header.uname, "root");
915 my_getgrgid(header.gname, statbuf->st_gid);
917 strcpy(header.uname, "root");
919 if (tbInfo->hlInfo) {
920 /* This is a hard link */
921 header.typeflag = LNKTYPE;
922 strncpy(header.linkname, tbInfo->hlInfo->name, sizeof(header.linkname));
923 } else if (S_ISLNK(statbuf->st_mode)) {
924 char *lpath = xreadlink(real_name);
925 if (!lpath) /* Already printed err msg inside xreadlink() */
927 header.typeflag = SYMTYPE;
928 strncpy(header.linkname, lpath, sizeof(header.linkname));
930 } else if (S_ISDIR(statbuf->st_mode)) {
931 header.typeflag = DIRTYPE;
932 strncat(header.name, "/", sizeof(header.name));
933 } else if (S_ISCHR(statbuf->st_mode)) {
934 header.typeflag = CHRTYPE;
935 putOctal(header.devmajor, sizeof(header.devmajor), MAJOR(statbuf->st_rdev));
936 putOctal(header.devminor, sizeof(header.devminor), MINOR(statbuf->st_rdev));
937 } else if (S_ISBLK(statbuf->st_mode)) {
938 header.typeflag = BLKTYPE;
939 putOctal(header.devmajor, sizeof(header.devmajor), MAJOR(statbuf->st_rdev));
940 putOctal(header.devminor, sizeof(header.devminor), MINOR(statbuf->st_rdev));
941 } else if (S_ISFIFO(statbuf->st_mode)) {
942 header.typeflag = FIFOTYPE;
943 } else if (S_ISREG(statbuf->st_mode)) {
944 header.typeflag = REGTYPE;
945 putOctal(header.size, sizeof(header.size), statbuf->st_size);
947 error_msg("%s: Unknown file type", real_name);
951 /* Calculate and store the checksum (i.e. the sum of all of the bytes of
952 * the header). The checksum field must be filled with blanks for the
953 * calculation. The checksum field is formatted differently from the
954 * other fields: it has [6] digits, a null, then a space -- rather than
955 * digits, followed by a null like the other fields... */
956 memset(header.chksum, ' ', sizeof(header.chksum));
957 cp = (const unsigned char *) &header;
960 putOctal(header.chksum, 7, chksum);
962 /* Now write the header out to disk */
963 if ((size=full_write(tbInfo->tarFd, (char*)&header, sizeof(struct TarHeader))) < 0) {
964 error_msg(io_error, real_name, strerror(errno));
967 /* Pad the header up to the tar block size */
968 for (; size<TAR_BLOCK_SIZE; size++) {
969 write(tbInfo->tarFd, "\0", 1);
971 /* Now do the verbose thing (or not) */
972 if (tbInfo->verboseFlag==TRUE) {
974 if (tbInfo->tarFd == fileno(stdout)) // If the archive goes to stdout, verbose to stderr
976 fprintf(vbFd, "%s\n", header.name);
983 static int writeFileToTarball(const char *fileName, struct stat *statbuf, void* userData)
985 struct TarBallInfo *tbInfo = (struct TarBallInfo *)userData;
986 const char *header_name;
989 ** Check to see if we are dealing with a hard link.
991 ** Treat the first occurance of a given dev/inode as a file while
992 ** treating any additional occurances as hard links. This is done
993 ** by adding the file information to the HardLinkInfo linked list.
995 tbInfo->hlInfo = NULL;
996 if (statbuf->st_nlink > 1) {
997 tbInfo->hlInfo = findHardLinkInfo(tbInfo->hlInfoHead, statbuf->st_dev,
999 if (tbInfo->hlInfo == NULL)
1000 addHardLinkInfo (&tbInfo->hlInfoHead, statbuf->st_dev,
1001 statbuf->st_ino, statbuf->st_nlink, fileName);
1004 /* It is against the rules to archive a socket */
1005 if (S_ISSOCK(statbuf->st_mode)) {
1006 error_msg("%s: socket ignored", fileName);
1010 /* It is a bad idea to store the archive we are in the process of creating,
1011 * so check the device and inode to be sure that this particular file isn't
1012 * the new tarball */
1013 if (tbInfo->statBuf.st_dev == statbuf->st_dev &&
1014 tbInfo->statBuf.st_ino == statbuf->st_ino) {
1015 error_msg("%s: file is the archive; skipping", fileName);
1019 header_name = fileName;
1020 while (header_name[0] == '/') {
1021 static int alreadyWarned=FALSE;
1022 if (alreadyWarned==FALSE) {
1023 error_msg("Removing leading '/' from member names");
1029 if (strlen(fileName) >= NAME_SIZE) {
1030 error_msg(name_longer_than_foo, NAME_SIZE);
1034 if (header_name[0] == '\0')
1037 #if defined BB_FEATURE_TAR_EXCLUDE
1038 if (exclude_file(tbInfo->excludeList, header_name)) {
1043 if (writeTarHeader(tbInfo, header_name, fileName, statbuf)==FALSE) {
1047 /* Now, if the file is a regular file, copy it out to the tarball */
1048 if ((tbInfo->hlInfo == NULL)
1049 && (S_ISREG(statbuf->st_mode))) {
1051 char buffer[BUFSIZ];
1052 ssize_t size=0, readSize=0;
1054 /* open the file we want to archive, and make sure all is well */
1055 if ((inputFileFd = open(fileName, O_RDONLY)) < 0) {
1056 error_msg("%s: Cannot open: %s", fileName, strerror(errno));
1060 /* write the file to the archive */
1061 while ( (size = full_read(inputFileFd, buffer, sizeof(buffer))) > 0 ) {
1062 if (full_write(tbInfo->tarFd, buffer, size) != size ) {
1063 /* Output file seems to have a problem */
1064 error_msg(io_error, fileName, strerror(errno));
1070 error_msg(io_error, fileName, strerror(errno));
1073 /* Pad the file up to the tar block size */
1074 for (; (readSize%TAR_BLOCK_SIZE) != 0; readSize++) {
1075 write(tbInfo->tarFd, "\0", 1);
1077 close( inputFileFd);
1083 static int writeTarFile(const char* tarName, int verboseFlag, char **argv,
1087 int errorFlag=FALSE;
1089 struct TarBallInfo tbInfo;
1090 tbInfo.verboseFlag = verboseFlag;
1091 tbInfo.hlInfoHead = NULL;
1093 /* Make sure there is at least one file to tar up. */
1095 error_msg_and_die("Cowardly refusing to create an empty archive");
1097 /* Open the tar file for writing. */
1098 if (!strcmp(tarName, "-"))
1099 tbInfo.tarFd = fileno(stdout);
1101 tbInfo.tarFd = open (tarName, O_WRONLY | O_CREAT | O_TRUNC, 0644);
1102 if (tbInfo.tarFd < 0) {
1103 perror_msg( "Error opening '%s'", tarName);
1104 freeHardLinkInfo(&tbInfo.hlInfoHead);
1107 tbInfo.excludeList=excludeList;
1108 /* Store the stat info for the tarball's file, so
1109 * can avoid including the tarball into itself.... */
1110 if (fstat(tbInfo.tarFd, &tbInfo.statBuf) < 0)
1111 error_msg_and_die(io_error, tarName, strerror(errno));
1113 /* Set the umask for this process so it doesn't
1114 * screw up permission setting for us later. */
1117 /* Read the directory/files and iterate over them one at a time */
1118 while (*argv != NULL) {
1119 if (recursive_action(*argv++, TRUE, FALSE, FALSE,
1120 writeFileToTarball, writeFileToTarball,
1121 (void*) &tbInfo) == FALSE) {
1125 /* Write two empty blocks to the end of the archive */
1126 for (size=0; size<(2*TAR_BLOCK_SIZE); size++) {
1127 write(tbInfo.tarFd, "\0", 1);
1130 /* To be pedantically correct, we would check if the tarball
1131 * is smaller than 20 tar blocks, and pad it if it was smaller,
1132 * but that isn't necessary for GNU tar interoperability, and
1133 * so is considered a waste of space */
1135 /* Hang up the tools, close up shop, head home */
1137 if (errorFlag == TRUE) {
1138 error_msg("Error exit delayed from previous errors");
1139 freeHardLinkInfo(&tbInfo.hlInfoHead);
1142 freeHardLinkInfo(&tbInfo.hlInfoHead);