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 * This program is free software; you can redistribute it and/or modify
14 * it under the terms of the GNU General Public License as published by
15 * the Free Software Foundation; either version 2 of the License, or
16 * (at your option) any later version.
18 * This program is distributed in the hope that it will be useful,
19 * but WITHOUT ANY WARRANTY; without even the implied warranty of
20 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
21 * General Public License for more details.
23 * You should have received a copy of the GNU General Public License
24 * along with this program; if not, write to the Free Software
25 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
39 static const char tar_usage[] =
40 "Create, extract, or list files from a TAR file\n\n"
41 "usage: tar -[cxtvOf] [tarFileName] [FILE] ...\n"
42 "\tc=create, x=extract, t=list contents, v=verbose,\n"
43 "\tO=extract to stdout, f=tarfile or \"-\" for stdin\n";
50 #define TAR_BLOCK_SIZE 512
51 #define TAR_NAME_SIZE 100
55 * The POSIX (and basic GNU) tar header format.
56 * This structure is always embedded in a TAR_BLOCK_SIZE sized block
57 * with zero padding. We only process this information minimally.
60 char name[TAR_NAME_SIZE];
68 char linkName[TAR_NAME_SIZE];
78 #define TAR_MAGIC "ustar"
79 #define TAR_VERSION "00"
81 #define TAR_TYPE_REGULAR '0'
82 #define TAR_TYPE_HARD_LINK '1'
83 #define TAR_TYPE_SOFT_LINK '2'
90 static int extractFlag;
91 static int createFlag;
92 static int verboseFlag;
93 static int tostdoutFlag;
98 static int skipFileFlag;
99 static int warnedRoot;
103 static char outName[TAR_NAME_SIZE];
107 * Static data associated with the tar file.
109 static const char *tarName;
112 static ino_t tarInode;
116 * Local procedures to restore files from a tar file.
118 static void readTarFile (int fileCount, char **fileTable);
119 static void readData (const char *cp, int count);
120 static long getOctal (const char *cp, int len);
122 static void readHeader (const TarHeader * hp,
123 int fileCount, char **fileTable);
127 * Local procedures to save files into a tar file.
129 static void saveFile (const char *fileName, int seeLinks);
131 static void saveRegularFile (const char *fileName,
132 const struct stat *statbuf);
134 static void saveDirectory (const char *fileName,
135 const struct stat *statbuf);
137 static int wantFileName (const char *fileName,
138 int fileCount, char **fileTable);
140 static void writeHeader (const char *fileName, const struct stat *statbuf);
142 static void writeTarFile (int fileCount, char **fileTable);
143 static void writeTarBlock (const char *buf, int len);
144 static int putOctal (char *cp, int len, long value);
147 extern int tar_main (int argc, char **argv)
155 fprintf (stderr, "%s", tar_usage);
165 tostdoutFlag = FALSE;
178 for (; *options; options++) {
181 if (tarName != NULL) {
182 fprintf (stderr, "Only one 'f' option allowed\n");
216 fprintf (stderr, "Unknown tar flag '%c'\n", *options);
224 * Validate the options.
226 if (extractFlag + listFlag + createFlag != 1) {
228 "Exactly one of 'c', 'x' or 't' must be specified\n");
234 * Do the correct type of action supplying the rest of the
235 * command line arguments as the list of files to process.
238 writeTarFile (argc, argv);
240 readTarFile (argc, argv);
242 fprintf (stderr, "\n");
248 * Read a tar file and extract or list the specified files within it.
249 * If the list is empty than all files are extracted or listed.
251 static void readTarFile (int fileCount, char **fileTable)
259 skipFileFlag = FALSE;
267 blockSize = sizeof (buf);
271 * Open the tar file for reading.
273 if ((tarName == NULL) || !strcmp (tarName, "-")) {
276 tarFd = open (tarName, O_RDONLY);
285 * Read blocks from the file until an end of file header block
286 * has been seen. (A real end of file from a read is an error.)
290 * Read the next block of data if necessary.
291 * This will be a large block if possible, which we will
292 * then process in the small tar blocks.
296 inCc = fullRead (tarFd, buf, blockSize);
306 "Unexpected end of file from \"%s\"", tarName);
313 * If we are expecting a header block then examine it.
316 readHeader ((const TarHeader *) cp, fileCount, fileTable);
318 cp += TAR_BLOCK_SIZE;
319 inCc -= TAR_BLOCK_SIZE;
325 * We are currently handling the data for a file.
326 * Process the minimum of the amount of data we have available
327 * and the amount left to be processed for the file.
337 * If the amount left isn't an exact multiple of the tar block
338 * size then round it up to the next block boundary since there
339 * is padding at the end of the file.
341 if (cc % TAR_BLOCK_SIZE)
342 cc += TAR_BLOCK_SIZE - (cc % TAR_BLOCK_SIZE);
350 * Close the tar file if needed.
352 if ((tarFd >= 0) && (close (tarFd) < 0))
356 * Close the output file if needed.
357 * This is only done here on a previous error and so no
358 * message is required on errors.
360 if (tostdoutFlag == FALSE) {
362 (void) close (outFd);
368 * Examine the header block that was just read.
369 * This can specify the information for another file, or it can mark
370 * the end of the tar file.
373 readHeader (const TarHeader * hp, int fileCount, char **fileTable)
387 * If the block is completely empty, then this is the end of the
388 * archive file. If the name is null, then just skip this header.
393 for (cc = TAR_BLOCK_SIZE; cc > 0; cc--) {
404 * There is another file in the archive to examine.
405 * Extract the encoded information and check it.
407 mode = getOctal (hp->mode, sizeof (hp->mode));
408 uid = getOctal (hp->uid, sizeof (hp->uid));
409 gid = getOctal (hp->gid, sizeof (hp->gid));
410 size = getOctal (hp->size, sizeof (hp->size));
411 mtime = getOctal (hp->mtime, sizeof (hp->mtime));
412 checkSum = getOctal (hp->checkSum, sizeof (hp->checkSum));
414 if ((mode < 0) || (uid < 0) || (gid < 0) || (size < 0)) {
416 fprintf (stderr, "Bad tar header, skipping\n");
424 skipFileFlag = FALSE;
427 * Check for the file modes.
429 hardLink = ((hp->typeFlag == TAR_TYPE_HARD_LINK) ||
430 (hp->typeFlag == TAR_TYPE_HARD_LINK - '0'));
432 softLink = ((hp->typeFlag == TAR_TYPE_SOFT_LINK) ||
433 (hp->typeFlag == TAR_TYPE_SOFT_LINK - '0'));
436 * Check for a directory or a regular file.
438 if (name[strlen (name) - 1] == '/')
440 else if ((mode & S_IFMT) == 0)
444 * Check for absolute paths in the file.
445 * If we find any, then warn the user and make them relative.
453 "Absolute path detected, removing leading slashes\n");
460 * See if we want this file to be restored.
461 * If not, then set up to skip it.
463 if (!wantFileName (name, fileCount, fileTable)) {
464 if (!hardLink && !softLink && S_ISREG (mode)) {
465 inHeader = (size == 0);
475 * This file is to be handled.
476 * If we aren't extracting then just list information about the file.
480 printf ("%s %3d/%-d %9ld %s %s", modeString (mode),
481 uid, gid, size, timeString (mtime), name);
486 printf (" (link to \"%s\")", hp->linkName);
488 printf (" (symlink to \"%s\")", hp->linkName);
489 else if (S_ISREG (mode)) {
490 inHeader = (size == 0);
500 * We really want to extract the file.
503 printf ("x %s\n", name);
506 if (link (hp->linkName, name) < 0)
514 if (symlink (hp->linkName, name) < 0)
517 fprintf (stderr, "Cannot create symbolic links\n");
523 * If the file is a directory, then just create the path.
525 if (S_ISDIR (mode)) {
526 createPath (name, mode);
532 * There is a file to write.
533 * First create the path to it if necessary with a default permission.
535 createPath (name, 0777);
537 inHeader = (size == 0);
541 * Start the output file.
543 if (tostdoutFlag == TRUE)
546 outFd = open (name, O_WRONLY | O_CREAT | O_TRUNC, mode);
555 * If the file is empty, then that's all we need to do.
557 if (size == 0 && tostdoutFlag == FALSE) {
558 (void) close (outFd);
565 * Handle a data block of some specified size that was read.
567 static void readData (const char *cp, int count)
570 * Reduce the amount of data left in this file.
571 * If there is no more data left, then we need to read
580 * If we aren't extracting files or this file is being
581 * skipped then do nothing more.
583 if (!extractFlag || skipFileFlag)
587 * Write the data to the output file.
589 if (fullWrite (outFd, cp, count) < 0) {
591 if (tostdoutFlag == FALSE) {
592 (void) close (outFd);
600 * If the write failed, close the file and disable further
601 * writes to this file.
603 if (dataCc <= 0 && tostdoutFlag == FALSE) {
613 * Write a tar file containing the specified files.
615 static void writeTarFile (int fileCount, char **fileTable)
620 * Make sure there is at least one file specified.
622 if (fileCount <= 0) {
623 fprintf (stderr, "No files specified to be saved\n");
628 * Create the tar file for writing.
630 if ((tarName == NULL) || !strcmp (tarName, "-")) {
634 tarFd = open (tarName, O_WRONLY | O_CREAT | O_TRUNC, 0666);
643 * Get the device and inode of the tar file for checking later.
645 if (fstat (tarFd, &statbuf) < 0) {
651 tarDev = statbuf.st_dev;
652 tarInode = statbuf.st_ino;
655 * Append each file name into the archive file.
656 * Follow symbolic links for these top level file names.
658 while (!errorFlag && (fileCount-- > 0)) {
659 saveFile (*fileTable++, FALSE);
663 * Now write an empty block of zeroes to end the archive.
665 writeTarBlock ("", 1);
670 * Close the tar file and check for errors if it was opened.
672 if ((tostdoutFlag == FALSE) && (tarFd >= 0) && (close (tarFd) < 0))
678 * Save one file into the tar file.
679 * If the file is a directory, then this will recursively save all of
680 * the files and directories within the directory. The seeLinks
681 * flag indicates whether or not we want to see symbolic links as
682 * they really are, instead of blindly following them.
684 static void saveFile (const char *fileName, int seeLinks)
691 printf ("a %s\n", fileName);
694 * Check that the file name will fit in the header.
696 if (strlen (fileName) >= TAR_NAME_SIZE) {
697 fprintf (stderr, "%s: File name is too long\n", fileName);
703 * Find out about the file.
707 status = lstat (fileName, &statbuf);
710 status = stat (fileName, &statbuf);
719 * Make sure we aren't trying to save our file into itself.
721 if ((statbuf.st_dev == tarDev) && (statbuf.st_ino == tarInode)) {
722 fprintf (stderr, "Skipping saving of archive file itself\n");
728 * Check the type of file.
730 mode = statbuf.st_mode;
732 if (S_ISDIR (mode)) {
733 saveDirectory (fileName, &statbuf);
738 if (S_ISREG (mode)) {
739 saveRegularFile (fileName, &statbuf);
745 * The file is a strange type of file, ignore it.
747 fprintf (stderr, "%s: not a directory or regular file\n", fileName);
752 * Save a regular file to the tar file.
755 saveRegularFile (const char *fileName, const struct stat *statbuf)
762 char data[TAR_BLOCK_SIZE * 16];
765 * Open the file for reading.
767 fileFd = open (fileName, O_RDONLY);
776 * Write out the header for the file.
778 writeHeader (fileName, statbuf);
781 * Write the data blocks of the file.
782 * We must be careful to write the amount of data that the stat
783 * buffer indicated, even if the file has changed size. Otherwise
784 * the tar file will be incorrect.
786 fullDataCount = statbuf->st_size;
789 while (fullDataCount > 0) {
791 * Get the amount to write this iteration which is
792 * the minumum of the amount left to write and the
795 dataCount = sizeof (data);
797 if (dataCount > fullDataCount)
798 dataCount = (int) fullDataCount;
801 * Read the data from the file if we haven't seen the
807 cc = fullRead (fileFd, data, dataCount);
812 (void) close (fileFd);
819 * If the file ended too soon, complain and set
820 * a flag so we will zero fill the rest of it.
822 if (cc < dataCount) {
824 "%s: Short read - zero filling", fileName);
831 * Zero fill the rest of the data if necessary.
834 memset (data + cc, 0, dataCount - cc);
837 * Write the buffer to the TAR file.
839 writeTarBlock (data, dataCount);
841 fullDataCount -= dataCount;
847 if ((tostdoutFlag == FALSE) && close (fileFd) < 0)
848 fprintf (stderr, "%s: close: %s\n", fileName, strerror (errno));
853 * Save a directory and all of its files to the tar file.
855 static void saveDirectory (const char *dirName, const struct stat *statbuf)
858 struct dirent *entry;
860 char fullName[NAME_MAX];
863 * Construct the directory name as used in the tar file by appending
864 * a slash character to it.
866 strcpy (fullName, dirName);
867 strcat (fullName, "/");
870 * Write out the header for the directory entry.
872 writeHeader (fullName, statbuf);
875 * Open the directory.
877 dir = opendir (dirName);
880 fprintf (stderr, "Cannot read directory \"%s\": %s\n",
881 dirName, strerror (errno));
887 * See if a slash is needed.
889 needSlash = (*dirName && (dirName[strlen (dirName) - 1] != '/'));
892 * Read all of the directory entries and check them,
893 * except for the current and parent directory entries.
895 while (!errorFlag && ((entry = readdir (dir)) != NULL)) {
896 if ((strcmp (entry->d_name, ".") == 0) ||
897 (strcmp (entry->d_name, "..") == 0)) {
902 * Build the full path name to the file.
904 strcpy (fullName, dirName);
907 strcat (fullName, "/");
909 strcat (fullName, entry->d_name);
912 * Write this file to the tar file, noticing whether or not
913 * the file is a symbolic link.
915 saveFile (fullName, TRUE);
919 * All done, close the directory.
926 * Write a tar header for the specified file name and status.
927 * It is assumed that the file name fits.
929 static void writeHeader (const char *fileName, const struct stat *statbuf)
932 const unsigned char *cp;
937 * Zero the header block in preparation for filling it in.
939 memset ((char *) &header, 0, sizeof (header));
942 * Fill in the header.
944 strcpy (header.name, fileName);
946 strncpy (header.magic, TAR_MAGIC, sizeof (header.magic));
947 strncpy (header.version, TAR_VERSION, sizeof (header.version));
949 putOctal (header.mode, sizeof (header.mode), statbuf->st_mode & 0777);
950 putOctal (header.uid, sizeof (header.uid), statbuf->st_uid);
951 putOctal (header.gid, sizeof (header.gid), statbuf->st_gid);
952 putOctal (header.size, sizeof (header.size), statbuf->st_size);
953 putOctal (header.mtime, sizeof (header.mtime), statbuf->st_mtime);
955 header.typeFlag = TAR_TYPE_REGULAR;
958 * Calculate and store the checksum.
959 * This is the sum of all of the bytes of the header,
960 * with the checksum field itself treated as blanks.
962 memset (header.checkSum, ' ', sizeof (header.checkSum));
964 cp = (const unsigned char *) &header;
965 len = sizeof (header);
971 putOctal (header.checkSum, sizeof (header.checkSum), checkSum);
974 * Write the tar header.
976 writeTarBlock ((const char *) &header, sizeof (header));
981 * Write data to one or more blocks of the tar file.
982 * The data is always padded out to a multiple of TAR_BLOCK_SIZE.
983 * The errorFlag static variable is set on an error.
985 static void writeTarBlock (const char *buf, int len)
989 char fullBlock[TAR_BLOCK_SIZE];
992 * If we had a write error before, then do nothing more.
998 * Get the amount of complete and partial blocks.
1000 partialLength = len % TAR_BLOCK_SIZE;
1001 completeLength = len - partialLength;
1004 * Write all of the complete blocks.
1006 if ((completeLength > 0) && !fullWrite (tarFd, buf, completeLength)) {
1015 * If there are no partial blocks left, we are done.
1017 if (partialLength == 0)
1021 * Copy the partial data into a complete block, and pad the rest
1022 * of it with zeroes.
1024 memcpy (fullBlock, buf + completeLength, partialLength);
1025 memset (fullBlock + partialLength, 0, TAR_BLOCK_SIZE - partialLength);
1028 * Write the last complete block.
1030 if (!fullWrite (tarFd, fullBlock, TAR_BLOCK_SIZE)) {
1039 * Read an octal value in a field of the specified width, with optional
1040 * spaces on both sides of the number and with an optional null character
1041 * at the end. Returns -1 on an illegal format.
1043 static long getOctal (const char *cp, int len)
1047 while ((len > 0) && (*cp == ' ')) {
1052 if ((len == 0) || !isOctal (*cp))
1057 while ((len > 0) && isOctal (*cp)) {
1058 val = val * 8 + *cp++ - '0';
1062 while ((len > 0) && (*cp == ' ')) {
1067 if ((len > 0) && *cp)
1075 * Put an octal string into the specified buffer.
1076 * The number is zero and space padded and possibly null padded.
1077 * Returns TRUE if successful.
1079 static int putOctal (char *cp, int len, long value)
1083 char tempBuffer[32];
1086 * Create a string of the specified length with an initial space,
1087 * leading zeroes and the octal number, and a trailing null.
1089 tempString = tempBuffer;
1091 sprintf (tempString, " %0*lo", len - 2, value);
1093 tempLength = strlen (tempString) + 1;
1096 * If the string is too large, suppress the leading space.
1098 if (tempLength > len) {
1104 * If the string is still too large, suppress the trailing null.
1106 if (tempLength > len)
1110 * If the string is still too large, fail.
1112 if (tempLength > len)
1116 * Copy the string to the field.
1118 memcpy (cp, tempString, len);
1125 * See if the specified file name belongs to one of the specified list
1126 * of path prefixes. An empty list implies that all files are wanted.
1127 * Returns TRUE if the file is selected.
1130 wantFileName (const char *fileName, int fileCount, char **fileTable)
1132 const char *pathName;
1137 * If there are no files in the list, then the file is wanted.
1142 fileLength = strlen (fileName);
1145 * Check each of the test paths.
1147 while (fileCount-- > 0) {
1148 pathName = *fileTable++;
1150 pathLength = strlen (pathName);
1152 if (fileLength < pathLength)
1155 if (memcmp (fileName, pathName, pathLength) != 0)
1158 if ((fileLength == pathLength) || (fileName[pathLength] == '/')) {