1 /* vi: set sw=4 ts=4: */
3 * Mini tar implementation for busybox based on code taken from sash.
5 * Copyright (c) 1999 by David I. Bell
6 * Permission is granted to use, distribute, or modify this source,
7 * provided that this copyright notice remains intact.
9 * Permission to distribute this code under the GPL has been granted.
11 * Modified for busybox by Erik Andersen <andersee@debian.org>
12 * Adjusted to grok stdin/stdout options.
14 * Modified to handle device special files by Matt Porter
17 * This program is free software; you can redistribute it and/or modify
18 * it under the terms of the GNU General Public License as published by
19 * the Free Software Foundation; either version 2 of the License, or
20 * (at your option) any later version.
22 * This program is distributed in the hope that it will be useful,
23 * but WITHOUT ANY WARRANTY; without even the implied warranty of
24 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
25 * General Public License for more details.
27 * You should have received a copy of the GNU General Public License
28 * along with this program; if not, write to the Free Software
29 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
42 #include <sys/types.h>
43 #include <sys/sysmacros.h>
44 #include <sys/param.h> /* for PATH_MAX */
47 #ifdef BB_FEATURE_TAR_CREATE
49 static const char tar_usage[] =
50 "tar -[cxtvOf] [tarFileName] [FILE] ...\n\n"
51 "Create, extract, or list files from a tar file.\n\n"
54 "\tc=create, x=extract, t=list contents, v=verbose,\n"
55 "\tO=extract to stdout, f=tarfile or \"-\" for stdin\n";
59 static const char tar_usage[] =
60 "tar -[xtvOf] [tarFileName] [FILE] ...\n\n"
61 "Extract, or list files stored in a tar file. This\n"
62 "version of tar does not support creation of tar files.\n\n"
65 "\tx=extract, t=list contents, v=verbose,\n"
66 "\tO=extract to stdout, f=tarfile or \"-\" for stdin\n";
74 #define TAR_BLOCK_SIZE 512
75 #define TAR_NAME_SIZE 100
79 * The POSIX (and basic GNU) tar header format.
80 * This structure is always embedded in a TAR_BLOCK_SIZE sized block
81 * with zero padding. We only process this information minimally.
84 char name[TAR_NAME_SIZE];
92 char linkName[TAR_NAME_SIZE];
102 #define TAR_MAGIC "ustar"
103 #define TAR_VERSION "00"
105 #define TAR_TYPE_REGULAR '0'
106 #define TAR_TYPE_HARD_LINK '1'
107 #define TAR_TYPE_SOFT_LINK '2'
114 static int extractFlag;
115 static int createFlag;
116 static int verboseFlag;
117 static int tostdoutFlag;
119 static int inHeader; // <- check me
120 static int badHeader;
121 static int errorFlag;
122 static int skipFileFlag;
123 static int warnedRoot;
127 static const char *outName;
135 * Static data associated with the tar file.
137 static const char *tarName;
140 static ino_t tarInode;
144 * Local procedures to restore files from a tar file.
146 static void readTarFile(int fileCount, char **fileTable);
147 static void readData(const char *cp, int count);
148 static long getOctal(const char *cp, int len);
150 static void readHeader(const TarHeader * hp,
152 int fileCount, char **fileTable);
154 static int wantFileName(const char *fileName,
156 int fileCount, char **fileTable);
158 #ifdef BB_FEATURE_TAR_CREATE
160 * Local procedures to save files into a tar file.
162 static void saveFile(const char *fileName, int seeLinks);
164 static void saveRegularFile(const char *fileName,
166 const struct stat *statbuf);
168 static void saveDirectory(const char *fileName,
170 const struct stat *statbuf);
172 static void writeHeader(const char *fileName, const struct stat *statbuf);
174 static void writeTarFile(int fileCount, char **fileTable);
175 static void writeTarBlock(const char *buf, int len);
176 static int putOctal(char *cp, int len, long value);
181 extern int tar_main(int argc, char **argv)
197 tostdoutFlag = FALSE;
207 options = (*argv++) + 1;
212 for (; *options; options++) {
215 if (tarName != NULL) {
216 fprintf(stderr, "Only one 'f' option allowed\n");
227 if (extractFlag == TRUE || createFlag == TRUE)
233 if (listFlag == TRUE || createFlag == TRUE)
238 if (extractFlag == TRUE || listFlag == TRUE)
256 fprintf(stderr, "Unknown tar flag '%c'\n"
257 "Try `tar --help' for more information\n", *options);
263 * Do the correct type of action supplying the rest of the
264 * command line arguments as the list of files to process.
266 if (createFlag == TRUE) {
267 #ifndef BB_FEATURE_TAR_CREATE
269 "This version of tar was not compiled with tar creation support.\n");
272 writeTarFile(argc, argv);
275 readTarFile(argc, argv);
277 if (errorFlag == TRUE) {
278 fprintf(stderr, "\n");
283 fprintf(stderr, "Exactly one of 'c', 'x' or 't' must be specified\n");
289 * Read a tar file and extract or list the specified files within it.
290 * If the list is empty than all files are extracted or listed.
292 static void readTarFile(int fileCount, char **fileTable)
300 skipFileFlag = FALSE;
308 blockSize = sizeof(buf);
312 * Open the tar file for reading.
314 if ((tarName == NULL) || !strcmp(tarName, "-")) {
315 tarFd = fileno(stdin);
317 tarFd = open(tarName, O_RDONLY);
326 * Read blocks from the file until an end of file header block
327 * has been seen. (A real end of file from a read is an error.)
329 while (eofFlag == FALSE) {
331 * Read the next block of data if necessary.
332 * This will be a large block if possible, which we will
333 * then process in the small tar blocks.
337 inCc = fullRead(tarFd, buf, blockSize);
347 "Unexpected end of file from \"%s\"", tarName);
354 * If we are expecting a header block then examine it.
356 if (inHeader == TRUE) {
357 readHeader((const TarHeader *) cp, fileCount, fileTable);
359 cp += TAR_BLOCK_SIZE;
360 inCc -= TAR_BLOCK_SIZE;
366 * We are currently handling the data for a file.
367 * Process the minimum of the amount of data we have available
368 * and the amount left to be processed for the file.
378 * If the amount left isn't an exact multiple of the tar block
379 * size then round it up to the next block boundary since there
380 * is padding at the end of the file.
382 if (cc % TAR_BLOCK_SIZE)
383 cc += TAR_BLOCK_SIZE - (cc % TAR_BLOCK_SIZE);
391 * Close the tar file if needed.
393 if ((tarFd >= 0) && (close(tarFd) < 0))
397 * Close the output file if needed.
398 * This is only done here on a previous error and so no
399 * message is required on errors.
401 if (tostdoutFlag == FALSE) {
410 * Examine the header block that was just read.
411 * This can specify the information for another file, or it can mark
412 * the end of the tar file.
415 readHeader(const TarHeader * hp, int fileCount, char **fileTable)
428 * If the block is completely empty, then this is the end of the
429 * archive file. If the name is null, then just skip this header.
433 if (*outName == '\0') {
434 for (cc = TAR_BLOCK_SIZE; cc > 0; cc--) {
445 * There is another file in the archive to examine.
446 * Extract the encoded information and check it.
448 mode = getOctal(hp->mode, sizeof(hp->mode));
449 uid = getOctal(hp->uid, sizeof(hp->uid));
450 gid = getOctal(hp->gid, sizeof(hp->gid));
451 size = getOctal(hp->size, sizeof(hp->size));
452 mtime = getOctal(hp->mtime, sizeof(hp->mtime));
453 checkSum = getOctal(hp->checkSum, sizeof(hp->checkSum));
454 major = getOctal(hp->devMajor, sizeof(hp->devMajor));
455 minor = getOctal(hp->devMinor, sizeof(hp->devMinor));
457 if ((mode < 0) || (uid < 0) || (gid < 0) || (size < 0)) {
458 if (badHeader == FALSE)
459 fprintf(stderr, "Bad tar header, skipping\n");
467 skipFileFlag = FALSE;
471 * Check for the file modes.
473 hardLink = ((hp->typeFlag == TAR_TYPE_HARD_LINK) ||
474 (hp->typeFlag == TAR_TYPE_HARD_LINK - '0'));
476 softLink = ((hp->typeFlag == TAR_TYPE_SOFT_LINK) ||
477 (hp->typeFlag == TAR_TYPE_SOFT_LINK - '0'));
480 * Check for a directory.
482 if (outName[strlen(outName) - 1] == '/')
486 * Check for absolute paths in the file.
487 * If we find any, then warn the user and make them relative.
489 if (*outName == '/') {
490 while (*outName == '/')
493 if (warnedRoot == FALSE) {
495 "Absolute path detected, removing leading slashes\n");
502 * See if we want this file to be restored.
503 * If not, then set up to skip it.
505 if (wantFileName(outName, fileCount, fileTable) == FALSE) {
506 if (!hardLink && !softLink && (S_ISREG(mode) || S_ISCHR(mode)
507 || S_ISBLK(mode) || S_ISSOCK(mode)
508 || S_ISFIFO(mode))) {
509 inHeader = (size == 0) ? TRUE : FALSE;
519 * This file is to be handled.
520 * If we aren't extracting then just list information about the file.
522 if (extractFlag == FALSE) {
523 if (verboseFlag == TRUE) {
524 printf("%s %3d/%-d ", modeString(mode), uid, gid);
525 if (S_ISCHR(mode) || S_ISBLK(mode))
526 printf("%4d,%4d %s ", major, minor, timeString(mtime));
528 printf("%9ld %s ", size, timeString(mtime));
530 printf("%s", outName);
533 printf(" (link to \"%s\")", hp->linkName);
535 printf(" (symlink to \"%s\")", hp->linkName);
536 else if (S_ISREG(mode) || S_ISCHR(mode) || S_ISBLK(mode) ||
537 S_ISSOCK(mode) || S_ISFIFO(mode)) {
538 inHeader = (size == 0) ? TRUE : FALSE;
548 * We really want to extract the file.
550 if (verboseFlag == TRUE)
551 printf("x %s\n", outName);
554 if (link(hp->linkName, outName) < 0) {
558 /* Set the file time */
561 utime(outName, &utb);
562 /* Set the file permissions */
563 chown(outName, uid, gid);
564 chmod(outName, mode);
570 if (symlink(hp->linkName, outName) < 0) {
574 /* Try to change ownership of the symlink.
575 * If libs doesn't support that, don't bother.
576 * Changing the pointed-to file is the Wrong Thing(tm).
578 #if (__GLIBC__ >= 2) && (__GLIBC_MINOR__ >= 1)
579 lchown(outName, uid, gid);
582 /* Do not change permissions or date on symlink,
583 * since it changes the pointed to file instead. duh. */
585 fprintf(stderr, "Cannot create symbolic links\n");
590 /* Set the umask for this process so it doesn't
591 * screw things up. */
595 * If the file is a directory, then just create the path.
598 if (createPath(outName, mode) == TRUE) {
599 /* make the final component, just in case it was
600 * omitted by createPath() (which will skip the
601 * directory if it doesn't have a terminating '/')
603 mkdir(outName, mode);
605 /* Set the file time */
608 utime(outName, &utb);
609 /* Set the file permissions */
610 chown(outName, uid, gid);
611 chmod(outName, mode);
618 * There is a file to write.
619 * First create the path to it if necessary with default permissions.
621 createPath(outName, 0777);
623 inHeader = (size == 0) ? TRUE : FALSE;
627 * Start the output file.
629 if (tostdoutFlag == TRUE)
630 outFd = fileno(stdout);
632 if (S_ISCHR(mode) || S_ISBLK(mode) || S_ISSOCK(mode)) {
634 outFd = mknod(outName, mode, makedev(major, minor));
635 } else if (S_ISFIFO(mode)) {
637 outFd = mkfifo(outName, mode);
639 outFd = open(outName, O_WRONLY | O_CREAT | O_TRUNC, mode);
646 /* Set the file time */
649 utime(outName, &utb);
650 /* Set the file permissions */
651 chown(outName, uid, gid);
652 chmod(outName, mode);
657 * If the file is empty, then that's all we need to do.
659 if (size == 0 && (tostdoutFlag == FALSE) && (devFileFlag == FALSE)) {
667 * Handle a data block of some specified size that was read.
669 static void readData(const char *cp, int count)
672 * Reduce the amount of data left in this file.
673 * If there is no more data left, then we need to read
682 * If we aren't extracting files or this file is being
683 * skipped then do nothing more.
685 if (extractFlag == FALSE || skipFileFlag == TRUE)
689 * Write the data to the output file.
691 if (fullWrite(outFd, cp, count) < 0) {
693 if (tostdoutFlag == FALSE) {
702 * Check if we are done writing to the file now.
704 if (dataCc <= 0 && tostdoutFlag == FALSE) {
710 /* Set the file time */
713 utime(outName, &utb);
714 /* Set the file permissions */
715 chown(outName, uid, gid);
716 chmod(outName, mode);
724 * See if the specified file name belongs to one of the specified list
725 * of path prefixes. An empty list implies that all files are wanted.
726 * Returns TRUE if the file is selected.
729 wantFileName(const char *fileName, int fileCount, char **fileTable)
731 const char *pathName;
736 * If there are no files in the list, then the file is wanted.
741 fileLength = strlen(fileName);
744 * Check each of the test paths.
746 while (fileCount-- > 0) {
747 pathName = *fileTable++;
749 pathLength = strlen(pathName);
751 if (fileLength < pathLength)
754 if (memcmp(fileName, pathName, pathLength) != 0)
757 if ((fileLength == pathLength) || (fileName[pathLength] == '/')) {
766 * Read an octal value in a field of the specified width, with optional
767 * spaces on both sides of the number and with an optional null character
768 * at the end. Returns -1 on an illegal format.
770 static long getOctal(const char *cp, int len)
774 while ((len > 0) && (*cp == ' ')) {
779 if ((len == 0) || !isOctal(*cp))
784 while ((len > 0) && isOctal(*cp)) {
785 val = val * 8 + *cp++ - '0';
789 while ((len > 0) && (*cp == ' ')) {
794 if ((len > 0) && *cp)
803 /* From here to the end of the file is the tar writing stuff.
804 * If you do not have BB_FEATURE_TAR_CREATE defined, this will
807 #ifdef BB_FEATURE_TAR_CREATE
810 * Write a tar file containing the specified files.
812 static void writeTarFile(int fileCount, char **fileTable)
817 * Make sure there is at least one file specified.
819 if (fileCount <= 0) {
820 fprintf(stderr, "No files specified to be saved\n");
825 * Create the tar file for writing.
827 if ((tarName == NULL) || !strcmp(tarName, "-")) {
829 tarFd = fileno(stdout);
831 tarFd = open(tarName, O_WRONLY | O_CREAT | O_TRUNC, 0666);
840 * Get the device and inode of the tar file for checking later.
842 if (fstat(tarFd, &statbuf) < 0) {
848 tarDev = statbuf.st_dev;
849 tarInode = statbuf.st_ino;
852 * Append each file name into the archive file.
853 * Follow symbolic links for these top level file names.
855 while (errorFlag == FALSE && (fileCount-- > 0)) {
856 saveFile(*fileTable++, FALSE);
860 * Now write an empty block of zeroes to end the archive.
862 writeTarBlock("", 1);
867 * Close the tar file and check for errors if it was opened.
869 if ((tostdoutFlag == FALSE) && (tarFd >= 0) && (close(tarFd) < 0))
874 * Save one file into the tar file.
875 * If the file is a directory, then this will recursively save all of
876 * the files and directories within the directory. The seeLinks
877 * flag indicates whether or not we want to see symbolic links as
878 * they really are, instead of blindly following them.
880 static void saveFile(const char *fileName, int seeLinks)
885 if (verboseFlag == TRUE)
886 printf("a %s\n", fileName);
889 * Check that the file name will fit in the header.
891 if (strlen(fileName) >= TAR_NAME_SIZE) {
892 fprintf(stderr, "%s: File name is too long\n", fileName);
898 * Find out about the file.
901 if (seeLinks == TRUE)
902 status = lstat(fileName, &statbuf);
905 status = stat(fileName, &statbuf);
914 * Make sure we aren't trying to save our file into itself.
916 if ((statbuf.st_dev == tarDev) && (statbuf.st_ino == tarInode)) {
917 fprintf(stderr, "Skipping saving of archive file itself\n");
923 * Check the type of file.
925 mode = statbuf.st_mode;
928 saveDirectory(fileName, &statbuf);
933 saveRegularFile(fileName, &statbuf);
938 /* Some day add support for tarring these up... but not today. :) */
939 // if (S_ISLNK(mode) || S_ISFIFO(mode) || S_ISBLK(mode) || S_ISCHR (mode) ) {
940 // fprintf (stderr, "%s: This version of tar can't store this type of file\n", fileName);
944 * The file is a strange type of file, ignore it.
946 fprintf(stderr, "%s: not a directory or regular file\n", fileName);
951 * Save a regular file to the tar file.
954 saveRegularFile(const char *fileName, const struct stat *statbuf)
961 char data[TAR_BLOCK_SIZE * 16];
964 * Open the file for reading.
966 fileFd = open(fileName, O_RDONLY);
975 * Write out the header for the file.
977 writeHeader(fileName, statbuf);
980 * Write the data blocks of the file.
981 * We must be careful to write the amount of data that the stat
982 * buffer indicated, even if the file has changed size. Otherwise
983 * the tar file will be incorrect.
985 fullDataCount = statbuf->st_size;
988 while (fullDataCount > 0) {
990 * Get the amount to write this iteration which is
991 * the minumum of the amount left to write and the
994 dataCount = sizeof(data);
996 if (dataCount > fullDataCount)
997 dataCount = (int) fullDataCount;
1000 * Read the data from the file if we haven't seen the
1005 if (sawEof == FALSE) {
1006 cc = fullRead(fileFd, data, dataCount);
1011 (void) close(fileFd);
1018 * If the file ended too soon, complain and set
1019 * a flag so we will zero fill the rest of it.
1021 if (cc < dataCount) {
1022 fprintf(stderr, "%s: Short read - zero filling", fileName);
1029 * Zero fill the rest of the data if necessary.
1032 memset(data + cc, 0, dataCount - cc);
1035 * Write the buffer to the TAR file.
1037 writeTarBlock(data, dataCount);
1039 fullDataCount -= dataCount;
1045 if ((tostdoutFlag == FALSE) && close(fileFd) < 0)
1046 fprintf(stderr, "%s: close: %s\n", fileName, strerror(errno));
1051 * Save a directory and all of its files to the tar file.
1053 static void saveDirectory(const char *dirName, const struct stat *statbuf)
1056 struct dirent *entry;
1058 char fullName[PATH_MAX + 1];
1061 * Construct the directory name as used in the tar file by appending
1062 * a slash character to it.
1064 strcpy(fullName, dirName);
1065 strcat(fullName, "/");
1068 * Write out the header for the directory entry.
1070 writeHeader(fullName, statbuf);
1073 * Open the directory.
1075 dir = opendir(dirName);
1078 fprintf(stderr, "Cannot read directory \"%s\": %s\n",
1079 dirName, strerror(errno));
1085 * See if a slash is needed.
1087 needSlash = (*dirName && (dirName[strlen(dirName) - 1] != '/'));
1090 * Read all of the directory entries and check them,
1091 * except for the current and parent directory entries.
1093 while (errorFlag == FALSE && ((entry = readdir(dir)) != NULL)) {
1094 if ((strcmp(entry->d_name, ".") == 0) ||
1095 (strcmp(entry->d_name, "..") == 0)) {
1100 * Build the full path name to the file.
1102 strcpy(fullName, dirName);
1105 strcat(fullName, "/");
1107 strcat(fullName, entry->d_name);
1110 * Write this file to the tar file, noticing whether or not
1111 * the file is a symbolic link.
1113 saveFile(fullName, TRUE);
1117 * All done, close the directory.
1124 * Write a tar header for the specified file name and status.
1125 * It is assumed that the file name fits.
1127 static void writeHeader(const char *fileName, const struct stat *statbuf)
1130 const unsigned char *cp;
1135 * Zero the header block in preparation for filling it in.
1137 memset((char *) &header, 0, sizeof(header));
1140 * Fill in the header.
1142 strcpy(header.name, fileName);
1144 strncpy(header.magic, TAR_MAGIC, sizeof(header.magic));
1145 strncpy(header.version, TAR_VERSION, sizeof(header.version));
1147 putOctal(header.mode, sizeof(header.mode), statbuf->st_mode & 0777);
1148 putOctal(header.uid, sizeof(header.uid), statbuf->st_uid);
1149 putOctal(header.gid, sizeof(header.gid), statbuf->st_gid);
1150 putOctal(header.size, sizeof(header.size), statbuf->st_size);
1151 putOctal(header.mtime, sizeof(header.mtime), statbuf->st_mtime);
1153 header.typeFlag = TAR_TYPE_REGULAR;
1156 * Calculate and store the checksum.
1157 * This is the sum of all of the bytes of the header,
1158 * with the checksum field itself treated as blanks.
1160 memset(header.checkSum, ' ', sizeof(header.checkSum));
1162 cp = (const unsigned char *) &header;
1163 len = sizeof(header);
1169 putOctal(header.checkSum, sizeof(header.checkSum), checkSum);
1172 * Write the tar header.
1174 writeTarBlock((const char *) &header, sizeof(header));
1179 * Write data to one or more blocks of the tar file.
1180 * The data is always padded out to a multiple of TAR_BLOCK_SIZE.
1181 * The errorFlag static variable is set on an error.
1183 static void writeTarBlock(const char *buf, int len)
1187 char fullBlock[TAR_BLOCK_SIZE];
1190 * If we had a write error before, then do nothing more.
1192 if (errorFlag == TRUE)
1196 * Get the amount of complete and partial blocks.
1198 partialLength = len % TAR_BLOCK_SIZE;
1199 completeLength = len - partialLength;
1202 * Write all of the complete blocks.
1204 if ((completeLength > 0) && !fullWrite(tarFd, buf, completeLength)) {
1213 * If there are no partial blocks left, we are done.
1215 if (partialLength == 0)
1219 * Copy the partial data into a complete block, and pad the rest
1220 * of it with zeroes.
1222 memcpy(fullBlock, buf + completeLength, partialLength);
1223 memset(fullBlock + partialLength, 0, TAR_BLOCK_SIZE - partialLength);
1226 * Write the last complete block.
1228 if (!fullWrite(tarFd, fullBlock, TAR_BLOCK_SIZE)) {
1237 * Put an octal string into the specified buffer.
1238 * The number is zero and space padded and possibly null padded.
1239 * Returns TRUE if successful.
1241 static int putOctal(char *cp, int len, long value)
1245 char tempBuffer[32];
1248 * Create a string of the specified length with an initial space,
1249 * leading zeroes and the octal number, and a trailing null.
1251 tempString = tempBuffer;
1253 sprintf(tempString, " %0*lo", len - 2, value);
1255 tempLength = strlen(tempString) + 1;
1258 * If the string is too large, suppress the leading space.
1260 if (tempLength > len) {
1266 * If the string is still too large, suppress the trailing null.
1268 if (tempLength > len)
1272 * If the string is still too large, fail.
1274 if (tempLength > len)
1278 * Copy the string to the field.
1280 memcpy(cp, tempString, len);