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 long getOctal (const char *cp, int len);
108 static void readHeader (const TarHeader * hp,
109 int fileCount, char **fileTable);
113 * Local procedures to save files into a tar file.
115 static void saveFile (const char *fileName, int seeLinks);
117 static void saveRegularFile (const char *fileName,
118 const struct stat *statbuf);
120 static void saveDirectory (const char *fileName,
121 const struct stat *statbuf);
123 static int wantFileName (const char *fileName,
124 int fileCount, char **fileTable);
126 static void writeHeader (const char *fileName, const struct stat *statbuf);
128 static void writeTarFile (int fileCount, char **fileTable);
129 static void writeTarBlock (const char *buf, int len);
130 static int putOctal (char *cp, int len, long value);
133 extern int tar_main (int argc, char **argv)
141 fprintf (stderr, "%s", tar_usage);
151 tostdoutFlag = FALSE;
164 for (; *options; options++) {
167 if (tarName != NULL) {
168 fprintf (stderr, "Only one 'f' option allowed\n");
202 fprintf (stderr, "Unknown tar flag '%c'\n", *options);
210 * Validate the options.
212 if (extractFlag + listFlag + createFlag != 1) {
214 "Exactly one of 'c', 'x' or 't' must be specified\n");
220 * Do the correct type of action supplying the rest of the
221 * command line arguments as the list of files to process.
224 writeTarFile (argc, argv);
226 readTarFile (argc, argv);
228 fprintf (stderr, "\n");
234 * Read a tar file and extract or list the specified files within it.
235 * If the list is empty than all files are extracted or listed.
237 static void readTarFile (int fileCount, char **fileTable)
245 skipFileFlag = FALSE;
253 blockSize = sizeof (buf);
257 * Open the tar file for reading.
259 if ((tarName == NULL) || !strcmp (tarName, "-")) {
262 tarFd = open (tarName, O_RDONLY);
271 * Read blocks from the file until an end of file header block
272 * has been seen. (A real end of file from a read is an error.)
276 * Read the next block of data if necessary.
277 * This will be a large block if possible, which we will
278 * then process in the small tar blocks.
282 inCc = fullRead (tarFd, buf, blockSize);
292 "Unexpected end of file from \"%s\"", tarName);
299 * If we are expecting a header block then examine it.
302 readHeader ((const TarHeader *) cp, fileCount, fileTable);
304 cp += TAR_BLOCK_SIZE;
305 inCc -= TAR_BLOCK_SIZE;
311 * We are currently handling the data for a file.
312 * Process the minimum of the amount of data we have available
313 * and the amount left to be processed for the file.
323 * If the amount left isn't an exact multiple of the tar block
324 * size then round it up to the next block boundary since there
325 * is padding at the end of the file.
327 if (cc % TAR_BLOCK_SIZE)
328 cc += TAR_BLOCK_SIZE - (cc % TAR_BLOCK_SIZE);
336 * Close the tar file if needed.
338 if ((tarFd >= 0) && (close (tarFd) < 0))
342 * Close the output file if needed.
343 * This is only done here on a previous error and so no
344 * message is required on errors.
346 if (tostdoutFlag == FALSE) {
348 (void) close (outFd);
354 * Examine the header block that was just read.
355 * This can specify the information for another file, or it can mark
356 * the end of the tar file.
359 readHeader (const TarHeader * hp, int fileCount, char **fileTable)
373 * If the block is completely empty, then this is the end of the
374 * archive file. If the name is null, then just skip this header.
379 for (cc = TAR_BLOCK_SIZE; cc > 0; cc--) {
390 * There is another file in the archive to examine.
391 * Extract the encoded information and check it.
393 mode = getOctal (hp->mode, sizeof (hp->mode));
394 uid = getOctal (hp->uid, sizeof (hp->uid));
395 gid = getOctal (hp->gid, sizeof (hp->gid));
396 size = getOctal (hp->size, sizeof (hp->size));
397 mtime = getOctal (hp->mtime, sizeof (hp->mtime));
398 checkSum = getOctal (hp->checkSum, sizeof (hp->checkSum));
400 if ((mode < 0) || (uid < 0) || (gid < 0) || (size < 0)) {
402 fprintf (stderr, "Bad tar header, skipping\n");
410 skipFileFlag = FALSE;
413 * Check for the file modes.
415 hardLink = ((hp->typeFlag == TAR_TYPE_HARD_LINK) ||
416 (hp->typeFlag == TAR_TYPE_HARD_LINK - '0'));
418 softLink = ((hp->typeFlag == TAR_TYPE_SOFT_LINK) ||
419 (hp->typeFlag == TAR_TYPE_SOFT_LINK - '0'));
422 * Check for a directory or a regular file.
424 if (name[strlen (name) - 1] == '/')
426 else if ((mode & S_IFMT) == 0)
430 * Check for absolute paths in the file.
431 * If we find any, then warn the user and make them relative.
439 "Absolute path detected, removing leading slashes\n");
446 * See if we want this file to be restored.
447 * If not, then set up to skip it.
449 if (!wantFileName (name, fileCount, fileTable)) {
450 if (!hardLink && !softLink && S_ISREG (mode)) {
451 inHeader = (size == 0);
461 * This file is to be handled.
462 * If we aren't extracting then just list information about the file.
466 printf ("%s %3d/%-d %9ld %s %s", modeString (mode),
467 uid, gid, size, timeString (mtime), name);
472 printf (" (link to \"%s\")", hp->linkName);
474 printf (" (symlink to \"%s\")", hp->linkName);
475 else if (S_ISREG (mode)) {
476 inHeader = (size == 0);
486 * We really want to extract the file.
489 printf ("x %s\n", name);
492 if (link (hp->linkName, name) < 0)
500 if (symlink (hp->linkName, name) < 0)
503 fprintf (stderr, "Cannot create symbolic links\n");
509 * If the file is a directory, then just create the path.
511 if (S_ISDIR (mode)) {
512 createPath (name, mode);
518 * There is a file to write.
519 * First create the path to it if necessary with a default permission.
521 createPath (name, 0777);
523 inHeader = (size == 0);
527 * Start the output file.
529 if (tostdoutFlag == TRUE)
532 outFd = open (name, O_WRONLY | O_CREAT | O_TRUNC, mode);
541 * If the file is empty, then that's all we need to do.
543 if (size == 0 && tostdoutFlag == FALSE) {
544 (void) close (outFd);
551 * Handle a data block of some specified size that was read.
553 static void readData (const char *cp, int count)
556 * Reduce the amount of data left in this file.
557 * If there is no more data left, then we need to read
566 * If we aren't extracting files or this file is being
567 * skipped then do nothing more.
569 if (!extractFlag || skipFileFlag)
573 * Write the data to the output file.
575 if (fullWrite (outFd, cp, count) < 0) {
577 if (tostdoutFlag == FALSE) {
578 (void) close (outFd);
586 * If the write failed, close the file and disable further
587 * writes to this file.
589 if (dataCc <= 0 && tostdoutFlag == FALSE) {
599 * Write a tar file containing the specified files.
601 static void writeTarFile (int fileCount, char **fileTable)
606 * Make sure there is at least one file specified.
608 if (fileCount <= 0) {
609 fprintf (stderr, "No files specified to be saved\n");
614 * Create the tar file for writing.
616 if ((tarName == NULL) || !strcmp (tarName, "-")) {
620 tarFd = open (tarName, O_WRONLY | O_CREAT | O_TRUNC, 0666);
629 * Get the device and inode of the tar file for checking later.
631 if (fstat (tarFd, &statbuf) < 0) {
637 tarDev = statbuf.st_dev;
638 tarInode = statbuf.st_ino;
641 * Append each file name into the archive file.
642 * Follow symbolic links for these top level file names.
644 while (!errorFlag && (fileCount-- > 0)) {
645 saveFile (*fileTable++, FALSE);
649 * Now write an empty block of zeroes to end the archive.
651 writeTarBlock ("", 1);
656 * Close the tar file and check for errors if it was opened.
658 if ((tostdoutFlag == FALSE) && (tarFd >= 0) && (close (tarFd) < 0))
664 * Save one file into the tar file.
665 * If the file is a directory, then this will recursively save all of
666 * the files and directories within the directory. The seeLinks
667 * flag indicates whether or not we want to see symbolic links as
668 * they really are, instead of blindly following them.
670 static void saveFile (const char *fileName, int seeLinks)
677 printf ("a %s\n", fileName);
680 * Check that the file name will fit in the header.
682 if (strlen (fileName) >= TAR_NAME_SIZE) {
683 fprintf (stderr, "%s: File name is too long\n", fileName);
689 * Find out about the file.
693 status = lstat (fileName, &statbuf);
696 status = stat (fileName, &statbuf);
705 * Make sure we aren't trying to save our file into itself.
707 if ((statbuf.st_dev == tarDev) && (statbuf.st_ino == tarInode)) {
708 fprintf (stderr, "Skipping saving of archive file itself\n");
714 * Check the type of file.
716 mode = statbuf.st_mode;
718 if (S_ISDIR (mode)) {
719 saveDirectory (fileName, &statbuf);
724 if (S_ISREG (mode)) {
725 saveRegularFile (fileName, &statbuf);
731 * The file is a strange type of file, ignore it.
733 fprintf (stderr, "%s: not a directory or regular file\n", fileName);
738 * Save a regular file to the tar file.
741 saveRegularFile (const char *fileName, const struct stat *statbuf)
748 char data[TAR_BLOCK_SIZE * 16];
751 * Open the file for reading.
753 fileFd = open (fileName, O_RDONLY);
762 * Write out the header for the file.
764 writeHeader (fileName, statbuf);
767 * Write the data blocks of the file.
768 * We must be careful to write the amount of data that the stat
769 * buffer indicated, even if the file has changed size. Otherwise
770 * the tar file will be incorrect.
772 fullDataCount = statbuf->st_size;
775 while (fullDataCount > 0) {
777 * Get the amount to write this iteration which is
778 * the minumum of the amount left to write and the
781 dataCount = sizeof (data);
783 if (dataCount > fullDataCount)
784 dataCount = (int) fullDataCount;
787 * Read the data from the file if we haven't seen the
793 cc = fullRead (fileFd, data, dataCount);
798 (void) close (fileFd);
805 * If the file ended too soon, complain and set
806 * a flag so we will zero fill the rest of it.
808 if (cc < dataCount) {
810 "%s: Short read - zero filling", fileName);
817 * Zero fill the rest of the data if necessary.
820 memset (data + cc, 0, dataCount - cc);
823 * Write the buffer to the TAR file.
825 writeTarBlock (data, dataCount);
827 fullDataCount -= dataCount;
833 if ((tostdoutFlag == FALSE) && close (fileFd) < 0)
834 fprintf (stderr, "%s: close: %s\n", fileName, strerror (errno));
839 * Save a directory and all of its files to the tar file.
841 static void saveDirectory (const char *dirName, const struct stat *statbuf)
844 struct dirent *entry;
846 char fullName[NAME_MAX];
849 * Construct the directory name as used in the tar file by appending
850 * a slash character to it.
852 strcpy (fullName, dirName);
853 strcat (fullName, "/");
856 * Write out the header for the directory entry.
858 writeHeader (fullName, statbuf);
861 * Open the directory.
863 dir = opendir (dirName);
866 fprintf (stderr, "Cannot read directory \"%s\": %s\n",
867 dirName, strerror (errno));
873 * See if a slash is needed.
875 needSlash = (*dirName && (dirName[strlen (dirName) - 1] != '/'));
878 * Read all of the directory entries and check them,
879 * except for the current and parent directory entries.
881 while (!errorFlag && ((entry = readdir (dir)) != NULL)) {
882 if ((strcmp (entry->d_name, ".") == 0) ||
883 (strcmp (entry->d_name, "..") == 0)) {
888 * Build the full path name to the file.
890 strcpy (fullName, dirName);
893 strcat (fullName, "/");
895 strcat (fullName, entry->d_name);
898 * Write this file to the tar file, noticing whether or not
899 * the file is a symbolic link.
901 saveFile (fullName, TRUE);
905 * All done, close the directory.
912 * Write a tar header for the specified file name and status.
913 * It is assumed that the file name fits.
915 static void writeHeader (const char *fileName, const struct stat *statbuf)
918 const unsigned char *cp;
923 * Zero the header block in preparation for filling it in.
925 memset ((char *) &header, 0, sizeof (header));
928 * Fill in the header.
930 strcpy (header.name, fileName);
932 strncpy (header.magic, TAR_MAGIC, sizeof (header.magic));
933 strncpy (header.version, TAR_VERSION, sizeof (header.version));
935 putOctal (header.mode, sizeof (header.mode), statbuf->st_mode & 0777);
936 putOctal (header.uid, sizeof (header.uid), statbuf->st_uid);
937 putOctal (header.gid, sizeof (header.gid), statbuf->st_gid);
938 putOctal (header.size, sizeof (header.size), statbuf->st_size);
939 putOctal (header.mtime, sizeof (header.mtime), statbuf->st_mtime);
941 header.typeFlag = TAR_TYPE_REGULAR;
944 * Calculate and store the checksum.
945 * This is the sum of all of the bytes of the header,
946 * with the checksum field itself treated as blanks.
948 memset (header.checkSum, ' ', sizeof (header.checkSum));
950 cp = (const unsigned char *) &header;
951 len = sizeof (header);
957 putOctal (header.checkSum, sizeof (header.checkSum), checkSum);
960 * Write the tar header.
962 writeTarBlock ((const char *) &header, sizeof (header));
967 * Write data to one or more blocks of the tar file.
968 * The data is always padded out to a multiple of TAR_BLOCK_SIZE.
969 * The errorFlag static variable is set on an error.
971 static void writeTarBlock (const char *buf, int len)
975 char fullBlock[TAR_BLOCK_SIZE];
978 * If we had a write error before, then do nothing more.
984 * Get the amount of complete and partial blocks.
986 partialLength = len % TAR_BLOCK_SIZE;
987 completeLength = len - partialLength;
990 * Write all of the complete blocks.
992 if ((completeLength > 0) && !fullWrite (tarFd, buf, completeLength)) {
1001 * If there are no partial blocks left, we are done.
1003 if (partialLength == 0)
1007 * Copy the partial data into a complete block, and pad the rest
1008 * of it with zeroes.
1010 memcpy (fullBlock, buf + completeLength, partialLength);
1011 memset (fullBlock + partialLength, 0, TAR_BLOCK_SIZE - partialLength);
1014 * Write the last complete block.
1016 if (!fullWrite (tarFd, fullBlock, TAR_BLOCK_SIZE)) {
1025 * Read an octal value in a field of the specified width, with optional
1026 * spaces on both sides of the number and with an optional null character
1027 * at the end. Returns -1 on an illegal format.
1029 static long getOctal (const char *cp, int len)
1033 while ((len > 0) && (*cp == ' ')) {
1038 if ((len == 0) || !isOctal (*cp))
1043 while ((len > 0) && isOctal (*cp)) {
1044 val = val * 8 + *cp++ - '0';
1048 while ((len > 0) && (*cp == ' ')) {
1053 if ((len > 0) && *cp)
1061 * Put an octal string into the specified buffer.
1062 * The number is zero and space padded and possibly null padded.
1063 * Returns TRUE if successful.
1065 static int putOctal (char *cp, int len, long value)
1069 char tempBuffer[32];
1072 * Create a string of the specified length with an initial space,
1073 * leading zeroes and the octal number, and a trailing null.
1075 tempString = tempBuffer;
1077 sprintf (tempString, " %0*lo", len - 2, value);
1079 tempLength = strlen (tempString) + 1;
1082 * If the string is too large, suppress the leading space.
1084 if (tempLength > len) {
1090 * If the string is still too large, suppress the trailing null.
1092 if (tempLength > len)
1096 * If the string is still too large, fail.
1098 if (tempLength > len)
1102 * Copy the string to the field.
1104 memcpy (cp, tempString, len);
1111 * See if the specified file name belongs to one of the specified list
1112 * of path prefixes. An empty list implies that all files are wanted.
1113 * Returns TRUE if the file is selected.
1116 wantFileName (const char *fileName, int fileCount, char **fileTable)
1118 const char *pathName;
1123 * If there are no files in the list, then the file is wanted.
1128 fileLength = strlen (fileName);
1131 * Check each of the test paths.
1133 while (fileCount-- > 0) {
1134 pathName = *fileTable++;
1136 pathLength = strlen (pathName);
1138 if (fileLength < pathLength)
1141 if (memcmp (fileName, pathName, pathLength) != 0)
1144 if ((fileLength == pathLength) || (fileName[pathLength] == '/')) {