2 * Copyright (c) 1999 by David I. Bell
3 * Permission is granted to use, distribute, or modify this source,
4 * provided that this copyright notice remains intact.
6 * The "tar" command, taken from sash.
7 * This allows creation, extraction, and listing of tar files.
9 * Permission to distribute this code under the GPL has been granted.
10 * Modified for busybox by Erik Andersen <andersee@debian.org>
23 static const char tar_usage[] =
24 "Create, extract, or list files from a TAR file\n\n"
25 "usage: tar -[cxtvOf] [tarFileName] [FILE] ...\n"
26 "\tc=create, x=extract, t=list contents, v=verbose,\n"
27 "\tO=extract to stdout, f=tarfile or \"-\" for stdin\n";
34 #define TAR_BLOCK_SIZE 512
35 #define TAR_NAME_SIZE 100
39 * The POSIX (and basic GNU) tar header format.
40 * This structure is always embedded in a TAR_BLOCK_SIZE sized block
41 * with zero padding. We only process this information minimally.
44 char name[TAR_NAME_SIZE];
52 char linkName[TAR_NAME_SIZE];
62 #define TAR_MAGIC "ustar"
63 #define TAR_VERSION "00"
65 #define TAR_TYPE_REGULAR '0'
66 #define TAR_TYPE_HARD_LINK '1'
67 #define TAR_TYPE_SOFT_LINK '2'
74 static int extractFlag;
75 static int createFlag;
76 static int verboseFlag;
77 static int tostdoutFlag;
82 static int skipFileFlag;
83 static int warnedRoot;
87 static char outName[TAR_NAME_SIZE];
91 * Static data associated with the tar file.
93 static const char *tarName;
96 static ino_t tarInode;
100 * Local procedures to restore files from a tar file.
102 static void readTarFile (int fileCount, char **fileTable);
103 static void readData (const char *cp, int count);
104 static long getOctal (const char *cp, int len);
106 static void readHeader (const TarHeader * hp,
107 int fileCount, char **fileTable);
111 * Local procedures to save files into a tar file.
113 static void saveFile (const char *fileName, int seeLinks);
115 static void saveRegularFile (const char *fileName,
116 const struct stat *statbuf);
118 static void saveDirectory (const char *fileName,
119 const struct stat *statbuf);
121 static int wantFileName (const char *fileName,
122 int fileCount, char **fileTable);
124 static void writeHeader (const char *fileName, const struct stat *statbuf);
126 static void writeTarFile (int fileCount, char **fileTable);
127 static void writeTarBlock (const char *buf, int len);
128 static int putOctal (char *cp, int len, long value);
131 extern int tar_main (int argc, char **argv)
139 fprintf (stderr, "%s", tar_usage);
149 tostdoutFlag = FALSE;
162 for (; *options; options++) {
165 if (tarName != NULL) {
166 fprintf (stderr, "Only one 'f' option allowed\n");
200 fprintf (stderr, "Unknown tar flag '%c'\n", *options);
208 * Validate the options.
210 if (extractFlag + listFlag + createFlag != 1) {
212 "Exactly one of 'c', 'x' or 't' must be specified\n");
218 * Do the correct type of action supplying the rest of the
219 * command line arguments as the list of files to process.
222 writeTarFile (argc, argv);
224 readTarFile (argc, argv);
226 fprintf (stderr, "\n");
232 * Read a tar file and extract or list the specified files within it.
233 * If the list is empty than all files are extracted or listed.
235 static void readTarFile (int fileCount, char **fileTable)
243 skipFileFlag = FALSE;
251 blockSize = sizeof (buf);
255 * Open the tar file for reading.
257 if ((tarName == NULL) || !strcmp (tarName, "-")) {
260 tarFd = open (tarName, O_RDONLY);
269 * Read blocks from the file until an end of file header block
270 * has been seen. (A real end of file from a read is an error.)
274 * Read the next block of data if necessary.
275 * This will be a large block if possible, which we will
276 * then process in the small tar blocks.
280 inCc = fullRead (tarFd, buf, blockSize);
290 "Unexpected end of file from \"%s\"", tarName);
297 * If we are expecting a header block then examine it.
300 readHeader ((const TarHeader *) cp, fileCount, fileTable);
302 cp += TAR_BLOCK_SIZE;
303 inCc -= TAR_BLOCK_SIZE;
309 * We are currently handling the data for a file.
310 * Process the minimum of the amount of data we have available
311 * and the amount left to be processed for the file.
321 * If the amount left isn't an exact multiple of the tar block
322 * size then round it up to the next block boundary since there
323 * is padding at the end of the file.
325 if (cc % TAR_BLOCK_SIZE)
326 cc += TAR_BLOCK_SIZE - (cc % TAR_BLOCK_SIZE);
334 * Close the tar file if needed.
336 if ((tarFd >= 0) && (close (tarFd) < 0))
340 * Close the output file if needed.
341 * This is only done here on a previous error and so no
342 * message is required on errors.
344 if (tostdoutFlag == FALSE) {
346 (void) close (outFd);
352 * Examine the header block that was just read.
353 * This can specify the information for another file, or it can mark
354 * the end of the tar file.
357 readHeader (const TarHeader * hp, int fileCount, char **fileTable)
371 * If the block is completely empty, then this is the end of the
372 * archive file. If the name is null, then just skip this header.
377 for (cc = TAR_BLOCK_SIZE; cc > 0; cc--) {
388 * There is another file in the archive to examine.
389 * Extract the encoded information and check it.
391 mode = getOctal (hp->mode, sizeof (hp->mode));
392 uid = getOctal (hp->uid, sizeof (hp->uid));
393 gid = getOctal (hp->gid, sizeof (hp->gid));
394 size = getOctal (hp->size, sizeof (hp->size));
395 mtime = getOctal (hp->mtime, sizeof (hp->mtime));
396 checkSum = getOctal (hp->checkSum, sizeof (hp->checkSum));
398 if ((mode < 0) || (uid < 0) || (gid < 0) || (size < 0)) {
400 fprintf (stderr, "Bad tar header, skipping\n");
408 skipFileFlag = FALSE;
411 * Check for the file modes.
413 hardLink = ((hp->typeFlag == TAR_TYPE_HARD_LINK) ||
414 (hp->typeFlag == TAR_TYPE_HARD_LINK - '0'));
416 softLink = ((hp->typeFlag == TAR_TYPE_SOFT_LINK) ||
417 (hp->typeFlag == TAR_TYPE_SOFT_LINK - '0'));
420 * Check for a directory or a regular file.
422 if (name[strlen (name) - 1] == '/')
424 else if ((mode & S_IFMT) == 0)
428 * Check for absolute paths in the file.
429 * If we find any, then warn the user and make them relative.
437 "Absolute path detected, removing leading slashes\n");
444 * See if we want this file to be restored.
445 * If not, then set up to skip it.
447 if (!wantFileName (name, fileCount, fileTable)) {
448 if (!hardLink && !softLink && S_ISREG (mode)) {
449 inHeader = (size == 0);
459 * This file is to be handled.
460 * If we aren't extracting then just list information about the file.
464 printf ("%s %3d/%-d %9ld %s %s", modeString (mode),
465 uid, gid, size, timeString (mtime), name);
470 printf (" (link to \"%s\")", hp->linkName);
472 printf (" (symlink to \"%s\")", hp->linkName);
473 else if (S_ISREG (mode)) {
474 inHeader = (size == 0);
484 * We really want to extract the file.
487 printf ("x %s\n", name);
490 if (link (hp->linkName, name) < 0)
498 if (symlink (hp->linkName, name) < 0)
501 fprintf (stderr, "Cannot create symbolic links\n");
507 * If the file is a directory, then just create the path.
509 if (S_ISDIR (mode)) {
510 createPath (name, mode);
516 * There is a file to write.
517 * First create the path to it if necessary with a default permission.
519 createPath (name, 0777);
521 inHeader = (size == 0);
525 * Start the output file.
527 if (tostdoutFlag == TRUE)
530 outFd = open (name, O_WRONLY | O_CREAT | O_TRUNC, mode);
539 * If the file is empty, then that's all we need to do.
541 if (size == 0 && tostdoutFlag == FALSE) {
542 (void) close (outFd);
549 * Handle a data block of some specified size that was read.
551 static void readData (const char *cp, int count)
554 * Reduce the amount of data left in this file.
555 * If there is no more data left, then we need to read
564 * If we aren't extracting files or this file is being
565 * skipped then do nothing more.
567 if (!extractFlag || skipFileFlag)
571 * Write the data to the output file.
573 if (fullWrite (outFd, cp, count) < 0) {
575 if (tostdoutFlag == FALSE) {
576 (void) close (outFd);
584 * If the write failed, close the file and disable further
585 * writes to this file.
587 if (dataCc <= 0 && tostdoutFlag == FALSE) {
597 * Write a tar file containing the specified files.
599 static void writeTarFile (int fileCount, char **fileTable)
604 * Make sure there is at least one file specified.
606 if (fileCount <= 0) {
607 fprintf (stderr, "No files specified to be saved\n");
612 * Create the tar file for writing.
614 if ((tarName == NULL) || !strcmp (tarName, "-")) {
618 tarFd = open (tarName, O_WRONLY | O_CREAT | O_TRUNC, 0666);
627 * Get the device and inode of the tar file for checking later.
629 if (fstat (tarFd, &statbuf) < 0) {
635 tarDev = statbuf.st_dev;
636 tarInode = statbuf.st_ino;
639 * Append each file name into the archive file.
640 * Follow symbolic links for these top level file names.
642 while (!errorFlag && (fileCount-- > 0)) {
643 saveFile (*fileTable++, FALSE);
647 * Now write an empty block of zeroes to end the archive.
649 writeTarBlock ("", 1);
654 * Close the tar file and check for errors if it was opened.
656 if ((tostdoutFlag == FALSE) && (tarFd >= 0) && (close (tarFd) < 0))
662 * Save one file into the tar file.
663 * If the file is a directory, then this will recursively save all of
664 * the files and directories within the directory. The seeLinks
665 * flag indicates whether or not we want to see symbolic links as
666 * they really are, instead of blindly following them.
668 static void saveFile (const char *fileName, int seeLinks)
675 printf ("a %s\n", fileName);
678 * Check that the file name will fit in the header.
680 if (strlen (fileName) >= TAR_NAME_SIZE) {
681 fprintf (stderr, "%s: File name is too long\n", fileName);
687 * Find out about the file.
691 status = lstat (fileName, &statbuf);
694 status = stat (fileName, &statbuf);
703 * Make sure we aren't trying to save our file into itself.
705 if ((statbuf.st_dev == tarDev) && (statbuf.st_ino == tarInode)) {
706 fprintf (stderr, "Skipping saving of archive file itself\n");
712 * Check the type of file.
714 mode = statbuf.st_mode;
716 if (S_ISDIR (mode)) {
717 saveDirectory (fileName, &statbuf);
722 if (S_ISREG (mode)) {
723 saveRegularFile (fileName, &statbuf);
729 * The file is a strange type of file, ignore it.
731 fprintf (stderr, "%s: not a directory or regular file\n", fileName);
736 * Save a regular file to the tar file.
739 saveRegularFile (const char *fileName, const struct stat *statbuf)
746 char data[TAR_BLOCK_SIZE * 16];
749 * Open the file for reading.
751 fileFd = open (fileName, O_RDONLY);
760 * Write out the header for the file.
762 writeHeader (fileName, statbuf);
765 * Write the data blocks of the file.
766 * We must be careful to write the amount of data that the stat
767 * buffer indicated, even if the file has changed size. Otherwise
768 * the tar file will be incorrect.
770 fullDataCount = statbuf->st_size;
773 while (fullDataCount > 0) {
775 * Get the amount to write this iteration which is
776 * the minumum of the amount left to write and the
779 dataCount = sizeof (data);
781 if (dataCount > fullDataCount)
782 dataCount = (int) fullDataCount;
785 * Read the data from the file if we haven't seen the
791 cc = fullRead (fileFd, data, dataCount);
796 (void) close (fileFd);
803 * If the file ended too soon, complain and set
804 * a flag so we will zero fill the rest of it.
806 if (cc < dataCount) {
808 "%s: Short read - zero filling", fileName);
815 * Zero fill the rest of the data if necessary.
818 memset (data + cc, 0, dataCount - cc);
821 * Write the buffer to the TAR file.
823 writeTarBlock (data, dataCount);
825 fullDataCount -= dataCount;
831 if ((tostdoutFlag == FALSE) && close (fileFd) < 0)
832 fprintf (stderr, "%s: close: %s\n", fileName, strerror (errno));
837 * Save a directory and all of its files to the tar file.
839 static void saveDirectory (const char *dirName, const struct stat *statbuf)
842 struct dirent *entry;
844 char fullName[NAME_MAX];
847 * Construct the directory name as used in the tar file by appending
848 * a slash character to it.
850 strcpy (fullName, dirName);
851 strcat (fullName, "/");
854 * Write out the header for the directory entry.
856 writeHeader (fullName, statbuf);
859 * Open the directory.
861 dir = opendir (dirName);
864 fprintf (stderr, "Cannot read directory \"%s\": %s\n",
865 dirName, strerror (errno));
871 * See if a slash is needed.
873 needSlash = (*dirName && (dirName[strlen (dirName) - 1] != '/'));
876 * Read all of the directory entries and check them,
877 * except for the current and parent directory entries.
879 while (!errorFlag && ((entry = readdir (dir)) != NULL)) {
880 if ((strcmp (entry->d_name, ".") == 0) ||
881 (strcmp (entry->d_name, "..") == 0)) {
886 * Build the full path name to the file.
888 strcpy (fullName, dirName);
891 strcat (fullName, "/");
893 strcat (fullName, entry->d_name);
896 * Write this file to the tar file, noticing whether or not
897 * the file is a symbolic link.
899 saveFile (fullName, TRUE);
903 * All done, close the directory.
910 * Write a tar header for the specified file name and status.
911 * It is assumed that the file name fits.
913 static void writeHeader (const char *fileName, const struct stat *statbuf)
916 const unsigned char *cp;
921 * Zero the header block in preparation for filling it in.
923 memset ((char *) &header, 0, sizeof (header));
926 * Fill in the header.
928 strcpy (header.name, fileName);
930 strncpy (header.magic, TAR_MAGIC, sizeof (header.magic));
931 strncpy (header.version, TAR_VERSION, sizeof (header.version));
933 putOctal (header.mode, sizeof (header.mode), statbuf->st_mode & 0777);
934 putOctal (header.uid, sizeof (header.uid), statbuf->st_uid);
935 putOctal (header.gid, sizeof (header.gid), statbuf->st_gid);
936 putOctal (header.size, sizeof (header.size), statbuf->st_size);
937 putOctal (header.mtime, sizeof (header.mtime), statbuf->st_mtime);
939 header.typeFlag = TAR_TYPE_REGULAR;
942 * Calculate and store the checksum.
943 * This is the sum of all of the bytes of the header,
944 * with the checksum field itself treated as blanks.
946 memset (header.checkSum, ' ', sizeof (header.checkSum));
948 cp = (const unsigned char *) &header;
949 len = sizeof (header);
955 putOctal (header.checkSum, sizeof (header.checkSum), checkSum);
958 * Write the tar header.
960 writeTarBlock ((const char *) &header, sizeof (header));
965 * Write data to one or more blocks of the tar file.
966 * The data is always padded out to a multiple of TAR_BLOCK_SIZE.
967 * The errorFlag static variable is set on an error.
969 static void writeTarBlock (const char *buf, int len)
973 char fullBlock[TAR_BLOCK_SIZE];
976 * If we had a write error before, then do nothing more.
982 * Get the amount of complete and partial blocks.
984 partialLength = len % TAR_BLOCK_SIZE;
985 completeLength = len - partialLength;
988 * Write all of the complete blocks.
990 if ((completeLength > 0) && !fullWrite (tarFd, buf, completeLength)) {
999 * If there are no partial blocks left, we are done.
1001 if (partialLength == 0)
1005 * Copy the partial data into a complete block, and pad the rest
1006 * of it with zeroes.
1008 memcpy (fullBlock, buf + completeLength, partialLength);
1009 memset (fullBlock + partialLength, 0, TAR_BLOCK_SIZE - partialLength);
1012 * Write the last complete block.
1014 if (!fullWrite (tarFd, fullBlock, TAR_BLOCK_SIZE)) {
1023 * Read an octal value in a field of the specified width, with optional
1024 * spaces on both sides of the number and with an optional null character
1025 * at the end. Returns -1 on an illegal format.
1027 static long getOctal (const char *cp, int len)
1031 while ((len > 0) && (*cp == ' ')) {
1036 if ((len == 0) || !isOctal (*cp))
1041 while ((len > 0) && isOctal (*cp)) {
1042 val = val * 8 + *cp++ - '0';
1046 while ((len > 0) && (*cp == ' ')) {
1051 if ((len > 0) && *cp)
1059 * Put an octal string into the specified buffer.
1060 * The number is zero and space padded and possibly null padded.
1061 * Returns TRUE if successful.
1063 static int putOctal (char *cp, int len, long value)
1067 char tempBuffer[32];
1070 * Create a string of the specified length with an initial space,
1071 * leading zeroes and the octal number, and a trailing null.
1073 tempString = tempBuffer;
1075 sprintf (tempString, " %0*lo", len - 2, value);
1077 tempLength = strlen (tempString) + 1;
1080 * If the string is too large, suppress the leading space.
1082 if (tempLength > len) {
1088 * If the string is still too large, suppress the trailing null.
1090 if (tempLength > len)
1094 * If the string is still too large, fail.
1096 if (tempLength > len)
1100 * Copy the string to the field.
1102 memcpy (cp, tempString, len);
1109 * See if the specified file name belongs to one of the specified list
1110 * of path prefixes. An empty list implies that all files are wanted.
1111 * Returns TRUE if the file is selected.
1114 wantFileName (const char *fileName, int fileCount, char **fileTable)
1116 const char *pathName;
1121 * If there are no files in the list, then the file is wanted.
1126 fileLength = strlen (fileName);
1129 * Check each of the test paths.
1131 while (fileCount-- > 0) {
1132 pathName = *fileTable++;
1134 pathLength = strlen (pathName);
1136 if (fileLength < pathLength)
1139 if (memcmp (fileName, pathName, pathLength) != 0)
1142 if ((fileLength == pathLength) || (fileName[pathLength] == '/')) {