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
40 #include <sys/types.h>
41 #include <sys/sysmacros.h>
44 static const char tar_usage[] =
45 "tar -[cxtvOf] [tarFileName] [FILE] ...\n\n"
46 "Create, extract, or list files from a tar file\n\n"
48 "\tc=create, x=extract, t=list contents, v=verbose,\n"
49 "\tO=extract to stdout, f=tarfile or \"-\" for stdin\n";
56 #define TAR_BLOCK_SIZE 512
57 #define TAR_NAME_SIZE 100
61 * The POSIX (and basic GNU) tar header format.
62 * This structure is always embedded in a TAR_BLOCK_SIZE sized block
63 * with zero padding. We only process this information minimally.
66 char name[TAR_NAME_SIZE];
74 char linkName[TAR_NAME_SIZE];
84 #define TAR_MAGIC "ustar"
85 #define TAR_VERSION "00"
87 #define TAR_TYPE_REGULAR '0'
88 #define TAR_TYPE_HARD_LINK '1'
89 #define TAR_TYPE_SOFT_LINK '2'
96 static int extractFlag;
97 static int createFlag;
98 static int verboseFlag;
99 static int tostdoutFlag;
101 static int inHeader; // <- check me
102 static int badHeader;
103 static int errorFlag;
104 static int skipFileFlag;
105 static int warnedRoot;
109 static char outName[TAR_NAME_SIZE];
113 * Static data associated with the tar file.
115 static const char *tarName;
118 static ino_t tarInode;
122 * Local procedures to restore files from a tar file.
124 static void readTarFile (int fileCount, char **fileTable);
125 static void readData (const char *cp, int count);
126 static long getOctal (const char *cp, int len);
128 static void readHeader (const TarHeader * hp,
129 int fileCount, char **fileTable);
133 * Local procedures to save files into a tar file.
135 static void saveFile (const char *fileName, int seeLinks);
137 static void saveRegularFile (const char *fileName,
138 const struct stat *statbuf);
140 static void saveDirectory (const char *fileName,
141 const struct stat *statbuf);
143 static int wantFileName (const char *fileName,
144 int fileCount, char **fileTable);
146 static void writeHeader (const char *fileName, const struct stat *statbuf);
148 static void writeTarFile (int fileCount, char **fileTable);
149 static void writeTarBlock (const char *buf, int len);
150 static int putOctal (char *cp, int len, long value);
153 extern int tar_main (int argc, char **argv)
169 tostdoutFlag = FALSE;
179 options = (*argv++) + 1;
181 for (; *options; options++) {
184 if (tarName != NULL) {
185 fprintf (stderr, "Only one 'f' option allowed\n");
220 fprintf (stderr, "Unknown tar flag '%c'\n"
221 "Try `tar --help' for more information\n",
230 * Validate the options.
232 if (extractFlag + listFlag + createFlag != (TRUE+FALSE+FALSE)) {
234 "Exactly one of 'c', 'x' or 't' must be specified\n");
240 * Do the correct type of action supplying the rest of the
241 * command line arguments as the list of files to process.
243 if (createFlag==TRUE)
244 writeTarFile (argc, argv);
246 readTarFile (argc, argv);
248 fprintf (stderr, "\n");
254 * Read a tar file and extract or list the specified files within it.
255 * If the list is empty than all files are extracted or listed.
257 static void readTarFile (int fileCount, char **fileTable)
265 skipFileFlag = FALSE;
273 blockSize = sizeof (buf);
277 * Open the tar file for reading.
279 if ((tarName == NULL) || !strcmp (tarName, "-")) {
280 tarFd = fileno(stdin);
282 tarFd = open (tarName, O_RDONLY);
291 * Read blocks from the file until an end of file header block
292 * has been seen. (A real end of file from a read is an error.)
294 while (eofFlag==FALSE) {
296 * Read the next block of data if necessary.
297 * This will be a large block if possible, which we will
298 * then process in the small tar blocks.
302 inCc = fullRead (tarFd, buf, blockSize);
312 "Unexpected end of file from \"%s\"", tarName);
319 * If we are expecting a header block then examine it.
321 if (inHeader==TRUE) {
322 readHeader ((const TarHeader *) cp, fileCount, fileTable);
324 cp += TAR_BLOCK_SIZE;
325 inCc -= TAR_BLOCK_SIZE;
331 * We are currently handling the data for a file.
332 * Process the minimum of the amount of data we have available
333 * and the amount left to be processed for the file.
343 * If the amount left isn't an exact multiple of the tar block
344 * size then round it up to the next block boundary since there
345 * is padding at the end of the file.
347 if (cc % TAR_BLOCK_SIZE)
348 cc += TAR_BLOCK_SIZE - (cc % TAR_BLOCK_SIZE);
356 * Close the tar file if needed.
358 if ((tarFd >= 0) && (close (tarFd) < 0))
362 * Close the output file if needed.
363 * This is only done here on a previous error and so no
364 * message is required on errors.
366 if (tostdoutFlag == FALSE) {
368 (void) close (outFd);
374 * Examine the header block that was just read.
375 * This can specify the information for another file, or it can mark
376 * the end of the tar file.
379 readHeader (const TarHeader * hp, int fileCount, char **fileTable)
396 * If the block is completely empty, then this is the end of the
397 * archive file. If the name is null, then just skip this header.
402 for (cc = TAR_BLOCK_SIZE; cc > 0; cc--) {
413 * There is another file in the archive to examine.
414 * Extract the encoded information and check it.
416 mode = getOctal (hp->mode, sizeof (hp->mode));
417 uid = getOctal (hp->uid, sizeof (hp->uid));
418 gid = getOctal (hp->gid, sizeof (hp->gid));
419 size = getOctal (hp->size, sizeof (hp->size));
420 mtime = getOctal (hp->mtime, sizeof (hp->mtime));
421 checkSum = getOctal (hp->checkSum, sizeof (hp->checkSum));
422 major = getOctal (hp->devMajor, sizeof (hp->devMajor));
423 minor = getOctal (hp->devMinor, sizeof (hp->devMinor));
425 if ((mode < 0) || (uid < 0) || (gid < 0) || (size < 0)) {
426 if (badHeader==FALSE)
427 fprintf (stderr, "Bad tar header, skipping\n");
435 skipFileFlag = FALSE;
439 * Check for the file modes.
441 hardLink = ((hp->typeFlag == TAR_TYPE_HARD_LINK) ||
442 (hp->typeFlag == TAR_TYPE_HARD_LINK - '0'));
444 softLink = ((hp->typeFlag == TAR_TYPE_SOFT_LINK) ||
445 (hp->typeFlag == TAR_TYPE_SOFT_LINK - '0'));
448 * Check for a directory.
450 if (name[strlen (name) - 1] == '/')
454 * Check for absolute paths in the file.
455 * If we find any, then warn the user and make them relative.
461 if (warnedRoot==FALSE) {
463 "Absolute path detected, removing leading slashes\n");
470 * See if we want this file to be restored.
471 * If not, then set up to skip it.
473 if (wantFileName (name, fileCount, fileTable) == FALSE) {
474 if ( !hardLink && !softLink && (S_ISREG (mode) || S_ISCHR (mode)
475 || S_ISBLK (mode) || S_ISSOCK(mode) || S_ISFIFO(mode) ) ) {
476 inHeader = (size == 0)? TRUE : FALSE;
486 * This file is to be handled.
487 * If we aren't extracting then just list information about the file.
489 if (extractFlag==FALSE) {
490 if (verboseFlag==TRUE) {
491 printf ("%s %3d/%-d ", modeString (mode), uid, gid);
492 if( S_ISCHR (mode) || S_ISBLK (mode) )
493 printf ("%4d,%4d %s ", major,minor, timeString (mtime));
495 printf ("%9ld %s ", size, timeString (mtime));
500 printf (" (link to \"%s\")", hp->linkName);
502 printf (" (symlink to \"%s\")", hp->linkName);
503 else if (S_ISREG (mode) || S_ISCHR (mode) || S_ISBLK (mode) ||
504 S_ISSOCK(mode) || S_ISFIFO(mode) ) {
505 inHeader = (size == 0)? TRUE : FALSE;
515 * We really want to extract the file.
517 if (verboseFlag==TRUE)
518 printf ("x %s\n", name);
521 if (link (hp->linkName, name) < 0)
524 chown(name, uid, gid);
530 if (symlink (hp->linkName, name) < 0)
533 chown(name, uid, gid);
535 fprintf (stderr, "Cannot create symbolic links\n");
540 /* Set the umask for this process so it doesn't
541 * screw things up. */
545 * If the file is a directory, then just create the path.
547 if (S_ISDIR (mode)) {
548 createPath (name, mode);
550 chown(name, uid, gid);
556 * There is a file to write.
557 * First create the path to it if necessary with default permissions.
559 createPath (name, 0777);
561 inHeader = (size == 0)? TRUE : FALSE;
565 * Start the output file.
567 if (tostdoutFlag == TRUE)
568 outFd = fileno(stdout);
570 if ( S_ISCHR(mode) || S_ISBLK(mode) || S_ISSOCK(mode) ) {
572 outFd = mknod (name, mode, makedev(major, minor) );
574 else if (S_ISFIFO(mode) ) {
576 outFd = mkfifo(name, mode);
578 outFd = open (name, O_WRONLY | O_CREAT | O_TRUNC, mode);
587 if (tostdoutFlag == FALSE) {
589 fchown(outFd, uid, gid);
593 * If the file is empty, then that's all we need to do.
595 if (size == 0 && (tostdoutFlag == FALSE) && (devFileFlag == FALSE)) {
596 (void) close (outFd);
603 * Handle a data block of some specified size that was read.
605 static void readData (const char *cp, int count)
608 * Reduce the amount of data left in this file.
609 * If there is no more data left, then we need to read
618 * If we aren't extracting files or this file is being
619 * skipped then do nothing more.
621 if (extractFlag==FALSE || skipFileFlag==TRUE)
625 * Write the data to the output file.
627 if (fullWrite (outFd, cp, count) < 0) {
629 if (tostdoutFlag == FALSE) {
630 (void) close (outFd);
638 * If the write failed, close the file and disable further
639 * writes to this file.
641 if (dataCc <= 0 && tostdoutFlag == FALSE) {
651 * Write a tar file containing the specified files.
653 static void writeTarFile (int fileCount, char **fileTable)
658 * Make sure there is at least one file specified.
660 if (fileCount <= 0) {
661 fprintf (stderr, "No files specified to be saved\n");
666 * Create the tar file for writing.
668 if ((tarName == NULL) || !strcmp (tarName, "-")) {
670 tarFd = fileno(stdout);
672 tarFd = open (tarName, O_WRONLY | O_CREAT | O_TRUNC, 0666);
681 * Get the device and inode of the tar file for checking later.
683 if (fstat (tarFd, &statbuf) < 0) {
689 tarDev = statbuf.st_dev;
690 tarInode = statbuf.st_ino;
693 * Append each file name into the archive file.
694 * Follow symbolic links for these top level file names.
696 while (errorFlag==FALSE && (fileCount-- > 0)) {
697 saveFile (*fileTable++, FALSE);
701 * Now write an empty block of zeroes to end the archive.
703 writeTarBlock ("", 1);
708 * Close the tar file and check for errors if it was opened.
710 if ((tostdoutFlag == FALSE) && (tarFd >= 0) && (close (tarFd) < 0))
716 * Save one file into the tar file.
717 * If the file is a directory, then this will recursively save all of
718 * the files and directories within the directory. The seeLinks
719 * flag indicates whether or not we want to see symbolic links as
720 * they really are, instead of blindly following them.
722 static void saveFile (const char *fileName, int seeLinks)
728 if (verboseFlag==TRUE)
729 printf ("a %s\n", fileName);
732 * Check that the file name will fit in the header.
734 if (strlen (fileName) >= TAR_NAME_SIZE) {
735 fprintf (stderr, "%s: File name is too long\n", fileName);
741 * Find out about the file.
745 status = lstat (fileName, &statbuf);
748 status = stat (fileName, &statbuf);
757 * Make sure we aren't trying to save our file into itself.
759 if ((statbuf.st_dev == tarDev) && (statbuf.st_ino == tarInode)) {
760 fprintf (stderr, "Skipping saving of archive file itself\n");
766 * Check the type of file.
768 mode = statbuf.st_mode;
770 if (S_ISDIR (mode)) {
771 saveDirectory (fileName, &statbuf);
775 if (S_ISREG (mode)) {
776 saveRegularFile (fileName, &statbuf);
781 /* Some day add support for tarring these up... but not today. :) */
782 // if (S_ISLNK(mode) || S_ISFIFO(mode) || S_ISBLK(mode) || S_ISCHR (mode) ) {
783 // fprintf (stderr, "%s: This version of tar can't store this type of file\n", fileName);
787 * The file is a strange type of file, ignore it.
789 fprintf (stderr, "%s: not a directory or regular file\n", fileName);
794 * Save a regular file to the tar file.
797 saveRegularFile (const char *fileName, const struct stat *statbuf)
804 char data[TAR_BLOCK_SIZE * 16];
807 * Open the file for reading.
809 fileFd = open (fileName, O_RDONLY);
818 * Write out the header for the file.
820 writeHeader (fileName, statbuf);
823 * Write the data blocks of the file.
824 * We must be careful to write the amount of data that the stat
825 * buffer indicated, even if the file has changed size. Otherwise
826 * the tar file will be incorrect.
828 fullDataCount = statbuf->st_size;
831 while (fullDataCount > 0) {
833 * Get the amount to write this iteration which is
834 * the minumum of the amount left to write and the
837 dataCount = sizeof (data);
839 if (dataCount > fullDataCount)
840 dataCount = (int) fullDataCount;
843 * Read the data from the file if we haven't seen the
849 cc = fullRead (fileFd, data, dataCount);
854 (void) close (fileFd);
861 * If the file ended too soon, complain and set
862 * a flag so we will zero fill the rest of it.
864 if (cc < dataCount) {
866 "%s: Short read - zero filling", fileName);
873 * Zero fill the rest of the data if necessary.
876 memset (data + cc, 0, dataCount - cc);
879 * Write the buffer to the TAR file.
881 writeTarBlock (data, dataCount);
883 fullDataCount -= dataCount;
889 if ((tostdoutFlag == FALSE) && close (fileFd) < 0)
890 fprintf (stderr, "%s: close: %s\n", fileName, strerror (errno));
895 * Save a directory and all of its files to the tar file.
897 static void saveDirectory (const char *dirName, const struct stat *statbuf)
900 struct dirent *entry;
902 char fullName[NAME_MAX];
905 * Construct the directory name as used in the tar file by appending
906 * a slash character to it.
908 strcpy (fullName, dirName);
909 strcat (fullName, "/");
912 * Write out the header for the directory entry.
914 writeHeader (fullName, statbuf);
917 * Open the directory.
919 dir = opendir (dirName);
922 fprintf (stderr, "Cannot read directory \"%s\": %s\n",
923 dirName, strerror (errno));
929 * See if a slash is needed.
931 needSlash = (*dirName && (dirName[strlen (dirName) - 1] != '/'));
934 * Read all of the directory entries and check them,
935 * except for the current and parent directory entries.
937 while (errorFlag==FALSE && ((entry = readdir (dir)) != NULL)) {
938 if ((strcmp (entry->d_name, ".") == 0) ||
939 (strcmp (entry->d_name, "..") == 0)) {
944 * Build the full path name to the file.
946 strcpy (fullName, dirName);
949 strcat (fullName, "/");
951 strcat (fullName, entry->d_name);
954 * Write this file to the tar file, noticing whether or not
955 * the file is a symbolic link.
957 saveFile (fullName, TRUE);
961 * All done, close the directory.
968 * Write a tar header for the specified file name and status.
969 * It is assumed that the file name fits.
971 static void writeHeader (const char *fileName, const struct stat *statbuf)
974 const unsigned char *cp;
979 * Zero the header block in preparation for filling it in.
981 memset ((char *) &header, 0, sizeof (header));
984 * Fill in the header.
986 strcpy (header.name, fileName);
988 strncpy (header.magic, TAR_MAGIC, sizeof (header.magic));
989 strncpy (header.version, TAR_VERSION, sizeof (header.version));
991 putOctal (header.mode, sizeof (header.mode), statbuf->st_mode & 0777);
992 putOctal (header.uid, sizeof (header.uid), statbuf->st_uid);
993 putOctal (header.gid, sizeof (header.gid), statbuf->st_gid);
994 putOctal (header.size, sizeof (header.size), statbuf->st_size);
995 putOctal (header.mtime, sizeof (header.mtime), statbuf->st_mtime);
997 header.typeFlag = TAR_TYPE_REGULAR;
1000 * Calculate and store the checksum.
1001 * This is the sum of all of the bytes of the header,
1002 * with the checksum field itself treated as blanks.
1004 memset (header.checkSum, ' ', sizeof (header.checkSum));
1006 cp = (const unsigned char *) &header;
1007 len = sizeof (header);
1013 putOctal (header.checkSum, sizeof (header.checkSum), checkSum);
1016 * Write the tar header.
1018 writeTarBlock ((const char *) &header, sizeof (header));
1023 * Write data to one or more blocks of the tar file.
1024 * The data is always padded out to a multiple of TAR_BLOCK_SIZE.
1025 * The errorFlag static variable is set on an error.
1027 static void writeTarBlock (const char *buf, int len)
1031 char fullBlock[TAR_BLOCK_SIZE];
1034 * If we had a write error before, then do nothing more.
1036 if (errorFlag==TRUE)
1040 * Get the amount of complete and partial blocks.
1042 partialLength = len % TAR_BLOCK_SIZE;
1043 completeLength = len - partialLength;
1046 * Write all of the complete blocks.
1048 if ((completeLength > 0) && !fullWrite (tarFd, buf, completeLength)) {
1057 * If there are no partial blocks left, we are done.
1059 if (partialLength == 0)
1063 * Copy the partial data into a complete block, and pad the rest
1064 * of it with zeroes.
1066 memcpy (fullBlock, buf + completeLength, partialLength);
1067 memset (fullBlock + partialLength, 0, TAR_BLOCK_SIZE - partialLength);
1070 * Write the last complete block.
1072 if (!fullWrite (tarFd, fullBlock, TAR_BLOCK_SIZE)) {
1081 * Read an octal value in a field of the specified width, with optional
1082 * spaces on both sides of the number and with an optional null character
1083 * at the end. Returns -1 on an illegal format.
1085 static long getOctal (const char *cp, int len)
1089 while ((len > 0) && (*cp == ' ')) {
1094 if ((len == 0) || !isOctal (*cp))
1099 while ((len > 0) && isOctal (*cp)) {
1100 val = val * 8 + *cp++ - '0';
1104 while ((len > 0) && (*cp == ' ')) {
1109 if ((len > 0) && *cp)
1117 * Put an octal string into the specified buffer.
1118 * The number is zero and space padded and possibly null padded.
1119 * Returns TRUE if successful.
1121 static int putOctal (char *cp, int len, long value)
1125 char tempBuffer[32];
1128 * Create a string of the specified length with an initial space,
1129 * leading zeroes and the octal number, and a trailing null.
1131 tempString = tempBuffer;
1133 sprintf (tempString, " %0*lo", len - 2, value);
1135 tempLength = strlen (tempString) + 1;
1138 * If the string is too large, suppress the leading space.
1140 if (tempLength > len) {
1146 * If the string is still too large, suppress the trailing null.
1148 if (tempLength > len)
1152 * If the string is still too large, fail.
1154 if (tempLength > len)
1158 * Copy the string to the field.
1160 memcpy (cp, tempString, len);
1167 * See if the specified file name belongs to one of the specified list
1168 * of path prefixes. An empty list implies that all files are wanted.
1169 * Returns TRUE if the file is selected.
1172 wantFileName (const char *fileName, int fileCount, char **fileTable)
1174 const char *pathName;
1179 * If there are no files in the list, then the file is wanted.
1184 fileLength = strlen (fileName);
1187 * Check each of the test paths.
1189 while (fileCount-- > 0) {
1190 pathName = *fileTable++;
1192 pathLength = strlen (pathName);
1194 if (fileLength < pathLength)
1197 if (memcmp (fileName, pathName, pathLength) != 0)
1200 if ((fileLength == pathLength) || (fileName[pathLength] == '/')) {