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 #ifdef BB_FEATURE_TAR_CREATE
112 static int createFlag;
114 static int verboseFlag;
115 static int tostdoutFlag;
117 static int inHeader; // <- check me
118 static int badHeader;
119 static int errorFlag;
120 static int skipFileFlag;
121 static int warnedRoot;
125 static const char *outName;
133 * Static data associated with the tar file.
135 static const char *tarName;
138 static ino_t tarInode;
142 * Local procedures to restore files from a tar file.
144 static void readTarFile (int fileCount, char **fileTable);
145 static void readData (const char *cp, int count);
146 static long getOctal (const char *cp, int len);
148 static void readHeader (const TarHeader * hp,
149 int fileCount, char **fileTable);
151 static int wantFileName (const char *fileName,
152 int fileCount, char **fileTable);
154 #ifdef BB_FEATURE_TAR_CREATE
156 * Local procedures to save files into a tar file.
158 static void saveFile (const char *fileName, int seeLinks);
160 static void saveRegularFile (const char *fileName,
161 const struct stat *statbuf);
163 static void saveDirectory (const char *fileName,
164 const struct stat *statbuf);
166 static void writeHeader (const char *fileName, const struct stat *statbuf);
168 static void writeTarFile (int fileCount, char **fileTable);
169 static void writeTarBlock (const char *buf, int len);
170 static int putOctal (char *cp, int len, long value);
175 extern int tar_main (int argc, char **argv)
188 #ifdef BB_FEATURE_TAR_CREATE
193 tostdoutFlag = FALSE;
203 options = (*argv++) + 1;
205 for (; *options; options++) {
208 if (tarName != NULL) {
209 fprintf (stderr, "Only one 'f' option allowed\n");
226 #ifdef BB_FEATURE_TAR_CREATE
232 fprintf (stderr, "This version of tar was not compiled with tar creation support.\n" );
250 fprintf (stderr, "Unknown tar flag '%c'\n"
251 "Try `tar --help' for more information\n",
260 * Validate the options.
262 if (extractFlag + listFlag
263 #ifdef BB_FEATURE_TAR_CREATE
266 != (TRUE+FALSE+FALSE)) {
268 "Exactly one of 'c', 'x' or 't' must be specified\n");
274 * Do the correct type of action supplying the rest of the
275 * command line arguments as the list of files to process.
277 #ifdef BB_FEATURE_TAR_CREATE
278 if (createFlag==TRUE)
279 writeTarFile (argc, argv);
282 readTarFile (argc, argv);
284 fprintf (stderr, "\n");
290 * Read a tar file and extract or list the specified files within it.
291 * If the list is empty than all files are extracted or listed.
293 static void readTarFile (int fileCount, char **fileTable)
301 skipFileFlag = FALSE;
309 blockSize = sizeof (buf);
313 * Open the tar file for reading.
315 if ((tarName == NULL) || !strcmp (tarName, "-")) {
316 tarFd = fileno(stdin);
318 tarFd = open (tarName, O_RDONLY);
327 * Read blocks from the file until an end of file header block
328 * has been seen. (A real end of file from a read is an error.)
330 while (eofFlag==FALSE) {
332 * Read the next block of data if necessary.
333 * This will be a large block if possible, which we will
334 * then process in the small tar blocks.
338 inCc = fullRead (tarFd, buf, blockSize);
348 "Unexpected end of file from \"%s\"", tarName);
355 * If we are expecting a header block then examine it.
357 if (inHeader==TRUE) {
358 readHeader ((const TarHeader *) cp, fileCount, fileTable);
360 cp += TAR_BLOCK_SIZE;
361 inCc -= TAR_BLOCK_SIZE;
367 * We are currently handling the data for a file.
368 * Process the minimum of the amount of data we have available
369 * and the amount left to be processed for the file.
379 * If the amount left isn't an exact multiple of the tar block
380 * size then round it up to the next block boundary since there
381 * is padding at the end of the file.
383 if (cc % TAR_BLOCK_SIZE)
384 cc += TAR_BLOCK_SIZE - (cc % TAR_BLOCK_SIZE);
392 * Close the tar file if needed.
394 if ((tarFd >= 0) && (close (tarFd) < 0))
398 * Close the output file if needed.
399 * This is only done here on a previous error and so no
400 * message is required on errors.
402 if (tostdoutFlag == FALSE) {
411 * Examine the header block that was just read.
412 * This can specify the information for another file, or it can mark
413 * the end of the tar file.
416 readHeader (const TarHeader * hp, int fileCount, char **fileTable)
429 * If the block is completely empty, then this is the end of the
430 * archive file. If the name is null, then just skip this header.
434 if (*outName == '\0') {
435 for (cc = TAR_BLOCK_SIZE; cc > 0; cc--) {
446 * There is another file in the archive to examine.
447 * Extract the encoded information and check it.
449 mode = getOctal (hp->mode, sizeof (hp->mode));
450 uid = getOctal (hp->uid, sizeof (hp->uid));
451 gid = getOctal (hp->gid, sizeof (hp->gid));
452 size = getOctal (hp->size, sizeof (hp->size));
453 mtime = getOctal (hp->mtime, sizeof (hp->mtime));
454 checkSum = getOctal (hp->checkSum, sizeof (hp->checkSum));
455 major = getOctal (hp->devMajor, sizeof (hp->devMajor));
456 minor = getOctal (hp->devMinor, sizeof (hp->devMinor));
458 if ((mode < 0) || (uid < 0) || (gid < 0) || (size < 0)) {
459 if (badHeader==FALSE)
460 fprintf (stderr, "Bad tar header, skipping\n");
468 skipFileFlag = FALSE;
472 * Check for the file modes.
474 hardLink = ((hp->typeFlag == TAR_TYPE_HARD_LINK) ||
475 (hp->typeFlag == TAR_TYPE_HARD_LINK - '0'));
477 softLink = ((hp->typeFlag == TAR_TYPE_SOFT_LINK) ||
478 (hp->typeFlag == TAR_TYPE_SOFT_LINK - '0'));
481 * Check for a directory.
483 if (outName[strlen (outName) - 1] == '/')
487 * Check for absolute paths in the file.
488 * If we find any, then warn the user and make them relative.
490 if (*outName == '/') {
491 while (*outName == '/')
494 if (warnedRoot==FALSE) {
496 "Absolute path detected, removing leading slashes\n");
503 * See if we want this file to be restored.
504 * If not, then set up to skip it.
506 if (wantFileName (outName, fileCount, fileTable) == FALSE) {
507 if ( !hardLink && !softLink && (S_ISREG (mode) || S_ISCHR (mode)
508 || S_ISBLK (mode) || S_ISSOCK(mode) || S_ISFIFO(mode) ) ) {
509 inHeader = (size == 0)? TRUE : FALSE;
519 * This file is to be handled.
520 * If we aren't extracting then just list information about the file.
522 if (extractFlag==FALSE) {
523 if (verboseFlag==TRUE) {
524 printf ("%s %3d/%-d ", modeString (mode), uid, gid);
525 if( S_ISCHR (mode) || S_ISBLK (mode) )
526 printf ("%4d,%4d %s ", major,minor, timeString (mtime));
528 printf ("%9ld %s ", size, timeString (mtime));
530 printf ("%s", outName);
533 printf (" (link to \"%s\")", hp->linkName);
535 printf (" (symlink to \"%s\")", hp->linkName);
536 else if (S_ISREG (mode) || S_ISCHR (mode) || S_ISBLK (mode) ||
537 S_ISSOCK(mode) || S_ISFIFO(mode) ) {
538 inHeader = (size == 0)? TRUE : FALSE;
548 * We really want to extract the file.
550 if (verboseFlag==TRUE)
551 printf ("x %s\n", outName);
554 if (link (hp->linkName, outName) < 0)
556 /* Set the file time */
559 utime (outName, &utb);
560 /* Set the file permissions */
561 chown(outName, uid, gid);
562 chmod(outName, mode);
568 if (symlink (hp->linkName, outName) < 0)
570 /* Try to change ownership of the symlink.
571 * If libs doesn't support that, don't bother.
572 * Changing the pointed-to file is the Wrong Thing(tm).
574 #if (__GLIBC__ >= 2) && (__GLIBC_MINOR__ >= 1)
575 lchown(outName, uid, gid);
578 /* Do not change permissions or date on symlink,
579 * since it changes the pointed to file instead. duh. */
581 fprintf (stderr, "Cannot create symbolic links\n");
586 /* Set the umask for this process so it doesn't
587 * screw things up. */
591 * If the file is a directory, then just create the path.
593 if (S_ISDIR (mode)) {
594 createPath (outName, mode);
595 /* Set the file time */
598 utime (outName, &utb);
599 /* Set the file permissions */
600 chown(outName, uid, gid);
601 chmod(outName, mode);
606 * There is a file to write.
607 * First create the path to it if necessary with default permissions.
609 createPath (outName, 0777);
611 inHeader = (size == 0)? TRUE : FALSE;
615 * Start the output file.
617 if (tostdoutFlag == TRUE)
618 outFd = fileno(stdout);
620 if ( S_ISCHR(mode) || S_ISBLK(mode) || S_ISSOCK(mode) ) {
622 outFd = mknod (outName, mode, makedev(major, minor) );
624 else if (S_ISFIFO(mode) ) {
626 outFd = mkfifo(outName, mode);
628 outFd = open (outName, O_WRONLY | O_CREAT | O_TRUNC, mode);
635 /* Set the file time */
638 utime (outName, &utb);
639 /* Set the file permissions */
640 chown(outName, uid, gid);
641 chmod(outName, mode);
646 * If the file is empty, then that's all we need to do.
648 if (size == 0 && (tostdoutFlag == FALSE) && (devFileFlag == FALSE)) {
656 * Handle a data block of some specified size that was read.
658 static void readData (const char *cp, int count)
661 * Reduce the amount of data left in this file.
662 * If there is no more data left, then we need to read
671 * If we aren't extracting files or this file is being
672 * skipped then do nothing more.
674 if (extractFlag==FALSE || skipFileFlag==TRUE)
678 * Write the data to the output file.
680 if (fullWrite (outFd, cp, count) < 0) {
682 if (tostdoutFlag == FALSE) {
691 * Check if we are done writing to the file now.
693 if (dataCc <= 0 && tostdoutFlag == FALSE) {
698 /* Set the file time */
701 utime (outName, &utb);
702 /* Set the file permissions */
703 chown(outName, uid, gid);
704 chmod(outName, mode);
712 * See if the specified file name belongs to one of the specified list
713 * of path prefixes. An empty list implies that all files are wanted.
714 * Returns TRUE if the file is selected.
717 wantFileName (const char *fileName, int fileCount, char **fileTable)
719 const char *pathName;
724 * If there are no files in the list, then the file is wanted.
729 fileLength = strlen (fileName);
732 * Check each of the test paths.
734 while (fileCount-- > 0) {
735 pathName = *fileTable++;
737 pathLength = strlen (pathName);
739 if (fileLength < pathLength)
742 if (memcmp (fileName, pathName, pathLength) != 0)
745 if ((fileLength == pathLength) || (fileName[pathLength] == '/')) {
754 * Read an octal value in a field of the specified width, with optional
755 * spaces on both sides of the number and with an optional null character
756 * at the end. Returns -1 on an illegal format.
758 static long getOctal (const char *cp, int len)
762 while ((len > 0) && (*cp == ' ')) {
767 if ((len == 0) || !isOctal (*cp))
772 while ((len > 0) && isOctal (*cp)) {
773 val = val * 8 + *cp++ - '0';
777 while ((len > 0) && (*cp == ' ')) {
782 if ((len > 0) && *cp)
791 /* From here to the end of the file is the tar writing stuff.
792 * If you do not have BB_FEATURE_TAR_CREATE defined, this will
795 #ifdef BB_FEATURE_TAR_CREATE
798 * Write a tar file containing the specified files.
800 static void writeTarFile (int fileCount, char **fileTable)
805 * Make sure there is at least one file specified.
807 if (fileCount <= 0) {
808 fprintf (stderr, "No files specified to be saved\n");
813 * Create the tar file for writing.
815 if ((tarName == NULL) || !strcmp (tarName, "-")) {
817 tarFd = fileno(stdout);
819 tarFd = open (tarName, O_WRONLY | O_CREAT | O_TRUNC, 0666);
828 * Get the device and inode of the tar file for checking later.
830 if (fstat (tarFd, &statbuf) < 0) {
836 tarDev = statbuf.st_dev;
837 tarInode = statbuf.st_ino;
840 * Append each file name into the archive file.
841 * Follow symbolic links for these top level file names.
843 while (errorFlag==FALSE && (fileCount-- > 0)) {
844 saveFile (*fileTable++, FALSE);
848 * Now write an empty block of zeroes to end the archive.
850 writeTarBlock ("", 1);
855 * Close the tar file and check for errors if it was opened.
857 if ((tostdoutFlag == FALSE) && (tarFd >= 0) && (close (tarFd) < 0))
862 * Save one file into the tar file.
863 * If the file is a directory, then this will recursively save all of
864 * the files and directories within the directory. The seeLinks
865 * flag indicates whether or not we want to see symbolic links as
866 * they really are, instead of blindly following them.
868 static void saveFile (const char *fileName, int seeLinks)
873 if (verboseFlag==TRUE)
874 printf ("a %s\n", fileName);
877 * Check that the file name will fit in the header.
879 if (strlen (fileName) >= TAR_NAME_SIZE) {
880 fprintf (stderr, "%s: File name is too long\n", fileName);
886 * Find out about the file.
890 status = lstat (fileName, &statbuf);
893 status = stat (fileName, &statbuf);
902 * Make sure we aren't trying to save our file into itself.
904 if ((statbuf.st_dev == tarDev) && (statbuf.st_ino == tarInode)) {
905 fprintf (stderr, "Skipping saving of archive file itself\n");
911 * Check the type of file.
913 mode = statbuf.st_mode;
915 if (S_ISDIR (mode)) {
916 saveDirectory (fileName, &statbuf);
920 if (S_ISREG (mode)) {
921 saveRegularFile (fileName, &statbuf);
926 /* Some day add support for tarring these up... but not today. :) */
927 // if (S_ISLNK(mode) || S_ISFIFO(mode) || S_ISBLK(mode) || S_ISCHR (mode) ) {
928 // fprintf (stderr, "%s: This version of tar can't store this type of file\n", fileName);
932 * The file is a strange type of file, ignore it.
934 fprintf (stderr, "%s: not a directory or regular file\n", fileName);
939 * Save a regular file to the tar file.
942 saveRegularFile (const char *fileName, const struct stat *statbuf)
949 char data[TAR_BLOCK_SIZE * 16];
952 * Open the file for reading.
954 fileFd = open (fileName, O_RDONLY);
963 * Write out the header for the file.
965 writeHeader (fileName, statbuf);
968 * Write the data blocks of the file.
969 * We must be careful to write the amount of data that the stat
970 * buffer indicated, even if the file has changed size. Otherwise
971 * the tar file will be incorrect.
973 fullDataCount = statbuf->st_size;
976 while (fullDataCount > 0) {
978 * Get the amount to write this iteration which is
979 * the minumum of the amount left to write and the
982 dataCount = sizeof (data);
984 if (dataCount > fullDataCount)
985 dataCount = (int) fullDataCount;
988 * Read the data from the file if we haven't seen the
994 cc = fullRead (fileFd, data, dataCount);
999 (void) close (fileFd);
1006 * If the file ended too soon, complain and set
1007 * a flag so we will zero fill the rest of it.
1009 if (cc < dataCount) {
1011 "%s: Short read - zero filling", fileName);
1018 * Zero fill the rest of the data if necessary.
1021 memset (data + cc, 0, dataCount - cc);
1024 * Write the buffer to the TAR file.
1026 writeTarBlock (data, dataCount);
1028 fullDataCount -= dataCount;
1034 if ((tostdoutFlag == FALSE) && close (fileFd) < 0)
1035 fprintf (stderr, "%s: close: %s\n", fileName, strerror (errno));
1040 * Save a directory and all of its files to the tar file.
1042 static void saveDirectory (const char *dirName, const struct stat *statbuf)
1045 struct dirent *entry;
1047 char fullName[NAME_MAX];
1050 * Construct the directory name as used in the tar file by appending
1051 * a slash character to it.
1053 strcpy (fullName, dirName);
1054 strcat (fullName, "/");
1057 * Write out the header for the directory entry.
1059 writeHeader (fullName, statbuf);
1062 * Open the directory.
1064 dir = opendir (dirName);
1067 fprintf (stderr, "Cannot read directory \"%s\": %s\n",
1068 dirName, strerror (errno));
1074 * See if a slash is needed.
1076 needSlash = (*dirName && (dirName[strlen (dirName) - 1] != '/'));
1079 * Read all of the directory entries and check them,
1080 * except for the current and parent directory entries.
1082 while (errorFlag==FALSE && ((entry = readdir (dir)) != NULL)) {
1083 if ((strcmp (entry->d_name, ".") == 0) ||
1084 (strcmp (entry->d_name, "..") == 0)) {
1089 * Build the full path name to the file.
1091 strcpy (fullName, dirName);
1094 strcat (fullName, "/");
1096 strcat (fullName, entry->d_name);
1099 * Write this file to the tar file, noticing whether or not
1100 * the file is a symbolic link.
1102 saveFile (fullName, TRUE);
1106 * All done, close the directory.
1113 * Write a tar header for the specified file name and status.
1114 * It is assumed that the file name fits.
1116 static void writeHeader (const char *fileName, const struct stat *statbuf)
1119 const unsigned char *cp;
1124 * Zero the header block in preparation for filling it in.
1126 memset ((char *) &header, 0, sizeof (header));
1129 * Fill in the header.
1131 strcpy (header.name, fileName);
1133 strncpy (header.magic, TAR_MAGIC, sizeof (header.magic));
1134 strncpy (header.version, TAR_VERSION, sizeof (header.version));
1136 putOctal (header.mode, sizeof (header.mode), statbuf->st_mode & 0777);
1137 putOctal (header.uid, sizeof (header.uid), statbuf->st_uid);
1138 putOctal (header.gid, sizeof (header.gid), statbuf->st_gid);
1139 putOctal (header.size, sizeof (header.size), statbuf->st_size);
1140 putOctal (header.mtime, sizeof (header.mtime), statbuf->st_mtime);
1142 header.typeFlag = TAR_TYPE_REGULAR;
1145 * Calculate and store the checksum.
1146 * This is the sum of all of the bytes of the header,
1147 * with the checksum field itself treated as blanks.
1149 memset (header.checkSum, ' ', sizeof (header.checkSum));
1151 cp = (const unsigned char *) &header;
1152 len = sizeof (header);
1158 putOctal (header.checkSum, sizeof (header.checkSum), checkSum);
1161 * Write the tar header.
1163 writeTarBlock ((const char *) &header, sizeof (header));
1168 * Write data to one or more blocks of the tar file.
1169 * The data is always padded out to a multiple of TAR_BLOCK_SIZE.
1170 * The errorFlag static variable is set on an error.
1172 static void writeTarBlock (const char *buf, int len)
1176 char fullBlock[TAR_BLOCK_SIZE];
1179 * If we had a write error before, then do nothing more.
1181 if (errorFlag==TRUE)
1185 * Get the amount of complete and partial blocks.
1187 partialLength = len % TAR_BLOCK_SIZE;
1188 completeLength = len - partialLength;
1191 * Write all of the complete blocks.
1193 if ((completeLength > 0) && !fullWrite (tarFd, buf, completeLength)) {
1202 * If there are no partial blocks left, we are done.
1204 if (partialLength == 0)
1208 * Copy the partial data into a complete block, and pad the rest
1209 * of it with zeroes.
1211 memcpy (fullBlock, buf + completeLength, partialLength);
1212 memset (fullBlock + partialLength, 0, TAR_BLOCK_SIZE - partialLength);
1215 * Write the last complete block.
1217 if (!fullWrite (tarFd, fullBlock, TAR_BLOCK_SIZE)) {
1226 * Put an octal string into the specified buffer.
1227 * The number is zero and space padded and possibly null padded.
1228 * Returns TRUE if successful.
1230 static int putOctal (char *cp, int len, long value)
1234 char tempBuffer[32];
1237 * Create a string of the specified length with an initial space,
1238 * leading zeroes and the octal number, and a trailing null.
1240 tempString = tempBuffer;
1242 sprintf (tempString, " %0*lo", len - 2, value);
1244 tempLength = strlen (tempString) + 1;
1247 * If the string is too large, suppress the leading space.
1249 if (tempLength > len) {
1255 * If the string is still too large, suppress the trailing null.
1257 if (tempLength > len)
1261 * If the string is still too large, fail.
1263 if (tempLength > len)
1267 * Copy the string to the field.
1269 memcpy (cp, tempString, len);