1 /* vi: set sw=4 ts=4: */
3 * Mini tar implementation for busybox
5 * Modified to use common extraction code used by ar, cpio, dpkg-deb, dpkg
8 * Note, that as of BusyBox-0.43, tar has been completely rewritten from the
9 * ground up. It still has remnants of the old code lying about, but it is
10 * very different now (i.e., cleaner, less global variables, etc.)
12 * Copyright (C) 1999-2004 by Erik Andersen <andersen@codepoet.org>
14 * Based in part in the tar implementation in sash
15 * Copyright (c) 1999 by David I. Bell
16 * Permission is granted to use, distribute, or modify this source,
17 * provided that this copyright notice remains intact.
18 * Permission to distribute sash derived code under the GPL has been granted.
20 * Based in part on the tar implementation from busybox-0.28
21 * Copyright (C) 1995 Bruce Perens
23 * Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
28 #include "unarchive.h"
29 /* FIXME: Stop using this non-standard feature */
30 #ifndef FNM_LEADING_DIR
31 # define FNM_LEADING_DIR 0
35 //#define DBG(fmt, ...) bb_error_msg("%s: " fmt, __func__, ## __VA_ARGS__)
36 #define DBG(...) ((void)0)
39 #define block_buf bb_common_bufsiz1
42 #if !ENABLE_FEATURE_SEAMLESS_GZ && !ENABLE_FEATURE_SEAMLESS_BZ2
43 /* Do not pass gzip flag to writeTarFile() */
44 #define writeTarFile(tar_fd, verboseFlag, dereferenceFlag, include, exclude, gzip) \
45 writeTarFile(tar_fd, verboseFlag, dereferenceFlag, include, exclude)
49 #if ENABLE_FEATURE_TAR_CREATE
51 /* Tar file constants */
53 #define TAR_BLOCK_SIZE 512
55 /* POSIX tar Header Block, from POSIX 1003.1-1990 */
57 #define NAME_SIZE_STR "100"
58 typedef struct TarHeader { /* byte offset */
59 char name[NAME_SIZE]; /* 0-99 */
60 char mode[8]; /* 100-107 */
61 char uid[8]; /* 108-115 */
62 char gid[8]; /* 116-123 */
63 char size[12]; /* 124-135 */
64 char mtime[12]; /* 136-147 */
65 char chksum[8]; /* 148-155 */
66 char typeflag; /* 156-156 */
67 char linkname[NAME_SIZE]; /* 157-256 */
68 /* POSIX: "ustar" NUL "00" */
69 /* GNU tar: "ustar " NUL */
70 /* Normally it's defined as magic[6] followed by
71 * version[2], but we put them together to save code.
73 char magic[8]; /* 257-264 */
74 char uname[32]; /* 265-296 */
75 char gname[32]; /* 297-328 */
76 char devmajor[8]; /* 329-336 */
77 char devminor[8]; /* 337-344 */
78 char prefix[155]; /* 345-499 */
79 char padding[12]; /* 500-512 (pad to exactly TAR_BLOCK_SIZE) */
83 ** writeTarFile(), writeFileToTarball(), and writeTarHeader() are
84 ** the only functions that deal with the HardLinkInfo structure.
85 ** Even these functions use the xxxHardLinkInfo() functions.
87 typedef struct HardLinkInfo {
88 struct HardLinkInfo *next; /* Next entry in list */
89 dev_t dev; /* Device number */
90 ino_t ino; /* Inode number */
91 // short linkCount; /* (Hard) Link Count */
92 char name[1]; /* Start of filename (must be last) */
95 /* Some info to be carried along when creating a new tarball */
96 typedef struct TarBallInfo {
97 int tarFd; /* Open-for-write file descriptor
99 int verboseFlag; /* Whether to print extra stuff or not */
100 const llist_t *excludeList; /* List of files to not include */
101 HardLinkInfo *hlInfoHead; /* Hard Link Tracking Information */
102 HardLinkInfo *hlInfo; /* Hard Link Info for the current file */
103 //TODO: save only st_dev + st_ino
104 struct stat tarFileStatBuf; /* Stat info for the tarball, letting
105 * us know the inode and device that the
106 * tarball lives, so we can avoid trying
107 * to include the tarball into itself */
110 /* A nice enum with all the possible tar file content types */
112 REGTYPE = '0', /* regular file */
113 REGTYPE0 = '\0', /* regular file (ancient bug compat) */
114 LNKTYPE = '1', /* hard link */
115 SYMTYPE = '2', /* symbolic link */
116 CHRTYPE = '3', /* character special */
117 BLKTYPE = '4', /* block special */
118 DIRTYPE = '5', /* directory */
119 FIFOTYPE = '6', /* FIFO special */
120 CONTTYPE = '7', /* reserved */
121 GNULONGLINK = 'K', /* GNU long (>100 chars) link name */
122 GNULONGNAME = 'L', /* GNU long (>100 chars) file name */
125 /* Might be faster (and bigger) if the dev/ino were stored in numeric order;) */
126 static void addHardLinkInfo(HardLinkInfo **hlInfoHeadPtr,
127 struct stat *statbuf,
128 const char *fileName)
130 /* Note: hlInfoHeadPtr can never be NULL! */
131 HardLinkInfo *hlInfo;
133 hlInfo = xmalloc(sizeof(HardLinkInfo) + strlen(fileName));
134 hlInfo->next = *hlInfoHeadPtr;
135 *hlInfoHeadPtr = hlInfo;
136 hlInfo->dev = statbuf->st_dev;
137 hlInfo->ino = statbuf->st_ino;
138 // hlInfo->linkCount = statbuf->st_nlink;
139 //TODO: "normalize" the name so that "./name/" == "name" etc?
140 strcpy(hlInfo->name, fileName);
143 static void freeHardLinkInfo(HardLinkInfo **hlInfoHeadPtr)
145 HardLinkInfo *hlInfo;
146 HardLinkInfo *hlInfoNext;
149 hlInfo = *hlInfoHeadPtr;
151 hlInfoNext = hlInfo->next;
155 *hlInfoHeadPtr = NULL;
159 /* Might be faster (and bigger) if the dev/ino were stored in numeric order;) */
160 static HardLinkInfo *findHardLinkInfo(HardLinkInfo *hlInfo, struct stat *statbuf, const char *filename)
163 if ((statbuf->st_ino == hlInfo->ino)
164 && (statbuf->st_dev == hlInfo->dev)
165 /* Name must NOT match. Think "tar cf t.tar file file"
166 * (same file tarred twice) */
167 && strcmp(filename, hlInfo->name) != 0
169 DBG("found hardlink:'%s'", hlInfo->name);
172 hlInfo = hlInfo->next;
177 /* Put an octal string into the specified buffer.
178 * The number is zero padded and possibly null terminated.
179 * Stores low-order bits only if whole value does not fit. */
180 static void putOctal(char *cp, int len, off_t value)
182 char tempBuffer[sizeof(off_t)*3 + 1];
183 char *tempString = tempBuffer;
186 width = sprintf(tempBuffer, "%0*"OFF_FMT"o", len, value);
187 tempString += (width - len);
189 /* If string has leading zeroes, we can drop one */
190 /* and field will have trailing '\0' */
191 /* (increases chances of compat with other tars) */
192 if (tempString[0] == '0')
195 /* Copy the string to the field */
196 memcpy(cp, tempString, len);
198 #define PUT_OCTAL(a, b) putOctal((a), sizeof(a), (b))
200 static void chksum_and_xwrite(int fd, struct TarHeader* hp)
202 /* POSIX says that checksum is done on unsigned bytes
203 * (Sun and HP-UX gets it wrong... more details in
205 const unsigned char *cp;
208 strcpy(hp->magic, "ustar ");
210 /* Calculate and store the checksum (i.e., the sum of all of the bytes of
211 * the header). The checksum field must be filled with blanks for the
212 * calculation. The checksum field is formatted differently from the
213 * other fields: it has 6 digits, a null, then a space -- rather than
214 * digits, followed by a null like the other fields... */
215 memset(hp->chksum, ' ', sizeof(hp->chksum));
216 cp = (const unsigned char *) hp;
219 do { chksum += *cp++; } while (--size);
220 putOctal(hp->chksum, sizeof(hp->chksum)-1, chksum);
222 /* Now write the header out to disk */
223 xwrite(fd, hp, sizeof(*hp));
226 #if ENABLE_FEATURE_TAR_GNU_EXTENSIONS
227 static void writeLongname(int fd, int type, const char *name, int dir)
229 static const struct {
230 char mode[8]; /* 100-107 */
231 char uid[8]; /* 108-115 */
232 char gid[8]; /* 116-123 */
233 char size[12]; /* 124-135 */
234 char mtime[12]; /* 136-147 */
242 struct TarHeader header;
245 dir = !!dir; /* normalize: 0/1 */
246 size = strlen(name) + 1 + dir; /* GNU tar uses strlen+1 */
247 /* + dir: account for possible '/' */
249 memset(&header, 0, sizeof(header));
250 strcpy(header.name, "././@LongLink");
251 memcpy(header.mode, prefilled.mode, sizeof(prefilled));
252 PUT_OCTAL(header.size, size);
253 header.typeflag = type;
254 chksum_and_xwrite(fd, &header);
256 /* Write filename[/] and pad the block. */
257 /* dir=0: writes 'name<NUL>', pads */
258 /* dir=1: writes 'name', writes '/<NUL>', pads */
260 xwrite(fd, name, size - dir);
261 xwrite(fd, "/", dir);
262 size = (-size) & (TAR_BLOCK_SIZE-1);
263 memset(&header, 0, size);
264 xwrite(fd, &header, size);
268 /* Write out a tar header for the specified file/directory/whatever */
269 void BUG_tar_header_size(void);
270 static int writeTarHeader(struct TarBallInfo *tbInfo,
271 const char *header_name, const char *fileName, struct stat *statbuf)
273 struct TarHeader header;
275 if (sizeof(header) != 512)
276 BUG_tar_header_size();
278 memset(&header, 0, sizeof(struct TarHeader));
280 strncpy(header.name, header_name, sizeof(header.name));
282 /* POSIX says to mask mode with 07777. */
283 PUT_OCTAL(header.mode, statbuf->st_mode & 07777);
284 PUT_OCTAL(header.uid, statbuf->st_uid);
285 PUT_OCTAL(header.gid, statbuf->st_gid);
286 memset(header.size, '0', sizeof(header.size)-1); /* Regular file size is handled later */
287 PUT_OCTAL(header.mtime, statbuf->st_mtime);
289 /* Enter the user and group names */
290 safe_strncpy(header.uname, get_cached_username(statbuf->st_uid), sizeof(header.uname));
291 safe_strncpy(header.gname, get_cached_groupname(statbuf->st_gid), sizeof(header.gname));
293 if (tbInfo->hlInfo) {
294 /* This is a hard link */
295 header.typeflag = LNKTYPE;
296 strncpy(header.linkname, tbInfo->hlInfo->name,
297 sizeof(header.linkname));
298 #if ENABLE_FEATURE_TAR_GNU_EXTENSIONS
299 /* Write out long linkname if needed */
300 if (header.linkname[sizeof(header.linkname)-1])
301 writeLongname(tbInfo->tarFd, GNULONGLINK,
302 tbInfo->hlInfo->name, 0);
304 } else if (S_ISLNK(statbuf->st_mode)) {
305 char *lpath = xmalloc_readlink_or_warn(fileName);
308 header.typeflag = SYMTYPE;
309 strncpy(header.linkname, lpath, sizeof(header.linkname));
310 #if ENABLE_FEATURE_TAR_GNU_EXTENSIONS
311 /* Write out long linkname if needed */
312 if (header.linkname[sizeof(header.linkname)-1])
313 writeLongname(tbInfo->tarFd, GNULONGLINK, lpath, 0);
315 /* If it is larger than 100 bytes, bail out */
316 if (header.linkname[sizeof(header.linkname)-1]) {
318 bb_error_msg("names longer than "NAME_SIZE_STR" chars not supported");
323 } else if (S_ISDIR(statbuf->st_mode)) {
324 header.typeflag = DIRTYPE;
325 /* Append '/' only if there is a space for it */
326 if (!header.name[sizeof(header.name)-1])
327 header.name[strlen(header.name)] = '/';
328 } else if (S_ISCHR(statbuf->st_mode)) {
329 header.typeflag = CHRTYPE;
330 PUT_OCTAL(header.devmajor, major(statbuf->st_rdev));
331 PUT_OCTAL(header.devminor, minor(statbuf->st_rdev));
332 } else if (S_ISBLK(statbuf->st_mode)) {
333 header.typeflag = BLKTYPE;
334 PUT_OCTAL(header.devmajor, major(statbuf->st_rdev));
335 PUT_OCTAL(header.devminor, minor(statbuf->st_rdev));
336 } else if (S_ISFIFO(statbuf->st_mode)) {
337 header.typeflag = FIFOTYPE;
338 } else if (S_ISREG(statbuf->st_mode)) {
339 if (sizeof(statbuf->st_size) > 4
340 && statbuf->st_size > (off_t)0777777777777LL
342 bb_error_msg_and_die("can't store file '%s' "
343 "of size %"OFF_FMT"d, aborting",
344 fileName, statbuf->st_size);
346 header.typeflag = REGTYPE;
347 PUT_OCTAL(header.size, statbuf->st_size);
349 bb_error_msg("%s: unknown file type", fileName);
353 #if ENABLE_FEATURE_TAR_GNU_EXTENSIONS
354 /* Write out long name if needed */
355 /* (we, like GNU tar, output long linkname *before* long name) */
356 if (header.name[sizeof(header.name)-1])
357 writeLongname(tbInfo->tarFd, GNULONGNAME,
358 header_name, S_ISDIR(statbuf->st_mode));
361 /* Now write the header out to disk */
362 chksum_and_xwrite(tbInfo->tarFd, &header);
364 /* Now do the verbose thing (or not) */
365 if (tbInfo->verboseFlag) {
368 /* If archive goes to stdout, verbose goes to stderr */
369 if (tbInfo->tarFd == STDOUT_FILENO)
371 /* GNU "tar cvvf" prints "extended" listing a-la "ls -l" */
372 /* We don't have such excesses here: for us "v" == "vv" */
373 /* '/' is probably a GNUism */
374 fprintf(vbFd, "%s%s\n", header_name,
375 S_ISDIR(statbuf->st_mode) ? "/" : "");
381 #if ENABLE_FEATURE_TAR_FROM
382 static int exclude_file(const llist_t *excluded_files, const char *file)
384 while (excluded_files) {
385 if (excluded_files->data[0] == '/') {
386 if (fnmatch(excluded_files->data, file,
387 FNM_PATHNAME | FNM_LEADING_DIR) == 0)
392 for (p = file; p[0] != '\0'; p++) {
393 if ((p == file || p[-1] == '/')
395 && fnmatch(excluded_files->data, p,
396 FNM_PATHNAME | FNM_LEADING_DIR) == 0
402 excluded_files = excluded_files->link;
408 # define exclude_file(excluded_files, file) 0
411 static int FAST_FUNC writeFileToTarball(const char *fileName, struct stat *statbuf,
412 void *userData, int depth UNUSED_PARAM)
414 struct TarBallInfo *tbInfo = (struct TarBallInfo *) userData;
415 const char *header_name;
416 int inputFileFd = -1;
418 DBG("writeFileToTarball('%s')", fileName);
420 /* Strip leading '/' (must be before memorizing hardlink's name) */
421 header_name = fileName;
422 while (header_name[0] == '/') {
423 static smallint warned;
426 bb_error_msg("removing leading '/' from member names");
432 if (header_name[0] == '\0')
435 /* It is against the rules to archive a socket */
436 if (S_ISSOCK(statbuf->st_mode)) {
437 bb_error_msg("%s: socket ignored", fileName);
442 * Check to see if we are dealing with a hard link.
444 * Treat the first occurance of a given dev/inode as a file while
445 * treating any additional occurances as hard links. This is done
446 * by adding the file information to the HardLinkInfo linked list.
448 tbInfo->hlInfo = NULL;
449 if (!S_ISDIR(statbuf->st_mode) && statbuf->st_nlink > 1) {
450 DBG("'%s': st_nlink > 1", header_name);
451 tbInfo->hlInfo = findHardLinkInfo(tbInfo->hlInfoHead, statbuf, header_name);
452 if (tbInfo->hlInfo == NULL) {
453 DBG("'%s': addHardLinkInfo", header_name);
454 addHardLinkInfo(&tbInfo->hlInfoHead, statbuf, header_name);
458 /* It is a bad idea to store the archive we are in the process of creating,
459 * so check the device and inode to be sure that this particular file isn't
461 if (tbInfo->tarFileStatBuf.st_dev == statbuf->st_dev
462 && tbInfo->tarFileStatBuf.st_ino == statbuf->st_ino
464 bb_error_msg("%s: file is the archive; skipping", fileName);
468 if (exclude_file(tbInfo->excludeList, header_name))
471 #if !ENABLE_FEATURE_TAR_GNU_EXTENSIONS
472 if (strlen(header_name) >= NAME_SIZE) {
473 bb_error_msg("names longer than "NAME_SIZE_STR" chars not supported");
478 /* Is this a regular file? */
479 if (tbInfo->hlInfo == NULL && S_ISREG(statbuf->st_mode)) {
480 /* open the file we want to archive, and make sure all is well */
481 inputFileFd = open_or_warn(fileName, O_RDONLY);
482 if (inputFileFd < 0) {
487 /* Add an entry to the tarball */
488 if (writeTarHeader(tbInfo, header_name, fileName, statbuf) == FALSE) {
492 /* If it was a regular file, write out the body */
493 if (inputFileFd >= 0) {
495 /* Write the file to the archive. */
496 /* We record size into header first, */
497 /* and then write out file. If file shrinks in between, */
498 /* tar will be corrupted. So we don't allow for that. */
499 /* NB: GNU tar 1.16 warns and pads with zeroes */
500 /* or even seeks back and updates header */
501 bb_copyfd_exact_size(inputFileFd, tbInfo->tarFd, statbuf->st_size);
503 ////readSize = bb_copyfd_size(inputFileFd, tbInfo->tarFd, statbuf->st_size);
504 ////if (readSize != statbuf->st_size && readSize >= 0) {
505 //// bb_error_msg_and_die("short read from %s, aborting", fileName);
508 /* Check that file did not grow in between? */
509 /* if (safe_read(inputFileFd, 1) == 1) warn but continue? */
513 /* Pad the file up to the tar block size */
514 /* (a few tricks here in the name of code size) */
515 readSize = (-(int)statbuf->st_size) & (TAR_BLOCK_SIZE-1);
516 memset(block_buf, 0, readSize);
517 xwrite(tbInfo->tarFd, block_buf, readSize);
523 #if ENABLE_FEATURE_SEAMLESS_GZ || ENABLE_FEATURE_SEAMLESS_BZ2
524 # if !(ENABLE_FEATURE_SEAMLESS_GZ && ENABLE_FEATURE_SEAMLESS_BZ2)
525 # define vfork_compressor(tar_fd, gzip) vfork_compressor(tar_fd)
527 /* Don't inline: vfork scares gcc and pessimizes code */
528 static void NOINLINE vfork_compressor(int tar_fd, int gzip)
531 # if ENABLE_FEATURE_SEAMLESS_GZ && ENABLE_FEATURE_SEAMLESS_BZ2
532 const char *zip_exec = (gzip == 1) ? "gzip" : "bzip2";
533 # elif ENABLE_FEATURE_SEAMLESS_GZ
534 const char *zip_exec = "gzip";
535 # else /* only ENABLE_FEATURE_SEAMLESS_BZ2 */
536 const char *zip_exec = "bzip2";
538 // On Linux, vfork never unpauses parent early, although standard
539 // allows for that. Do we want to waste bytes checking for it?
540 # define WAIT_FOR_CHILD 0
541 volatile int vfork_exec_errno = 0;
542 struct fd_pair gzipDataPipe;
544 struct fd_pair gzipStatusPipe;
545 xpiped_pair(gzipStatusPipe);
547 xpiped_pair(gzipDataPipe);
549 signal(SIGPIPE, SIG_IGN); /* we only want EPIPE on errors */
551 # if defined(__GNUC__) && __GNUC__
552 /* Avoid vfork clobbering */
558 bb_perror_msg_and_die("vfork");
562 /* NB: close _first_, then move fds! */
563 close(gzipDataPipe.wr);
565 close(gzipStatusPipe.rd);
566 /* gzipStatusPipe.wr will close only on exec -
567 * parent waits for this close to happen */
568 fcntl(gzipStatusPipe.wr, F_SETFD, FD_CLOEXEC);
570 xmove_fd(gzipDataPipe.rd, 0);
572 /* exec gzip/bzip2 program/applet */
573 BB_EXECLP(zip_exec, zip_exec, "-f", NULL);
574 vfork_exec_errno = errno;
579 xmove_fd(gzipDataPipe.wr, tar_fd);
580 close(gzipDataPipe.rd);
582 close(gzipStatusPipe.wr);
587 /* Wait until child execs (or fails to) */
588 n = full_read(gzipStatusPipe.rd, &buf, 1);
589 if (n < 0 /* && errno == EAGAIN */)
590 continue; /* try it again */
592 close(gzipStatusPipe.rd);
594 if (vfork_exec_errno) {
595 errno = vfork_exec_errno;
596 bb_perror_msg_and_die("can't execute '%s'", zip_exec);
599 #endif /* ENABLE_FEATURE_SEAMLESS_GZ || ENABLE_FEATURE_SEAMLESS_BZ2 */
602 /* gcc 4.2.1 inlines it, making code bigger */
603 static NOINLINE int writeTarFile(int tar_fd, int verboseFlag,
604 int dereferenceFlag, const llist_t *include,
605 const llist_t *exclude, int gzip)
607 int errorFlag = FALSE;
608 struct TarBallInfo tbInfo;
610 tbInfo.hlInfoHead = NULL;
611 tbInfo.tarFd = tar_fd;
612 tbInfo.verboseFlag = verboseFlag;
614 /* Store the stat info for the tarball's file, so
615 * can avoid including the tarball into itself.... */
616 if (fstat(tbInfo.tarFd, &tbInfo.tarFileStatBuf) < 0)
617 bb_perror_msg_and_die("can't stat tar file");
619 #if ENABLE_FEATURE_SEAMLESS_GZ || ENABLE_FEATURE_SEAMLESS_BZ2
621 vfork_compressor(tbInfo.tarFd, gzip);
624 tbInfo.excludeList = exclude;
626 /* Read the directory/files and iterate over them one at a time */
628 if (!recursive_action(include->data, ACTION_RECURSE |
629 (dereferenceFlag ? ACTION_FOLLOWLINKS : 0),
630 writeFileToTarball, writeFileToTarball, &tbInfo, 0))
634 include = include->link;
636 /* Write two empty blocks to the end of the archive */
637 memset(block_buf, 0, 2*TAR_BLOCK_SIZE);
638 xwrite(tbInfo.tarFd, block_buf, 2*TAR_BLOCK_SIZE);
640 /* To be pedantically correct, we would check if the tarball
641 * is smaller than 20 tar blocks, and pad it if it was smaller,
642 * but that isn't necessary for GNU tar interoperability, and
643 * so is considered a waste of space */
645 /* Close so the child process (if any) will exit */
648 /* Hang up the tools, close up shop, head home */
649 if (ENABLE_FEATURE_CLEAN_UP)
650 freeHardLinkInfo(&tbInfo.hlInfoHead);
653 bb_error_msg("error exit delayed from previous errors");
655 #if ENABLE_FEATURE_SEAMLESS_GZ || ENABLE_FEATURE_SEAMLESS_BZ2
658 if (safe_waitpid(-1, &status, 0) == -1)
659 bb_perror_msg("waitpid");
660 else if (!WIFEXITED(status) || WEXITSTATUS(status))
661 /* gzip was killed or has exited with nonzero! */
668 int writeTarFile(int tar_fd, int verboseFlag,
669 int dereferenceFlag, const llist_t *include,
670 const llist_t *exclude, int gzip);
671 #endif /* FEATURE_TAR_CREATE */
673 #if ENABLE_FEATURE_TAR_FROM
674 static llist_t *append_file_list_to_list(llist_t *list)
678 llist_t *newlist = NULL;
681 src_stream = xfopen_for_read(llist_pop(&list));
682 while ((line = xmalloc_fgetline(src_stream)) != NULL) {
683 /* kill trailing '/' unless the string is just "/" */
684 char *cp = last_char_is(line, '/');
687 llist_add_to(&newlist, line);
694 # define append_file_list_to_list(x) 0
697 #if ENABLE_FEATURE_SEAMLESS_Z
698 static char FAST_FUNC get_header_tar_Z(archive_handle_t *archive_handle)
700 /* Can't lseek over pipes */
701 archive_handle->seek = seek_by_read;
703 /* do the decompression, and cleanup */
704 if (xread_char(archive_handle->src_fd) != 0x1f
705 || xread_char(archive_handle->src_fd) != 0x9d
707 bb_error_msg_and_die("invalid magic");
710 open_transformer(archive_handle->src_fd, unpack_Z_stream, "uncompress");
711 archive_handle->offset = 0;
712 while (get_header_tar(archive_handle) == EXIT_SUCCESS)
715 /* Can only do one file at a time */
719 # define get_header_tar_Z NULL
722 #ifdef CHECK_FOR_CHILD_EXITCODE
723 /* Looks like it isn't needed - tar detects malformed (truncated)
724 * archive if e.g. bunzip2 fails */
725 static int child_error;
727 static void handle_SIGCHLD(int status)
729 /* Actually, 'status' is a signo. We reuse it for other needs */
731 /* Wait for any child without blocking */
732 if (wait_any_nohang(&status) < 0)
733 /* wait failed?! I'm confused... */
736 if (WIFEXITED(status) && WEXITSTATUS(status)==0)
737 /* child exited with 0 */
740 if (!WIFSIGNALED(status) && !WIFEXITED(status)) return; */
747 IF_FEATURE_TAR_CREATE( OPTBIT_CREATE ,)
748 IF_FEATURE_TAR_CREATE( OPTBIT_DEREFERENCE ,)
749 IF_FEATURE_SEAMLESS_BZ2( OPTBIT_BZIP2 ,)
750 IF_FEATURE_SEAMLESS_LZMA(OPTBIT_LZMA ,)
751 IF_FEATURE_TAR_FROM( OPTBIT_INCLUDE_FROM,)
752 IF_FEATURE_TAR_FROM( OPTBIT_EXCLUDE_FROM,)
753 IF_FEATURE_SEAMLESS_GZ( OPTBIT_GZIP ,)
754 IF_FEATURE_SEAMLESS_Z( OPTBIT_COMPRESS ,) // 16th bit
755 OPTBIT_NUMERIC_OWNER,
756 OPTBIT_NOPRESERVE_OWNER,
757 OPTBIT_NOPRESERVE_PERM,
758 OPT_TEST = 1 << 0, // t
759 OPT_EXTRACT = 1 << 1, // x
760 OPT_BASEDIR = 1 << 2, // C
761 OPT_TARNAME = 1 << 3, // f
762 OPT_2STDOUT = 1 << 4, // O
763 OPT_NOPRESERVE_OWNER = 1 << 5, // no-same-owner
765 OPT_VERBOSE = 1 << 7, // v
766 OPT_KEEP_OLD = 1 << 8, // k
767 OPT_CREATE = IF_FEATURE_TAR_CREATE( (1 << OPTBIT_CREATE )) + 0, // c
768 OPT_DEREFERENCE = IF_FEATURE_TAR_CREATE( (1 << OPTBIT_DEREFERENCE )) + 0, // h
769 OPT_BZIP2 = IF_FEATURE_SEAMLESS_BZ2( (1 << OPTBIT_BZIP2 )) + 0, // j
770 OPT_LZMA = IF_FEATURE_SEAMLESS_LZMA((1 << OPTBIT_LZMA )) + 0, // a
771 OPT_INCLUDE_FROM = IF_FEATURE_TAR_FROM( (1 << OPTBIT_INCLUDE_FROM)) + 0, // T
772 OPT_EXCLUDE_FROM = IF_FEATURE_TAR_FROM( (1 << OPTBIT_EXCLUDE_FROM)) + 0, // X
773 OPT_GZIP = IF_FEATURE_SEAMLESS_GZ( (1 << OPTBIT_GZIP )) + 0, // z
774 OPT_COMPRESS = IF_FEATURE_SEAMLESS_Z( (1 << OPTBIT_COMPRESS )) + 0, // Z
775 OPT_NUMERIC_OWNER = 1 << OPTBIT_NUMERIC_OWNER,
776 OPT_NOPRESERVE_PERM = 1 << OPTBIT_NOPRESERVE_PERM, // no-same-permissions
778 #if ENABLE_FEATURE_TAR_LONG_OPTIONS
779 static const char tar_longopts[] ALIGN1 =
780 "list\0" No_argument "t"
781 "extract\0" No_argument "x"
782 "directory\0" Required_argument "C"
783 "file\0" Required_argument "f"
784 "to-stdout\0" No_argument "O"
785 /* do not restore owner */
786 /* Note: GNU tar handles 'o' as no-same-owner only on extract,
787 * on create, 'o' is --old-archive. We do not support --old-archive. */
788 "no-same-owner\0" No_argument "o"
789 "same-permissions\0" No_argument "p"
790 "verbose\0" No_argument "v"
791 "keep-old\0" No_argument "k"
792 # if ENABLE_FEATURE_TAR_CREATE
793 "create\0" No_argument "c"
794 "dereference\0" No_argument "h"
796 # if ENABLE_FEATURE_SEAMLESS_BZ2
797 "bzip2\0" No_argument "j"
799 # if ENABLE_FEATURE_SEAMLESS_LZMA
800 "lzma\0" No_argument "a"
802 # if ENABLE_FEATURE_TAR_FROM
803 "files-from\0" Required_argument "T"
804 "exclude-from\0" Required_argument "X"
806 # if ENABLE_FEATURE_SEAMLESS_GZ
807 "gzip\0" No_argument "z"
809 # if ENABLE_FEATURE_SEAMLESS_Z
810 "compress\0" No_argument "Z"
812 /* use numeric uid/gid from tar header, not textual */
813 "numeric-owner\0" No_argument "\xfd"
814 /* do not restore mode */
815 "no-same-permissions\0" No_argument "\xfe"
816 /* --exclude takes next bit position in option mask, */
817 /* therefore we have to either put it _after_ --no-same-perm */
818 /* or add OPT[BIT]_EXCLUDE before OPT[BIT]_NOPRESERVE_OWNER */
819 # if ENABLE_FEATURE_TAR_FROM
820 "exclude\0" Required_argument "\xff"
825 int tar_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
826 int tar_main(int argc UNUSED_PARAM, char **argv)
828 char FAST_FUNC (*get_header_ptr)(archive_handle_t *) = get_header_tar;
829 archive_handle_t *tar_handle;
830 char *base_dir = NULL;
831 const char *tar_filename = "-";
834 #if ENABLE_FEATURE_TAR_LONG_OPTIONS && ENABLE_FEATURE_TAR_FROM
835 llist_t *excludes = NULL;
838 /* Initialise default values */
839 tar_handle = init_handle();
840 tar_handle->ah_flags = ARCHIVE_CREATE_LEADING_DIRS
841 | ARCHIVE_RESTORE_DATE
842 | ARCHIVE_UNLINK_OLD;
844 /* Apparently only root's tar preserves perms (see bug 3844) */
846 tar_handle->ah_flags |= ARCHIVE_DONT_RESTORE_PERM;
848 /* Prepend '-' to the first argument if required */
849 opt_complementary = "--:" // first arg is options
850 "tt:vv:" // count -t,-v
851 "?:" // bail out with usage instead of error return
852 "X::T::" // cumulative lists
853 #if ENABLE_FEATURE_TAR_LONG_OPTIONS && ENABLE_FEATURE_TAR_FROM
854 "\xff::" // cumulative lists for --exclude
856 IF_FEATURE_TAR_CREATE("c:") "t:x:" // at least one of these is reqd
857 IF_FEATURE_TAR_CREATE("c--tx:t--cx:x--ct") // mutually exclusive
858 IF_NOT_FEATURE_TAR_CREATE("t--x:x--t"); // mutually exclusive
859 #if ENABLE_FEATURE_TAR_LONG_OPTIONS
860 applet_long_options = tar_longopts;
863 if (argv[1][0] != '-') {
865 * 1st argument without dash handles options with parameters
866 * differently from dashed one: it takes *next argv[i]*
867 * as paramenter even if there are more chars in 1st argument:
868 * "tar fx TARFILE" - "x" is not taken as f's param
869 * but is interpreted as -x option
870 * "tar -xf TARFILE" - dashed equivalent of the above
871 * "tar -fx ..." - "x" is taken as f's param
872 * getopt32 wouldn't handle 1st command correctly.
873 * Unfortunately, people do use such commands.
874 * We massage argv[1] to work around it by moving 'f'
875 * to the end of the string.
876 * More contrived "tar fCx TARFILE DIR" still fails,
877 * but such commands are much less likely to be used.
879 char *f = strchr(argv[1], 'f');
881 while (f[1] != '\0') {
891 IF_FEATURE_TAR_CREATE( "ch" )
892 IF_FEATURE_SEAMLESS_BZ2( "j" )
893 IF_FEATURE_SEAMLESS_LZMA("a" )
894 IF_FEATURE_TAR_FROM( "T:X:")
895 IF_FEATURE_SEAMLESS_GZ( "z" )
896 IF_FEATURE_SEAMLESS_Z( "Z" )
897 , &base_dir // -C dir
898 , &tar_filename // -f filename
899 IF_FEATURE_TAR_FROM(, &(tar_handle->accept)) // T
900 IF_FEATURE_TAR_FROM(, &(tar_handle->reject)) // X
901 #if ENABLE_FEATURE_TAR_LONG_OPTIONS && ENABLE_FEATURE_TAR_FROM
902 , &excludes // --exclude
904 , &verboseFlag // combined count for -t and -v
905 , &verboseFlag // combined count for -t and -v
907 //bb_error_msg("opt:%08x", opt);
910 if (verboseFlag) tar_handle->action_header = header_verbose_list;
911 if (verboseFlag == 1) tar_handle->action_header = header_list;
913 if (opt & OPT_EXTRACT)
914 tar_handle->action_data = data_extract_all;
916 if (opt & OPT_2STDOUT)
917 tar_handle->action_data = data_extract_to_stdout;
919 if (opt & OPT_KEEP_OLD)
920 tar_handle->ah_flags &= ~ARCHIVE_UNLINK_OLD;
922 if (opt & OPT_NUMERIC_OWNER)
923 tar_handle->ah_flags |= ARCHIVE_NUMERIC_OWNER;
925 if (opt & OPT_NOPRESERVE_OWNER)
926 tar_handle->ah_flags |= ARCHIVE_DONT_RESTORE_OWNER;
928 if (opt & OPT_NOPRESERVE_PERM)
929 tar_handle->ah_flags |= ARCHIVE_DONT_RESTORE_PERM;
932 get_header_ptr = get_header_tar_gz;
935 get_header_ptr = get_header_tar_bz2;
938 get_header_ptr = get_header_tar_lzma;
940 if (opt & OPT_COMPRESS)
941 get_header_ptr = get_header_tar_Z;
943 #if ENABLE_FEATURE_TAR_FROM
944 tar_handle->reject = append_file_list_to_list(tar_handle->reject);
945 #if ENABLE_FEATURE_TAR_LONG_OPTIONS
946 /* Append excludes to reject */
948 llist_t *next = excludes->link;
949 excludes->link = tar_handle->reject;
950 tar_handle->reject = excludes;
954 tar_handle->accept = append_file_list_to_list(tar_handle->accept);
957 /* Setup an array of filenames to work with */
958 /* TODO: This is the same as in ar, separate function ? */
960 /* kill trailing '/' unless the string is just "/" */
961 char *cp = last_char_is(*argv, '/');
964 llist_add_to_end(&tar_handle->accept, *argv);
968 if (tar_handle->accept || tar_handle->reject)
969 tar_handle->filter = filter_accept_reject_list;
971 /* Open the tar file */
976 if (opt & OPT_CREATE) {
977 /* Make sure there is at least one file to tar up. */
978 if (tar_handle->accept == NULL)
979 bb_error_msg_and_die("empty archive");
982 /* Mimicking GNU tar 1.15.1: */
983 flags = O_WRONLY | O_CREAT | O_TRUNC;
989 if (LONE_DASH(tar_filename)) {
990 tar_handle->src_fd = fileno(tar_stream);
991 tar_handle->seek = seek_by_read;
993 if (ENABLE_FEATURE_TAR_AUTODETECT && flags == O_RDONLY) {
994 get_header_ptr = get_header_tar;
995 tar_handle->src_fd = open_zipped(tar_filename);
996 if (tar_handle->src_fd < 0)
997 bb_perror_msg_and_die("can't open '%s'", tar_filename);
999 tar_handle->src_fd = xopen(tar_filename, flags);
1007 #ifdef CHECK_FOR_CHILD_EXITCODE
1008 /* We need to know whether child (gzip/bzip/etc) exits abnormally */
1009 signal(SIGCHLD, handle_SIGCHLD);
1012 /* create an archive */
1013 if (opt & OPT_CREATE) {
1014 #if ENABLE_FEATURE_SEAMLESS_GZ || ENABLE_FEATURE_SEAMLESS_BZ2
1016 if (ENABLE_FEATURE_SEAMLESS_GZ && (opt & OPT_GZIP))
1018 if (ENABLE_FEATURE_SEAMLESS_BZ2 && (opt & OPT_BZIP2))
1021 /* NB: writeTarFile() closes tar_handle->src_fd */
1022 return writeTarFile(tar_handle->src_fd, verboseFlag, opt & OPT_DEREFERENCE,
1024 tar_handle->reject, zipMode);
1027 while (get_header_ptr(tar_handle) == EXIT_SUCCESS)
1030 /* Check that every file that should have been extracted was */
1031 while (tar_handle->accept) {
1032 if (!find_list_entry(tar_handle->reject, tar_handle->accept->data)
1033 && !find_list_entry(tar_handle->passed, tar_handle->accept->data)
1035 bb_error_msg_and_die("%s: not found in archive",
1036 tar_handle->accept->data);
1038 tar_handle->accept = tar_handle->accept->link;
1040 if (ENABLE_FEATURE_CLEAN_UP /* && tar_handle->src_fd != STDIN_FILENO */)
1041 close(tar_handle->src_fd);
1043 return EXIT_SUCCESS;