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
38 /* Note that tar.c expects TRUE and FALSE to be defined
39 * exactly the opposite of how they are used everywhere else.
40 * Some time this should be integrated a bit better, but this
41 * does the job for now.
45 //#define FALSE ((int) 0)
46 //#define TRUE ((int) 1)
49 static const char tar_usage[] =
50 "tar -[cxtvOf] [tarFileName] [FILE] ...\n"
51 "Create, extract, or list files from a tar file\n\n"
52 "\tc=create, x=extract, t=list contents, v=verbose,\n"
53 "\tO=extract to stdout, f=tarfile or \"-\" for stdin\n";
60 #define TAR_BLOCK_SIZE 512
61 #define TAR_NAME_SIZE 100
65 * The POSIX (and basic GNU) tar header format.
66 * This structure is always embedded in a TAR_BLOCK_SIZE sized block
67 * with zero padding. We only process this information minimally.
70 char name[TAR_NAME_SIZE];
78 char linkName[TAR_NAME_SIZE];
88 #define TAR_MAGIC "ustar"
89 #define TAR_VERSION "00"
91 #define TAR_TYPE_REGULAR '0'
92 #define TAR_TYPE_HARD_LINK '1'
93 #define TAR_TYPE_SOFT_LINK '2'
99 static int listFlag; //
100 static int extractFlag; //
101 static int createFlag; //
102 static int verboseFlag; //
103 static int tostdoutFlag; //
105 static int inHeader; // <- check me
106 static int badHeader; //
107 static int errorFlag; //
108 static int skipFileFlag; //
109 static int warnedRoot; //
110 static int eofFlag; //
113 static char outName[TAR_NAME_SIZE];
117 * Static data associated with the tar file.
119 static const char *tarName;
122 static ino_t tarInode;
126 * Local procedures to restore files from a tar file.
128 static void readTarFile (int fileCount, char **fileTable);
129 static void readData (const char *cp, int count);
130 static long getOctal (const char *cp, int len);
132 static void readHeader (const TarHeader * hp,
133 int fileCount, char **fileTable);
137 * Local procedures to save files into a tar file.
139 static void saveFile (const char *fileName, int seeLinks); //
141 static void saveRegularFile (const char *fileName,
142 const struct stat *statbuf);
144 static void saveDirectory (const char *fileName,
145 const struct stat *statbuf);
147 static int wantFileName (const char *fileName,
148 int fileCount, char **fileTable); //
150 static void writeHeader (const char *fileName, const struct stat *statbuf);
152 static void writeTarFile (int fileCount, char **fileTable);
153 static void writeTarBlock (const char *buf, int len);
154 static int putOctal (char *cp, int len, long value); //
157 extern int tar_main (int argc, char **argv)
173 tostdoutFlag = FALSE;
183 options = (*argv++) + 1;
185 for (; *options; options++) {
188 if (tarName != NULL) {
189 fprintf (stderr, "Only one 'f' option allowed\n");
223 fprintf (stderr, "Unknown tar flag '%c'\n", *options);
231 * Validate the options.
233 fprintf(stderr, "TRUE=%d FALSE=%d\n", TRUE, FALSE);
234 if (extractFlag + listFlag + createFlag != (TRUE+FALSE+FALSE)) {
236 "Exactly one of 'c', 'x' or 't' must be specified\n");
242 * Do the correct type of action supplying the rest of the
243 * command line arguments as the list of files to process.
245 if (createFlag==TRUE)
246 writeTarFile (argc, argv);
248 readTarFile (argc, argv);
250 fprintf (stderr, "\n");
256 * Read a tar file and extract or list the specified files within it.
257 * If the list is empty than all files are extracted or listed.
259 static void readTarFile (int fileCount, char **fileTable)
267 skipFileFlag = FALSE;
275 blockSize = sizeof (buf);
279 * Open the tar file for reading.
281 if ((tarName == NULL) || !strcmp (tarName, "-")) {
284 tarFd = open (tarName, O_RDONLY);
293 * Read blocks from the file until an end of file header block
294 * has been seen. (A real end of file from a read is an error.)
296 while (eofFlag==FALSE) {
298 * Read the next block of data if necessary.
299 * This will be a large block if possible, which we will
300 * then process in the small tar blocks.
304 inCc = fullRead (tarFd, buf, blockSize);
314 "Unexpected end of file from \"%s\"", tarName);
321 * If we are expecting a header block then examine it.
323 if (inHeader==TRUE) {
324 readHeader ((const TarHeader *) cp, fileCount, fileTable);
326 cp += TAR_BLOCK_SIZE;
327 inCc -= TAR_BLOCK_SIZE;
333 * We are currently handling the data for a file.
334 * Process the minimum of the amount of data we have available
335 * and the amount left to be processed for the file.
345 * If the amount left isn't an exact multiple of the tar block
346 * size then round it up to the next block boundary since there
347 * is padding at the end of the file.
349 if (cc % TAR_BLOCK_SIZE)
350 cc += TAR_BLOCK_SIZE - (cc % TAR_BLOCK_SIZE);
358 * Close the tar file if needed.
360 if ((tarFd >= 0) && (close (tarFd) < 0))
364 * Close the output file if needed.
365 * This is only done here on a previous error and so no
366 * message is required on errors.
368 if (tostdoutFlag == FALSE) {
370 (void) close (outFd);
376 * Examine the header block that was just read.
377 * This can specify the information for another file, or it can mark
378 * the end of the tar file.
381 readHeader (const TarHeader * hp, int fileCount, char **fileTable)
395 * If the block is completely empty, then this is the end of the
396 * archive file. If the name is null, then just skip this header.
401 for (cc = TAR_BLOCK_SIZE; cc > 0; cc--) {
412 * There is another file in the archive to examine.
413 * Extract the encoded information and check it.
415 mode = getOctal (hp->mode, sizeof (hp->mode));
416 uid = getOctal (hp->uid, sizeof (hp->uid));
417 gid = getOctal (hp->gid, sizeof (hp->gid));
418 size = getOctal (hp->size, sizeof (hp->size));
419 mtime = getOctal (hp->mtime, sizeof (hp->mtime));
420 checkSum = getOctal (hp->checkSum, sizeof (hp->checkSum));
422 if ((mode < 0) || (uid < 0) || (gid < 0) || (size < 0)) {
423 if (badHeader==FALSE)
424 fprintf (stderr, "Bad tar header, skipping\n");
432 skipFileFlag = FALSE;
435 * Check for the file modes.
437 hardLink = ((hp->typeFlag == TAR_TYPE_HARD_LINK) ||
438 (hp->typeFlag == TAR_TYPE_HARD_LINK - '0'));
440 softLink = ((hp->typeFlag == TAR_TYPE_SOFT_LINK) ||
441 (hp->typeFlag == TAR_TYPE_SOFT_LINK - '0'));
444 * Check for a directory or a regular file.
446 if (name[strlen (name) - 1] == '/')
448 else if ((mode & S_IFMT) == 0)
452 * Check for absolute paths in the file.
453 * If we find any, then warn the user and make them relative.
459 if (warnedRoot==FALSE) {
461 "Absolute path detected, removing leading slashes\n");
468 * See if we want this file to be restored.
469 * If not, then set up to skip it.
471 if (wantFileName (name, fileCount, fileTable) == FALSE) {
472 if (!hardLink && !softLink && S_ISREG (mode)) {
473 inHeader = (size == 0)? TRUE : FALSE;
483 * This file is to be handled.
484 * If we aren't extracting then just list information about the file.
486 if (extractFlag==FALSE) {
487 if (verboseFlag==TRUE) {
488 printf ("%s %3d/%-d %9ld %s %s", modeString (mode),
489 uid, gid, size, timeString (mtime), name);
494 printf (" (link to \"%s\")", hp->linkName);
496 printf (" (symlink to \"%s\")", hp->linkName);
497 else if (S_ISREG (mode)) {
498 inHeader = (size == 0)? TRUE : FALSE;
508 * We really want to extract the file.
510 if (verboseFlag==TRUE)
511 printf ("x %s\n", name);
514 if (link (hp->linkName, name) < 0)
522 if (symlink (hp->linkName, name) < 0)
525 fprintf (stderr, "Cannot create symbolic links\n");
531 * If the file is a directory, then just create the path.
533 if (S_ISDIR (mode)) {
534 createPath (name, mode);
540 * There is a file to write.
541 * First create the path to it if necessary with a default permission.
543 createPath (name, 0777);
545 inHeader = (size == 0)? TRUE : FALSE;
549 * Start the output file.
551 if (tostdoutFlag == TRUE)
554 outFd = open (name, O_WRONLY | O_CREAT | O_TRUNC, mode);
563 * If the file is empty, then that's all we need to do.
565 if (size == 0 && tostdoutFlag == FALSE) {
566 (void) close (outFd);
573 * Handle a data block of some specified size that was read.
575 static void readData (const char *cp, int count)
578 * Reduce the amount of data left in this file.
579 * If there is no more data left, then we need to read
588 * If we aren't extracting files or this file is being
589 * skipped then do nothing more.
591 if (extractFlag==FALSE || skipFileFlag==TRUE)
595 * Write the data to the output file.
597 if (fullWrite (outFd, cp, count) < 0) {
599 if (tostdoutFlag == FALSE) {
600 (void) close (outFd);
608 * If the write failed, close the file and disable further
609 * writes to this file.
611 if (dataCc <= 0 && tostdoutFlag == FALSE) {
621 * Write a tar file containing the specified files.
623 static void writeTarFile (int fileCount, char **fileTable)
628 * Make sure there is at least one file specified.
630 if (fileCount <= 0) {
631 fprintf (stderr, "No files specified to be saved\n");
636 * Create the tar file for writing.
638 if ((tarName == NULL) || !strcmp (tarName, "-")) {
642 tarFd = open (tarName, O_WRONLY | O_CREAT | O_TRUNC, 0666);
651 * Get the device and inode of the tar file for checking later.
653 if (fstat (tarFd, &statbuf) < 0) {
659 tarDev = statbuf.st_dev;
660 tarInode = statbuf.st_ino;
663 * Append each file name into the archive file.
664 * Follow symbolic links for these top level file names.
666 while (errorFlag==FALSE && (fileCount-- > 0)) {
667 saveFile (*fileTable++, FALSE);
671 * Now write an empty block of zeroes to end the archive.
673 writeTarBlock ("", 1);
678 * Close the tar file and check for errors if it was opened.
680 if ((tostdoutFlag == FALSE) && (tarFd >= 0) && (close (tarFd) < 0))
686 * Save one file into the tar file.
687 * If the file is a directory, then this will recursively save all of
688 * the files and directories within the directory. The seeLinks
689 * flag indicates whether or not we want to see symbolic links as
690 * they really are, instead of blindly following them.
692 static void saveFile (const char *fileName, int seeLinks)
698 if (verboseFlag==TRUE)
699 printf ("a %s\n", fileName);
702 * Check that the file name will fit in the header.
704 if (strlen (fileName) >= TAR_NAME_SIZE) {
705 fprintf (stderr, "%s: File name is too long\n", fileName);
711 * Find out about the file.
715 status = lstat (fileName, &statbuf);
718 status = stat (fileName, &statbuf);
727 * Make sure we aren't trying to save our file into itself.
729 if ((statbuf.st_dev == tarDev) && (statbuf.st_ino == tarInode)) {
730 fprintf (stderr, "Skipping saving of archive file itself\n");
736 * Check the type of file.
738 mode = statbuf.st_mode;
740 if (S_ISDIR (mode)) {
741 saveDirectory (fileName, &statbuf);
746 if (S_ISREG (mode)) {
747 saveRegularFile (fileName, &statbuf);
753 * The file is a strange type of file, ignore it.
755 fprintf (stderr, "%s: not a directory or regular file\n", fileName);
760 * Save a regular file to the tar file.
763 saveRegularFile (const char *fileName, const struct stat *statbuf)
770 char data[TAR_BLOCK_SIZE * 16];
773 * Open the file for reading.
775 fileFd = open (fileName, O_RDONLY);
784 * Write out the header for the file.
786 writeHeader (fileName, statbuf);
789 * Write the data blocks of the file.
790 * We must be careful to write the amount of data that the stat
791 * buffer indicated, even if the file has changed size. Otherwise
792 * the tar file will be incorrect.
794 fullDataCount = statbuf->st_size;
797 while (fullDataCount > 0) {
799 * Get the amount to write this iteration which is
800 * the minumum of the amount left to write and the
803 dataCount = sizeof (data);
805 if (dataCount > fullDataCount)
806 dataCount = (int) fullDataCount;
809 * Read the data from the file if we haven't seen the
815 cc = fullRead (fileFd, data, dataCount);
820 (void) close (fileFd);
827 * If the file ended too soon, complain and set
828 * a flag so we will zero fill the rest of it.
830 if (cc < dataCount) {
832 "%s: Short read - zero filling", fileName);
839 * Zero fill the rest of the data if necessary.
842 memset (data + cc, 0, dataCount - cc);
845 * Write the buffer to the TAR file.
847 writeTarBlock (data, dataCount);
849 fullDataCount -= dataCount;
855 if ((tostdoutFlag == FALSE) && close (fileFd) < 0)
856 fprintf (stderr, "%s: close: %s\n", fileName, strerror (errno));
861 * Save a directory and all of its files to the tar file.
863 static void saveDirectory (const char *dirName, const struct stat *statbuf)
866 struct dirent *entry;
868 char fullName[NAME_MAX];
871 * Construct the directory name as used in the tar file by appending
872 * a slash character to it.
874 strcpy (fullName, dirName);
875 strcat (fullName, "/");
878 * Write out the header for the directory entry.
880 writeHeader (fullName, statbuf);
883 * Open the directory.
885 dir = opendir (dirName);
888 fprintf (stderr, "Cannot read directory \"%s\": %s\n",
889 dirName, strerror (errno));
895 * See if a slash is needed.
897 needSlash = (*dirName && (dirName[strlen (dirName) - 1] != '/'));
900 * Read all of the directory entries and check them,
901 * except for the current and parent directory entries.
903 while (errorFlag==FALSE && ((entry = readdir (dir)) != NULL)) {
904 if ((strcmp (entry->d_name, ".") == 0) ||
905 (strcmp (entry->d_name, "..") == 0)) {
910 * Build the full path name to the file.
912 strcpy (fullName, dirName);
915 strcat (fullName, "/");
917 strcat (fullName, entry->d_name);
920 * Write this file to the tar file, noticing whether or not
921 * the file is a symbolic link.
923 saveFile (fullName, TRUE);
927 * All done, close the directory.
934 * Write a tar header for the specified file name and status.
935 * It is assumed that the file name fits.
937 static void writeHeader (const char *fileName, const struct stat *statbuf)
940 const unsigned char *cp;
945 * Zero the header block in preparation for filling it in.
947 memset ((char *) &header, 0, sizeof (header));
950 * Fill in the header.
952 strcpy (header.name, fileName);
954 strncpy (header.magic, TAR_MAGIC, sizeof (header.magic));
955 strncpy (header.version, TAR_VERSION, sizeof (header.version));
957 putOctal (header.mode, sizeof (header.mode), statbuf->st_mode & 0777);
958 putOctal (header.uid, sizeof (header.uid), statbuf->st_uid);
959 putOctal (header.gid, sizeof (header.gid), statbuf->st_gid);
960 putOctal (header.size, sizeof (header.size), statbuf->st_size);
961 putOctal (header.mtime, sizeof (header.mtime), statbuf->st_mtime);
963 header.typeFlag = TAR_TYPE_REGULAR;
966 * Calculate and store the checksum.
967 * This is the sum of all of the bytes of the header,
968 * with the checksum field itself treated as blanks.
970 memset (header.checkSum, ' ', sizeof (header.checkSum));
972 cp = (const unsigned char *) &header;
973 len = sizeof (header);
979 putOctal (header.checkSum, sizeof (header.checkSum), checkSum);
982 * Write the tar header.
984 writeTarBlock ((const char *) &header, sizeof (header));
989 * Write data to one or more blocks of the tar file.
990 * The data is always padded out to a multiple of TAR_BLOCK_SIZE.
991 * The errorFlag static variable is set on an error.
993 static void writeTarBlock (const char *buf, int len)
997 char fullBlock[TAR_BLOCK_SIZE];
1000 * If we had a write error before, then do nothing more.
1002 if (errorFlag==TRUE)
1006 * Get the amount of complete and partial blocks.
1008 partialLength = len % TAR_BLOCK_SIZE;
1009 completeLength = len - partialLength;
1012 * Write all of the complete blocks.
1014 if ((completeLength > 0) && !fullWrite (tarFd, buf, completeLength)) {
1023 * If there are no partial blocks left, we are done.
1025 if (partialLength == 0)
1029 * Copy the partial data into a complete block, and pad the rest
1030 * of it with zeroes.
1032 memcpy (fullBlock, buf + completeLength, partialLength);
1033 memset (fullBlock + partialLength, 0, TAR_BLOCK_SIZE - partialLength);
1036 * Write the last complete block.
1038 if (!fullWrite (tarFd, fullBlock, TAR_BLOCK_SIZE)) {
1047 * Read an octal value in a field of the specified width, with optional
1048 * spaces on both sides of the number and with an optional null character
1049 * at the end. Returns -1 on an illegal format.
1051 static long getOctal (const char *cp, int len)
1055 while ((len > 0) && (*cp == ' ')) {
1060 if ((len == 0) || !isOctal (*cp))
1065 while ((len > 0) && isOctal (*cp)) {
1066 val = val * 8 + *cp++ - '0';
1070 while ((len > 0) && (*cp == ' ')) {
1075 if ((len > 0) && *cp)
1083 * Put an octal string into the specified buffer.
1084 * The number is zero and space padded and possibly null padded.
1085 * Returns TRUE if successful.
1087 static int putOctal (char *cp, int len, long value)
1091 char tempBuffer[32];
1094 * Create a string of the specified length with an initial space,
1095 * leading zeroes and the octal number, and a trailing null.
1097 tempString = tempBuffer;
1099 sprintf (tempString, " %0*lo", len - 2, value);
1101 tempLength = strlen (tempString) + 1;
1104 * If the string is too large, suppress the leading space.
1106 if (tempLength > len) {
1112 * If the string is still too large, suppress the trailing null.
1114 if (tempLength > len)
1118 * If the string is still too large, fail.
1120 if (tempLength > len)
1124 * Copy the string to the field.
1126 memcpy (cp, tempString, len);
1133 * See if the specified file name belongs to one of the specified list
1134 * of path prefixes. An empty list implies that all files are wanted.
1135 * Returns TRUE if the file is selected.
1138 wantFileName (const char *fileName, int fileCount, char **fileTable)
1140 const char *pathName;
1145 * If there are no files in the list, then the file is wanted.
1150 fileLength = strlen (fileName);
1153 * Check each of the test paths.
1155 while (fileCount-- > 0) {
1156 pathName = *fileTable++;
1158 pathLength = strlen (pathName);
1160 if (fileLength < pathLength)
1163 if (memcmp (fileName, pathName, pathLength) != 0)
1166 if ((fileLength == pathLength) || (fileName[pathLength] == '/')) {