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 -[cxtvOf] [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);
602 * There is a file to write.
603 * First create the path to it if necessary with default permissions.
605 createPath (outName, 0777);
607 inHeader = (size == 0)? TRUE : FALSE;
611 * Start the output file.
613 if (tostdoutFlag == TRUE)
614 outFd = fileno(stdout);
616 if ( S_ISCHR(mode) || S_ISBLK(mode) || S_ISSOCK(mode) ) {
618 outFd = mknod (outName, mode, makedev(major, minor) );
620 else if (S_ISFIFO(mode) ) {
622 outFd = mkfifo(outName, mode);
624 outFd = open (outName, O_WRONLY | O_CREAT | O_TRUNC, mode);
631 /* Set the file time */
634 utime (outName, &utb);
635 /* Set the file permissions */
636 chown(outName, uid, gid);
637 chmod(outName, mode);
642 * If the file is empty, then that's all we need to do.
644 if (size == 0 && (tostdoutFlag == FALSE) && (devFileFlag == FALSE)) {
652 * Handle a data block of some specified size that was read.
654 static void readData (const char *cp, int count)
657 * Reduce the amount of data left in this file.
658 * If there is no more data left, then we need to read
667 * If we aren't extracting files or this file is being
668 * skipped then do nothing more.
670 if (extractFlag==FALSE || skipFileFlag==TRUE)
674 * Write the data to the output file.
676 if (fullWrite (outFd, cp, count) < 0) {
678 if (tostdoutFlag == FALSE) {
687 * Check if we are done writing to the file now.
689 if (dataCc <= 0 && tostdoutFlag == FALSE) {
694 /* Set the file time */
697 utime (outName, &utb);
698 /* Set the file permissions */
699 chown(outName, uid, gid);
700 chmod(outName, mode);
708 * See if the specified file name belongs to one of the specified list
709 * of path prefixes. An empty list implies that all files are wanted.
710 * Returns TRUE if the file is selected.
713 wantFileName (const char *fileName, int fileCount, char **fileTable)
715 const char *pathName;
720 * If there are no files in the list, then the file is wanted.
725 fileLength = strlen (fileName);
728 * Check each of the test paths.
730 while (fileCount-- > 0) {
731 pathName = *fileTable++;
733 pathLength = strlen (pathName);
735 if (fileLength < pathLength)
738 if (memcmp (fileName, pathName, pathLength) != 0)
741 if ((fileLength == pathLength) || (fileName[pathLength] == '/')) {
750 * Read an octal value in a field of the specified width, with optional
751 * spaces on both sides of the number and with an optional null character
752 * at the end. Returns -1 on an illegal format.
754 static long getOctal (const char *cp, int len)
758 while ((len > 0) && (*cp == ' ')) {
763 if ((len == 0) || !isOctal (*cp))
768 while ((len > 0) && isOctal (*cp)) {
769 val = val * 8 + *cp++ - '0';
773 while ((len > 0) && (*cp == ' ')) {
778 if ((len > 0) && *cp)
787 /* From here to the end of the file is the tar writing stuff.
788 * If you do not have BB_FEATURE_TAR_CREATE defined, this will
791 #ifdef BB_FEATURE_TAR_CREATE
794 * Write a tar file containing the specified files.
796 static void writeTarFile (int fileCount, char **fileTable)
801 * Make sure there is at least one file specified.
803 if (fileCount <= 0) {
804 fprintf (stderr, "No files specified to be saved\n");
809 * Create the tar file for writing.
811 if ((tarName == NULL) || !strcmp (tarName, "-")) {
813 tarFd = fileno(stdout);
815 tarFd = open (tarName, O_WRONLY | O_CREAT | O_TRUNC, 0666);
824 * Get the device and inode of the tar file for checking later.
826 if (fstat (tarFd, &statbuf) < 0) {
832 tarDev = statbuf.st_dev;
833 tarInode = statbuf.st_ino;
836 * Append each file name into the archive file.
837 * Follow symbolic links for these top level file names.
839 while (errorFlag==FALSE && (fileCount-- > 0)) {
840 saveFile (*fileTable++, FALSE);
844 * Now write an empty block of zeroes to end the archive.
846 writeTarBlock ("", 1);
851 * Close the tar file and check for errors if it was opened.
853 if ((tostdoutFlag == FALSE) && (tarFd >= 0) && (close (tarFd) < 0))
858 * Save one file into the tar file.
859 * If the file is a directory, then this will recursively save all of
860 * the files and directories within the directory. The seeLinks
861 * flag indicates whether or not we want to see symbolic links as
862 * they really are, instead of blindly following them.
864 static void saveFile (const char *fileName, int seeLinks)
869 if (verboseFlag==TRUE)
870 printf ("a %s\n", fileName);
873 * Check that the file name will fit in the header.
875 if (strlen (fileName) >= TAR_NAME_SIZE) {
876 fprintf (stderr, "%s: File name is too long\n", fileName);
882 * Find out about the file.
886 status = lstat (fileName, &statbuf);
889 status = stat (fileName, &statbuf);
898 * Make sure we aren't trying to save our file into itself.
900 if ((statbuf.st_dev == tarDev) && (statbuf.st_ino == tarInode)) {
901 fprintf (stderr, "Skipping saving of archive file itself\n");
907 * Check the type of file.
909 mode = statbuf.st_mode;
911 if (S_ISDIR (mode)) {
912 saveDirectory (fileName, &statbuf);
916 if (S_ISREG (mode)) {
917 saveRegularFile (fileName, &statbuf);
922 /* Some day add support for tarring these up... but not today. :) */
923 // if (S_ISLNK(mode) || S_ISFIFO(mode) || S_ISBLK(mode) || S_ISCHR (mode) ) {
924 // fprintf (stderr, "%s: This version of tar can't store this type of file\n", fileName);
928 * The file is a strange type of file, ignore it.
930 fprintf (stderr, "%s: not a directory or regular file\n", fileName);
935 * Save a regular file to the tar file.
938 saveRegularFile (const char *fileName, const struct stat *statbuf)
945 char data[TAR_BLOCK_SIZE * 16];
948 * Open the file for reading.
950 fileFd = open (fileName, O_RDONLY);
959 * Write out the header for the file.
961 writeHeader (fileName, statbuf);
964 * Write the data blocks of the file.
965 * We must be careful to write the amount of data that the stat
966 * buffer indicated, even if the file has changed size. Otherwise
967 * the tar file will be incorrect.
969 fullDataCount = statbuf->st_size;
972 while (fullDataCount > 0) {
974 * Get the amount to write this iteration which is
975 * the minumum of the amount left to write and the
978 dataCount = sizeof (data);
980 if (dataCount > fullDataCount)
981 dataCount = (int) fullDataCount;
984 * Read the data from the file if we haven't seen the
990 cc = fullRead (fileFd, data, dataCount);
995 (void) close (fileFd);
1002 * If the file ended too soon, complain and set
1003 * a flag so we will zero fill the rest of it.
1005 if (cc < dataCount) {
1007 "%s: Short read - zero filling", fileName);
1014 * Zero fill the rest of the data if necessary.
1017 memset (data + cc, 0, dataCount - cc);
1020 * Write the buffer to the TAR file.
1022 writeTarBlock (data, dataCount);
1024 fullDataCount -= dataCount;
1030 if ((tostdoutFlag == FALSE) && close (fileFd) < 0)
1031 fprintf (stderr, "%s: close: %s\n", fileName, strerror (errno));
1036 * Save a directory and all of its files to the tar file.
1038 static void saveDirectory (const char *dirName, const struct stat *statbuf)
1041 struct dirent *entry;
1043 char fullName[NAME_MAX];
1046 * Construct the directory name as used in the tar file by appending
1047 * a slash character to it.
1049 strcpy (fullName, dirName);
1050 strcat (fullName, "/");
1053 * Write out the header for the directory entry.
1055 writeHeader (fullName, statbuf);
1058 * Open the directory.
1060 dir = opendir (dirName);
1063 fprintf (stderr, "Cannot read directory \"%s\": %s\n",
1064 dirName, strerror (errno));
1070 * See if a slash is needed.
1072 needSlash = (*dirName && (dirName[strlen (dirName) - 1] != '/'));
1075 * Read all of the directory entries and check them,
1076 * except for the current and parent directory entries.
1078 while (errorFlag==FALSE && ((entry = readdir (dir)) != NULL)) {
1079 if ((strcmp (entry->d_name, ".") == 0) ||
1080 (strcmp (entry->d_name, "..") == 0)) {
1085 * Build the full path name to the file.
1087 strcpy (fullName, dirName);
1090 strcat (fullName, "/");
1092 strcat (fullName, entry->d_name);
1095 * Write this file to the tar file, noticing whether or not
1096 * the file is a symbolic link.
1098 saveFile (fullName, TRUE);
1102 * All done, close the directory.
1109 * Write a tar header for the specified file name and status.
1110 * It is assumed that the file name fits.
1112 static void writeHeader (const char *fileName, const struct stat *statbuf)
1115 const unsigned char *cp;
1120 * Zero the header block in preparation for filling it in.
1122 memset ((char *) &header, 0, sizeof (header));
1125 * Fill in the header.
1127 strcpy (header.name, fileName);
1129 strncpy (header.magic, TAR_MAGIC, sizeof (header.magic));
1130 strncpy (header.version, TAR_VERSION, sizeof (header.version));
1132 putOctal (header.mode, sizeof (header.mode), statbuf->st_mode & 0777);
1133 putOctal (header.uid, sizeof (header.uid), statbuf->st_uid);
1134 putOctal (header.gid, sizeof (header.gid), statbuf->st_gid);
1135 putOctal (header.size, sizeof (header.size), statbuf->st_size);
1136 putOctal (header.mtime, sizeof (header.mtime), statbuf->st_mtime);
1138 header.typeFlag = TAR_TYPE_REGULAR;
1141 * Calculate and store the checksum.
1142 * This is the sum of all of the bytes of the header,
1143 * with the checksum field itself treated as blanks.
1145 memset (header.checkSum, ' ', sizeof (header.checkSum));
1147 cp = (const unsigned char *) &header;
1148 len = sizeof (header);
1154 putOctal (header.checkSum, sizeof (header.checkSum), checkSum);
1157 * Write the tar header.
1159 writeTarBlock ((const char *) &header, sizeof (header));
1164 * Write data to one or more blocks of the tar file.
1165 * The data is always padded out to a multiple of TAR_BLOCK_SIZE.
1166 * The errorFlag static variable is set on an error.
1168 static void writeTarBlock (const char *buf, int len)
1172 char fullBlock[TAR_BLOCK_SIZE];
1175 * If we had a write error before, then do nothing more.
1177 if (errorFlag==TRUE)
1181 * Get the amount of complete and partial blocks.
1183 partialLength = len % TAR_BLOCK_SIZE;
1184 completeLength = len - partialLength;
1187 * Write all of the complete blocks.
1189 if ((completeLength > 0) && !fullWrite (tarFd, buf, completeLength)) {
1198 * If there are no partial blocks left, we are done.
1200 if (partialLength == 0)
1204 * Copy the partial data into a complete block, and pad the rest
1205 * of it with zeroes.
1207 memcpy (fullBlock, buf + completeLength, partialLength);
1208 memset (fullBlock + partialLength, 0, TAR_BLOCK_SIZE - partialLength);
1211 * Write the last complete block.
1213 if (!fullWrite (tarFd, fullBlock, TAR_BLOCK_SIZE)) {
1222 * Put an octal string into the specified buffer.
1223 * The number is zero and space padded and possibly null padded.
1224 * Returns TRUE if successful.
1226 static int putOctal (char *cp, int len, long value)
1230 char tempBuffer[32];
1233 * Create a string of the specified length with an initial space,
1234 * leading zeroes and the octal number, and a trailing null.
1236 tempString = tempBuffer;
1238 sprintf (tempString, " %0*lo", len - 2, value);
1240 tempLength = strlen (tempString) + 1;
1243 * If the string is too large, suppress the leading space.
1245 if (tempLength > len) {
1251 * If the string is still too large, suppress the trailing null.
1253 if (tempLength > len)
1257 * If the string is still too large, fail.
1259 if (tempLength > len)
1263 * Copy the string to the field.
1265 memcpy (cp, tempString, len);