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>
18 const char tar_usage[] =
19 "Create, extract, or list files from a TAR file\n\n"
20 "usage: tar -[cxtvOf] [tarFileName] [FILE] ...\n"
21 "\tc=create, x=extract, t=list contents, v=verbose,\n"
22 "\tO=extract to stdout, f=tarfile or \"-\" for stdin\n";
36 #define TAR_BLOCK_SIZE 512
37 #define TAR_NAME_SIZE 100
41 * The POSIX (and basic GNU) tar header format.
42 * This structure is always embedded in a TAR_BLOCK_SIZE sized block
43 * with zero padding. We only process this information minimally.
46 char name[TAR_NAME_SIZE];
54 char linkName[TAR_NAME_SIZE];
64 #define TAR_MAGIC "ustar"
65 #define TAR_VERSION "00"
67 #define TAR_TYPE_REGULAR '0'
68 #define TAR_TYPE_HARD_LINK '1'
69 #define TAR_TYPE_SOFT_LINK '2'
76 static int extractFlag;
77 static int createFlag;
78 static int verboseFlag;
79 static int tostdoutFlag;
84 static int skipFileFlag;
85 static int warnedRoot;
89 static char outName[TAR_NAME_SIZE];
93 * Static data associated with the tar file.
95 static const char *tarName;
98 static ino_t tarInode;
102 * Local procedures to restore files from a tar file.
104 static void readTarFile (int fileCount, char **fileTable);
105 static void readData (const char *cp, int count);
106 static void createPath (const char *name, int mode);
107 static long getOctal (const char *cp, int len);
109 static void readHeader (const TarHeader * hp,
110 int fileCount, char **fileTable);
114 * Local procedures to save files into a tar file.
116 static void saveFile (const char *fileName, int seeLinks);
118 static void saveRegularFile (const char *fileName,
119 const struct stat *statbuf);
121 static void saveDirectory (const char *fileName,
122 const struct stat *statbuf);
124 static int wantFileName (const char *fileName,
125 int fileCount, char **fileTable);
127 static void writeHeader (const char *fileName, const struct stat *statbuf);
129 static void writeTarFile (int fileCount, char **fileTable);
130 static void writeTarBlock (const char *buf, int len);
131 static int putOctal (char *cp, int len, long value);
134 extern int tar_main (int argc, char **argv)
142 fprintf (stderr, "%s", tar_usage);
152 tostdoutFlag = FALSE;
165 for (; *options; options++) {
168 if (tarName != NULL) {
169 fprintf (stderr, "Only one 'f' option allowed\n");
203 fprintf (stderr, "Unknown tar flag '%c'\n", *options);
211 * Validate the options.
213 if (extractFlag + listFlag + createFlag != 1) {
215 "Exactly one of 'c', 'x' or 't' must be specified\n");
221 * Do the correct type of action supplying the rest of the
222 * command line arguments as the list of files to process.
225 writeTarFile (argc, argv);
227 readTarFile (argc, argv);
229 fprintf (stderr, "\n");
235 * Read a tar file and extract or list the specified files within it.
236 * If the list is empty than all files are extracted or listed.
238 static void readTarFile (int fileCount, char **fileTable)
246 skipFileFlag = FALSE;
254 blockSize = sizeof (buf);
258 * Open the tar file for reading.
260 if ((tarName == NULL) || !strcmp (tarName, "-")) {
263 tarFd = open (tarName, O_RDONLY);
272 * Read blocks from the file until an end of file header block
273 * has been seen. (A real end of file from a read is an error.)
277 * Read the next block of data if necessary.
278 * This will be a large block if possible, which we will
279 * then process in the small tar blocks.
283 inCc = fullRead (tarFd, buf, blockSize);
293 "Unexpected end of file from \"%s\"", tarName);
300 * If we are expecting a header block then examine it.
303 readHeader ((const TarHeader *) cp, fileCount, fileTable);
305 cp += TAR_BLOCK_SIZE;
306 inCc -= TAR_BLOCK_SIZE;
312 * We are currently handling the data for a file.
313 * Process the minimum of the amount of data we have available
314 * and the amount left to be processed for the file.
324 * If the amount left isn't an exact multiple of the tar block
325 * size then round it up to the next block boundary since there
326 * is padding at the end of the file.
328 if (cc % TAR_BLOCK_SIZE)
329 cc += TAR_BLOCK_SIZE - (cc % TAR_BLOCK_SIZE);
337 * Close the tar file if needed.
339 if ((tarFd >= 0) && (close (tarFd) < 0))
343 * Close the output file if needed.
344 * This is only done here on a previous error and so no
345 * message is required on errors.
347 if (tostdoutFlag == FALSE) {
349 (void) close (outFd);
355 * Examine the header block that was just read.
356 * This can specify the information for another file, or it can mark
357 * the end of the tar file.
360 readHeader (const TarHeader * hp, int fileCount, char **fileTable)
374 * If the block is completely empty, then this is the end of the
375 * archive file. If the name is null, then just skip this header.
380 for (cc = TAR_BLOCK_SIZE; cc > 0; cc--) {
391 * There is another file in the archive to examine.
392 * Extract the encoded information and check it.
394 mode = getOctal (hp->mode, sizeof (hp->mode));
395 uid = getOctal (hp->uid, sizeof (hp->uid));
396 gid = getOctal (hp->gid, sizeof (hp->gid));
397 size = getOctal (hp->size, sizeof (hp->size));
398 mtime = getOctal (hp->mtime, sizeof (hp->mtime));
399 checkSum = getOctal (hp->checkSum, sizeof (hp->checkSum));
401 if ((mode < 0) || (uid < 0) || (gid < 0) || (size < 0)) {
403 fprintf (stderr, "Bad tar header, skipping\n");
411 skipFileFlag = FALSE;
414 * Check for the file modes.
416 hardLink = ((hp->typeFlag == TAR_TYPE_HARD_LINK) ||
417 (hp->typeFlag == TAR_TYPE_HARD_LINK - '0'));
419 softLink = ((hp->typeFlag == TAR_TYPE_SOFT_LINK) ||
420 (hp->typeFlag == TAR_TYPE_SOFT_LINK - '0'));
423 * Check for a directory or a regular file.
425 if (name[strlen (name) - 1] == '/')
427 else if ((mode & S_IFMT) == 0)
431 * Check for absolute paths in the file.
432 * If we find any, then warn the user and make them relative.
440 "Absolute path detected, removing leading slashes\n");
447 * See if we want this file to be restored.
448 * If not, then set up to skip it.
450 if (!wantFileName (name, fileCount, fileTable)) {
451 if (!hardLink && !softLink && S_ISREG (mode)) {
452 inHeader = (size == 0);
462 * This file is to be handled.
463 * If we aren't extracting then just list information about the file.
467 printf ("%s %3d/%-d %9ld %s %s", modeString (mode),
468 uid, gid, size, timeString (mtime), name);
473 printf (" (link to \"%s\")", hp->linkName);
475 printf (" (symlink to \"%s\")", hp->linkName);
476 else if (S_ISREG (mode)) {
477 inHeader = (size == 0);
487 * We really want to extract the file.
490 printf ("x %s\n", name);
493 if (link (hp->linkName, name) < 0)
501 if (symlink (hp->linkName, name) < 0)
504 fprintf (stderr, "Cannot create symbolic links\n");
510 * If the file is a directory, then just create the path.
512 if (S_ISDIR (mode)) {
513 createPath (name, mode);
519 * There is a file to write.
520 * First create the path to it if necessary with a default permission.
522 createPath (name, 0777);
524 inHeader = (size == 0);
528 * Start the output file.
530 if (tostdoutFlag == TRUE)
533 outFd = open (name, O_WRONLY | O_CREAT | O_TRUNC, mode);
542 * If the file is empty, then that's all we need to do.
544 if (size == 0 && tostdoutFlag == FALSE) {
545 (void) close (outFd);
552 * Handle a data block of some specified size that was read.
554 static void readData (const char *cp, int count)
557 * Reduce the amount of data left in this file.
558 * If there is no more data left, then we need to read
567 * If we aren't extracting files or this file is being
568 * skipped then do nothing more.
570 if (!extractFlag || skipFileFlag)
574 * Write the data to the output file.
576 if (fullWrite (outFd, cp, count) < 0) {
578 if (tostdoutFlag == FALSE) {
579 (void) close (outFd);
587 * If the write failed, close the file and disable further
588 * writes to this file.
590 if (dataCc <= 0 && tostdoutFlag == FALSE) {
600 * Write a tar file containing the specified files.
602 static void writeTarFile (int fileCount, char **fileTable)
607 * Make sure there is at least one file specified.
609 if (fileCount <= 0) {
610 fprintf (stderr, "No files specified to be saved\n");
615 * Create the tar file for writing.
617 if ((tarName == NULL) || !strcmp (tarName, "-")) {
621 tarFd = open (tarName, O_WRONLY | O_CREAT | O_TRUNC, 0666);
630 * Get the device and inode of the tar file for checking later.
632 if (fstat (tarFd, &statbuf) < 0) {
638 tarDev = statbuf.st_dev;
639 tarInode = statbuf.st_ino;
642 * Append each file name into the archive file.
643 * Follow symbolic links for these top level file names.
645 while (!errorFlag && (fileCount-- > 0)) {
646 saveFile (*fileTable++, FALSE);
650 * Now write an empty block of zeroes to end the archive.
652 writeTarBlock ("", 1);
657 * Close the tar file and check for errors if it was opened.
659 if ((tostdoutFlag == FALSE) && (tarFd >= 0) && (close (tarFd) < 0))
665 * Save one file into the tar file.
666 * If the file is a directory, then this will recursively save all of
667 * the files and directories within the directory. The seeLinks
668 * flag indicates whether or not we want to see symbolic links as
669 * they really are, instead of blindly following them.
671 static void saveFile (const char *fileName, int seeLinks)
678 printf ("a %s\n", fileName);
681 * Check that the file name will fit in the header.
683 if (strlen (fileName) >= TAR_NAME_SIZE) {
684 fprintf (stderr, "%s: File name is too long\n", fileName);
690 * Find out about the file.
694 status = lstat (fileName, &statbuf);
697 status = stat (fileName, &statbuf);
706 * Make sure we aren't trying to save our file into itself.
708 if ((statbuf.st_dev == tarDev) && (statbuf.st_ino == tarInode)) {
709 fprintf (stderr, "Skipping saving of archive file itself\n");
715 * Check the type of file.
717 mode = statbuf.st_mode;
719 if (S_ISDIR (mode)) {
720 saveDirectory (fileName, &statbuf);
725 if (S_ISREG (mode)) {
726 saveRegularFile (fileName, &statbuf);
732 * The file is a strange type of file, ignore it.
734 fprintf (stderr, "%s: not a directory or regular file\n", fileName);
739 * Save a regular file to the tar file.
742 saveRegularFile (const char *fileName, const struct stat *statbuf)
749 char data[TAR_BLOCK_SIZE * 16];
752 * Open the file for reading.
754 fileFd = open (fileName, O_RDONLY);
763 * Write out the header for the file.
765 writeHeader (fileName, statbuf);
768 * Write the data blocks of the file.
769 * We must be careful to write the amount of data that the stat
770 * buffer indicated, even if the file has changed size. Otherwise
771 * the tar file will be incorrect.
773 fullDataCount = statbuf->st_size;
776 while (fullDataCount > 0) {
778 * Get the amount to write this iteration which is
779 * the minumum of the amount left to write and the
782 dataCount = sizeof (data);
784 if (dataCount > fullDataCount)
785 dataCount = (int) fullDataCount;
788 * Read the data from the file if we haven't seen the
794 cc = fullRead (fileFd, data, dataCount);
799 (void) close (fileFd);
806 * If the file ended too soon, complain and set
807 * a flag so we will zero fill the rest of it.
809 if (cc < dataCount) {
811 "%s: Short read - zero filling", fileName);
818 * Zero fill the rest of the data if necessary.
821 memset (data + cc, 0, dataCount - cc);
824 * Write the buffer to the TAR file.
826 writeTarBlock (data, dataCount);
828 fullDataCount -= dataCount;
834 if ((tostdoutFlag == FALSE) && close (fileFd) < 0)
835 fprintf (stderr, "%s: close: %s\n", fileName, strerror (errno));
840 * Save a directory and all of its files to the tar file.
842 static void saveDirectory (const char *dirName, const struct stat *statbuf)
845 struct dirent *entry;
847 char fullName[NAME_MAX];
850 * Construct the directory name as used in the tar file by appending
851 * a slash character to it.
853 strcpy (fullName, dirName);
854 strcat (fullName, "/");
857 * Write out the header for the directory entry.
859 writeHeader (fullName, statbuf);
862 * Open the directory.
864 dir = opendir (dirName);
867 fprintf (stderr, "Cannot read directory \"%s\": %s\n",
868 dirName, strerror (errno));
874 * See if a slash is needed.
876 needSlash = (*dirName && (dirName[strlen (dirName) - 1] != '/'));
879 * Read all of the directory entries and check them,
880 * except for the current and parent directory entries.
882 while (!errorFlag && ((entry = readdir (dir)) != NULL)) {
883 if ((strcmp (entry->d_name, ".") == 0) ||
884 (strcmp (entry->d_name, "..") == 0)) {
889 * Build the full path name to the file.
891 strcpy (fullName, dirName);
894 strcat (fullName, "/");
896 strcat (fullName, entry->d_name);
899 * Write this file to the tar file, noticing whether or not
900 * the file is a symbolic link.
902 saveFile (fullName, TRUE);
906 * All done, close the directory.
913 * Write a tar header for the specified file name and status.
914 * It is assumed that the file name fits.
916 static void writeHeader (const char *fileName, const struct stat *statbuf)
919 const unsigned char *cp;
924 * Zero the header block in preparation for filling it in.
926 memset ((char *) &header, 0, sizeof (header));
929 * Fill in the header.
931 strcpy (header.name, fileName);
933 strncpy (header.magic, TAR_MAGIC, sizeof (header.magic));
934 strncpy (header.version, TAR_VERSION, sizeof (header.version));
936 putOctal (header.mode, sizeof (header.mode), statbuf->st_mode & 0777);
937 putOctal (header.uid, sizeof (header.uid), statbuf->st_uid);
938 putOctal (header.gid, sizeof (header.gid), statbuf->st_gid);
939 putOctal (header.size, sizeof (header.size), statbuf->st_size);
940 putOctal (header.mtime, sizeof (header.mtime), statbuf->st_mtime);
942 header.typeFlag = TAR_TYPE_REGULAR;
945 * Calculate and store the checksum.
946 * This is the sum of all of the bytes of the header,
947 * with the checksum field itself treated as blanks.
949 memset (header.checkSum, ' ', sizeof (header.checkSum));
951 cp = (const unsigned char *) &header;
952 len = sizeof (header);
958 putOctal (header.checkSum, sizeof (header.checkSum), checkSum);
961 * Write the tar header.
963 writeTarBlock ((const char *) &header, sizeof (header));
968 * Write data to one or more blocks of the tar file.
969 * The data is always padded out to a multiple of TAR_BLOCK_SIZE.
970 * The errorFlag static variable is set on an error.
972 static void writeTarBlock (const char *buf, int len)
976 char fullBlock[TAR_BLOCK_SIZE];
979 * If we had a write error before, then do nothing more.
985 * Get the amount of complete and partial blocks.
987 partialLength = len % TAR_BLOCK_SIZE;
988 completeLength = len - partialLength;
991 * Write all of the complete blocks.
993 if ((completeLength > 0) && !fullWrite (tarFd, buf, completeLength)) {
1002 * If there are no partial blocks left, we are done.
1004 if (partialLength == 0)
1008 * Copy the partial data into a complete block, and pad the rest
1009 * of it with zeroes.
1011 memcpy (fullBlock, buf + completeLength, partialLength);
1012 memset (fullBlock + partialLength, 0, TAR_BLOCK_SIZE - partialLength);
1015 * Write the last complete block.
1017 if (!fullWrite (tarFd, fullBlock, TAR_BLOCK_SIZE)) {
1026 * Attempt to create the directories along the specified path, except for
1027 * the final component. The mode is given for the final directory only,
1028 * while all previous ones get default protections. Errors are not reported
1029 * here, as failures to restore files can be reported later.
1031 static void createPath (const char *name, int mode)
1035 char buf[TAR_NAME_SIZE];
1039 cp = strchr (buf, '/');
1043 cp = strchr (cp + 1, '/');
1047 if (mkdir (buf, cp ? 0777 : mode) == 0)
1048 printf ("Directory \"%s\" created\n", buf);
1056 * Read an octal value in a field of the specified width, with optional
1057 * spaces on both sides of the number and with an optional null character
1058 * at the end. Returns -1 on an illegal format.
1060 static long getOctal (const char *cp, int len)
1064 while ((len > 0) && (*cp == ' ')) {
1069 if ((len == 0) || !isOctal (*cp))
1074 while ((len > 0) && isOctal (*cp)) {
1075 val = val * 8 + *cp++ - '0';
1079 while ((len > 0) && (*cp == ' ')) {
1084 if ((len > 0) && *cp)
1092 * Put an octal string into the specified buffer.
1093 * The number is zero and space padded and possibly null padded.
1094 * Returns TRUE if successful.
1096 static int putOctal (char *cp, int len, long value)
1100 char tempBuffer[32];
1103 * Create a string of the specified length with an initial space,
1104 * leading zeroes and the octal number, and a trailing null.
1106 tempString = tempBuffer;
1108 sprintf (tempString, " %0*lo", len - 2, value);
1110 tempLength = strlen (tempString) + 1;
1113 * If the string is too large, suppress the leading space.
1115 if (tempLength > len) {
1121 * If the string is still too large, suppress the trailing null.
1123 if (tempLength > len)
1127 * If the string is still too large, fail.
1129 if (tempLength > len)
1133 * Copy the string to the field.
1135 memcpy (cp, tempString, len);
1142 * See if the specified file name belongs to one of the specified list
1143 * of path prefixes. An empty list implies that all files are wanted.
1144 * Returns TRUE if the file is selected.
1147 wantFileName (const char *fileName, int fileCount, char **fileTable)
1149 const char *pathName;
1154 * If there are no files in the list, then the file is wanted.
1159 fileLength = strlen (fileName);
1162 * Check each of the test paths.
1164 while (fileCount-- > 0) {
1165 pathName = *fileTable++;
1167 pathLength = strlen (pathName);
1169 if (fileLength < pathLength)
1172 if (memcmp (fileName, pathName, pathLength) != 0)
1175 if ((fileLength == pathLength) || (fileName[pathLength] == '/')) {