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> <andersen@lineo.com>
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.
47 char name[TAR_NAME_SIZE];
55 char linkName[TAR_NAME_SIZE];
65 #define TAR_MAGIC "ustar"
66 #define TAR_VERSION "00"
68 #define TAR_TYPE_REGULAR '0'
69 #define TAR_TYPE_HARD_LINK '1'
70 #define TAR_TYPE_SOFT_LINK '2'
77 static BOOL extractFlag;
78 static BOOL createFlag;
79 static BOOL verboseFlag;
80 static BOOL tostdoutFlag;
83 static BOOL badHeader;
84 static BOOL errorFlag;
85 static BOOL skipFileFlag;
86 static BOOL warnedRoot;
90 static char outName[TAR_NAME_SIZE];
94 * Static data associated with the tar file.
96 static const char * tarName;
99 static ino_t tarInode;
103 * Local procedures to restore files from a tar file.
105 static void readTarFile(int fileCount, char ** fileTable);
106 static void readData(const char * cp, int count);
107 static void createPath(const char * name, int mode);
108 static long getOctal(const char * cp, int len);
110 static void readHeader(const TarHeader * hp,
111 int fileCount, char ** fileTable);
115 * Local procedures to save files into a tar file.
117 static void saveFile(const char * fileName, BOOL seeLinks);
119 static void saveRegularFile(const char * fileName,
120 const struct stat * statbuf);
122 static void saveDirectory(const char * fileName,
123 const struct stat * statbuf);
125 static BOOL wantFileName(const char * fileName,
126 int fileCount, char ** fileTable);
128 static void writeHeader(const char * fileName,
129 const struct stat * statbuf);
131 static void writeTarFile(int fileCount, char ** fileTable);
132 static void writeTarBlock(const char * buf, int len);
133 static BOOL putOctal(char * cp, int len, long value);
137 tar_main(int argc, char ** argv)
139 const char * options;
146 fprintf(stderr, "%s", tar_usage);
156 tostdoutFlag = FALSE;
169 for (; *options; options++)
176 fprintf(stderr, "Only one 'f' option allowed\n");
210 fprintf(stderr, "Unknown tar flag '%c'\n", *options);
218 * Validate the options.
220 if (extractFlag + listFlag + createFlag != 1)
222 fprintf(stderr, "Exactly one of 'c', 'x' or 't' must be specified\n");
228 * Do the correct type of action supplying the rest of the
229 * command line arguments as the list of files to process.
232 writeTarFile(argc, argv);
234 readTarFile(argc, argv);
236 fprintf(stderr, "\n");
242 * Read a tar file and extract or list the specified files within it.
243 * If the list is empty than all files are extracted or listed.
246 readTarFile(int fileCount, char ** fileTable)
254 skipFileFlag = FALSE;
262 blockSize = sizeof(buf);
266 * Open the tar file for reading.
268 if ( (tarName==NULL) || !strcmp( tarName, "-") ) {
272 tarFd = open(tarName, O_RDONLY);
282 * Read blocks from the file until an end of file header block
283 * 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.
295 inCc = fullRead(tarFd, buf, blockSize);
307 "Unexpected end of file from \"%s\"",
315 * If we are expecting a header block then examine it.
319 readHeader((const TarHeader *) cp, fileCount, fileTable);
321 cp += TAR_BLOCK_SIZE;
322 inCc -= TAR_BLOCK_SIZE;
328 * We are currently handling the data for a file.
329 * Process the minimum of the amount of data we have available
330 * and the amount left to be processed for the file.
340 * If the amount left isn't an exact multiple of the tar block
341 * size then round it up to the next block boundary since there
342 * is padding at the end of the file.
344 if (cc % TAR_BLOCK_SIZE)
345 cc += TAR_BLOCK_SIZE - (cc % TAR_BLOCK_SIZE);
353 * Close the tar file if needed.
355 if ((tarFd >= 0) && (close(tarFd) < 0))
359 * Close the output file if needed.
360 * This is only done here on a previous error and so no
361 * message is required on errors.
363 if (tostdoutFlag==FALSE) {
371 * Examine the header block that was just read.
372 * This can specify the information for another file, or it can mark
373 * the end of the tar file.
376 readHeader(const TarHeader * hp, int fileCount, char ** fileTable)
390 * If the block is completely empty, then this is the end of the
391 * archive file. If the name is null, then just skip this header.
397 for (cc = TAR_BLOCK_SIZE; cc > 0; cc--)
409 * There is another file in the archive to examine.
410 * Extract the encoded information and check it.
412 mode = getOctal(hp->mode, sizeof(hp->mode));
413 uid = getOctal(hp->uid, sizeof(hp->uid));
414 gid = getOctal(hp->gid, sizeof(hp->gid));
415 size = getOctal(hp->size, sizeof(hp->size));
416 mtime = getOctal(hp->mtime, sizeof(hp->mtime));
417 checkSum = getOctal(hp->checkSum, sizeof(hp->checkSum));
419 if ((mode < 0) || (uid < 0) || (gid < 0) || (size < 0))
422 fprintf(stderr, "Bad tar header, skipping\n");
430 skipFileFlag = FALSE;
433 * Check for the file modes.
435 hardLink = ((hp->typeFlag == TAR_TYPE_HARD_LINK) ||
436 (hp->typeFlag == TAR_TYPE_HARD_LINK - '0'));
438 softLink = ((hp->typeFlag == TAR_TYPE_SOFT_LINK) ||
439 (hp->typeFlag == TAR_TYPE_SOFT_LINK - '0'));
442 * Check for a directory or a regular file.
444 if (name[strlen(name) - 1] == '/')
446 else if ((mode & S_IFMT) == 0)
450 * Check for absolute paths in the file.
451 * If we find any, then warn the user and make them relative.
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))
473 if (!hardLink && !softLink && S_ISREG(mode))
475 inHeader = (size == 0);
485 * This file is to be handled.
486 * If we aren't extracting then just list information about the file.
492 printf("%s %3d/%-d %9ld %s %s", modeString(mode),
493 uid, gid, size, timeString(mtime), name);
499 printf(" (link to \"%s\")", hp->linkName);
501 printf(" (symlink to \"%s\")", hp->linkName);
502 else if (S_ISREG(mode))
504 inHeader = (size == 0);
514 * We really want to extract the file.
517 printf("x %s\n", name);
521 if (link(hp->linkName, name) < 0)
530 if (symlink(hp->linkName, name) < 0)
533 fprintf(stderr, "Cannot create symbolic links\n");
539 * If the file is a directory, then just create the path.
543 createPath(name, mode);
549 * There is a file to write.
550 * First create the path to it if necessary with a default permission.
552 createPath(name, 0777);
554 inHeader = (size == 0);
558 * Start the output file.
560 if (tostdoutFlag==TRUE)
563 outFd = open(name, O_WRONLY | O_CREAT | O_TRUNC, mode);
573 * If the file is empty, then that's all we need to do.
575 if (size == 0 && tostdoutFlag == FALSE)
584 * Handle a data block of some specified size that was read.
587 readData(const char * cp, int count)
590 * Reduce the amount of data left in this file.
591 * If there is no more data left, then we need to read
600 * If we aren't extracting files or this file is being
601 * skipped then do nothing more.
603 if (!extractFlag || skipFileFlag)
607 * Write the data to the output file.
609 if (fullWrite(outFd, cp, count) < 0)
612 if (tostdoutFlag==FALSE) {
621 * If the write failed, close the file and disable further
622 * writes to this file.
624 if (dataCc <= 0 && tostdoutFlag==FALSE)
635 * Write a tar file containing the specified files.
638 writeTarFile(int fileCount, char ** fileTable)
643 * Make sure there is at least one file specified.
647 fprintf(stderr, "No files specified to be saved\n");
652 * Create the tar file for writing.
654 if ( (tarName==NULL) || !strcmp( tarName, "-") ) {
659 tarFd = open(tarName, O_WRONLY | O_CREAT | O_TRUNC, 0666);
669 * Get the device and inode of the tar file for checking later.
671 if (fstat(tarFd, &statbuf) < 0)
678 tarDev = statbuf.st_dev;
679 tarInode = statbuf.st_ino;
682 * Append each file name into the archive file.
683 * Follow symbolic links for these top level file names.
685 while (!errorFlag && (fileCount-- > 0))
687 saveFile(*fileTable++, FALSE);
691 * Now write an empty block of zeroes to end the archive.
693 writeTarBlock("", 1);
698 * Close the tar file and check for errors if it was opened.
700 if ( (tostdoutFlag==FALSE) && (tarFd >= 0) && (close(tarFd) < 0))
706 * Save one file into the tar file.
707 * If the file is a directory, then this will recursively save all of
708 * the files and directories within the directory. The seeLinks
709 * flag indicates whether or not we want to see symbolic links as
710 * they really are, instead of blindly following them.
713 saveFile(const char * fileName, BOOL seeLinks)
720 printf("a %s\n", fileName);
723 * Check that the file name will fit in the header.
725 if (strlen(fileName) >= TAR_NAME_SIZE)
727 fprintf(stderr, "%s: File name is too long\n", fileName);
733 * Find out about the file.
737 status = lstat(fileName, &statbuf);
740 status = stat(fileName, &statbuf);
750 * Make sure we aren't trying to save our file into itself.
752 if ((statbuf.st_dev == tarDev) && (statbuf.st_ino == tarInode))
754 fprintf(stderr, "Skipping saving of archive file itself\n");
760 * Check the type of file.
762 mode = statbuf.st_mode;
766 saveDirectory(fileName, &statbuf);
773 saveRegularFile(fileName, &statbuf);
779 * The file is a strange type of file, ignore it.
781 fprintf(stderr, "%s: not a directory or regular file\n", fileName);
786 * Save a regular file to the tar file.
789 saveRegularFile(const char * fileName, const struct stat * statbuf)
796 char data[TAR_BLOCK_SIZE * 16];
799 * Open the file for reading.
801 fileFd = open(fileName, O_RDONLY);
811 * Write out the header for the file.
813 writeHeader(fileName, statbuf);
816 * Write the data blocks of the file.
817 * We must be careful to write the amount of data that the stat
818 * buffer indicated, even if the file has changed size. Otherwise
819 * the tar file will be incorrect.
821 fullDataCount = statbuf->st_size;
824 while (fullDataCount > 0)
827 * Get the amount to write this iteration which is
828 * the minumum of the amount left to write and the
831 dataCount = sizeof(data);
833 if (dataCount > fullDataCount)
834 dataCount = (int) fullDataCount;
837 * Read the data from the file if we haven't seen the
844 cc = fullRead(fileFd, data, dataCount);
850 (void) close(fileFd);
857 * If the file ended too soon, complain and set
858 * a flag so we will zero fill the rest of it.
863 "%s: Short read - zero filling",
871 * Zero fill the rest of the data if necessary.
874 memset(data + cc, 0, dataCount - cc);
877 * Write the buffer to the TAR file.
879 writeTarBlock(data, dataCount);
881 fullDataCount -= dataCount;
887 if ( (tostdoutFlag==FALSE) && close(fileFd) < 0)
888 fprintf(stderr, "%s: close: %s\n", fileName, strerror(errno));
893 * Save a directory and all of its files to the tar file.
896 saveDirectory(const char * dirName, const struct stat * statbuf)
899 struct dirent * entry;
901 char fullName[PATH_LEN];
904 * Construct the directory name as used in the tar file by appending
905 * a slash character to it.
907 strcpy(fullName, dirName);
908 strcat(fullName, "/");
911 * Write out the header for the directory entry.
913 writeHeader(fullName, statbuf);
916 * Open the directory.
918 dir = opendir(dirName);
922 fprintf(stderr, "Cannot read directory \"%s\": %s\n",
923 dirName, strerror(errno));
929 * See if a slash is needed.
931 needSlash = (*dirName && (dirName[strlen(dirName) - 1] != '/'));
934 * Read all of the directory entries and check them,
935 * except for the current and parent directory entries.
937 while (!errorFlag && ((entry = readdir(dir)) != NULL))
939 if ((strcmp(entry->d_name, ".") == 0) ||
940 (strcmp(entry->d_name, "..") == 0))
946 * Build the full path name to the file.
948 strcpy(fullName, dirName);
951 strcat(fullName, "/");
953 strcat(fullName, entry->d_name);
956 * Write this file to the tar file, noticing whether or not
957 * the file is a symbolic link.
959 saveFile(fullName, TRUE);
963 * All done, close the directory.
970 * Write a tar header for the specified file name and status.
971 * It is assumed that the file name fits.
974 writeHeader(const char * fileName, const struct stat * statbuf)
977 const unsigned char * cp;
982 * Zero the header block in preparation for filling it in.
984 memset((char *) &header, 0, sizeof(header));
987 * Fill in the header.
989 strcpy(header.name, fileName);
991 strncpy(header.magic, TAR_MAGIC, sizeof(header.magic));
992 strncpy(header.version, TAR_VERSION, sizeof(header.version));
994 putOctal(header.mode, sizeof(header.mode), statbuf->st_mode & 0777);
995 putOctal(header.uid, sizeof(header.uid), statbuf->st_uid);
996 putOctal(header.gid, sizeof(header.gid), statbuf->st_gid);
997 putOctal(header.size, sizeof(header.size), statbuf->st_size);
998 putOctal(header.mtime, sizeof(header.mtime), statbuf->st_mtime);
1000 header.typeFlag = TAR_TYPE_REGULAR;
1003 * Calculate and store the checksum.
1004 * This is the sum of all of the bytes of the header,
1005 * with the checksum field itself treated as blanks.
1007 memset(header.checkSum, ' ', sizeof(header.checkSum));
1009 cp = (const unsigned char *) &header;
1010 len = sizeof(header);
1016 putOctal(header.checkSum, sizeof(header.checkSum), checkSum);
1019 * Write the tar header.
1021 writeTarBlock((const char *) &header, sizeof(header));
1026 * Write data to one or more blocks of the tar file.
1027 * The data is always padded out to a multiple of TAR_BLOCK_SIZE.
1028 * The errorFlag static variable is set on an error.
1031 writeTarBlock(const char * buf, int len)
1035 char fullBlock[TAR_BLOCK_SIZE];
1038 * If we had a write error before, then do nothing more.
1044 * Get the amount of complete and partial blocks.
1046 partialLength = len % TAR_BLOCK_SIZE;
1047 completeLength = len - partialLength;
1050 * Write all of the complete blocks.
1052 if ((completeLength > 0) && !fullWrite(tarFd, buf, completeLength))
1062 * If there are no partial blocks left, we are done.
1064 if (partialLength == 0)
1068 * Copy the partial data into a complete block, and pad the rest
1069 * of it with zeroes.
1071 memcpy(fullBlock, buf + completeLength, partialLength);
1072 memset(fullBlock + partialLength, 0, TAR_BLOCK_SIZE - partialLength);
1075 * Write the last complete block.
1077 if (!fullWrite(tarFd, fullBlock, TAR_BLOCK_SIZE))
1087 * Attempt to create the directories along the specified path, except for
1088 * the final component. The mode is given for the final directory only,
1089 * while all previous ones get default protections. Errors are not reported
1090 * here, as failures to restore files can be reported later.
1093 createPath(const char * name, int mode)
1097 char buf[TAR_NAME_SIZE];
1101 cp = strchr(buf, '/');
1106 cp = strchr(cp + 1, '/');
1110 if (mkdir(buf, cp ? 0777 : mode) == 0)
1111 printf("Directory \"%s\" created\n", buf);
1119 * Read an octal value in a field of the specified width, with optional
1120 * spaces on both sides of the number and with an optional null character
1121 * at the end. Returns -1 on an illegal format.
1124 getOctal(const char * cp, int len)
1128 while ((len > 0) && (*cp == ' '))
1134 if ((len == 0) || !isOctal(*cp))
1139 while ((len > 0) && isOctal(*cp))
1141 val = val * 8 + *cp++ - '0';
1145 while ((len > 0) && (*cp == ' '))
1151 if ((len > 0) && *cp)
1159 * Put an octal string into the specified buffer.
1160 * The number is zero and space padded and possibly null padded.
1161 * Returns TRUE if successful.
1164 putOctal(char * cp, int len, long value)
1168 char tempBuffer[32];
1171 * Create a string of the specified length with an initial space,
1172 * leading zeroes and the octal number, and a trailing null.
1174 tempString = tempBuffer;
1176 sprintf(tempString, " %0*lo", len - 2, value);
1178 tempLength = strlen(tempString) + 1;
1181 * If the string is too large, suppress the leading space.
1183 if (tempLength > len)
1190 * If the string is still too large, suppress the trailing null.
1192 if (tempLength > len)
1196 * If the string is still too large, fail.
1198 if (tempLength > len)
1202 * Copy the string to the field.
1204 memcpy(cp, tempString, len);
1211 * See if the specified file name belongs to one of the specified list
1212 * of path prefixes. An empty list implies that all files are wanted.
1213 * Returns TRUE if the file is selected.
1216 wantFileName(const char * fileName, int fileCount, char ** fileTable)
1218 const char * pathName;
1223 * If there are no files in the list, then the file is wanted.
1228 fileLength = strlen(fileName);
1231 * Check each of the test paths.
1233 while (fileCount-- > 0)
1235 pathName = *fileTable++;
1237 pathLength = strlen(pathName);
1239 if (fileLength < pathLength)
1242 if (memcmp(fileName, pathName, pathLength) != 0)
1245 if ((fileLength == pathLength) ||
1246 (fileName[pathLength] == '/'))