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
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>
59 #ifdef BB_FEATURE_TAR_GZIP
60 extern int unzip(int in, int out);
61 extern int gunzip_init();
64 /* Tar file constants */
66 #define MAJOR(dev) (((dev)>>8)&0xff)
67 #define MINOR(dev) ((dev)&0xff)
70 enum { NAME_SIZE = 100 }; /* because gcc won't let me use 'static const int' */
72 /* POSIX tar Header Block, from POSIX 1003.1-1990 */
76 char name[NAME_SIZE]; /* 0-99 */
77 char mode[8]; /* 100-107 */
78 char uid[8]; /* 108-115 */
79 char gid[8]; /* 116-123 */
80 char size[12]; /* 124-135 */
81 char mtime[12]; /* 136-147 */
82 char chksum[8]; /* 148-155 */
83 char typeflag; /* 156-156 */
84 char linkname[NAME_SIZE]; /* 157-256 */
85 char magic[6]; /* 257-262 */
86 char version[2]; /* 263-264 */
87 char uname[32]; /* 265-296 */
88 char gname[32]; /* 297-328 */
89 char devmajor[8]; /* 329-336 */
90 char devminor[8]; /* 337-344 */
91 char prefix[155]; /* 345-499 */
92 char padding[12]; /* 500-512 (pad to exactly the TAR_BLOCK_SIZE) */
94 typedef struct TarHeader TarHeader;
97 /* A few useful constants */
98 #define TAR_MAGIC "ustar" /* ustar and a null */
99 #define TAR_VERSION " " /* Be compatable with GNU tar format */
100 static const int TAR_MAGIC_LEN = 6;
101 static const int TAR_VERSION_LEN = 2;
102 static const int TAR_BLOCK_SIZE = 512;
104 /* A nice enum with all the possible tar file content types */
107 REGTYPE = '0', /* regular file */
108 REGTYPE0 = '\0', /* regular file (ancient bug compat)*/
109 LNKTYPE = '1', /* hard link */
110 SYMTYPE = '2', /* symbolic link */
111 CHRTYPE = '3', /* character special */
112 BLKTYPE = '4', /* block special */
113 DIRTYPE = '5', /* directory */
114 FIFOTYPE = '6', /* FIFO special */
115 CONTTYPE = '7', /* reserved */
116 GNULONGLINK = 'K', /* GNU long (>100 chars) link name */
117 GNULONGNAME = 'L', /* GNU long (>100 chars) file name */
119 typedef enum TarFileType TarFileType;
121 /* This struct ignores magic, non-numeric user name,
122 * non-numeric group name, and the checksum, since
123 * these are all ignored by BusyBox tar. */
126 int tarFd; /* An open file descriptor for reading from the tarball */
127 char * name; /* File name */
128 mode_t mode; /* Unix mode, including device bits. */
129 uid_t uid; /* Numeric UID */
130 gid_t gid; /* Numeric GID */
131 size_t size; /* Size of file */
132 time_t mtime; /* Last-modified time */
133 enum TarFileType type; /* Regular, directory, link, etc */
134 char * linkname; /* Name for symbolic and hard links */
135 long devmajor; /* Major number for special device */
136 long devminor; /* Minor number for special device */
138 typedef struct TarInfo TarInfo;
140 /* Local procedures to restore files from a tar file. */
141 extern int readTarFile(int tarFd, int extractFlag, int listFlag,
142 int tostdoutFlag, int verboseFlag, char** extractList,
145 #ifdef BB_FEATURE_TAR_CREATE
146 /* Local procedures to save files into a tar file. */
147 static int writeTarFile(const char* tarName, int verboseFlag, char **argv,
151 #ifdef BB_FEATURE_TAR_GZIP
152 /* Signal handler for when child gzip process dies... */
160 extern int tar_unzip_init(int tarFd)
163 static int unzip_pipe[2];
164 /* Cope if child dies... Otherwise we block forever in read()... */
165 signal(SIGCHLD, child_died);
167 if (pipe(unzip_pipe)!=0)
168 error_msg_and_die("pipe error\n");
170 if ( (child_pid = fork()) == -1)
171 error_msg_and_die("fork failure\n");
175 close(unzip_pipe[0]);
177 unzip(tarFd, unzip_pipe[1]);
181 /* return fd of uncompressed data to parent process */
182 close(unzip_pipe[1]);
183 return(unzip_pipe[0]);
188 #if defined BB_FEATURE_TAR_EXCLUDE
189 struct option longopts[] = {
190 { "exclude", 1, NULL, 'e' },
195 extern int tar_main(int argc, char **argv)
197 char** excludeList=NULL;
198 char** extractList=NULL;
199 const char *tarName="-";
200 #if defined BB_FEATURE_TAR_EXCLUDE
201 int excludeListSize=0;
205 #if defined BB_FEATURE_TAR_GZIP
206 int unzipFlag = FALSE;
208 int listFlag = FALSE;
209 int extractFlag = FALSE;
210 int createFlag = FALSE;
211 int verboseFlag = FALSE;
212 int tostdoutFlag = FALSE;
219 if (argv[1][0] != '-') {
220 char *tmp = xmalloc(strlen(argv[1]) + 2);
222 strcpy(tmp + 1, argv[1]);
227 #ifndef BB_FEATURE_TAR_EXCLUDE
228 (opt = getopt(argc, argv, "cxtzvOf:"))
230 (opt = getopt_long(argc, argv, "cxtzvOf:X:", longopts, NULL))
235 if (extractFlag == TRUE || listFlag == TRUE)
240 if (listFlag == TRUE || createFlag == TRUE)
245 if (extractFlag == TRUE || createFlag == TRUE)
249 #ifdef BB_FEATURE_TAR_GZIP
262 error_msg_and_die( "Only one 'f' option allowed\n");
265 #if defined BB_FEATURE_TAR_EXCLUDE
267 excludeList=xrealloc( excludeList,
268 sizeof(char *) * (excludeListSize+2));
269 excludeList[excludeListSize] = optarg;
270 /* Tack a NULL onto the end of the list */
271 excludeList[++excludeListSize] = NULL;
273 fileList = xfopen(optarg, "r");
274 while (fgets(file, sizeof(file), fileList) != NULL) {
275 excludeList = xrealloc(excludeList,
276 sizeof(char *) * (excludeListSize+2));
277 if (file[strlen(file)-1] == '\n')
278 file[strlen(file)-1] = '\0';
279 excludeList[excludeListSize] = xstrdup(file);
280 /* Tack a NULL onto the end of the list */
281 excludeList[++excludeListSize] = NULL;
292 * Do the correct type of action supplying the rest of the
293 * command line arguments as the list of files to process.
295 if (createFlag == TRUE) {
296 #ifndef BB_FEATURE_TAR_CREATE
297 error_msg_and_die( "This version of tar was not compiled with tar creation support.\n");
299 #ifdef BB_FEATURE_TAR_GZIP
301 error_msg_and_die("Creation of compressed not internally support by tar, pipe to busybox gunzip\n");
303 status = writeTarFile(tarName, verboseFlag, argv + optind, excludeList);
306 if (listFlag == TRUE || extractFlag == TRUE) {
309 extractList = argv + optind;
310 /* Open the tar file for reading. */
311 if (!strcmp(tarName, "-"))
312 tarFd = fileno(stdin);
314 tarFd = open(tarName, O_RDONLY);
316 perror_msg_and_die("Error opening '%s'", tarName);
318 #ifdef BB_FEATURE_TAR_GZIP
319 /* unzip tarFd in a seperate process */
320 if (unzipFlag == TRUE)
321 tarFd = tar_unzip_init(tarFd);
323 status = readTarFile(tarFd, extractFlag, listFlag, tostdoutFlag,
324 verboseFlag, extractList, excludeList);
333 error_msg_and_die( "Exactly one of 'c', 'x' or 't' must be specified\n");
337 fixUpPermissions(TarInfo *header)
340 /* Now set permissions etc for the new file */
341 chown(header->name, header->uid, header->gid);
342 chmod(header->name, header->mode);
345 t.modtime = header->mtime;
346 utime(header->name, &t);
350 tarExtractRegularFile(TarInfo *header, int extractFlag, int tostdoutFlag)
354 size_t actualWriteSz;
356 size_t size = header->size;
357 int outFd=fileno(stdout);
359 /* Open the file to be written, if a file is supposed to be written */
360 if (extractFlag==TRUE && tostdoutFlag==FALSE) {
361 /* Create the path to the file, just in case it isn't there...
362 * This should not screw up path permissions or anything. */
363 create_path(header->name, 0777);
364 if ((outFd=open(header->name, O_CREAT|O_TRUNC|O_WRONLY,
365 header->mode & ~S_IFMT)) < 0) {
366 error_msg(io_error, header->name, strerror(errno));
371 /* Write out the file, if we are supposed to be doing that */
374 if ( size > sizeof(buffer) )
375 writeSize = readSize = sizeof(buffer);
377 int mod = size % 512;
379 readSize = size + (512 - mod);
384 if ( (readSize = full_read(header->tarFd, buffer, readSize)) <= 0 ) {
385 /* Tarball seems to have a problem */
386 error_msg("Unexpected EOF in archive\n");
389 if ( readSize < writeSize )
390 writeSize = readSize;
392 /* Write out the file, if we are supposed to be doing that */
393 if (extractFlag==TRUE) {
395 if ((actualWriteSz=full_write(outFd, buffer, writeSize)) != writeSize ) {
396 /* Output file seems to have a problem */
397 error_msg(io_error, header->name, strerror(errno));
401 actualWriteSz=writeSize;
404 size -= actualWriteSz;
407 /* Now we are done writing the file out, so try
408 * and fix up the permissions and whatnot */
409 if (extractFlag==TRUE && tostdoutFlag==FALSE) {
411 fixUpPermissions(header);
417 tarExtractDirectory(TarInfo *header, int extractFlag, int tostdoutFlag)
420 if (extractFlag==FALSE || tostdoutFlag==TRUE)
423 if (create_path(header->name, header->mode) != TRUE) {
424 perror_msg("%s: Cannot mkdir", header->name);
427 /* make the final component, just in case it was
428 * omitted by create_path() (which will skip the
429 * directory if it doesn't have a terminating '/') */
430 if (mkdir(header->name, header->mode) < 0 && errno != EEXIST) {
431 perror_msg("%s", header->name);
435 fixUpPermissions(header);
440 tarExtractHardLink(TarInfo *header, int extractFlag, int tostdoutFlag)
442 if (extractFlag==FALSE || tostdoutFlag==TRUE)
445 if (link(header->linkname, header->name) < 0) {
446 perror_msg("%s: Cannot create hard link to '%s'", header->name,
451 /* Now set permissions etc for the new directory */
452 fixUpPermissions(header);
457 tarExtractSymLink(TarInfo *header, int extractFlag, int tostdoutFlag)
459 if (extractFlag==FALSE || tostdoutFlag==TRUE)
463 if (symlink(header->linkname, header->name) < 0) {
464 perror_msg("%s: Cannot create symlink to '%s'", header->name,
468 /* Try to change ownership of the symlink.
469 * If libs doesn't support that, don't bother.
470 * Changing the pointed-to-file is the Wrong Thing(tm).
472 #if (__GLIBC__ >= 2) && (__GLIBC_MINOR__ >= 1)
473 lchown(header->name, header->uid, header->gid);
476 /* Do not change permissions or date on symlink,
477 * since it changes the pointed to file instead. duh. */
479 error_msg("%s: Cannot create symlink to '%s': %s\n",
480 header->name, header->linkname,
481 "symlinks not supported");
487 tarExtractSpecial(TarInfo *header, int extractFlag, int tostdoutFlag)
489 if (extractFlag==FALSE || tostdoutFlag==TRUE)
492 if (S_ISCHR(header->mode) || S_ISBLK(header->mode) || S_ISSOCK(header->mode)) {
493 if (mknod(header->name, header->mode, makedev(header->devmajor, header->devminor)) < 0) {
494 perror_msg("%s: Cannot mknod", header->name);
497 } else if (S_ISFIFO(header->mode)) {
498 if (mkfifo(header->name, header->mode) < 0) {
499 perror_msg("%s: Cannot mkfifo", header->name);
504 /* Now set permissions etc for the new directory */
505 fixUpPermissions(header);
509 /* Read an octal value in a field of the specified width, with optional
510 * spaces on both sides of the number and with an optional null character
511 * at the end. Returns -1 on an illegal format. */
512 static long getOctal(const char *cp, int size)
516 for(;(size > 0) && (*cp == ' '); cp++, size--);
517 if ((size == 0) || !is_octal(*cp))
519 for(; (size > 0) && is_octal(*cp); size--) {
520 val = val * 8 + *cp++ - '0';
522 for (;(size > 0) && (*cp == ' '); cp++, size--);
523 if ((size > 0) && *cp)
529 /* Parse the tar header and fill in the nice struct with the details */
531 readTarHeader(struct TarHeader *rawHeader, struct TarInfo *header)
535 unsigned char *s = (unsigned char *)rawHeader;
537 header->name = rawHeader->name;
538 /* Check for and relativify any absolute paths */
539 if ( *(header->name) == '/' ) {
540 static int alreadyWarned=FALSE;
542 while (*(header->name) == '/')
545 if (alreadyWarned == FALSE) {
546 error_msg("Removing leading '/' from member names\n");
547 alreadyWarned = TRUE;
551 header->mode = getOctal(rawHeader->mode, sizeof(rawHeader->mode));
552 header->uid = getOctal(rawHeader->uid, sizeof(rawHeader->uid));
553 header->gid = getOctal(rawHeader->gid, sizeof(rawHeader->gid));
554 header->size = getOctal(rawHeader->size, sizeof(rawHeader->size));
555 header->mtime = getOctal(rawHeader->mtime, sizeof(rawHeader->mtime));
556 chksum = getOctal(rawHeader->chksum, sizeof(rawHeader->chksum));
557 header->type = rawHeader->typeflag;
558 header->linkname = rawHeader->linkname;
559 header->devmajor = getOctal(rawHeader->devmajor, sizeof(rawHeader->devmajor));
560 header->devminor = getOctal(rawHeader->devminor, sizeof(rawHeader->devminor));
562 /* Check the checksum */
563 for (i = sizeof(*rawHeader); i-- != 0;) {
566 /* Remove the effects of the checksum field (replace
567 * with blanks for the purposes of the checksum) */
568 s = rawHeader->chksum;
569 for (i = sizeof(rawHeader->chksum) ; i-- != 0;) {
572 sum += ' ' * sizeof(rawHeader->chksum);
578 int exclude_file(char **excluded_files, const char *file)
582 if (excluded_files == NULL)
585 for (i = 0; excluded_files[i] != NULL; i++) {
586 if (excluded_files[i][0] == '/') {
587 if (fnmatch(excluded_files[i], file,
588 FNM_PATHNAME | FNM_LEADING_DIR) == 0)
593 for (p = file; p[0] != '\0'; p++) {
594 if ((p == file || p[-1] == '/') && p[0] != '/' &&
595 fnmatch(excluded_files[i], p,
596 FNM_PATHNAME | FNM_LEADING_DIR) == 0)
605 int extract_file(char **extract_files, const char *file)
609 if (extract_files == NULL)
612 for (i = 0; extract_files[i] != NULL; i++) {
613 if (fnmatch(extract_files[i], file, FNM_LEADING_DIR) == 0)
621 * Read a tar file and extract or list the specified files within it.
622 * If the list is empty than all files are extracted or listed.
624 extern int readTarFile(int tarFd, int extractFlag, int listFlag,
625 int tostdoutFlag, int verboseFlag, char** extractList,
630 int skipNextHeaderFlag=FALSE;
634 /* Set the umask for this process so it doesn't
635 * screw up permission setting for us later. */
638 /* Read the tar file, and iterate over it one file at a time */
639 while ( (status = full_read(tarFd, (char*)&rawHeader, TAR_BLOCK_SIZE)) == TAR_BLOCK_SIZE ) {
641 /* Try to read the header */
642 if ( readTarHeader(&rawHeader, &header) == FALSE ) {
643 if ( *(header.name) == '\0' ) {
647 error_msg("Bad tar header, skipping\n");
651 if ( *(header.name) == '\0' )
653 header.tarFd = tarFd;
655 /* Skip funky extra GNU headers that precede long files */
656 if ( (header.type == GNULONGNAME) || (header.type == GNULONGLINK) ) {
657 skipNextHeaderFlag=TRUE;
658 if (tarExtractRegularFile(&header, FALSE, FALSE) == FALSE)
662 if ( skipNextHeaderFlag == TRUE ) {
663 skipNextHeaderFlag=FALSE;
664 error_msg(name_longer_than_foo, NAME_SIZE);
665 if (tarExtractRegularFile(&header, FALSE, FALSE) == FALSE)
670 #if defined BB_FEATURE_TAR_EXCLUDE
671 if (exclude_file(excludeList, header.name)) {
672 /* There are not the droids you're looking for, move along */
673 /* If it is a regular file, pretend to extract it with
674 * the extractFlag set to FALSE, so the junk in the tarball
675 * is properly skipped over */
676 if ( header.type==REGTYPE || header.type==REGTYPE0 ) {
677 if (tarExtractRegularFile(&header, FALSE, FALSE) == FALSE)
684 if (!extract_file(extractList, header.name)) {
685 /* There are not the droids you're looking for, move along */
686 /* If it is a regular file, pretend to extract it with
687 * the extractFlag set to FALSE, so the junk in the tarball
688 * is properly skipped over */
689 if ( header.type==REGTYPE || header.type==REGTYPE0 ) {
690 if (tarExtractRegularFile(&header, FALSE, FALSE) == FALSE)
696 if (listFlag == TRUE) {
697 /* Special treatment if the list (-t) flag is on */
698 if (verboseFlag == TRUE) {
701 struct tm *tm = localtime (&(header.mtime));
703 len=printf("%s ", mode_string(header.mode));
704 my_getpwuid(buf, header.uid);
706 len+=printf("%d", header.uid);
708 len+=printf("%s", buf);
709 my_getgrgid(buf, header.gid);
711 len+=printf("/%-d ", header.gid);
713 len+=printf("/%-s ", buf);
715 if (header.type==CHRTYPE || header.type==BLKTYPE) {
716 len1=snprintf(buf, sizeof(buf), "%ld,%-ld ",
717 header.devmajor, header.devminor);
719 len1=snprintf(buf, sizeof(buf), "%lu ", (long)header.size);
721 /* Jump through some hoops to make the columns match up */
722 for(;(len+len1)<31;len++)
726 /* Use ISO 8610 time format */
728 printf ("%04d-%02d-%02d %02d:%02d:%02d ",
729 tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday,
730 tm->tm_hour, tm->tm_min, tm->tm_sec);
733 printf("%s", header.name);
734 if (verboseFlag == TRUE) {
735 if (header.type==LNKTYPE) /* If this is a link, say so */
736 printf(" link to %s", header.linkname);
737 else if (header.type==SYMTYPE)
738 printf(" -> %s", header.linkname);
743 /* List contents if we are supposed to do that */
744 if (verboseFlag == TRUE && extractFlag == TRUE) {
745 /* Now the normal listing */
747 if (tostdoutFlag == TRUE) // If the archive goes to stdout, verbose to stderr
749 fprintf(vbFd, "%s\n", header.name);
752 /* Remove files if we would overwrite them */
753 if (extractFlag == TRUE && tostdoutFlag == FALSE)
756 /* If we got here, we can be certain we have a legitimate
757 * header to work with. So work with it. */
758 switch ( header.type ) {
761 /* If the name ends in a '/' then assume it is
762 * supposed to be a directory, and fall through */
763 if (header.name[strlen(header.name)-1] != '/') {
764 if (tarExtractRegularFile(&header, extractFlag, tostdoutFlag)==FALSE)
769 if (tarExtractDirectory( &header, extractFlag, tostdoutFlag)==FALSE)
773 if (tarExtractHardLink( &header, extractFlag, tostdoutFlag)==FALSE)
777 if (tarExtractSymLink( &header, extractFlag, tostdoutFlag)==FALSE)
783 if (tarExtractSpecial( &header, extractFlag, tostdoutFlag)==FALSE)
787 /* Handled earlier */
790 skipNextHeaderFlag=TRUE;
794 error_msg("Unknown file type '%c' in tar file\n", header.type);
801 /* Bummer - we read a partial header */
802 perror_msg("Error reading tar file");
805 else if (errorFlag==TRUE) {
806 error_msg( "Error exit delayed from previous errors\n");
811 /* Stuff to do when we are done */
814 if ( *(header.name) == '\0' ) {
816 error_msg( "Error exit delayed from previous errors\n");
824 #ifdef BB_FEATURE_TAR_CREATE
827 ** writeTarFile(), writeFileToTarball(), and writeTarHeader() are
828 ** the only functions that deal with the HardLinkInfo structure.
829 ** Even these functions use the xxxHardLinkInfo() functions.
831 typedef struct HardLinkInfo HardLinkInfo;
834 HardLinkInfo *next; /* Next entry in list */
835 dev_t dev; /* Device number */
836 ino_t ino; /* Inode number */
837 short linkCount; /* (Hard) Link Count */
838 char name[1]; /* Start of filename (must be last) */
841 /* Some info to be carried along when creating a new tarball */
844 char* fileName; /* File name of the tarball */
845 int tarFd; /* Open-for-write file descriptor
847 struct stat statBuf; /* Stat info for the tarball, letting
848 us know the inode and device that the
849 tarball lives, so we can avoid trying
850 to include the tarball into itself */
851 int verboseFlag; /* Whether to print extra stuff or not */
852 char** excludeList; /* List of files to not include */
853 HardLinkInfo *hlInfoHead; /* Hard Link Tracking Information */
854 HardLinkInfo *hlInfo; /* Hard Link Info for the current file */
856 typedef struct TarBallInfo TarBallInfo;
859 /* Might be faster (and bigger) if the dev/ino were stored in numeric order;) */
861 addHardLinkInfo (HardLinkInfo **hlInfoHeadPtr, dev_t dev, ino_t ino,
862 short linkCount, const char *name)
864 /* Note: hlInfoHeadPtr can never be NULL! */
865 HardLinkInfo *hlInfo;
867 hlInfo = (HardLinkInfo *)xmalloc(sizeof(HardLinkInfo)+strlen(name)+1);
869 hlInfo->next = *hlInfoHeadPtr;
870 *hlInfoHeadPtr = hlInfo;
873 hlInfo->linkCount = linkCount;
874 strcpy(hlInfo->name, name);
880 freeHardLinkInfo (HardLinkInfo **hlInfoHeadPtr)
882 HardLinkInfo *hlInfo = NULL;
883 HardLinkInfo *hlInfoNext = NULL;
886 hlInfo = *hlInfoHeadPtr;
888 hlInfoNext = hlInfo->next;
892 *hlInfoHeadPtr = NULL;
897 /* Might be faster (and bigger) if the dev/ino were stored in numeric order;) */
898 static HardLinkInfo *
899 findHardLinkInfo (HardLinkInfo *hlInfo, dev_t dev, ino_t ino)
902 if ((ino == hlInfo->ino) && (dev == hlInfo->dev))
904 hlInfo = hlInfo->next;
909 /* Put an octal string into the specified buffer.
910 * The number is zero and space padded and possibly null padded.
911 * Returns TRUE if successful. */
912 static int putOctal (char *cp, int len, long value)
916 char *tempString = tempBuffer;
918 /* Create a string of the specified length with an initial space,
919 * leading zeroes and the octal number, and a trailing null. */
920 sprintf (tempString, "%0*lo", len - 1, value);
922 /* If the string is too large, suppress the leading space. */
923 tempLength = strlen (tempString) + 1;
924 if (tempLength > len) {
929 /* If the string is still too large, suppress the trailing null. */
930 if (tempLength > len)
933 /* If the string is still too large, fail. */
934 if (tempLength > len)
937 /* Copy the string to the field. */
938 memcpy (cp, tempString, len);
943 /* Write out a tar header for the specified file/directory/whatever */
945 writeTarHeader(struct TarBallInfo *tbInfo, const char *header_name,
946 const char *real_name, struct stat *statbuf)
949 struct TarHeader header;
950 const unsigned char *cp = (const unsigned char *) &header;
951 ssize_t size = sizeof(struct TarHeader);
953 memset( &header, 0, size);
955 strncpy(header.name, header_name, sizeof(header.name));
957 putOctal(header.mode, sizeof(header.mode), statbuf->st_mode);
958 putOctal(header.uid, sizeof(header.uid), statbuf->st_uid);
959 putOctal(header.gid, sizeof(header.gid), statbuf->st_gid);
960 putOctal(header.size, sizeof(header.size), 0); /* Regular file size is handled later */
961 putOctal(header.mtime, sizeof(header.mtime), statbuf->st_mtime);
962 strncpy(header.magic, TAR_MAGIC TAR_VERSION,
963 TAR_MAGIC_LEN + TAR_VERSION_LEN );
965 /* Enter the user and group names (default to root if it fails) */
966 my_getpwuid(header.uname, statbuf->st_uid);
968 strcpy(header.uname, "root");
969 my_getgrgid(header.gname, statbuf->st_gid);
971 strcpy(header.uname, "root");
973 if (tbInfo->hlInfo) {
974 /* This is a hard link */
975 header.typeflag = LNKTYPE;
976 strncpy(header.linkname, tbInfo->hlInfo->name, sizeof(header.linkname));
977 } else if (S_ISLNK(statbuf->st_mode)) {
980 header.typeflag = SYMTYPE;
981 link_size = readlink(real_name, buffer, sizeof(buffer) - 1);
982 if ( link_size < 0) {
983 perror_msg("Error reading symlink '%s'", header.name);
986 buffer[link_size] = '\0';
987 strncpy(header.linkname, buffer, sizeof(header.linkname));
988 } else if (S_ISDIR(statbuf->st_mode)) {
989 header.typeflag = DIRTYPE;
990 strncat(header.name, "/", sizeof(header.name));
991 } else if (S_ISCHR(statbuf->st_mode)) {
992 header.typeflag = CHRTYPE;
993 putOctal(header.devmajor, sizeof(header.devmajor), MAJOR(statbuf->st_rdev));
994 putOctal(header.devminor, sizeof(header.devminor), MINOR(statbuf->st_rdev));
995 } else if (S_ISBLK(statbuf->st_mode)) {
996 header.typeflag = BLKTYPE;
997 putOctal(header.devmajor, sizeof(header.devmajor), MAJOR(statbuf->st_rdev));
998 putOctal(header.devminor, sizeof(header.devminor), MINOR(statbuf->st_rdev));
999 } else if (S_ISFIFO(statbuf->st_mode)) {
1000 header.typeflag = FIFOTYPE;
1001 } else if (S_ISREG(statbuf->st_mode)) {
1002 header.typeflag = REGTYPE;
1003 putOctal(header.size, sizeof(header.size), statbuf->st_size);
1005 error_msg("%s: Unknown file type\n", real_name);
1009 /* Calculate and store the checksum (i.e. the sum of all of the bytes of
1010 * the header). The checksum field must be filled with blanks for the
1011 * calculation. The checksum field is formatted differently from the
1012 * other fields: it has [6] digits, a null, then a space -- rather than
1013 * digits, followed by a null like the other fields... */
1014 memset(header.chksum, ' ', sizeof(header.chksum));
1015 cp = (const unsigned char *) &header;
1018 putOctal(header.chksum, 7, chksum);
1020 /* Now write the header out to disk */
1021 if ((size=full_write(tbInfo->tarFd, (char*)&header, sizeof(struct TarHeader))) < 0) {
1022 error_msg(io_error, real_name, strerror(errno));
1025 /* Pad the header up to the tar block size */
1026 for (; size<TAR_BLOCK_SIZE; size++) {
1027 write(tbInfo->tarFd, "\0", 1);
1029 /* Now do the verbose thing (or not) */
1030 if (tbInfo->verboseFlag==TRUE) {
1031 FILE *vbFd = stdout;
1032 if (tbInfo->tarFd == fileno(stdout)) // If the archive goes to stdout, verbose to stderr
1034 fprintf(vbFd, "%s\n", header.name);
1041 static int writeFileToTarball(const char *fileName, struct stat *statbuf, void* userData)
1043 struct TarBallInfo *tbInfo = (struct TarBallInfo *)userData;
1044 const char *header_name;
1047 ** Check to see if we are dealing with a hard link.
1049 ** Treat the first occurance of a given dev/inode as a file while
1050 ** treating any additional occurances as hard links. This is done
1051 ** by adding the file information to the HardLinkInfo linked list.
1053 tbInfo->hlInfo = NULL;
1054 if (statbuf->st_nlink > 1) {
1055 tbInfo->hlInfo = findHardLinkInfo(tbInfo->hlInfoHead, statbuf->st_dev,
1057 if (tbInfo->hlInfo == NULL)
1058 addHardLinkInfo (&tbInfo->hlInfoHead, statbuf->st_dev,
1059 statbuf->st_ino, statbuf->st_nlink, fileName);
1062 /* It is against the rules to archive a socket */
1063 if (S_ISSOCK(statbuf->st_mode)) {
1064 error_msg("%s: socket ignored\n", fileName);
1068 /* It is a bad idea to store the archive we are in the process of creating,
1069 * so check the device and inode to be sure that this particular file isn't
1070 * the new tarball */
1071 if (tbInfo->statBuf.st_dev == statbuf->st_dev &&
1072 tbInfo->statBuf.st_ino == statbuf->st_ino) {
1073 error_msg("%s: file is the archive; skipping\n", fileName);
1077 header_name = fileName;
1078 while (header_name[0] == '/') {
1079 static int alreadyWarned=FALSE;
1080 if (alreadyWarned==FALSE) {
1081 error_msg("Removing leading '/' from member names\n");
1087 if (strlen(fileName) >= NAME_SIZE) {
1088 error_msg(name_longer_than_foo, NAME_SIZE);
1092 if (header_name[0] == '\0')
1095 #if defined BB_FEATURE_TAR_EXCLUDE
1096 if (exclude_file(tbInfo->excludeList, header_name)) {
1101 if (writeTarHeader(tbInfo, header_name, fileName, statbuf)==FALSE) {
1105 /* Now, if the file is a regular file, copy it out to the tarball */
1106 if ((tbInfo->hlInfo == NULL)
1107 && (S_ISREG(statbuf->st_mode))) {
1109 char buffer[BUFSIZ];
1110 ssize_t size=0, readSize=0;
1112 /* open the file we want to archive, and make sure all is well */
1113 if ((inputFileFd = open(fileName, O_RDONLY)) < 0) {
1114 error_msg("%s: Cannot open: %s\n", fileName, strerror(errno));
1118 /* write the file to the archive */
1119 while ( (size = full_read(inputFileFd, buffer, sizeof(buffer))) > 0 ) {
1120 if (full_write(tbInfo->tarFd, buffer, size) != size ) {
1121 /* Output file seems to have a problem */
1122 error_msg(io_error, fileName, strerror(errno));
1128 error_msg(io_error, fileName, strerror(errno));
1131 /* Pad the file up to the tar block size */
1132 for (; (readSize%TAR_BLOCK_SIZE) != 0; readSize++) {
1133 write(tbInfo->tarFd, "\0", 1);
1135 close( inputFileFd);
1141 static int writeTarFile(const char* tarName, int verboseFlag, char **argv,
1145 int errorFlag=FALSE;
1147 struct TarBallInfo tbInfo;
1148 tbInfo.verboseFlag = verboseFlag;
1149 tbInfo.hlInfoHead = NULL;
1151 /* Make sure there is at least one file to tar up. */
1153 error_msg_and_die("Cowardly refusing to create an empty archive\n");
1155 /* Open the tar file for writing. */
1156 if (!strcmp(tarName, "-"))
1157 tbInfo.tarFd = fileno(stdout);
1159 tbInfo.tarFd = open (tarName, O_WRONLY | O_CREAT | O_TRUNC, 0644);
1160 if (tbInfo.tarFd < 0) {
1161 perror_msg( "Error opening '%s'", tarName);
1162 freeHardLinkInfo(&tbInfo.hlInfoHead);
1165 tbInfo.excludeList=excludeList;
1166 /* Store the stat info for the tarball's file, so
1167 * can avoid including the tarball into itself.... */
1168 if (fstat(tbInfo.tarFd, &tbInfo.statBuf) < 0)
1169 error_msg_and_die(io_error, tarName, strerror(errno));
1171 /* Set the umask for this process so it doesn't
1172 * screw up permission setting for us later. */
1175 /* Read the directory/files and iterate over them one at a time */
1176 while (*argv != NULL) {
1177 if (recursive_action(*argv++, TRUE, FALSE, FALSE,
1178 writeFileToTarball, writeFileToTarball,
1179 (void*) &tbInfo) == FALSE) {
1183 /* Write two empty blocks to the end of the archive */
1184 for (size=0; size<(2*TAR_BLOCK_SIZE); size++) {
1185 write(tbInfo.tarFd, "\0", 1);
1188 /* To be pedantically correct, we would check if the tarball
1189 * is smaller than 20 tar blocks, and pad it if it was smaller,
1190 * but that isn't necessary for GNU tar interoperability, and
1191 * so is considered a waste of space */
1193 /* Hang up the tools, close up shop, head home */
1195 if (errorFlag == TRUE) {
1196 error_msg("Error exit delayed from previous errors\n");
1197 freeHardLinkInfo(&tbInfo.hlInfoHead);
1200 freeHardLinkInfo(&tbInfo.hlInfoHead);