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);
134 extern const char * modeString(int mode);
135 extern const char * timeString(time_t timeVal);
136 extern int fullWrite(int fd, const char * buf, int len);
137 extern int fullRead(int fd, char * buf, int len);
141 tar_main(struct FileInfo *unused, int argc, char ** argv)
143 const char * options;
150 fprintf(stderr, "%s", tar_usage);
160 tostdoutFlag = FALSE;
173 for (; *options; options++)
180 fprintf(stderr, "Only one 'f' option allowed\n");
214 fprintf(stderr, "Unknown tar flag '%c'\n", *options);
222 * Validate the options.
224 if (extractFlag + listFlag + createFlag != 1)
226 fprintf(stderr, "Exactly one of 'c', 'x' or 't' must be specified\n");
232 * Do the correct type of action supplying the rest of the
233 * command line arguments as the list of files to process.
236 writeTarFile(argc, argv);
238 readTarFile(argc, argv);
240 fprintf(stderr, "\n");
246 * Read a tar file and extract or list the specified files within it.
247 * If the list is empty than all files are extracted or listed.
250 readTarFile(int fileCount, char ** fileTable)
258 skipFileFlag = FALSE;
266 blockSize = sizeof(buf);
270 * Open the tar file for reading.
272 if ( (tarName==NULL) || !strcmp( tarName, "-") ) {
276 tarFd = open(tarName, O_RDONLY);
286 * Read blocks from the file until an end of file header block
287 * has been seen. (A real end of file from a read is an error.)
292 * Read the next block of data if necessary.
293 * This will be a large block if possible, which we will
294 * then process in the small tar blocks.
299 inCc = fullRead(tarFd, buf, blockSize);
311 "Unexpected end of file from \"%s\"",
319 * If we are expecting a header block then examine it.
323 readHeader((const TarHeader *) cp, fileCount, fileTable);
325 cp += TAR_BLOCK_SIZE;
326 inCc -= TAR_BLOCK_SIZE;
332 * We are currently handling the data for a file.
333 * Process the minimum of the amount of data we have available
334 * and the amount left to be processed for the file.
344 * If the amount left isn't an exact multiple of the tar block
345 * size then round it up to the next block boundary since there
346 * is padding at the end of the file.
348 if (cc % TAR_BLOCK_SIZE)
349 cc += TAR_BLOCK_SIZE - (cc % TAR_BLOCK_SIZE);
357 * Close the tar file if needed.
359 if ((tarFd >= 0) && (close(tarFd) < 0))
363 * Close the output file if needed.
364 * This is only done here on a previous error and so no
365 * message is required on errors.
367 if (tostdoutFlag==FALSE) {
375 * Examine the header block that was just read.
376 * This can specify the information for another file, or it can mark
377 * the end of the tar file.
380 readHeader(const TarHeader * hp, int fileCount, char ** fileTable)
394 * If the block is completely empty, then this is the end of the
395 * archive file. If the name is null, then just skip this header.
401 for (cc = TAR_BLOCK_SIZE; cc > 0; cc--)
413 * There is another file in the archive to examine.
414 * Extract the encoded information and check it.
416 mode = getOctal(hp->mode, sizeof(hp->mode));
417 uid = getOctal(hp->uid, sizeof(hp->uid));
418 gid = getOctal(hp->gid, sizeof(hp->gid));
419 size = getOctal(hp->size, sizeof(hp->size));
420 mtime = getOctal(hp->mtime, sizeof(hp->mtime));
421 checkSum = getOctal(hp->checkSum, sizeof(hp->checkSum));
423 if ((mode < 0) || (uid < 0) || (gid < 0) || (size < 0))
426 fprintf(stderr, "Bad tar header, skipping\n");
434 skipFileFlag = FALSE;
437 * Check for the file modes.
439 hardLink = ((hp->typeFlag == TAR_TYPE_HARD_LINK) ||
440 (hp->typeFlag == TAR_TYPE_HARD_LINK - '0'));
442 softLink = ((hp->typeFlag == TAR_TYPE_SOFT_LINK) ||
443 (hp->typeFlag == TAR_TYPE_SOFT_LINK - '0'));
446 * Check for a directory or a regular file.
448 if (name[strlen(name) - 1] == '/')
450 else if ((mode & S_IFMT) == 0)
454 * Check for absolute paths in the file.
455 * If we find any, then warn the user and make them relative.
465 "Absolute path detected, removing leading slashes\n");
472 * See if we want this file to be restored.
473 * If not, then set up to skip it.
475 if (!wantFileName(name, fileCount, fileTable))
477 if (!hardLink && !softLink && S_ISREG(mode))
479 inHeader = (size == 0);
489 * This file is to be handled.
490 * If we aren't extracting then just list information about the file.
496 printf("%s %3d/%-d %9ld %s %s", modeString(mode),
497 uid, gid, size, timeString(mtime), name);
503 printf(" (link to \"%s\")", hp->linkName);
505 printf(" (symlink to \"%s\")", hp->linkName);
506 else if (S_ISREG(mode))
508 inHeader = (size == 0);
518 * We really want to extract the file.
521 printf("x %s\n", name);
525 if (link(hp->linkName, name) < 0)
534 if (symlink(hp->linkName, name) < 0)
537 fprintf(stderr, "Cannot create symbolic links\n");
543 * If the file is a directory, then just create the path.
547 createPath(name, mode);
553 * There is a file to write.
554 * First create the path to it if necessary with a default permission.
556 createPath(name, 0777);
558 inHeader = (size == 0);
562 * Start the output file.
564 if (tostdoutFlag==TRUE)
567 outFd = open(name, O_WRONLY | O_CREAT | O_TRUNC, mode);
577 * If the file is empty, then that's all we need to do.
579 if (size == 0 && tostdoutFlag == FALSE)
588 * Handle a data block of some specified size that was read.
591 readData(const char * cp, int count)
594 * Reduce the amount of data left in this file.
595 * If there is no more data left, then we need to read
604 * If we aren't extracting files or this file is being
605 * skipped then do nothing more.
607 if (!extractFlag || skipFileFlag)
611 * Write the data to the output file.
613 if (fullWrite(outFd, cp, count) < 0)
616 if (tostdoutFlag==FALSE) {
625 * If the write failed, close the file and disable further
626 * writes to this file.
628 if (dataCc <= 0 && tostdoutFlag==FALSE)
639 * Write a tar file containing the specified files.
642 writeTarFile(int fileCount, char ** fileTable)
647 * Make sure there is at least one file specified.
651 fprintf(stderr, "No files specified to be saved\n");
656 * Create the tar file for writing.
658 if ( (tarName==NULL) || !strcmp( tarName, "-") ) {
663 tarFd = open(tarName, O_WRONLY | O_CREAT | O_TRUNC, 0666);
673 * Get the device and inode of the tar file for checking later.
675 if (fstat(tarFd, &statbuf) < 0)
682 tarDev = statbuf.st_dev;
683 tarInode = statbuf.st_ino;
686 * Append each file name into the archive file.
687 * Follow symbolic links for these top level file names.
689 while (!errorFlag && (fileCount-- > 0))
691 saveFile(*fileTable++, FALSE);
695 * Now write an empty block of zeroes to end the archive.
697 writeTarBlock("", 1);
702 * Close the tar file and check for errors if it was opened.
704 if ( (tostdoutFlag==FALSE) && (tarFd >= 0) && (close(tarFd) < 0))
710 * Save one file into the tar file.
711 * If the file is a directory, then this will recursively save all of
712 * the files and directories within the directory. The seeLinks
713 * flag indicates whether or not we want to see symbolic links as
714 * they really are, instead of blindly following them.
717 saveFile(const char * fileName, BOOL seeLinks)
724 printf("a %s\n", fileName);
727 * Check that the file name will fit in the header.
729 if (strlen(fileName) >= TAR_NAME_SIZE)
731 fprintf(stderr, "%s: File name is too long\n", fileName);
737 * Find out about the file.
741 status = lstat(fileName, &statbuf);
744 status = stat(fileName, &statbuf);
754 * Make sure we aren't trying to save our file into itself.
756 if ((statbuf.st_dev == tarDev) && (statbuf.st_ino == tarInode))
758 fprintf(stderr, "Skipping saving of archive file itself\n");
764 * Check the type of file.
766 mode = statbuf.st_mode;
770 saveDirectory(fileName, &statbuf);
777 saveRegularFile(fileName, &statbuf);
783 * The file is a strange type of file, ignore it.
785 fprintf(stderr, "%s: not a directory or regular file\n", fileName);
790 * Save a regular file to the tar file.
793 saveRegularFile(const char * fileName, const struct stat * statbuf)
800 char data[TAR_BLOCK_SIZE * 16];
803 * Open the file for reading.
805 fileFd = open(fileName, O_RDONLY);
815 * Write out the header for the file.
817 writeHeader(fileName, statbuf);
820 * Write the data blocks of the file.
821 * We must be careful to write the amount of data that the stat
822 * buffer indicated, even if the file has changed size. Otherwise
823 * the tar file will be incorrect.
825 fullDataCount = statbuf->st_size;
828 while (fullDataCount > 0)
831 * Get the amount to write this iteration which is
832 * the minumum of the amount left to write and the
835 dataCount = sizeof(data);
837 if (dataCount > fullDataCount)
838 dataCount = (int) fullDataCount;
841 * Read the data from the file if we haven't seen the
848 cc = fullRead(fileFd, data, dataCount);
854 (void) close(fileFd);
861 * If the file ended too soon, complain and set
862 * a flag so we will zero fill the rest of it.
867 "%s: Short read - zero filling",
875 * Zero fill the rest of the data if necessary.
878 memset(data + cc, 0, dataCount - cc);
881 * Write the buffer to the TAR file.
883 writeTarBlock(data, dataCount);
885 fullDataCount -= dataCount;
891 if ( (tostdoutFlag==FALSE) && close(fileFd) < 0)
892 fprintf(stderr, "%s: close: %s\n", fileName, strerror(errno));
897 * Save a directory and all of its files to the tar file.
900 saveDirectory(const char * dirName, const struct stat * statbuf)
903 struct dirent * entry;
905 char fullName[PATH_LEN];
908 * Construct the directory name as used in the tar file by appending
909 * a slash character to it.
911 strcpy(fullName, dirName);
912 strcat(fullName, "/");
915 * Write out the header for the directory entry.
917 writeHeader(fullName, statbuf);
920 * Open the directory.
922 dir = opendir(dirName);
926 fprintf(stderr, "Cannot read directory \"%s\": %s\n",
927 dirName, strerror(errno));
933 * See if a slash is needed.
935 needSlash = (*dirName && (dirName[strlen(dirName) - 1] != '/'));
938 * Read all of the directory entries and check them,
939 * except for the current and parent directory entries.
941 while (!errorFlag && ((entry = readdir(dir)) != NULL))
943 if ((strcmp(entry->d_name, ".") == 0) ||
944 (strcmp(entry->d_name, "..") == 0))
950 * Build the full path name to the file.
952 strcpy(fullName, dirName);
955 strcat(fullName, "/");
957 strcat(fullName, entry->d_name);
960 * Write this file to the tar file, noticing whether or not
961 * the file is a symbolic link.
963 saveFile(fullName, TRUE);
967 * All done, close the directory.
974 * Write a tar header for the specified file name and status.
975 * It is assumed that the file name fits.
978 writeHeader(const char * fileName, const struct stat * statbuf)
981 const unsigned char * cp;
986 * Zero the header block in preparation for filling it in.
988 memset((char *) &header, 0, sizeof(header));
991 * Fill in the header.
993 strcpy(header.name, fileName);
995 strncpy(header.magic, TAR_MAGIC, sizeof(header.magic));
996 strncpy(header.version, TAR_VERSION, sizeof(header.version));
998 putOctal(header.mode, sizeof(header.mode), statbuf->st_mode & 0777);
999 putOctal(header.uid, sizeof(header.uid), statbuf->st_uid);
1000 putOctal(header.gid, sizeof(header.gid), statbuf->st_gid);
1001 putOctal(header.size, sizeof(header.size), statbuf->st_size);
1002 putOctal(header.mtime, sizeof(header.mtime), statbuf->st_mtime);
1004 header.typeFlag = TAR_TYPE_REGULAR;
1007 * Calculate and store the checksum.
1008 * This is the sum of all of the bytes of the header,
1009 * with the checksum field itself treated as blanks.
1011 memset(header.checkSum, ' ', sizeof(header.checkSum));
1013 cp = (const unsigned char *) &header;
1014 len = sizeof(header);
1020 putOctal(header.checkSum, sizeof(header.checkSum), checkSum);
1023 * Write the tar header.
1025 writeTarBlock((const char *) &header, sizeof(header));
1030 * Write data to one or more blocks of the tar file.
1031 * The data is always padded out to a multiple of TAR_BLOCK_SIZE.
1032 * The errorFlag static variable is set on an error.
1035 writeTarBlock(const char * buf, int len)
1039 char fullBlock[TAR_BLOCK_SIZE];
1042 * If we had a write error before, then do nothing more.
1048 * Get the amount of complete and partial blocks.
1050 partialLength = len % TAR_BLOCK_SIZE;
1051 completeLength = len - partialLength;
1054 * Write all of the complete blocks.
1056 if ((completeLength > 0) && !fullWrite(tarFd, buf, completeLength))
1066 * If there are no partial blocks left, we are done.
1068 if (partialLength == 0)
1072 * Copy the partial data into a complete block, and pad the rest
1073 * of it with zeroes.
1075 memcpy(fullBlock, buf + completeLength, partialLength);
1076 memset(fullBlock + partialLength, 0, TAR_BLOCK_SIZE - partialLength);
1079 * Write the last complete block.
1081 if (!fullWrite(tarFd, fullBlock, TAR_BLOCK_SIZE))
1091 * Attempt to create the directories along the specified path, except for
1092 * the final component. The mode is given for the final directory only,
1093 * while all previous ones get default protections. Errors are not reported
1094 * here, as failures to restore files can be reported later.
1097 createPath(const char * name, int mode)
1101 char buf[TAR_NAME_SIZE];
1105 cp = strchr(buf, '/');
1110 cp = strchr(cp + 1, '/');
1114 if (mkdir(buf, cp ? 0777 : mode) == 0)
1115 printf("Directory \"%s\" created\n", buf);
1123 * Read an octal value in a field of the specified width, with optional
1124 * spaces on both sides of the number and with an optional null character
1125 * at the end. Returns -1 on an illegal format.
1128 getOctal(const char * cp, int len)
1132 while ((len > 0) && (*cp == ' '))
1138 if ((len == 0) || !isOctal(*cp))
1143 while ((len > 0) && isOctal(*cp))
1145 val = val * 8 + *cp++ - '0';
1149 while ((len > 0) && (*cp == ' '))
1155 if ((len > 0) && *cp)
1163 * Put an octal string into the specified buffer.
1164 * The number is zero and space padded and possibly null padded.
1165 * Returns TRUE if successful.
1168 putOctal(char * cp, int len, long value)
1172 char tempBuffer[32];
1175 * Create a string of the specified length with an initial space,
1176 * leading zeroes and the octal number, and a trailing null.
1178 tempString = tempBuffer;
1180 sprintf(tempString, " %0*lo", len - 2, value);
1182 tempLength = strlen(tempString) + 1;
1185 * If the string is too large, suppress the leading space.
1187 if (tempLength > len)
1194 * If the string is still too large, suppress the trailing null.
1196 if (tempLength > len)
1200 * If the string is still too large, fail.
1202 if (tempLength > len)
1206 * Copy the string to the field.
1208 memcpy(cp, tempString, len);
1215 * See if the specified file name belongs to one of the specified list
1216 * of path prefixes. An empty list implies that all files are wanted.
1217 * Returns TRUE if the file is selected.
1220 wantFileName(const char * fileName, int fileCount, char ** fileTable)
1222 const char * pathName;
1227 * If there are no files in the list, then the file is wanted.
1232 fileLength = strlen(fileName);
1235 * Check each of the test paths.
1237 while (fileCount-- > 0)
1239 pathName = *fileTable++;
1241 pathLength = strlen(pathName);
1243 if (fileLength < pathLength)
1246 if (memcmp(fileName, pathName, pathLength) != 0)
1249 if ((fileLength == pathLength) ||
1250 (fileName[pathLength] == '/'))
1262 * Return the standard ls-like mode string from a file mode.
1263 * This is static and so is overwritten on each call.
1266 modeString(int mode)
1268 static char buf[12];
1270 strcpy(buf, "----------");
1273 * Fill in the file type.
1293 * Now fill in the normal file permissions.
1315 * Finally fill in magic stuff like suid and sticky text.
1318 buf[3] = ((mode & S_IXUSR) ? 's' : 'S');
1320 buf[6] = ((mode & S_IXGRP) ? 's' : 'S');
1322 buf[9] = ((mode & S_IXOTH) ? 't' : 'T');
1329 * Get the time string to be used for a file.
1330 * This is down to the minute for new files, but only the date for old files.
1331 * The string is returned from a static buffer, and so is overwritten for
1335 timeString(time_t timeVal)
1339 static char buf[26];
1343 str = ctime(&timeVal);
1345 strcpy(buf, &str[4]);
1348 if ((timeVal > now) || (timeVal < now - 365*24*60*60L))
1350 strcpy(&buf[7], &str[20]);
1360 * Write all of the supplied buffer out to a file.
1361 * This does multiple writes as necessary.
1362 * Returns the amount written, or -1 on an error.
1365 fullWrite(int fd, const char * buf, int len)
1374 cc = write(fd, buf, len);
1389 * Read all of the supplied buffer from a file.
1390 * This does multiple reads as necessary.
1391 * Returns the amount read, or -1 on an error.
1392 * A short read is returned on an end of file.
1395 fullRead(int fd, char * buf, int len)
1404 cc = read(fd, buf, len);