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 "tar -[cxtvOf] [tarFileName] [FILE] ...\n"
41 "Create, extract, or list files from a tar file\n\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)
163 tostdoutFlag = FALSE;
176 for (; *options; options++) {
179 if (tarName != NULL) {
180 fprintf (stderr, "Only one 'f' option allowed\n");
214 fprintf (stderr, "Unknown tar flag '%c'\n", *options);
222 * Validate the options.
224 if (extractFlag + listFlag + createFlag != 1) {
226 "Exactly one of 'c', 'x' or 't' must be specified\n");
232 * Do the correct type of action supplying the rest of the
233 * command line arguments as the list of files to process.
236 writeTarFile (argc, argv);
238 readTarFile (argc, argv);
240 fprintf (stderr, "\n");
246 * Read a tar file and extract or list the specified files within it.
247 * If the list is empty than all files are extracted or listed.
249 static void readTarFile (int fileCount, char **fileTable)
257 skipFileFlag = FALSE;
265 blockSize = sizeof (buf);
269 * Open the tar file for reading.
271 if ((tarName == NULL) || !strcmp (tarName, "-")) {
274 tarFd = open (tarName, O_RDONLY);
283 * Read blocks from the file until an end of file header block
284 * has been seen. (A real end of file from a read is an error.)
288 * Read the next block of data if necessary.
289 * This will be a large block if possible, which we will
290 * then process in the small tar blocks.
294 inCc = fullRead (tarFd, buf, blockSize);
304 "Unexpected end of file from \"%s\"", tarName);
311 * If we are expecting a header block then examine it.
314 readHeader ((const TarHeader *) cp, fileCount, fileTable);
316 cp += TAR_BLOCK_SIZE;
317 inCc -= TAR_BLOCK_SIZE;
323 * We are currently handling the data for a file.
324 * Process the minimum of the amount of data we have available
325 * and the amount left to be processed for the file.
335 * If the amount left isn't an exact multiple of the tar block
336 * size then round it up to the next block boundary since there
337 * is padding at the end of the file.
339 if (cc % TAR_BLOCK_SIZE)
340 cc += TAR_BLOCK_SIZE - (cc % TAR_BLOCK_SIZE);
348 * Close the tar file if needed.
350 if ((tarFd >= 0) && (close (tarFd) < 0))
354 * Close the output file if needed.
355 * This is only done here on a previous error and so no
356 * message is required on errors.
358 if (tostdoutFlag == FALSE) {
360 (void) close (outFd);
366 * Examine the header block that was just read.
367 * This can specify the information for another file, or it can mark
368 * the end of the tar file.
371 readHeader (const TarHeader * hp, int fileCount, char **fileTable)
385 * If the block is completely empty, then this is the end of the
386 * archive file. If the name is null, then just skip this header.
391 for (cc = TAR_BLOCK_SIZE; cc > 0; cc--) {
402 * There is another file in the archive to examine.
403 * Extract the encoded information and check it.
405 mode = getOctal (hp->mode, sizeof (hp->mode));
406 uid = getOctal (hp->uid, sizeof (hp->uid));
407 gid = getOctal (hp->gid, sizeof (hp->gid));
408 size = getOctal (hp->size, sizeof (hp->size));
409 mtime = getOctal (hp->mtime, sizeof (hp->mtime));
410 checkSum = getOctal (hp->checkSum, sizeof (hp->checkSum));
412 if ((mode < 0) || (uid < 0) || (gid < 0) || (size < 0)) {
414 fprintf (stderr, "Bad tar header, skipping\n");
422 skipFileFlag = FALSE;
425 * Check for the file modes.
427 hardLink = ((hp->typeFlag == TAR_TYPE_HARD_LINK) ||
428 (hp->typeFlag == TAR_TYPE_HARD_LINK - '0'));
430 softLink = ((hp->typeFlag == TAR_TYPE_SOFT_LINK) ||
431 (hp->typeFlag == TAR_TYPE_SOFT_LINK - '0'));
434 * Check for a directory or a regular file.
436 if (name[strlen (name) - 1] == '/')
438 else if ((mode & S_IFMT) == 0)
442 * Check for absolute paths in the file.
443 * If we find any, then warn the user and make them relative.
451 "Absolute path detected, removing leading slashes\n");
458 * See if we want this file to be restored.
459 * If not, then set up to skip it.
461 if (!wantFileName (name, fileCount, fileTable)) {
462 if (!hardLink && !softLink && S_ISREG (mode)) {
463 inHeader = (size == 0);
473 * This file is to be handled.
474 * If we aren't extracting then just list information about the file.
478 printf ("%s %3d/%-d %9ld %s %s", modeString (mode),
479 uid, gid, size, timeString (mtime), name);
484 printf (" (link to \"%s\")", hp->linkName);
486 printf (" (symlink to \"%s\")", hp->linkName);
487 else if (S_ISREG (mode)) {
488 inHeader = (size == 0);
498 * We really want to extract the file.
501 printf ("x %s\n", name);
504 if (link (hp->linkName, name) < 0)
512 if (symlink (hp->linkName, name) < 0)
515 fprintf (stderr, "Cannot create symbolic links\n");
521 * If the file is a directory, then just create the path.
523 if (S_ISDIR (mode)) {
524 createPath (name, mode);
530 * There is a file to write.
531 * First create the path to it if necessary with a default permission.
533 createPath (name, 0777);
535 inHeader = (size == 0);
539 * Start the output file.
541 if (tostdoutFlag == TRUE)
544 outFd = open (name, O_WRONLY | O_CREAT | O_TRUNC, mode);
553 * If the file is empty, then that's all we need to do.
555 if (size == 0 && tostdoutFlag == FALSE) {
556 (void) close (outFd);
563 * Handle a data block of some specified size that was read.
565 static void readData (const char *cp, int count)
568 * Reduce the amount of data left in this file.
569 * If there is no more data left, then we need to read
578 * If we aren't extracting files or this file is being
579 * skipped then do nothing more.
581 if (!extractFlag || skipFileFlag)
585 * Write the data to the output file.
587 if (fullWrite (outFd, cp, count) < 0) {
589 if (tostdoutFlag == FALSE) {
590 (void) close (outFd);
598 * If the write failed, close the file and disable further
599 * writes to this file.
601 if (dataCc <= 0 && tostdoutFlag == FALSE) {
611 * Write a tar file containing the specified files.
613 static void writeTarFile (int fileCount, char **fileTable)
618 * Make sure there is at least one file specified.
620 if (fileCount <= 0) {
621 fprintf (stderr, "No files specified to be saved\n");
626 * Create the tar file for writing.
628 if ((tarName == NULL) || !strcmp (tarName, "-")) {
632 tarFd = open (tarName, O_WRONLY | O_CREAT | O_TRUNC, 0666);
641 * Get the device and inode of the tar file for checking later.
643 if (fstat (tarFd, &statbuf) < 0) {
649 tarDev = statbuf.st_dev;
650 tarInode = statbuf.st_ino;
653 * Append each file name into the archive file.
654 * Follow symbolic links for these top level file names.
656 while (!errorFlag && (fileCount-- > 0)) {
657 saveFile (*fileTable++, FALSE);
661 * Now write an empty block of zeroes to end the archive.
663 writeTarBlock ("", 1);
668 * Close the tar file and check for errors if it was opened.
670 if ((tostdoutFlag == FALSE) && (tarFd >= 0) && (close (tarFd) < 0))
676 * Save one file into the tar file.
677 * If the file is a directory, then this will recursively save all of
678 * the files and directories within the directory. The seeLinks
679 * flag indicates whether or not we want to see symbolic links as
680 * they really are, instead of blindly following them.
682 static void saveFile (const char *fileName, int seeLinks)
689 printf ("a %s\n", fileName);
692 * Check that the file name will fit in the header.
694 if (strlen (fileName) >= TAR_NAME_SIZE) {
695 fprintf (stderr, "%s: File name is too long\n", fileName);
701 * Find out about the file.
705 status = lstat (fileName, &statbuf);
708 status = stat (fileName, &statbuf);
717 * Make sure we aren't trying to save our file into itself.
719 if ((statbuf.st_dev == tarDev) && (statbuf.st_ino == tarInode)) {
720 fprintf (stderr, "Skipping saving of archive file itself\n");
726 * Check the type of file.
728 mode = statbuf.st_mode;
730 if (S_ISDIR (mode)) {
731 saveDirectory (fileName, &statbuf);
736 if (S_ISREG (mode)) {
737 saveRegularFile (fileName, &statbuf);
743 * The file is a strange type of file, ignore it.
745 fprintf (stderr, "%s: not a directory or regular file\n", fileName);
750 * Save a regular file to the tar file.
753 saveRegularFile (const char *fileName, const struct stat *statbuf)
760 char data[TAR_BLOCK_SIZE * 16];
763 * Open the file for reading.
765 fileFd = open (fileName, O_RDONLY);
774 * Write out the header for the file.
776 writeHeader (fileName, statbuf);
779 * Write the data blocks of the file.
780 * We must be careful to write the amount of data that the stat
781 * buffer indicated, even if the file has changed size. Otherwise
782 * the tar file will be incorrect.
784 fullDataCount = statbuf->st_size;
787 while (fullDataCount > 0) {
789 * Get the amount to write this iteration which is
790 * the minumum of the amount left to write and the
793 dataCount = sizeof (data);
795 if (dataCount > fullDataCount)
796 dataCount = (int) fullDataCount;
799 * Read the data from the file if we haven't seen the
805 cc = fullRead (fileFd, data, dataCount);
810 (void) close (fileFd);
817 * If the file ended too soon, complain and set
818 * a flag so we will zero fill the rest of it.
820 if (cc < dataCount) {
822 "%s: Short read - zero filling", fileName);
829 * Zero fill the rest of the data if necessary.
832 memset (data + cc, 0, dataCount - cc);
835 * Write the buffer to the TAR file.
837 writeTarBlock (data, dataCount);
839 fullDataCount -= dataCount;
845 if ((tostdoutFlag == FALSE) && close (fileFd) < 0)
846 fprintf (stderr, "%s: close: %s\n", fileName, strerror (errno));
851 * Save a directory and all of its files to the tar file.
853 static void saveDirectory (const char *dirName, const struct stat *statbuf)
856 struct dirent *entry;
858 char fullName[NAME_MAX];
861 * Construct the directory name as used in the tar file by appending
862 * a slash character to it.
864 strcpy (fullName, dirName);
865 strcat (fullName, "/");
868 * Write out the header for the directory entry.
870 writeHeader (fullName, statbuf);
873 * Open the directory.
875 dir = opendir (dirName);
878 fprintf (stderr, "Cannot read directory \"%s\": %s\n",
879 dirName, strerror (errno));
885 * See if a slash is needed.
887 needSlash = (*dirName && (dirName[strlen (dirName) - 1] != '/'));
890 * Read all of the directory entries and check them,
891 * except for the current and parent directory entries.
893 while (!errorFlag && ((entry = readdir (dir)) != NULL)) {
894 if ((strcmp (entry->d_name, ".") == 0) ||
895 (strcmp (entry->d_name, "..") == 0)) {
900 * Build the full path name to the file.
902 strcpy (fullName, dirName);
905 strcat (fullName, "/");
907 strcat (fullName, entry->d_name);
910 * Write this file to the tar file, noticing whether or not
911 * the file is a symbolic link.
913 saveFile (fullName, TRUE);
917 * All done, close the directory.
924 * Write a tar header for the specified file name and status.
925 * It is assumed that the file name fits.
927 static void writeHeader (const char *fileName, const struct stat *statbuf)
930 const unsigned char *cp;
935 * Zero the header block in preparation for filling it in.
937 memset ((char *) &header, 0, sizeof (header));
940 * Fill in the header.
942 strcpy (header.name, fileName);
944 strncpy (header.magic, TAR_MAGIC, sizeof (header.magic));
945 strncpy (header.version, TAR_VERSION, sizeof (header.version));
947 putOctal (header.mode, sizeof (header.mode), statbuf->st_mode & 0777);
948 putOctal (header.uid, sizeof (header.uid), statbuf->st_uid);
949 putOctal (header.gid, sizeof (header.gid), statbuf->st_gid);
950 putOctal (header.size, sizeof (header.size), statbuf->st_size);
951 putOctal (header.mtime, sizeof (header.mtime), statbuf->st_mtime);
953 header.typeFlag = TAR_TYPE_REGULAR;
956 * Calculate and store the checksum.
957 * This is the sum of all of the bytes of the header,
958 * with the checksum field itself treated as blanks.
960 memset (header.checkSum, ' ', sizeof (header.checkSum));
962 cp = (const unsigned char *) &header;
963 len = sizeof (header);
969 putOctal (header.checkSum, sizeof (header.checkSum), checkSum);
972 * Write the tar header.
974 writeTarBlock ((const char *) &header, sizeof (header));
979 * Write data to one or more blocks of the tar file.
980 * The data is always padded out to a multiple of TAR_BLOCK_SIZE.
981 * The errorFlag static variable is set on an error.
983 static void writeTarBlock (const char *buf, int len)
987 char fullBlock[TAR_BLOCK_SIZE];
990 * If we had a write error before, then do nothing more.
996 * Get the amount of complete and partial blocks.
998 partialLength = len % TAR_BLOCK_SIZE;
999 completeLength = len - partialLength;
1002 * Write all of the complete blocks.
1004 if ((completeLength > 0) && !fullWrite (tarFd, buf, completeLength)) {
1013 * If there are no partial blocks left, we are done.
1015 if (partialLength == 0)
1019 * Copy the partial data into a complete block, and pad the rest
1020 * of it with zeroes.
1022 memcpy (fullBlock, buf + completeLength, partialLength);
1023 memset (fullBlock + partialLength, 0, TAR_BLOCK_SIZE - partialLength);
1026 * Write the last complete block.
1028 if (!fullWrite (tarFd, fullBlock, TAR_BLOCK_SIZE)) {
1037 * Read an octal value in a field of the specified width, with optional
1038 * spaces on both sides of the number and with an optional null character
1039 * at the end. Returns -1 on an illegal format.
1041 static long getOctal (const char *cp, int len)
1045 while ((len > 0) && (*cp == ' ')) {
1050 if ((len == 0) || !isOctal (*cp))
1055 while ((len > 0) && isOctal (*cp)) {
1056 val = val * 8 + *cp++ - '0';
1060 while ((len > 0) && (*cp == ' ')) {
1065 if ((len > 0) && *cp)
1073 * Put an octal string into the specified buffer.
1074 * The number is zero and space padded and possibly null padded.
1075 * Returns TRUE if successful.
1077 static int putOctal (char *cp, int len, long value)
1081 char tempBuffer[32];
1084 * Create a string of the specified length with an initial space,
1085 * leading zeroes and the octal number, and a trailing null.
1087 tempString = tempBuffer;
1089 sprintf (tempString, " %0*lo", len - 2, value);
1091 tempLength = strlen (tempString) + 1;
1094 * If the string is too large, suppress the leading space.
1096 if (tempLength > len) {
1102 * If the string is still too large, suppress the trailing null.
1104 if (tempLength > len)
1108 * If the string is still too large, fail.
1110 if (tempLength > len)
1114 * Copy the string to the field.
1116 memcpy (cp, tempString, len);
1123 * See if the specified file name belongs to one of the specified list
1124 * of path prefixes. An empty list implies that all files are wanted.
1125 * Returns TRUE if the file is selected.
1128 wantFileName (const char *fileName, int fileCount, char **fileTable)
1130 const char *pathName;
1135 * If there are no files in the list, then the file is wanted.
1140 fileLength = strlen (fileName);
1143 * Check each of the test paths.
1145 while (fileCount-- > 0) {
1146 pathName = *fileTable++;
1148 pathLength = strlen (pathName);
1150 if (fileLength < pathLength)
1153 if (memcmp (fileName, pathName, pathLength) != 0)
1156 if ((fileLength == pathLength) || (fileName[pathLength] == '/')) {