2 * Mini tar implementation for busybox based on code taken from sash.
4 * Copyright (c) 1999 by David I. Bell
5 * Permission is granted to use, distribute, or modify this source,
6 * provided that this copyright notice remains intact.
8 * Permission to distribute this code under the GPL has been granted.
10 * Modified for busybox by Erik Andersen <andersee@debian.org>
11 * Adjusted to grok stdin/stdout options.
13 * Modified to handle device special files by Matt Porter
16 * This program is free software; you can redistribute it and/or modify
17 * it under the terms of the GNU General Public License as published by
18 * the Free Software Foundation; either version 2 of the License, or
19 * (at your option) any later version.
21 * This program is distributed in the hope that it will be useful,
22 * but WITHOUT ANY WARRANTY; without even the implied warranty of
23 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
24 * General Public License for more details.
26 * You should have received a copy of the GNU General Public License
27 * along with this program; if not, write to the Free Software
28 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
41 #include <sys/types.h>
42 #include <sys/sysmacros.h>
45 #ifdef BB_FEATURE_TAR_CREATE
47 static const char tar_usage[] =
48 "tar -[cxtvOf] [tarFileName] [FILE] ...\n\n"
49 "Create, extract, or list files from a tar file.\n\n"
51 "\tc=create, x=extract, t=list contents, v=verbose,\n"
52 "\tO=extract to stdout, f=tarfile or \"-\" for stdin\n";
56 static const char tar_usage[] =
57 "tar -[xtvOf] [tarFileName] [FILE] ...\n\n"
58 "Extract, or list files stored in a tar file. This\n"
59 "version of tar does not support creation of tar files.\n\n"
61 "\tx=extract, t=list contents, v=verbose,\n"
62 "\tO=extract to stdout, f=tarfile or \"-\" for stdin\n";
70 #define TAR_BLOCK_SIZE 512
71 #define TAR_NAME_SIZE 100
75 * The POSIX (and basic GNU) tar header format.
76 * This structure is always embedded in a TAR_BLOCK_SIZE sized block
77 * with zero padding. We only process this information minimally.
80 char name[TAR_NAME_SIZE];
88 char linkName[TAR_NAME_SIZE];
98 #define TAR_MAGIC "ustar"
99 #define TAR_VERSION "00"
101 #define TAR_TYPE_REGULAR '0'
102 #define TAR_TYPE_HARD_LINK '1'
103 #define TAR_TYPE_SOFT_LINK '2'
110 static int extractFlag;
111 static int createFlag;
112 static int verboseFlag;
113 static int tostdoutFlag;
115 static int inHeader; // <- check me
116 static int badHeader;
117 static int errorFlag;
118 static int skipFileFlag;
119 static int warnedRoot;
123 static const char *outName;
131 * Static data associated with the tar file.
133 static const char *tarName;
136 static ino_t tarInode;
140 * Local procedures to restore files from a tar file.
142 static void readTarFile (int fileCount, char **fileTable);
143 static void readData (const char *cp, int count);
144 static long getOctal (const char *cp, int len);
146 static void readHeader (const TarHeader * hp,
147 int fileCount, char **fileTable);
149 static int wantFileName (const char *fileName,
150 int fileCount, char **fileTable);
152 #ifdef BB_FEATURE_TAR_CREATE
154 * Local procedures to save files into a tar file.
156 static void saveFile (const char *fileName, int seeLinks);
158 static void saveRegularFile (const char *fileName,
159 const struct stat *statbuf);
161 static void saveDirectory (const char *fileName,
162 const struct stat *statbuf);
164 static void writeHeader (const char *fileName, const struct stat *statbuf);
166 static void writeTarFile (int fileCount, char **fileTable);
167 static void writeTarBlock (const char *buf, int len);
168 static int putOctal (char *cp, int len, long value);
173 extern int tar_main (int argc, char **argv)
189 tostdoutFlag = FALSE;
199 options = (*argv++) + 1;
204 for (; *options; options++) {
207 if (tarName != NULL) {
208 fprintf (stderr, "Only one 'f' option allowed\n");
219 if (extractFlag == TRUE || createFlag == TRUE )
225 if (listFlag == TRUE || createFlag == TRUE )
230 if (extractFlag == TRUE || listFlag == TRUE)
248 fprintf (stderr, "Unknown tar flag '%c'\n"
249 "Try `tar --help' for more information\n",
256 * Do the correct type of action supplying the rest of the
257 * command line arguments as the list of files to process.
259 if (createFlag==TRUE) {
260 #ifndef BB_FEATURE_TAR_CREATE
261 fprintf (stderr, "This version of tar was not compiled with tar creation support.\n" );
264 writeTarFile (argc, argv);
267 readTarFile (argc, argv);
269 if (errorFlag==TRUE) {
270 fprintf (stderr, "\n");
275 fprintf (stderr, "Exactly one of 'c', 'x' or 't' must be specified\n");
281 * Read a tar file and extract or list the specified files within it.
282 * If the list is empty than all files are extracted or listed.
284 static void readTarFile (int fileCount, char **fileTable)
292 skipFileFlag = FALSE;
300 blockSize = sizeof (buf);
304 * Open the tar file for reading.
306 if ((tarName == NULL) || !strcmp (tarName, "-")) {
307 tarFd = fileno(stdin);
309 tarFd = open (tarName, O_RDONLY);
318 * Read blocks from the file until an end of file header block
319 * has been seen. (A real end of file from a read is an error.)
321 while (eofFlag==FALSE) {
323 * Read the next block of data if necessary.
324 * This will be a large block if possible, which we will
325 * then process in the small tar blocks.
329 inCc = fullRead (tarFd, buf, blockSize);
339 "Unexpected end of file from \"%s\"", tarName);
346 * If we are expecting a header block then examine it.
348 if (inHeader==TRUE) {
349 readHeader ((const TarHeader *) cp, fileCount, fileTable);
351 cp += TAR_BLOCK_SIZE;
352 inCc -= TAR_BLOCK_SIZE;
358 * We are currently handling the data for a file.
359 * Process the minimum of the amount of data we have available
360 * and the amount left to be processed for the file.
370 * If the amount left isn't an exact multiple of the tar block
371 * size then round it up to the next block boundary since there
372 * is padding at the end of the file.
374 if (cc % TAR_BLOCK_SIZE)
375 cc += TAR_BLOCK_SIZE - (cc % TAR_BLOCK_SIZE);
383 * Close the tar file if needed.
385 if ((tarFd >= 0) && (close (tarFd) < 0))
389 * Close the output file if needed.
390 * This is only done here on a previous error and so no
391 * message is required on errors.
393 if (tostdoutFlag == FALSE) {
402 * Examine the header block that was just read.
403 * This can specify the information for another file, or it can mark
404 * the end of the tar file.
407 readHeader (const TarHeader * hp, int fileCount, char **fileTable)
420 * If the block is completely empty, then this is the end of the
421 * archive file. If the name is null, then just skip this header.
425 if (*outName == '\0') {
426 for (cc = TAR_BLOCK_SIZE; cc > 0; cc--) {
437 * There is another file in the archive to examine.
438 * Extract the encoded information and check it.
440 mode = getOctal (hp->mode, sizeof (hp->mode));
441 uid = getOctal (hp->uid, sizeof (hp->uid));
442 gid = getOctal (hp->gid, sizeof (hp->gid));
443 size = getOctal (hp->size, sizeof (hp->size));
444 mtime = getOctal (hp->mtime, sizeof (hp->mtime));
445 checkSum = getOctal (hp->checkSum, sizeof (hp->checkSum));
446 major = getOctal (hp->devMajor, sizeof (hp->devMajor));
447 minor = getOctal (hp->devMinor, sizeof (hp->devMinor));
449 if ((mode < 0) || (uid < 0) || (gid < 0) || (size < 0)) {
450 if (badHeader==FALSE)
451 fprintf (stderr, "Bad tar header, skipping\n");
459 skipFileFlag = FALSE;
463 * Check for the file modes.
465 hardLink = ((hp->typeFlag == TAR_TYPE_HARD_LINK) ||
466 (hp->typeFlag == TAR_TYPE_HARD_LINK - '0'));
468 softLink = ((hp->typeFlag == TAR_TYPE_SOFT_LINK) ||
469 (hp->typeFlag == TAR_TYPE_SOFT_LINK - '0'));
472 * Check for a directory.
474 if (outName[strlen (outName) - 1] == '/')
478 * Check for absolute paths in the file.
479 * If we find any, then warn the user and make them relative.
481 if (*outName == '/') {
482 while (*outName == '/')
485 if (warnedRoot==FALSE) {
487 "Absolute path detected, removing leading slashes\n");
494 * See if we want this file to be restored.
495 * If not, then set up to skip it.
497 if (wantFileName (outName, fileCount, fileTable) == FALSE) {
498 if ( !hardLink && !softLink && (S_ISREG (mode) || S_ISCHR (mode)
499 || S_ISBLK (mode) || S_ISSOCK(mode) || S_ISFIFO(mode) ) ) {
500 inHeader = (size == 0)? TRUE : FALSE;
510 * This file is to be handled.
511 * If we aren't extracting then just list information about the file.
513 if (extractFlag==FALSE) {
514 if (verboseFlag==TRUE) {
515 printf ("%s %3d/%-d ", modeString (mode), uid, gid);
516 if( S_ISCHR (mode) || S_ISBLK (mode) )
517 printf ("%4d,%4d %s ", major,minor, timeString (mtime));
519 printf ("%9ld %s ", size, timeString (mtime));
521 printf ("%s", outName);
524 printf (" (link to \"%s\")", hp->linkName);
526 printf (" (symlink to \"%s\")", hp->linkName);
527 else if (S_ISREG (mode) || S_ISCHR (mode) || S_ISBLK (mode) ||
528 S_ISSOCK(mode) || S_ISFIFO(mode) ) {
529 inHeader = (size == 0)? TRUE : FALSE;
539 * We really want to extract the file.
541 if (verboseFlag==TRUE)
542 printf ("x %s\n", outName);
545 if (link (hp->linkName, outName) < 0) {
549 /* Set the file time */
552 utime (outName, &utb);
553 /* Set the file permissions */
554 chown(outName, uid, gid);
555 chmod(outName, mode);
561 if (symlink (hp->linkName, outName) < 0) {
565 /* Try to change ownership of the symlink.
566 * If libs doesn't support that, don't bother.
567 * Changing the pointed-to file is the Wrong Thing(tm).
569 #if (__GLIBC__ >= 2) && (__GLIBC_MINOR__ >= 1)
570 lchown(outName, uid, gid);
573 /* Do not change permissions or date on symlink,
574 * since it changes the pointed to file instead. duh. */
576 fprintf (stderr, "Cannot create symbolic links\n");
581 /* Set the umask for this process so it doesn't
582 * screw things up. */
586 * If the file is a directory, then just create the path.
588 if (S_ISDIR (mode)) {
589 if (createPath (outName, mode)==TRUE) {
590 /* Set the file time */
593 utime (outName, &utb);
594 /* Set the file permissions */
595 chown(outName, uid, gid);
596 chmod(outName, mode);
603 * There is a file to write.
604 * First create the path to it if necessary with default permissions.
606 createPath (outName, 0777);
608 inHeader = (size == 0)? TRUE : FALSE;
612 * Start the output file.
614 if (tostdoutFlag == TRUE)
615 outFd = fileno(stdout);
617 if ( S_ISCHR(mode) || S_ISBLK(mode) || S_ISSOCK(mode) ) {
619 outFd = mknod (outName, mode, makedev(major, minor) );
621 else if (S_ISFIFO(mode) ) {
623 outFd = mkfifo(outName, mode);
625 outFd = open (outName, O_WRONLY | O_CREAT | O_TRUNC, mode);
632 /* Set the file time */
635 utime (outName, &utb);
636 /* Set the file permissions */
637 chown(outName, uid, gid);
638 chmod(outName, mode);
643 * If the file is empty, then that's all we need to do.
645 if (size == 0 && (tostdoutFlag == FALSE) && (devFileFlag == FALSE)) {
653 * Handle a data block of some specified size that was read.
655 static void readData (const char *cp, int count)
658 * Reduce the amount of data left in this file.
659 * If there is no more data left, then we need to read
668 * If we aren't extracting files or this file is being
669 * skipped then do nothing more.
671 if (extractFlag==FALSE || skipFileFlag==TRUE)
675 * Write the data to the output file.
677 if (fullWrite (outFd, cp, count) < 0) {
679 if (tostdoutFlag == FALSE) {
688 * Check if we are done writing to the file now.
690 if (dataCc <= 0 && tostdoutFlag == FALSE) {
695 /* Set the file time */
698 utime (outName, &utb);
699 /* Set the file permissions */
700 chown(outName, uid, gid);
701 chmod(outName, mode);
709 * See if the specified file name belongs to one of the specified list
710 * of path prefixes. An empty list implies that all files are wanted.
711 * Returns TRUE if the file is selected.
714 wantFileName (const char *fileName, int fileCount, char **fileTable)
716 const char *pathName;
721 * If there are no files in the list, then the file is wanted.
726 fileLength = strlen (fileName);
729 * Check each of the test paths.
731 while (fileCount-- > 0) {
732 pathName = *fileTable++;
734 pathLength = strlen (pathName);
736 if (fileLength < pathLength)
739 if (memcmp (fileName, pathName, pathLength) != 0)
742 if ((fileLength == pathLength) || (fileName[pathLength] == '/')) {
751 * Read an octal value in a field of the specified width, with optional
752 * spaces on both sides of the number and with an optional null character
753 * at the end. Returns -1 on an illegal format.
755 static long getOctal (const char *cp, int len)
759 while ((len > 0) && (*cp == ' ')) {
764 if ((len == 0) || !isOctal (*cp))
769 while ((len > 0) && isOctal (*cp)) {
770 val = val * 8 + *cp++ - '0';
774 while ((len > 0) && (*cp == ' ')) {
779 if ((len > 0) && *cp)
788 /* From here to the end of the file is the tar writing stuff.
789 * If you do not have BB_FEATURE_TAR_CREATE defined, this will
792 #ifdef BB_FEATURE_TAR_CREATE
795 * Write a tar file containing the specified files.
797 static void writeTarFile (int fileCount, char **fileTable)
802 * Make sure there is at least one file specified.
804 if (fileCount <= 0) {
805 fprintf (stderr, "No files specified to be saved\n");
810 * Create the tar file for writing.
812 if ((tarName == NULL) || !strcmp (tarName, "-")) {
814 tarFd = fileno(stdout);
816 tarFd = open (tarName, O_WRONLY | O_CREAT | O_TRUNC, 0666);
825 * Get the device and inode of the tar file for checking later.
827 if (fstat (tarFd, &statbuf) < 0) {
833 tarDev = statbuf.st_dev;
834 tarInode = statbuf.st_ino;
837 * Append each file name into the archive file.
838 * Follow symbolic links for these top level file names.
840 while (errorFlag==FALSE && (fileCount-- > 0)) {
841 saveFile (*fileTable++, FALSE);
845 * Now write an empty block of zeroes to end the archive.
847 writeTarBlock ("", 1);
852 * Close the tar file and check for errors if it was opened.
854 if ((tostdoutFlag == FALSE) && (tarFd >= 0) && (close (tarFd) < 0))
859 * Save one file into the tar file.
860 * If the file is a directory, then this will recursively save all of
861 * the files and directories within the directory. The seeLinks
862 * flag indicates whether or not we want to see symbolic links as
863 * they really are, instead of blindly following them.
865 static void saveFile (const char *fileName, int seeLinks)
870 if (verboseFlag==TRUE)
871 printf ("a %s\n", fileName);
874 * Check that the file name will fit in the header.
876 if (strlen (fileName) >= TAR_NAME_SIZE) {
877 fprintf (stderr, "%s: File name is too long\n", fileName);
883 * Find out about the file.
887 status = lstat (fileName, &statbuf);
890 status = stat (fileName, &statbuf);
899 * Make sure we aren't trying to save our file into itself.
901 if ((statbuf.st_dev == tarDev) && (statbuf.st_ino == tarInode)) {
902 fprintf (stderr, "Skipping saving of archive file itself\n");
908 * Check the type of file.
910 mode = statbuf.st_mode;
912 if (S_ISDIR (mode)) {
913 saveDirectory (fileName, &statbuf);
917 if (S_ISREG (mode)) {
918 saveRegularFile (fileName, &statbuf);
923 /* Some day add support for tarring these up... but not today. :) */
924 // if (S_ISLNK(mode) || S_ISFIFO(mode) || S_ISBLK(mode) || S_ISCHR (mode) ) {
925 // fprintf (stderr, "%s: This version of tar can't store this type of file\n", fileName);
929 * The file is a strange type of file, ignore it.
931 fprintf (stderr, "%s: not a directory or regular file\n", fileName);
936 * Save a regular file to the tar file.
939 saveRegularFile (const char *fileName, const struct stat *statbuf)
946 char data[TAR_BLOCK_SIZE * 16];
949 * Open the file for reading.
951 fileFd = open (fileName, O_RDONLY);
960 * Write out the header for the file.
962 writeHeader (fileName, statbuf);
965 * Write the data blocks of the file.
966 * We must be careful to write the amount of data that the stat
967 * buffer indicated, even if the file has changed size. Otherwise
968 * the tar file will be incorrect.
970 fullDataCount = statbuf->st_size;
973 while (fullDataCount > 0) {
975 * Get the amount to write this iteration which is
976 * the minumum of the amount left to write and the
979 dataCount = sizeof (data);
981 if (dataCount > fullDataCount)
982 dataCount = (int) fullDataCount;
985 * Read the data from the file if we haven't seen the
991 cc = fullRead (fileFd, data, dataCount);
996 (void) close (fileFd);
1003 * If the file ended too soon, complain and set
1004 * a flag so we will zero fill the rest of it.
1006 if (cc < dataCount) {
1008 "%s: Short read - zero filling", fileName);
1015 * Zero fill the rest of the data if necessary.
1018 memset (data + cc, 0, dataCount - cc);
1021 * Write the buffer to the TAR file.
1023 writeTarBlock (data, dataCount);
1025 fullDataCount -= dataCount;
1031 if ((tostdoutFlag == FALSE) && close (fileFd) < 0)
1032 fprintf (stderr, "%s: close: %s\n", fileName, strerror (errno));
1037 * Save a directory and all of its files to the tar file.
1039 static void saveDirectory (const char *dirName, const struct stat *statbuf)
1042 struct dirent *entry;
1044 char fullName[NAME_MAX];
1047 * Construct the directory name as used in the tar file by appending
1048 * a slash character to it.
1050 strcpy (fullName, dirName);
1051 strcat (fullName, "/");
1054 * Write out the header for the directory entry.
1056 writeHeader (fullName, statbuf);
1059 * Open the directory.
1061 dir = opendir (dirName);
1064 fprintf (stderr, "Cannot read directory \"%s\": %s\n",
1065 dirName, strerror (errno));
1071 * See if a slash is needed.
1073 needSlash = (*dirName && (dirName[strlen (dirName) - 1] != '/'));
1076 * Read all of the directory entries and check them,
1077 * except for the current and parent directory entries.
1079 while (errorFlag==FALSE && ((entry = readdir (dir)) != NULL)) {
1080 if ((strcmp (entry->d_name, ".") == 0) ||
1081 (strcmp (entry->d_name, "..") == 0)) {
1086 * Build the full path name to the file.
1088 strcpy (fullName, dirName);
1091 strcat (fullName, "/");
1093 strcat (fullName, entry->d_name);
1096 * Write this file to the tar file, noticing whether or not
1097 * the file is a symbolic link.
1099 saveFile (fullName, TRUE);
1103 * All done, close the directory.
1110 * Write a tar header for the specified file name and status.
1111 * It is assumed that the file name fits.
1113 static void writeHeader (const char *fileName, const struct stat *statbuf)
1116 const unsigned char *cp;
1121 * Zero the header block in preparation for filling it in.
1123 memset ((char *) &header, 0, sizeof (header));
1126 * Fill in the header.
1128 strcpy (header.name, fileName);
1130 strncpy (header.magic, TAR_MAGIC, sizeof (header.magic));
1131 strncpy (header.version, TAR_VERSION, sizeof (header.version));
1133 putOctal (header.mode, sizeof (header.mode), statbuf->st_mode & 0777);
1134 putOctal (header.uid, sizeof (header.uid), statbuf->st_uid);
1135 putOctal (header.gid, sizeof (header.gid), statbuf->st_gid);
1136 putOctal (header.size, sizeof (header.size), statbuf->st_size);
1137 putOctal (header.mtime, sizeof (header.mtime), statbuf->st_mtime);
1139 header.typeFlag = TAR_TYPE_REGULAR;
1142 * Calculate and store the checksum.
1143 * This is the sum of all of the bytes of the header,
1144 * with the checksum field itself treated as blanks.
1146 memset (header.checkSum, ' ', sizeof (header.checkSum));
1148 cp = (const unsigned char *) &header;
1149 len = sizeof (header);
1155 putOctal (header.checkSum, sizeof (header.checkSum), checkSum);
1158 * Write the tar header.
1160 writeTarBlock ((const char *) &header, sizeof (header));
1165 * Write data to one or more blocks of the tar file.
1166 * The data is always padded out to a multiple of TAR_BLOCK_SIZE.
1167 * The errorFlag static variable is set on an error.
1169 static void writeTarBlock (const char *buf, int len)
1173 char fullBlock[TAR_BLOCK_SIZE];
1176 * If we had a write error before, then do nothing more.
1178 if (errorFlag==TRUE)
1182 * Get the amount of complete and partial blocks.
1184 partialLength = len % TAR_BLOCK_SIZE;
1185 completeLength = len - partialLength;
1188 * Write all of the complete blocks.
1190 if ((completeLength > 0) && !fullWrite (tarFd, buf, completeLength)) {
1199 * If there are no partial blocks left, we are done.
1201 if (partialLength == 0)
1205 * Copy the partial data into a complete block, and pad the rest
1206 * of it with zeroes.
1208 memcpy (fullBlock, buf + completeLength, partialLength);
1209 memset (fullBlock + partialLength, 0, TAR_BLOCK_SIZE - partialLength);
1212 * Write the last complete block.
1214 if (!fullWrite (tarFd, fullBlock, TAR_BLOCK_SIZE)) {
1223 * Put an octal string into the specified buffer.
1224 * The number is zero and space padded and possibly null padded.
1225 * Returns TRUE if successful.
1227 static int putOctal (char *cp, int len, long value)
1231 char tempBuffer[32];
1234 * Create a string of the specified length with an initial space,
1235 * leading zeroes and the octal number, and a trailing null.
1237 tempString = tempBuffer;
1239 sprintf (tempString, " %0*lo", len - 2, value);
1241 tempLength = strlen (tempString) + 1;
1244 * If the string is too large, suppress the leading space.
1246 if (tempLength > len) {
1252 * If the string is still too large, suppress the trailing null.
1254 if (tempLength > len)
1258 * If the string is still too large, fail.
1260 if (tempLength > len)
1264 * Copy the string to the field.
1266 memcpy (cp, tempString, len);