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 * Modified to handle device special files by Matt Porter
16 * This program is free software; you can redistribute it and/or modify
17 * it under the terms of the GNU General Public License as published by
18 * the Free Software Foundation; either version 2 of the License, or
19 * (at your option) any later version.
21 * This program is distributed in the hope that it will be useful,
22 * but WITHOUT ANY WARRANTY; without even the implied warranty of
23 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
24 * General Public License for more details.
26 * You should have received a copy of the GNU General Public License
27 * along with this program; if not, write to the Free Software
28 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
40 #include <sys/types.h>
43 static const char tar_usage[] =
44 "tar -[cxtvOf] [tarFileName] [FILE] ...\n\n"
45 "Create, extract, or list files from a tar file\n\n"
47 "\tc=create, x=extract, t=list contents, v=verbose,\n"
48 "\tO=extract to stdout, f=tarfile or \"-\" for stdin\n";
55 #define TAR_BLOCK_SIZE 512
56 #define TAR_NAME_SIZE 100
60 * The POSIX (and basic GNU) tar header format.
61 * This structure is always embedded in a TAR_BLOCK_SIZE sized block
62 * with zero padding. We only process this information minimally.
65 char name[TAR_NAME_SIZE];
73 char linkName[TAR_NAME_SIZE];
83 #define TAR_MAGIC "ustar"
84 #define TAR_VERSION "00"
86 #define TAR_TYPE_REGULAR '0'
87 #define TAR_TYPE_HARD_LINK '1'
88 #define TAR_TYPE_SOFT_LINK '2'
95 static int extractFlag;
96 static int createFlag;
97 static int verboseFlag;
98 static int tostdoutFlag;
100 static int inHeader; // <- check me
101 static int badHeader;
102 static int errorFlag;
103 static int skipFileFlag;
104 static int warnedRoot;
108 static char outName[TAR_NAME_SIZE];
112 * Static data associated with the tar file.
114 static const char *tarName;
117 static ino_t tarInode;
121 * Local procedures to restore files from a tar file.
123 static void readTarFile (int fileCount, char **fileTable);
124 static void readData (const char *cp, int count);
125 static long getOctal (const char *cp, int len);
127 static void readHeader (const TarHeader * hp,
128 int fileCount, char **fileTable);
132 * Local procedures to save files into a tar file.
134 static void saveFile (const char *fileName, int seeLinks);
136 static void saveRegularFile (const char *fileName,
137 const struct stat *statbuf);
139 static void saveDirectory (const char *fileName,
140 const struct stat *statbuf);
142 static int wantFileName (const char *fileName,
143 int fileCount, char **fileTable);
145 static void writeHeader (const char *fileName, const struct stat *statbuf);
147 static void writeTarFile (int fileCount, char **fileTable);
148 static void writeTarBlock (const char *buf, int len);
149 static int putOctal (char *cp, int len, long value);
152 extern int tar_main (int argc, char **argv)
168 tostdoutFlag = FALSE;
178 options = (*argv++) + 1;
180 for (; *options; options++) {
183 if (tarName != NULL) {
184 fprintf (stderr, "Only one 'f' option allowed\n");
219 fprintf (stderr, "Unknown tar flag '%c'\n"
220 "Try `tar --help' for more information\n",
229 * Validate the options.
231 if (extractFlag + listFlag + createFlag != (TRUE+FALSE+FALSE)) {
233 "Exactly one of 'c', 'x' or 't' must be specified\n");
239 * Do the correct type of action supplying the rest of the
240 * command line arguments as the list of files to process.
242 if (createFlag==TRUE)
243 writeTarFile (argc, argv);
245 readTarFile (argc, argv);
247 fprintf (stderr, "\n");
253 * Read a tar file and extract or list the specified files within it.
254 * If the list is empty than all files are extracted or listed.
256 static void readTarFile (int fileCount, char **fileTable)
264 skipFileFlag = FALSE;
272 blockSize = sizeof (buf);
276 * Open the tar file for reading.
278 if ((tarName == NULL) || !strcmp (tarName, "-")) {
281 tarFd = open (tarName, O_RDONLY);
290 * Read blocks from the file until an end of file header block
291 * has been seen. (A real end of file from a read is an error.)
293 while (eofFlag==FALSE) {
295 * Read the next block of data if necessary.
296 * This will be a large block if possible, which we will
297 * then process in the small tar blocks.
301 inCc = fullRead (tarFd, buf, blockSize);
311 "Unexpected end of file from \"%s\"", tarName);
318 * If we are expecting a header block then examine it.
320 if (inHeader==TRUE) {
321 readHeader ((const TarHeader *) cp, fileCount, fileTable);
323 cp += TAR_BLOCK_SIZE;
324 inCc -= TAR_BLOCK_SIZE;
330 * We are currently handling the data for a file.
331 * Process the minimum of the amount of data we have available
332 * and the amount left to be processed for the file.
342 * If the amount left isn't an exact multiple of the tar block
343 * size then round it up to the next block boundary since there
344 * is padding at the end of the file.
346 if (cc % TAR_BLOCK_SIZE)
347 cc += TAR_BLOCK_SIZE - (cc % TAR_BLOCK_SIZE);
355 * Close the tar file if needed.
357 if ((tarFd >= 0) && (close (tarFd) < 0))
361 * Close the output file if needed.
362 * This is only done here on a previous error and so no
363 * message is required on errors.
365 if (tostdoutFlag == FALSE) {
367 (void) close (outFd);
373 * Examine the header block that was just read.
374 * This can specify the information for another file, or it can mark
375 * the end of the tar file.
378 readHeader (const TarHeader * hp, int fileCount, char **fileTable)
395 * If the block is completely empty, then this is the end of the
396 * archive file. If the name is null, then just skip this header.
401 for (cc = TAR_BLOCK_SIZE; cc > 0; cc--) {
412 * There is another file in the archive to examine.
413 * Extract the encoded information and check it.
415 mode = getOctal (hp->mode, sizeof (hp->mode));
416 uid = getOctal (hp->uid, sizeof (hp->uid));
417 gid = getOctal (hp->gid, sizeof (hp->gid));
418 size = getOctal (hp->size, sizeof (hp->size));
419 mtime = getOctal (hp->mtime, sizeof (hp->mtime));
420 checkSum = getOctal (hp->checkSum, sizeof (hp->checkSum));
421 major = getOctal (hp->devMajor, sizeof (hp->devMajor));
422 minor = getOctal (hp->devMinor, sizeof (hp->devMinor));
424 if ((mode < 0) || (uid < 0) || (gid < 0) || (size < 0)) {
425 if (badHeader==FALSE)
426 fprintf (stderr, "Bad tar header, skipping\n");
434 skipFileFlag = FALSE;
438 * Check for the file modes.
440 hardLink = ((hp->typeFlag == TAR_TYPE_HARD_LINK) ||
441 (hp->typeFlag == TAR_TYPE_HARD_LINK - '0'));
443 softLink = ((hp->typeFlag == TAR_TYPE_SOFT_LINK) ||
444 (hp->typeFlag == TAR_TYPE_SOFT_LINK - '0'));
447 * Check for a directory.
449 if (name[strlen (name) - 1] == '/')
453 * Check for absolute paths in the file.
454 * If we find any, then warn the user and make them relative.
460 if (warnedRoot==FALSE) {
462 "Absolute path detected, removing leading slashes\n");
469 * See if we want this file to be restored.
470 * If not, then set up to skip it.
472 if (wantFileName (name, fileCount, fileTable) == FALSE) {
473 if ( !hardLink && !softLink && (S_ISREG (mode) || S_ISCHR (mode)
474 || S_ISBLK (mode) || S_ISSOCK(mode) || S_ISFIFO(mode) ) ) {
475 inHeader = (size == 0)? TRUE : FALSE;
485 * This file is to be handled.
486 * If we aren't extracting then just list information about the file.
488 if (extractFlag==FALSE) {
489 if (verboseFlag==TRUE) {
490 printf ("%s %3d/%-d %9ld %s %s", modeString (mode),
491 uid, gid, size, timeString (mtime), name);
496 printf (" (link to \"%s\")", hp->linkName);
498 printf (" (symlink to \"%s\")", hp->linkName);
499 else if (S_ISREG (mode) || S_ISCHR (mode) || S_ISBLK (mode) ||
500 S_ISSOCK(mode) || S_ISFIFO(mode) ) {
501 inHeader = (size == 0)? TRUE : FALSE;
511 * We really want to extract the file.
513 if (verboseFlag==TRUE)
514 printf ("x %s\n", name);
517 if (link (hp->linkName, name) < 0)
525 if (symlink (hp->linkName, name) < 0)
528 fprintf (stderr, "Cannot create symbolic links\n");
534 * If the file is a directory, then just create the path.
536 if (S_ISDIR (mode)) {
537 createPath (name, mode);
543 * There is a file to write.
544 * First create the path to it if necessary with a default permission.
546 createPath (name, 0777);
548 inHeader = (size == 0)? TRUE : FALSE;
552 * Start the output file.
554 if (tostdoutFlag == TRUE)
557 if ( S_ISCHR(mode) || S_ISBLK(mode) || S_ISSOCK(mode) ) {
559 outFd = mknod (name, mode, makedev(major, minor) );
561 else if (S_ISFIFO(mode) ) {
563 outFd = mkfifo(name, mode);
565 outFd = open (name, O_WRONLY | O_CREAT | O_TRUNC, mode);
576 * If the file is empty, then that's all we need to do.
578 if (size == 0 && (tostdoutFlag == FALSE) && (devFileFlag == FALSE)) {
579 (void) close (outFd);
586 * Handle a data block of some specified size that was read.
588 static void readData (const char *cp, int count)
591 * Reduce the amount of data left in this file.
592 * If there is no more data left, then we need to read
601 * If we aren't extracting files or this file is being
602 * skipped then do nothing more.
604 if (extractFlag==FALSE || skipFileFlag==TRUE)
608 * Write the data to the output file.
610 if (fullWrite (outFd, cp, count) < 0) {
612 if (tostdoutFlag == FALSE) {
613 (void) close (outFd);
621 * If the write failed, close the file and disable further
622 * writes to this file.
624 if (dataCc <= 0 && tostdoutFlag == FALSE) {
634 * Write a tar file containing the specified files.
636 static void writeTarFile (int fileCount, char **fileTable)
641 * Make sure there is at least one file specified.
643 if (fileCount <= 0) {
644 fprintf (stderr, "No files specified to be saved\n");
649 * Create the tar file for writing.
651 if ((tarName == NULL) || !strcmp (tarName, "-")) {
655 tarFd = open (tarName, O_WRONLY | O_CREAT | O_TRUNC, 0666);
664 * Get the device and inode of the tar file for checking later.
666 if (fstat (tarFd, &statbuf) < 0) {
672 tarDev = statbuf.st_dev;
673 tarInode = statbuf.st_ino;
676 * Append each file name into the archive file.
677 * Follow symbolic links for these top level file names.
679 while (errorFlag==FALSE && (fileCount-- > 0)) {
680 saveFile (*fileTable++, FALSE);
684 * Now write an empty block of zeroes to end the archive.
686 writeTarBlock ("", 1);
691 * Close the tar file and check for errors if it was opened.
693 if ((tostdoutFlag == FALSE) && (tarFd >= 0) && (close (tarFd) < 0))
699 * Save one file into the tar file.
700 * If the file is a directory, then this will recursively save all of
701 * the files and directories within the directory. The seeLinks
702 * flag indicates whether or not we want to see symbolic links as
703 * they really are, instead of blindly following them.
705 static void saveFile (const char *fileName, int seeLinks)
711 if (verboseFlag==TRUE)
712 printf ("a %s\n", fileName);
715 * Check that the file name will fit in the header.
717 if (strlen (fileName) >= TAR_NAME_SIZE) {
718 fprintf (stderr, "%s: File name is too long\n", fileName);
724 * Find out about the file.
728 status = lstat (fileName, &statbuf);
731 status = stat (fileName, &statbuf);
740 * Make sure we aren't trying to save our file into itself.
742 if ((statbuf.st_dev == tarDev) && (statbuf.st_ino == tarInode)) {
743 fprintf (stderr, "Skipping saving of archive file itself\n");
749 * Check the type of file.
751 mode = statbuf.st_mode;
753 if (S_ISDIR (mode)) {
754 saveDirectory (fileName, &statbuf);
758 if (S_ISREG (mode)) {
759 saveRegularFile (fileName, &statbuf);
764 /* Some day add support for tarring these up... but not today. :) */
765 // if (S_ISLNK(mode) || S_ISFIFO(mode) || S_ISBLK(mode) || S_ISCHR (mode) ) {
766 // fprintf (stderr, "%s: This version of tar can't store this type of file\n", fileName);
770 * The file is a strange type of file, ignore it.
772 fprintf (stderr, "%s: not a directory or regular file\n", fileName);
777 * Save a regular file to the tar file.
780 saveRegularFile (const char *fileName, const struct stat *statbuf)
787 char data[TAR_BLOCK_SIZE * 16];
790 * Open the file for reading.
792 fileFd = open (fileName, O_RDONLY);
801 * Write out the header for the file.
803 writeHeader (fileName, statbuf);
806 * Write the data blocks of the file.
807 * We must be careful to write the amount of data that the stat
808 * buffer indicated, even if the file has changed size. Otherwise
809 * the tar file will be incorrect.
811 fullDataCount = statbuf->st_size;
814 while (fullDataCount > 0) {
816 * Get the amount to write this iteration which is
817 * the minumum of the amount left to write and the
820 dataCount = sizeof (data);
822 if (dataCount > fullDataCount)
823 dataCount = (int) fullDataCount;
826 * Read the data from the file if we haven't seen the
832 cc = fullRead (fileFd, data, dataCount);
837 (void) close (fileFd);
844 * If the file ended too soon, complain and set
845 * a flag so we will zero fill the rest of it.
847 if (cc < dataCount) {
849 "%s: Short read - zero filling", fileName);
856 * Zero fill the rest of the data if necessary.
859 memset (data + cc, 0, dataCount - cc);
862 * Write the buffer to the TAR file.
864 writeTarBlock (data, dataCount);
866 fullDataCount -= dataCount;
872 if ((tostdoutFlag == FALSE) && close (fileFd) < 0)
873 fprintf (stderr, "%s: close: %s\n", fileName, strerror (errno));
878 * Save a directory and all of its files to the tar file.
880 static void saveDirectory (const char *dirName, const struct stat *statbuf)
883 struct dirent *entry;
885 char fullName[NAME_MAX];
888 * Construct the directory name as used in the tar file by appending
889 * a slash character to it.
891 strcpy (fullName, dirName);
892 strcat (fullName, "/");
895 * Write out the header for the directory entry.
897 writeHeader (fullName, statbuf);
900 * Open the directory.
902 dir = opendir (dirName);
905 fprintf (stderr, "Cannot read directory \"%s\": %s\n",
906 dirName, strerror (errno));
912 * See if a slash is needed.
914 needSlash = (*dirName && (dirName[strlen (dirName) - 1] != '/'));
917 * Read all of the directory entries and check them,
918 * except for the current and parent directory entries.
920 while (errorFlag==FALSE && ((entry = readdir (dir)) != NULL)) {
921 if ((strcmp (entry->d_name, ".") == 0) ||
922 (strcmp (entry->d_name, "..") == 0)) {
927 * Build the full path name to the file.
929 strcpy (fullName, dirName);
932 strcat (fullName, "/");
934 strcat (fullName, entry->d_name);
937 * Write this file to the tar file, noticing whether or not
938 * the file is a symbolic link.
940 saveFile (fullName, TRUE);
944 * All done, close the directory.
951 * Write a tar header for the specified file name and status.
952 * It is assumed that the file name fits.
954 static void writeHeader (const char *fileName, const struct stat *statbuf)
957 const unsigned char *cp;
962 * Zero the header block in preparation for filling it in.
964 memset ((char *) &header, 0, sizeof (header));
967 * Fill in the header.
969 strcpy (header.name, fileName);
971 strncpy (header.magic, TAR_MAGIC, sizeof (header.magic));
972 strncpy (header.version, TAR_VERSION, sizeof (header.version));
974 putOctal (header.mode, sizeof (header.mode), statbuf->st_mode & 0777);
975 putOctal (header.uid, sizeof (header.uid), statbuf->st_uid);
976 putOctal (header.gid, sizeof (header.gid), statbuf->st_gid);
977 putOctal (header.size, sizeof (header.size), statbuf->st_size);
978 putOctal (header.mtime, sizeof (header.mtime), statbuf->st_mtime);
980 header.typeFlag = TAR_TYPE_REGULAR;
983 * Calculate and store the checksum.
984 * This is the sum of all of the bytes of the header,
985 * with the checksum field itself treated as blanks.
987 memset (header.checkSum, ' ', sizeof (header.checkSum));
989 cp = (const unsigned char *) &header;
990 len = sizeof (header);
996 putOctal (header.checkSum, sizeof (header.checkSum), checkSum);
999 * Write the tar header.
1001 writeTarBlock ((const char *) &header, sizeof (header));
1006 * Write data to one or more blocks of the tar file.
1007 * The data is always padded out to a multiple of TAR_BLOCK_SIZE.
1008 * The errorFlag static variable is set on an error.
1010 static void writeTarBlock (const char *buf, int len)
1014 char fullBlock[TAR_BLOCK_SIZE];
1017 * If we had a write error before, then do nothing more.
1019 if (errorFlag==TRUE)
1023 * Get the amount of complete and partial blocks.
1025 partialLength = len % TAR_BLOCK_SIZE;
1026 completeLength = len - partialLength;
1029 * Write all of the complete blocks.
1031 if ((completeLength > 0) && !fullWrite (tarFd, buf, completeLength)) {
1040 * If there are no partial blocks left, we are done.
1042 if (partialLength == 0)
1046 * Copy the partial data into a complete block, and pad the rest
1047 * of it with zeroes.
1049 memcpy (fullBlock, buf + completeLength, partialLength);
1050 memset (fullBlock + partialLength, 0, TAR_BLOCK_SIZE - partialLength);
1053 * Write the last complete block.
1055 if (!fullWrite (tarFd, fullBlock, TAR_BLOCK_SIZE)) {
1064 * Read an octal value in a field of the specified width, with optional
1065 * spaces on both sides of the number and with an optional null character
1066 * at the end. Returns -1 on an illegal format.
1068 static long getOctal (const char *cp, int len)
1072 while ((len > 0) && (*cp == ' ')) {
1077 if ((len == 0) || !isOctal (*cp))
1082 while ((len > 0) && isOctal (*cp)) {
1083 val = val * 8 + *cp++ - '0';
1087 while ((len > 0) && (*cp == ' ')) {
1092 if ((len > 0) && *cp)
1100 * Put an octal string into the specified buffer.
1101 * The number is zero and space padded and possibly null padded.
1102 * Returns TRUE if successful.
1104 static int putOctal (char *cp, int len, long value)
1108 char tempBuffer[32];
1111 * Create a string of the specified length with an initial space,
1112 * leading zeroes and the octal number, and a trailing null.
1114 tempString = tempBuffer;
1116 sprintf (tempString, " %0*lo", len - 2, value);
1118 tempLength = strlen (tempString) + 1;
1121 * If the string is too large, suppress the leading space.
1123 if (tempLength > len) {
1129 * If the string is still too large, suppress the trailing null.
1131 if (tempLength > len)
1135 * If the string is still too large, fail.
1137 if (tempLength > len)
1141 * Copy the string to the field.
1143 memcpy (cp, tempString, len);
1150 * See if the specified file name belongs to one of the specified list
1151 * of path prefixes. An empty list implies that all files are wanted.
1152 * Returns TRUE if the file is selected.
1155 wantFileName (const char *fileName, int fileCount, char **fileTable)
1157 const char *pathName;
1162 * If there are no files in the list, then the file is wanted.
1167 fileLength = strlen (fileName);
1170 * Check each of the test paths.
1172 while (fileCount-- > 0) {
1173 pathName = *fileTable++;
1175 pathLength = strlen (pathName);
1177 if (fileLength < pathLength)
1180 if (memcmp (fileName, pathName, pathLength) != 0)
1183 if ((fileLength == pathLength) || (fileName[pathLength] == '/')) {