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 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 source tree.
26 /* TODO: security with -C DESTDIR option can be enhanced.
27 * Consider tar file created via:
28 * $ tar cvf bug.tar anything.txt
29 * $ ln -s /tmp symlink
30 * $ tar --append -f bug.tar symlink
33 * $ tar --append -f bug.tar symlink/evil.py
35 * This will result in an archive which contains:
36 * $ tar --list -f bug.tar
41 * Untarring it puts evil.py in '/tmp' even if the -C DESTDIR is given.
42 * This doesn't feel right, and IIRC GNU tar doesn't do that.
45 //applet:IF_TAR(APPLET(tar, BB_DIR_BIN, BB_SUID_DROP))
46 //kbuild:lib-$(CONFIG_TAR) += tar.o
50 #include "bb_archive.h"
51 /* FIXME: Stop using this non-standard feature */
52 #ifndef FNM_LEADING_DIR
53 # define FNM_LEADING_DIR 0
57 //#define DBG(fmt, ...) bb_error_msg("%s: " fmt, __func__, ## __VA_ARGS__)
58 #define DBG(...) ((void)0)
61 #define block_buf bb_common_bufsiz1
64 #if !ENABLE_FEATURE_SEAMLESS_GZ && !ENABLE_FEATURE_SEAMLESS_BZ2
65 /* Do not pass gzip flag to writeTarFile() */
66 #define writeTarFile(tar_fd, verboseFlag, recurseFlags, include, exclude, gzip) \
67 writeTarFile(tar_fd, verboseFlag, recurseFlags, include, exclude)
71 #if ENABLE_FEATURE_TAR_CREATE
74 ** writeTarFile(), writeFileToTarball(), and writeTarHeader() are
75 ** the only functions that deal with the HardLinkInfo structure.
76 ** Even these functions use the xxxHardLinkInfo() functions.
78 typedef struct HardLinkInfo {
79 struct HardLinkInfo *next; /* Next entry in list */
80 dev_t dev; /* Device number */
81 ino_t ino; /* Inode number */
82 // short linkCount; /* (Hard) Link Count */
83 char name[1]; /* Start of filename (must be last) */
86 /* Some info to be carried along when creating a new tarball */
87 typedef struct TarBallInfo {
88 int tarFd; /* Open-for-write file descriptor
90 int verboseFlag; /* Whether to print extra stuff or not */
91 const llist_t *excludeList; /* List of files to not include */
92 HardLinkInfo *hlInfoHead; /* Hard Link Tracking Information */
93 HardLinkInfo *hlInfo; /* Hard Link Info for the current file */
94 //TODO: save only st_dev + st_ino
95 struct stat tarFileStatBuf; /* Stat info for the tarball, letting
96 * us know the inode and device that the
97 * tarball lives, so we can avoid trying
98 * to include the tarball into itself */
101 /* A nice enum with all the possible tar file content types */
103 REGTYPE = '0', /* regular file */
104 REGTYPE0 = '\0', /* regular file (ancient bug compat) */
105 LNKTYPE = '1', /* hard link */
106 SYMTYPE = '2', /* symbolic link */
107 CHRTYPE = '3', /* character special */
108 BLKTYPE = '4', /* block special */
109 DIRTYPE = '5', /* directory */
110 FIFOTYPE = '6', /* FIFO special */
111 CONTTYPE = '7', /* reserved */
112 GNULONGLINK = 'K', /* GNU long (>100 chars) link name */
113 GNULONGNAME = 'L', /* GNU long (>100 chars) file name */
116 /* Might be faster (and bigger) if the dev/ino were stored in numeric order;) */
117 static void addHardLinkInfo(HardLinkInfo **hlInfoHeadPtr,
118 struct stat *statbuf,
119 const char *fileName)
121 /* Note: hlInfoHeadPtr can never be NULL! */
122 HardLinkInfo *hlInfo;
124 hlInfo = xmalloc(sizeof(HardLinkInfo) + strlen(fileName));
125 hlInfo->next = *hlInfoHeadPtr;
126 *hlInfoHeadPtr = hlInfo;
127 hlInfo->dev = statbuf->st_dev;
128 hlInfo->ino = statbuf->st_ino;
129 // hlInfo->linkCount = statbuf->st_nlink;
130 strcpy(hlInfo->name, fileName);
133 static void freeHardLinkInfo(HardLinkInfo **hlInfoHeadPtr)
135 HardLinkInfo *hlInfo;
136 HardLinkInfo *hlInfoNext;
139 hlInfo = *hlInfoHeadPtr;
141 hlInfoNext = hlInfo->next;
145 *hlInfoHeadPtr = NULL;
149 /* Might be faster (and bigger) if the dev/ino were stored in numeric order ;) */
150 static HardLinkInfo *findHardLinkInfo(HardLinkInfo *hlInfo, struct stat *statbuf)
153 if (statbuf->st_ino == hlInfo->ino
154 && statbuf->st_dev == hlInfo->dev
156 DBG("found hardlink:'%s'", hlInfo->name);
159 hlInfo = hlInfo->next;
164 /* Put an octal string into the specified buffer.
165 * The number is zero padded and possibly null terminated.
166 * Stores low-order bits only if whole value does not fit. */
167 static void putOctal(char *cp, int len, off_t value)
169 char tempBuffer[sizeof(off_t)*3 + 1];
170 char *tempString = tempBuffer;
173 width = sprintf(tempBuffer, "%0*"OFF_FMT"o", len, value);
174 tempString += (width - len);
176 /* If string has leading zeroes, we can drop one */
177 /* and field will have trailing '\0' */
178 /* (increases chances of compat with other tars) */
179 if (tempString[0] == '0')
182 /* Copy the string to the field */
183 memcpy(cp, tempString, len);
185 #define PUT_OCTAL(a, b) putOctal((a), sizeof(a), (b))
187 static void chksum_and_xwrite(int fd, struct tar_header_t* hp)
189 /* POSIX says that checksum is done on unsigned bytes
190 * (Sun and HP-UX gets it wrong... more details in
192 const unsigned char *cp;
195 strcpy(hp->magic, "ustar ");
197 /* Calculate and store the checksum (i.e., the sum of all of the bytes of
198 * the header). The checksum field must be filled with blanks for the
199 * calculation. The checksum field is formatted differently from the
200 * other fields: it has 6 digits, a null, then a space -- rather than
201 * digits, followed by a null like the other fields... */
202 memset(hp->chksum, ' ', sizeof(hp->chksum));
203 cp = (const unsigned char *) hp;
206 do { chksum += *cp++; } while (--size);
207 putOctal(hp->chksum, sizeof(hp->chksum)-1, chksum);
209 /* Now write the header out to disk */
210 xwrite(fd, hp, sizeof(*hp));
213 #if ENABLE_FEATURE_TAR_GNU_EXTENSIONS
214 static void writeLongname(int fd, int type, const char *name, int dir)
216 static const struct {
217 char mode[8]; /* 100-107 */
218 char uid[8]; /* 108-115 */
219 char gid[8]; /* 116-123 */
220 char size[12]; /* 124-135 */
221 char mtime[12]; /* 136-147 */
229 struct tar_header_t header;
232 dir = !!dir; /* normalize: 0/1 */
233 size = strlen(name) + 1 + dir; /* GNU tar uses strlen+1 */
234 /* + dir: account for possible '/' */
236 memset(&header, 0, sizeof(header));
237 strcpy(header.name, "././@LongLink");
238 memcpy(header.mode, prefilled.mode, sizeof(prefilled));
239 PUT_OCTAL(header.size, size);
240 header.typeflag = type;
241 chksum_and_xwrite(fd, &header);
243 /* Write filename[/] and pad the block. */
244 /* dir=0: writes 'name<NUL>', pads */
245 /* dir=1: writes 'name', writes '/<NUL>', pads */
247 xwrite(fd, name, size - dir);
248 xwrite(fd, "/", dir);
249 size = (-size) & (TAR_BLOCK_SIZE-1);
250 memset(&header, 0, size);
251 xwrite(fd, &header, size);
255 /* Write out a tar header for the specified file/directory/whatever */
256 static int writeTarHeader(struct TarBallInfo *tbInfo,
257 const char *header_name, const char *fileName, struct stat *statbuf)
259 struct tar_header_t header;
261 memset(&header, 0, sizeof(header));
263 strncpy(header.name, header_name, sizeof(header.name));
265 /* POSIX says to mask mode with 07777. */
266 PUT_OCTAL(header.mode, statbuf->st_mode & 07777);
267 PUT_OCTAL(header.uid, statbuf->st_uid);
268 PUT_OCTAL(header.gid, statbuf->st_gid);
269 memset(header.size, '0', sizeof(header.size)-1); /* Regular file size is handled later */
270 /* users report that files with negative st_mtime cause trouble, so: */
271 PUT_OCTAL(header.mtime, statbuf->st_mtime >= 0 ? statbuf->st_mtime : 0);
273 /* Enter the user and group names */
274 safe_strncpy(header.uname, get_cached_username(statbuf->st_uid), sizeof(header.uname));
275 safe_strncpy(header.gname, get_cached_groupname(statbuf->st_gid), sizeof(header.gname));
277 if (tbInfo->hlInfo) {
278 /* This is a hard link */
279 header.typeflag = LNKTYPE;
280 strncpy(header.linkname, tbInfo->hlInfo->name,
281 sizeof(header.linkname));
282 #if ENABLE_FEATURE_TAR_GNU_EXTENSIONS
283 /* Write out long linkname if needed */
284 if (header.linkname[sizeof(header.linkname)-1])
285 writeLongname(tbInfo->tarFd, GNULONGLINK,
286 tbInfo->hlInfo->name, 0);
288 } else if (S_ISLNK(statbuf->st_mode)) {
289 char *lpath = xmalloc_readlink_or_warn(fileName);
292 header.typeflag = SYMTYPE;
293 strncpy(header.linkname, lpath, sizeof(header.linkname));
294 #if ENABLE_FEATURE_TAR_GNU_EXTENSIONS
295 /* Write out long linkname if needed */
296 if (header.linkname[sizeof(header.linkname)-1])
297 writeLongname(tbInfo->tarFd, GNULONGLINK, lpath, 0);
299 /* If it is larger than 100 bytes, bail out */
300 if (header.linkname[sizeof(header.linkname)-1]) {
302 bb_error_msg("names longer than "NAME_SIZE_STR" chars not supported");
307 } else if (S_ISDIR(statbuf->st_mode)) {
308 header.typeflag = DIRTYPE;
309 /* Append '/' only if there is a space for it */
310 if (!header.name[sizeof(header.name)-1])
311 header.name[strlen(header.name)] = '/';
312 } else if (S_ISCHR(statbuf->st_mode)) {
313 header.typeflag = CHRTYPE;
314 PUT_OCTAL(header.devmajor, major(statbuf->st_rdev));
315 PUT_OCTAL(header.devminor, minor(statbuf->st_rdev));
316 } else if (S_ISBLK(statbuf->st_mode)) {
317 header.typeflag = BLKTYPE;
318 PUT_OCTAL(header.devmajor, major(statbuf->st_rdev));
319 PUT_OCTAL(header.devminor, minor(statbuf->st_rdev));
320 } else if (S_ISFIFO(statbuf->st_mode)) {
321 header.typeflag = FIFOTYPE;
322 } else if (S_ISREG(statbuf->st_mode)) {
323 /* header.size field is 12 bytes long */
324 /* Does octal-encoded size fit? */
325 uoff_t filesize = statbuf->st_size;
326 if (sizeof(filesize) <= 4
327 || filesize <= (uoff_t)0777777777777LL
329 PUT_OCTAL(header.size, filesize);
331 /* Does base256-encoded size fit?
332 * It always does unless off_t is wider than 64 bits.
334 else if (ENABLE_FEATURE_TAR_GNU_EXTENSIONS
335 #if ULLONG_MAX > 0xffffffffffffffffLL /* 2^64-1 */
336 && (filesize <= 0x3fffffffffffffffffffffffLL)
339 /* GNU tar uses "base-256 encoding" for very large numbers.
340 * Encoding is binary, with highest bit always set as a marker
341 * and sign in next-highest bit:
343 * bf ff .. ff - largest positive number
344 * ff ff .. ff - minus 1
345 * c0 00 .. 00 - smallest negative number
347 char *p8 = header.size + sizeof(header.size);
349 *--p8 = (uint8_t)filesize;
351 } while (p8 != header.size);
354 bb_error_msg_and_die("can't store file '%s' "
355 "of size %"OFF_FMT"u, aborting",
356 fileName, statbuf->st_size);
358 header.typeflag = REGTYPE;
360 bb_error_msg("%s: unknown file type", fileName);
364 #if ENABLE_FEATURE_TAR_GNU_EXTENSIONS
365 /* Write out long name if needed */
366 /* (we, like GNU tar, output long linkname *before* long name) */
367 if (header.name[sizeof(header.name)-1])
368 writeLongname(tbInfo->tarFd, GNULONGNAME,
369 header_name, S_ISDIR(statbuf->st_mode));
372 /* Now write the header out to disk */
373 chksum_and_xwrite(tbInfo->tarFd, &header);
375 /* Now do the verbose thing (or not) */
376 if (tbInfo->verboseFlag) {
379 /* If archive goes to stdout, verbose goes to stderr */
380 if (tbInfo->tarFd == STDOUT_FILENO)
382 /* GNU "tar cvvf" prints "extended" listing a-la "ls -l" */
383 /* We don't have such excesses here: for us "v" == "vv" */
384 /* '/' is probably a GNUism */
385 fprintf(vbFd, "%s%s\n", header_name,
386 S_ISDIR(statbuf->st_mode) ? "/" : "");
392 #if ENABLE_FEATURE_TAR_FROM
393 static int exclude_file(const llist_t *excluded_files, const char *file)
395 while (excluded_files) {
396 if (excluded_files->data[0] == '/') {
397 if (fnmatch(excluded_files->data, file,
398 FNM_PATHNAME | FNM_LEADING_DIR) == 0)
403 for (p = file; p[0] != '\0'; p++) {
404 if ((p == file || p[-1] == '/')
406 && fnmatch(excluded_files->data, p,
407 FNM_PATHNAME | FNM_LEADING_DIR) == 0
413 excluded_files = excluded_files->link;
419 # define exclude_file(excluded_files, file) 0
422 static int FAST_FUNC writeFileToTarball(const char *fileName, struct stat *statbuf,
423 void *userData, int depth UNUSED_PARAM)
425 struct TarBallInfo *tbInfo = (struct TarBallInfo *) userData;
426 const char *header_name;
427 int inputFileFd = -1;
429 DBG("writeFileToTarball('%s')", fileName);
431 /* Strip leading '/' and such (must be before memorizing hardlink's name) */
432 header_name = strip_unsafe_prefix(fileName);
434 if (header_name[0] == '\0')
437 /* It is against the rules to archive a socket */
438 if (S_ISSOCK(statbuf->st_mode)) {
439 bb_error_msg("%s: socket ignored", fileName);
444 * Check to see if we are dealing with a hard link.
446 * Treat the first occurance of a given dev/inode as a file while
447 * treating any additional occurances as hard links. This is done
448 * by adding the file information to the HardLinkInfo linked list.
450 tbInfo->hlInfo = NULL;
451 if (!S_ISDIR(statbuf->st_mode) && statbuf->st_nlink > 1) {
452 DBG("'%s': st_nlink > 1", header_name);
453 tbInfo->hlInfo = findHardLinkInfo(tbInfo->hlInfoHead, statbuf);
454 if (tbInfo->hlInfo == NULL) {
455 DBG("'%s': addHardLinkInfo", header_name);
456 addHardLinkInfo(&tbInfo->hlInfoHead, statbuf, header_name);
460 /* It is a bad idea to store the archive we are in the process of creating,
461 * so check the device and inode to be sure that this particular file isn't
463 if (tbInfo->tarFileStatBuf.st_dev == statbuf->st_dev
464 && tbInfo->tarFileStatBuf.st_ino == statbuf->st_ino
466 bb_error_msg("%s: file is the archive; skipping", fileName);
470 if (exclude_file(tbInfo->excludeList, header_name))
473 #if !ENABLE_FEATURE_TAR_GNU_EXTENSIONS
474 if (strlen(header_name) >= NAME_SIZE) {
475 bb_error_msg("names longer than "NAME_SIZE_STR" chars not supported");
480 /* Is this a regular file? */
481 if (tbInfo->hlInfo == NULL && S_ISREG(statbuf->st_mode)) {
482 /* open the file we want to archive, and make sure all is well */
483 inputFileFd = open_or_warn(fileName, O_RDONLY);
484 if (inputFileFd < 0) {
489 /* Add an entry to the tarball */
490 if (writeTarHeader(tbInfo, header_name, fileName, statbuf) == FALSE) {
494 /* If it was a regular file, write out the body */
495 if (inputFileFd >= 0) {
497 /* Write the file to the archive. */
498 /* We record size into header first, */
499 /* and then write out file. If file shrinks in between, */
500 /* tar will be corrupted. So we don't allow for that. */
501 /* NB: GNU tar 1.16 warns and pads with zeroes */
502 /* or even seeks back and updates header */
503 bb_copyfd_exact_size(inputFileFd, tbInfo->tarFd, statbuf->st_size);
505 ////readSize = bb_copyfd_size(inputFileFd, tbInfo->tarFd, statbuf->st_size);
506 ////if (readSize != statbuf->st_size && readSize >= 0) {
507 //// bb_error_msg_and_die("short read from %s, aborting", fileName);
510 /* Check that file did not grow in between? */
511 /* if (safe_read(inputFileFd, 1) == 1) warn but continue? */
515 /* Pad the file up to the tar block size */
516 /* (a few tricks here in the name of code size) */
517 readSize = (-(int)statbuf->st_size) & (TAR_BLOCK_SIZE-1);
518 memset(block_buf, 0, readSize);
519 xwrite(tbInfo->tarFd, block_buf, readSize);
525 #if ENABLE_FEATURE_SEAMLESS_GZ || ENABLE_FEATURE_SEAMLESS_BZ2
526 # if !(ENABLE_FEATURE_SEAMLESS_GZ && ENABLE_FEATURE_SEAMLESS_BZ2)
527 # define vfork_compressor(tar_fd, gzip) vfork_compressor(tar_fd)
529 /* Don't inline: vfork scares gcc and pessimizes code */
530 static void NOINLINE vfork_compressor(int tar_fd, int gzip)
533 # if ENABLE_FEATURE_SEAMLESS_GZ && ENABLE_FEATURE_SEAMLESS_BZ2
534 const char *zip_exec = (gzip == 1) ? "gzip" : "bzip2";
535 # elif ENABLE_FEATURE_SEAMLESS_GZ
536 const char *zip_exec = "gzip";
537 # else /* only ENABLE_FEATURE_SEAMLESS_BZ2 */
538 const char *zip_exec = "bzip2";
540 // On Linux, vfork never unpauses parent early, although standard
541 // allows for that. Do we want to waste bytes checking for it?
542 # define WAIT_FOR_CHILD 0
543 volatile int vfork_exec_errno = 0;
544 struct fd_pair gzipDataPipe;
546 struct fd_pair gzipStatusPipe;
547 xpiped_pair(gzipStatusPipe);
549 xpiped_pair(gzipDataPipe);
551 signal(SIGPIPE, SIG_IGN); /* we only want EPIPE on errors */
553 # if defined(__GNUC__) && __GNUC__
554 /* Avoid vfork clobbering */
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", (char *)0);
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 recurseFlags, 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 xfstat(tbInfo.tarFd, &tbInfo.tarFileStatBuf, "can't stat tar file");
618 #if ENABLE_FEATURE_SEAMLESS_GZ || ENABLE_FEATURE_SEAMLESS_BZ2
620 vfork_compressor(tbInfo.tarFd, gzip);
623 tbInfo.excludeList = exclude;
625 /* Read the directory/files and iterate over them one at a time */
627 if (!recursive_action(include->data, recurseFlags,
628 writeFileToTarball, writeFileToTarball, &tbInfo, 0)
632 include = include->link;
634 /* Write two empty blocks to the end of the archive */
635 memset(block_buf, 0, 2*TAR_BLOCK_SIZE);
636 xwrite(tbInfo.tarFd, block_buf, 2*TAR_BLOCK_SIZE);
638 /* To be pedantically correct, we would check if the tarball
639 * is smaller than 20 tar blocks, and pad it if it was smaller,
640 * but that isn't necessary for GNU tar interoperability, and
641 * so is considered a waste of space */
643 /* Close so the child process (if any) will exit */
646 /* Hang up the tools, close up shop, head home */
647 if (ENABLE_FEATURE_CLEAN_UP)
648 freeHardLinkInfo(&tbInfo.hlInfoHead);
651 bb_error_msg("error exit delayed from previous errors");
653 #if ENABLE_FEATURE_SEAMLESS_GZ || ENABLE_FEATURE_SEAMLESS_BZ2
656 if (safe_waitpid(-1, &status, 0) == -1)
657 bb_perror_msg("waitpid");
658 else if (!WIFEXITED(status) || WEXITSTATUS(status))
659 /* gzip was killed or has exited with nonzero! */
666 int writeTarFile(int tar_fd, int verboseFlag,
667 int recurseFlags, const llist_t *include,
668 const llist_t *exclude, int gzip);
669 #endif /* FEATURE_TAR_CREATE */
671 #if ENABLE_FEATURE_TAR_FROM
672 static llist_t *append_file_list_to_list(llist_t *list)
676 llist_t *newlist = NULL;
679 src_stream = xfopen_stdin(llist_pop(&list));
680 while ((line = xmalloc_fgetline(src_stream)) != NULL) {
681 /* kill trailing '/' unless the string is just "/" */
682 char *cp = last_char_is(line, '/');
685 llist_add_to_end(&newlist, line);
693 //usage:#define tar_trivial_usage
694 //usage: "-[" IF_FEATURE_TAR_CREATE("c") "xt"
695 //usage: IF_FEATURE_SEAMLESS_Z("Z")
696 //usage: IF_FEATURE_SEAMLESS_GZ("z")
697 //usage: IF_FEATURE_SEAMLESS_XZ("J")
698 //usage: IF_FEATURE_SEAMLESS_BZ2("j")
699 //usage: IF_FEATURE_SEAMLESS_LZMA("a")
700 //usage: IF_FEATURE_TAR_CREATE("h")
701 //usage: IF_FEATURE_TAR_NOPRESERVE_TIME("m")
703 //usage: IF_FEATURE_TAR_FROM("[-X FILE] [-T FILE] ")
704 //usage: "[-f TARFILE] [-C DIR] [FILE]..."
705 //usage:#define tar_full_usage "\n\n"
706 //usage: IF_FEATURE_TAR_CREATE("Create, extract, ")
707 //usage: IF_NOT_FEATURE_TAR_CREATE("Extract ")
708 //usage: "or list files from a tar file\n"
709 //usage: "\nOperation:"
710 //usage: IF_FEATURE_TAR_CREATE(
711 //usage: "\n c Create"
713 //usage: "\n x Extract"
715 //usage: "\n f Name of TARFILE ('-' for stdin/out)"
716 //usage: "\n C Change to DIR before operation"
717 //usage: "\n v Verbose"
718 //usage: IF_FEATURE_SEAMLESS_Z(
719 //usage: "\n Z (De)compress using compress"
721 //usage: IF_FEATURE_SEAMLESS_GZ(
722 //usage: "\n z (De)compress using gzip"
724 //usage: IF_FEATURE_SEAMLESS_XZ(
725 //usage: "\n J (De)compress using xz"
727 //usage: IF_FEATURE_SEAMLESS_BZ2(
728 //usage: "\n j (De)compress using bzip2"
730 //usage: IF_FEATURE_SEAMLESS_LZMA(
731 //usage: "\n a (De)compress using lzma"
733 //usage: "\n O Extract to stdout"
734 //usage: IF_FEATURE_TAR_CREATE(
735 //usage: "\n h Follow symlinks"
737 //usage: IF_FEATURE_TAR_NOPRESERVE_TIME(
738 //usage: "\n m Don't restore mtime"
740 //usage: IF_FEATURE_TAR_FROM(
741 //usage: IF_FEATURE_TAR_LONG_OPTIONS(
742 //usage: "\n exclude File to exclude"
744 //usage: "\n X File with names to exclude"
745 //usage: "\n T File with names to include"
748 //usage:#define tar_example_usage
749 //usage: "$ zcat /tmp/tarball.tar.gz | tar -xf -\n"
750 //usage: "$ tar -cf /tmp/tarball.tar /usr/local\n"
752 // Supported but aren't in --help:
754 // p same-permissions
758 // no-same-permissions
760 //IF_FEATURE_TAR_TO_COMMAND(
766 IF_FEATURE_TAR_CREATE( OPTBIT_CREATE ,)
767 IF_FEATURE_TAR_CREATE( OPTBIT_DEREFERENCE ,)
768 IF_FEATURE_SEAMLESS_BZ2( OPTBIT_BZIP2 ,)
769 IF_FEATURE_SEAMLESS_LZMA(OPTBIT_LZMA ,)
770 IF_FEATURE_TAR_FROM( OPTBIT_INCLUDE_FROM,)
771 IF_FEATURE_TAR_FROM( OPTBIT_EXCLUDE_FROM,)
772 IF_FEATURE_SEAMLESS_GZ( OPTBIT_GZIP ,)
773 IF_FEATURE_SEAMLESS_XZ( OPTBIT_XZ ,) // 16th bit
774 IF_FEATURE_SEAMLESS_Z( OPTBIT_COMPRESS ,)
775 IF_FEATURE_TAR_NOPRESERVE_TIME(OPTBIT_NOPRESERVE_TIME,)
776 #if ENABLE_FEATURE_TAR_LONG_OPTIONS
778 IF_FEATURE_TAR_TO_COMMAND(OPTBIT_2COMMAND ,)
779 OPTBIT_NUMERIC_OWNER,
780 OPTBIT_NOPRESERVE_PERM,
783 OPT_TEST = 1 << 0, // t
784 OPT_EXTRACT = 1 << 1, // x
785 OPT_BASEDIR = 1 << 2, // C
786 OPT_TARNAME = 1 << 3, // f
787 OPT_2STDOUT = 1 << 4, // O
788 OPT_NOPRESERVE_OWNER = 1 << 5, // o == no-same-owner
790 OPT_VERBOSE = 1 << 7, // v
791 OPT_KEEP_OLD = 1 << 8, // k
792 OPT_CREATE = IF_FEATURE_TAR_CREATE( (1 << OPTBIT_CREATE )) + 0, // c
793 OPT_DEREFERENCE = IF_FEATURE_TAR_CREATE( (1 << OPTBIT_DEREFERENCE )) + 0, // h
794 OPT_BZIP2 = IF_FEATURE_SEAMLESS_BZ2( (1 << OPTBIT_BZIP2 )) + 0, // j
795 OPT_LZMA = IF_FEATURE_SEAMLESS_LZMA((1 << OPTBIT_LZMA )) + 0, // a
796 OPT_INCLUDE_FROM = IF_FEATURE_TAR_FROM( (1 << OPTBIT_INCLUDE_FROM)) + 0, // T
797 OPT_EXCLUDE_FROM = IF_FEATURE_TAR_FROM( (1 << OPTBIT_EXCLUDE_FROM)) + 0, // X
798 OPT_GZIP = IF_FEATURE_SEAMLESS_GZ( (1 << OPTBIT_GZIP )) + 0, // z
799 OPT_XZ = IF_FEATURE_SEAMLESS_XZ( (1 << OPTBIT_XZ )) + 0, // J
800 OPT_COMPRESS = IF_FEATURE_SEAMLESS_Z( (1 << OPTBIT_COMPRESS )) + 0, // Z
801 OPT_NOPRESERVE_TIME = IF_FEATURE_TAR_NOPRESERVE_TIME((1 << OPTBIT_NOPRESERVE_TIME)) + 0, // m
802 OPT_NORECURSION = IF_FEATURE_TAR_LONG_OPTIONS((1 << OPTBIT_NORECURSION )) + 0, // no-recursion
803 OPT_2COMMAND = IF_FEATURE_TAR_TO_COMMAND( (1 << OPTBIT_2COMMAND )) + 0, // to-command
804 OPT_NUMERIC_OWNER = IF_FEATURE_TAR_LONG_OPTIONS((1 << OPTBIT_NUMERIC_OWNER )) + 0, // numeric-owner
805 OPT_NOPRESERVE_PERM = IF_FEATURE_TAR_LONG_OPTIONS((1 << OPTBIT_NOPRESERVE_PERM)) + 0, // no-same-permissions
806 OPT_OVERWRITE = IF_FEATURE_TAR_LONG_OPTIONS((1 << OPTBIT_OVERWRITE )) + 0, // overwrite
808 OPT_ANY_COMPRESS = (OPT_BZIP2 | OPT_LZMA | OPT_GZIP | OPT_XZ | OPT_COMPRESS),
810 #if ENABLE_FEATURE_TAR_LONG_OPTIONS
811 static const char tar_longopts[] ALIGN1 =
812 "list\0" No_argument "t"
813 "extract\0" No_argument "x"
814 "directory\0" Required_argument "C"
815 "file\0" Required_argument "f"
816 "to-stdout\0" No_argument "O"
817 /* do not restore owner */
818 /* Note: GNU tar handles 'o' as no-same-owner only on extract,
819 * on create, 'o' is --old-archive. We do not support --old-archive. */
820 "no-same-owner\0" No_argument "o"
821 "same-permissions\0" No_argument "p"
822 "verbose\0" No_argument "v"
823 "keep-old\0" No_argument "k"
824 # if ENABLE_FEATURE_TAR_CREATE
825 "create\0" No_argument "c"
826 "dereference\0" No_argument "h"
828 # if ENABLE_FEATURE_SEAMLESS_BZ2
829 "bzip2\0" No_argument "j"
831 # if ENABLE_FEATURE_SEAMLESS_LZMA
832 "lzma\0" No_argument "a"
834 # if ENABLE_FEATURE_TAR_FROM
835 "files-from\0" Required_argument "T"
836 "exclude-from\0" Required_argument "X"
838 # if ENABLE_FEATURE_SEAMLESS_GZ
839 "gzip\0" No_argument "z"
841 # if ENABLE_FEATURE_SEAMLESS_XZ
842 "xz\0" No_argument "J"
844 # if ENABLE_FEATURE_SEAMLESS_Z
845 "compress\0" No_argument "Z"
847 # if ENABLE_FEATURE_TAR_NOPRESERVE_TIME
848 "touch\0" No_argument "m"
850 "no-recursion\0" No_argument "\xfa"
851 # if ENABLE_FEATURE_TAR_TO_COMMAND
852 "to-command\0" Required_argument "\xfb"
854 /* use numeric uid/gid from tar header, not textual */
855 "numeric-owner\0" No_argument "\xfc"
856 /* do not restore mode */
857 "no-same-permissions\0" No_argument "\xfd"
858 /* on unpack, open with O_TRUNC and !O_EXCL */
859 "overwrite\0" No_argument "\xfe"
860 /* --exclude takes next bit position in option mask, */
861 /* therefore we have to put it _after_ --no-same-permissions */
862 # if ENABLE_FEATURE_TAR_FROM
863 "exclude\0" Required_argument "\xff"
868 int tar_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
869 int tar_main(int argc UNUSED_PARAM, char **argv)
871 archive_handle_t *tar_handle;
872 char *base_dir = NULL;
873 const char *tar_filename = "-";
876 #if ENABLE_FEATURE_TAR_LONG_OPTIONS && ENABLE_FEATURE_TAR_FROM
877 llist_t *excludes = NULL;
880 /* Initialise default values */
881 tar_handle = init_handle();
882 tar_handle->ah_flags = ARCHIVE_CREATE_LEADING_DIRS
883 | ARCHIVE_RESTORE_DATE
884 | ARCHIVE_UNLINK_OLD;
886 /* Apparently only root's tar preserves perms (see bug 3844) */
888 tar_handle->ah_flags |= ARCHIVE_DONT_RESTORE_PERM;
890 /* Prepend '-' to the first argument if required */
891 opt_complementary = "--:" // first arg is options
892 "tt:vv:" // count -t,-v
893 IF_FEATURE_TAR_FROM("X::T::") // cumulative lists
894 #if ENABLE_FEATURE_TAR_LONG_OPTIONS && ENABLE_FEATURE_TAR_FROM
895 "\xff::" // cumulative lists for --exclude
897 IF_FEATURE_TAR_CREATE("c:") "t:x:" // at least one of these is reqd
898 IF_FEATURE_TAR_CREATE("c--tx:t--cx:x--ct") // mutually exclusive
899 IF_NOT_FEATURE_TAR_CREATE("t--x:x--t"); // mutually exclusive
900 #if ENABLE_FEATURE_TAR_LONG_OPTIONS
901 applet_long_options = tar_longopts;
904 if (argv[1] && argv[1][0] != '-') {
906 * 1st argument without dash handles options with parameters
907 * differently from dashed one: it takes *next argv[i]*
908 * as paramenter even if there are more chars in 1st argument:
909 * "tar fx TARFILE" - "x" is not taken as f's param
910 * but is interpreted as -x option
911 * "tar -xf TARFILE" - dashed equivalent of the above
912 * "tar -fx ..." - "x" is taken as f's param
913 * getopt32 wouldn't handle 1st command correctly.
914 * Unfortunately, people do use such commands.
915 * We massage argv[1] to work around it by moving 'f'
916 * to the end of the string.
917 * More contrived "tar fCx TARFILE DIR" still fails,
918 * but such commands are much less likely to be used.
920 char *f = strchr(argv[1], 'f');
922 while (f[1] != '\0') {
932 IF_FEATURE_TAR_CREATE( "ch" )
933 IF_FEATURE_SEAMLESS_BZ2( "j" )
934 IF_FEATURE_SEAMLESS_LZMA("a" )
935 IF_FEATURE_TAR_FROM( "T:X:")
936 IF_FEATURE_SEAMLESS_GZ( "z" )
937 IF_FEATURE_SEAMLESS_XZ( "J" )
938 IF_FEATURE_SEAMLESS_Z( "Z" )
939 IF_FEATURE_TAR_NOPRESERVE_TIME("m")
940 , &base_dir // -C dir
941 , &tar_filename // -f filename
942 IF_FEATURE_TAR_FROM(, &(tar_handle->accept)) // T
943 IF_FEATURE_TAR_FROM(, &(tar_handle->reject)) // X
944 IF_FEATURE_TAR_TO_COMMAND(, &(tar_handle->tar__to_command)) // --to-command
945 #if ENABLE_FEATURE_TAR_LONG_OPTIONS && ENABLE_FEATURE_TAR_FROM
946 , &excludes // --exclude
948 , &verboseFlag // combined count for -t and -v
949 , &verboseFlag // combined count for -t and -v
951 //bb_error_msg("opt:%08x", opt);
954 if (verboseFlag) tar_handle->action_header = header_verbose_list;
955 if (verboseFlag == 1) tar_handle->action_header = header_list;
957 if (opt & OPT_EXTRACT)
958 tar_handle->action_data = data_extract_all;
960 if (opt & OPT_2STDOUT)
961 tar_handle->action_data = data_extract_to_stdout;
963 if (opt & OPT_2COMMAND) {
964 putenv((char*)"TAR_FILETYPE=f");
965 signal(SIGPIPE, SIG_IGN);
966 tar_handle->action_data = data_extract_to_command;
967 IF_FEATURE_TAR_TO_COMMAND(tar_handle->tar__to_command_shell = xstrdup(get_shell_name());)
970 if (opt & OPT_KEEP_OLD)
971 tar_handle->ah_flags &= ~ARCHIVE_UNLINK_OLD;
973 if (opt & OPT_NUMERIC_OWNER)
974 tar_handle->ah_flags |= ARCHIVE_NUMERIC_OWNER;
976 if (opt & OPT_NOPRESERVE_OWNER)
977 tar_handle->ah_flags |= ARCHIVE_DONT_RESTORE_OWNER;
979 if (opt & OPT_NOPRESERVE_PERM)
980 tar_handle->ah_flags |= ARCHIVE_DONT_RESTORE_PERM;
982 if (opt & OPT_OVERWRITE) {
983 tar_handle->ah_flags &= ~ARCHIVE_UNLINK_OLD;
984 tar_handle->ah_flags |= ARCHIVE_O_TRUNC;
987 if (opt & OPT_NOPRESERVE_TIME)
988 tar_handle->ah_flags &= ~ARCHIVE_RESTORE_DATE;
990 #if ENABLE_FEATURE_TAR_FROM
991 tar_handle->reject = append_file_list_to_list(tar_handle->reject);
992 # if ENABLE_FEATURE_TAR_LONG_OPTIONS
993 /* Append excludes to reject */
995 llist_t *next = excludes->link;
996 excludes->link = tar_handle->reject;
997 tar_handle->reject = excludes;
1001 tar_handle->accept = append_file_list_to_list(tar_handle->accept);
1004 /* Setup an array of filenames to work with */
1005 /* TODO: This is the same as in ar, make a separate function? */
1007 /* kill trailing '/' unless the string is just "/" */
1008 char *cp = last_char_is(*argv, '/');
1011 llist_add_to_end(&tar_handle->accept, *argv);
1015 if (tar_handle->accept || tar_handle->reject)
1016 tar_handle->filter = filter_accept_reject_list;
1018 /* Open the tar file */
1020 int tar_fd = STDIN_FILENO;
1021 int flags = O_RDONLY;
1023 if (opt & OPT_CREATE) {
1024 /* Make sure there is at least one file to tar up */
1025 if (tar_handle->accept == NULL)
1026 bb_error_msg_and_die("empty archive");
1028 tar_fd = STDOUT_FILENO;
1029 /* Mimicking GNU tar 1.15.1: */
1030 flags = O_WRONLY | O_CREAT | O_TRUNC;
1033 if (LONE_DASH(tar_filename)) {
1034 tar_handle->src_fd = tar_fd;
1035 tar_handle->seek = seek_by_read;
1037 if (ENABLE_FEATURE_TAR_AUTODETECT
1038 && flags == O_RDONLY
1039 && !(opt & OPT_ANY_COMPRESS)
1041 tar_handle->src_fd = open_zipped(tar_filename);
1042 if (tar_handle->src_fd < 0)
1043 bb_perror_msg_and_die("can't open '%s'", tar_filename);
1045 tar_handle->src_fd = xopen(tar_filename, flags);
1053 //if (SEAMLESS_COMPRESSION || OPT_COMPRESS)
1054 // /* We need to know whether child (gzip/bzip/etc) exits abnormally */
1055 // signal(SIGCHLD, check_errors_in_children);
1057 /* Create an archive */
1058 if (opt & OPT_CREATE) {
1059 #if ENABLE_FEATURE_SEAMLESS_GZ || ENABLE_FEATURE_SEAMLESS_BZ2
1061 if (ENABLE_FEATURE_SEAMLESS_GZ && (opt & OPT_GZIP))
1063 if (ENABLE_FEATURE_SEAMLESS_BZ2 && (opt & OPT_BZIP2))
1066 /* NB: writeTarFile() closes tar_handle->src_fd */
1067 return writeTarFile(tar_handle->src_fd, verboseFlag,
1068 (opt & OPT_DEREFERENCE ? ACTION_FOLLOWLINKS : 0)
1069 | (opt & OPT_NORECURSION ? 0 : ACTION_RECURSE),
1071 tar_handle->reject, zipMode);
1074 if (opt & OPT_ANY_COMPRESS) {
1075 USE_FOR_MMU(IF_DESKTOP(long long) int FAST_FUNC (*xformer)(transformer_aux_data_t *aux, int src_fd, int dst_fd);)
1076 USE_FOR_NOMMU(const char *xformer_prog;)
1078 if (opt & OPT_COMPRESS)
1079 USE_FOR_MMU(xformer = unpack_Z_stream;)
1080 USE_FOR_NOMMU(xformer_prog = "uncompress";)
1082 USE_FOR_MMU(xformer = unpack_gz_stream;)
1083 USE_FOR_NOMMU(xformer_prog = "gunzip";)
1084 if (opt & OPT_BZIP2)
1085 USE_FOR_MMU(xformer = unpack_bz2_stream;)
1086 USE_FOR_NOMMU(xformer_prog = "bunzip2";)
1088 USE_FOR_MMU(xformer = unpack_lzma_stream;)
1089 USE_FOR_NOMMU(xformer_prog = "unlzma";)
1091 USE_FOR_MMU(xformer = unpack_xz_stream;)
1092 USE_FOR_NOMMU(xformer_prog = "unxz";)
1094 open_transformer_with_sig(tar_handle->src_fd, xformer, xformer_prog);
1095 /* Can't lseek over pipes */
1096 tar_handle->seek = seek_by_read;
1097 /*tar_handle->offset = 0; - already is */
1100 while (get_header_tar(tar_handle) == EXIT_SUCCESS)
1103 /* Check that every file that should have been extracted was */
1104 while (tar_handle->accept) {
1105 if (!find_list_entry(tar_handle->reject, tar_handle->accept->data)
1106 && !find_list_entry(tar_handle->passed, tar_handle->accept->data)
1108 bb_error_msg_and_die("%s: not found in archive",
1109 tar_handle->accept->data);
1111 tar_handle->accept = tar_handle->accept->link;
1113 if (ENABLE_FEATURE_CLEAN_UP /* && tar_handle->src_fd != STDIN_FILENO */)
1114 close(tar_handle->src_fd);
1116 if (SEAMLESS_COMPRESSION || OPT_COMPRESS) {
1117 check_errors_in_children(0);
1118 return bb_got_signal;
1120 return EXIT_SUCCESS;