1 /* vi: set sw=4 ts=4: */
2 /*
3  * Mini tar implementation for busybox
4  *
5  * Modified to use common extraction code used by ar, cpio, dpkg-deb, dpkg
6  *  by Glenn McGrath
7  *
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.)
11  *
12  * Copyright (C) 1999-2004 by Erik Andersen <andersen@codepoet.org>
13  *
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.
19  *
20  * Based in part on the tar implementation from busybox-0.28
21  *  Copyright (C) 1995 Bruce Perens
22  *
23  * Licensed under GPLv2 or later, see file LICENSE in this source tree.
24  */
25 //config:config TAR
26 //config:	bool "tar (39 kb)"
27 //config:	default y
28 //config:	help
29 //config:	tar is an archiving program. It's commonly used with gzip to
30 //config:	create compressed archives. It's probably the most widely used
31 //config:	UNIX archive program.
32 //config:
33 //config:config FEATURE_TAR_LONG_OPTIONS
34 //config:	bool "Enable long options"
35 //config:	default y
36 //config:	depends on TAR && LONG_OPTS
37 //config:
38 //config:config FEATURE_TAR_CREATE
39 //config:	bool "Enable -c (archive creation)"
40 //config:	default y
41 //config:	depends on TAR
42 //config:
43 //config:config FEATURE_TAR_AUTODETECT
44 //config:	bool "Autodetect compressed tarballs"
45 //config:	default y
46 //config:	depends on TAR && (FEATURE_SEAMLESS_Z || FEATURE_SEAMLESS_GZ || FEATURE_SEAMLESS_BZ2 || FEATURE_SEAMLESS_LZMA || FEATURE_SEAMLESS_XZ)
47 //config:	help
48 //config:	With this option tar can automatically detect compressed
49 //config:	tarballs. Currently it works only on files (not pipes etc).
50 //config:
51 //config:config FEATURE_TAR_FROM
52 //config:	bool "Enable -X (exclude from) and -T (include from) options"
53 //config:	default y
54 //config:	depends on TAR
55 //config:	help
56 //config:	If you enable this option you'll be able to specify
57 //config:	a list of files to include or exclude from an archive.
58 //config:
59 //config:config FEATURE_TAR_OLDGNU_COMPATIBILITY
60 //config:	bool "Support old tar header format"
61 //config:	default y
62 //config:	depends on TAR || DPKG
63 //config:	help
64 //config:	This option is required to unpack archives created in
65 //config:	the old GNU format; help to kill this old format by
66 //config:	repacking your ancient archives with the new format.
67 //config:
68 //config:config FEATURE_TAR_OLDSUN_COMPATIBILITY
69 //config:	bool "Enable untarring of tarballs with checksums produced by buggy Sun tar"
70 //config:	default y
71 //config:	depends on TAR || DPKG
72 //config:	help
73 //config:	This option is required to unpack archives created by some old
74 //config:	version of Sun's tar (it was calculating checksum using signed
75 //config:	arithmetic). It is said to be fixed in newer Sun tar, but "old"
76 //config:	tarballs still exist.
77 //config:
78 //config:config FEATURE_TAR_GNU_EXTENSIONS
79 //config:	bool "Support GNU tar extensions (long filenames)"
80 //config:	default y
81 //config:	depends on TAR || DPKG
82 //config:
83 //config:config FEATURE_TAR_TO_COMMAND
84 //config:	bool "Support writing to an external program (--to-command)"
85 //config:	default y
86 //config:	depends on TAR && FEATURE_TAR_LONG_OPTIONS
87 //config:	help
88 //config:	If you enable this option you'll be able to instruct tar to send
89 //config:	the contents of each extracted file to the standard input of an
90 //config:	external program.
91 //config:
92 //config:config FEATURE_TAR_UNAME_GNAME
93 //config:	bool "Enable use of user and group names"
94 //config:	default y
95 //config:	depends on TAR
96 //config:	help
97 //config:	Enable use of user and group names in tar. This affects contents
98 //config:	listings (-t) and preserving permissions when unpacking (-p).
99 //config:	+200 bytes.
100 //config:
101 //config:config FEATURE_TAR_NOPRESERVE_TIME
102 //config:	bool "Enable -m (do not preserve time) GNU option"
103 //config:	default y
104 //config:	depends on TAR
105 //config:
106 //config:config FEATURE_TAR_SELINUX
107 //config:	bool "Support extracting SELinux labels"
108 //config:	default n
109 //config:	depends on TAR && SELINUX
110 //config:	help
111 //config:	With this option busybox supports restoring SELinux labels
112 //config:	when extracting files from tar archives.
113 
114 //applet:IF_TAR(APPLET(tar, BB_DIR_BIN, BB_SUID_DROP))
115 
116 //kbuild:lib-$(CONFIG_TAR) += tar.o
117 
118 #include <fnmatch.h>
119 #include "libbb.h"
120 #include "common_bufsiz.h"
121 #include "bb_archive.h"
122 /* FIXME: Stop using this non-standard feature */
123 #ifndef FNM_LEADING_DIR
124 # define FNM_LEADING_DIR 0
125 #endif
126 
127 #if 0
128 # define DBG(fmt, ...) bb_error_msg("%s: " fmt, __func__, ## __VA_ARGS__)
129 #else
130 # define DBG(...) ((void)0)
131 #endif
132 #define DBG_OPTION_PARSING 0
133 
134 
135 #define block_buf bb_common_bufsiz1
136 #define INIT_G() do { setup_common_bufsiz(); } while (0)
137 
138 
139 #if ENABLE_FEATURE_TAR_CREATE
140 
141 /*
142 ** writeTarFile(), writeFileToTarball(), and writeTarHeader() are
143 ** the only functions that deal with the HardLinkInfo structure.
144 ** Even these functions use the xxxHardLinkInfo() functions.
145 */
146 typedef struct HardLinkInfo {
147 	struct HardLinkInfo *next; /* Next entry in list */
148 	dev_t dev;                 /* Device number */
149 	ino_t ino;                 /* Inode number */
150 //	short linkCount;           /* (Hard) Link Count */
151 	char name[1];              /* Start of filename (must be last) */
152 } HardLinkInfo;
153 
154 /* Some info to be carried along when creating a new tarball */
155 typedef struct TarBallInfo {
156 	int tarFd;                      /* Open-for-write file descriptor
157 	                                 * for the tarball */
158 	int verboseFlag;                /* Whether to print extra stuff or not */
159 # if ENABLE_FEATURE_TAR_FROM
160 	const llist_t *excludeList;     /* List of files to not include */
161 # endif
162 	HardLinkInfo *hlInfoHead;       /* Hard Link Tracking Information */
163 	HardLinkInfo *hlInfo;           /* Hard Link Info for the current file */
164 //TODO: save only st_dev + st_ino
165 	struct stat tarFileStatBuf;     /* Stat info for the tarball, letting
166 	                                 * us know the inode and device that the
167 	                                 * tarball lives, so we can avoid trying
168 	                                 * to include the tarball into itself */
169 } TarBallInfo;
170 
171 /* A nice enum with all the possible tar file content types */
172 enum {
173 	REGTYPE = '0',		/* regular file */
174 	REGTYPE0 = '\0',	/* regular file (ancient bug compat) */
175 	LNKTYPE = '1',		/* hard link */
176 	SYMTYPE = '2',		/* symbolic link */
177 	CHRTYPE = '3',		/* character special */
178 	BLKTYPE = '4',		/* block special */
179 	DIRTYPE = '5',		/* directory */
180 	FIFOTYPE = '6',		/* FIFO special */
181 	CONTTYPE = '7',		/* reserved */
182 	GNULONGLINK = 'K',	/* GNU long (>100 chars) link name */
183 	GNULONGNAME = 'L',	/* GNU long (>100 chars) file name */
184 };
185 
186 /* Might be faster (and bigger) if the dev/ino were stored in numeric order;) */
addHardLinkInfo(HardLinkInfo ** hlInfoHeadPtr,struct stat * statbuf,const char * fileName)187 static void addHardLinkInfo(HardLinkInfo **hlInfoHeadPtr,
188 					struct stat *statbuf,
189 					const char *fileName)
190 {
191 	/* Note: hlInfoHeadPtr can never be NULL! */
192 	HardLinkInfo *hlInfo;
193 
194 	hlInfo = xmalloc(sizeof(HardLinkInfo) + strlen(fileName));
195 	hlInfo->next = *hlInfoHeadPtr;
196 	*hlInfoHeadPtr = hlInfo;
197 	hlInfo->dev = statbuf->st_dev;
198 	hlInfo->ino = statbuf->st_ino;
199 //	hlInfo->linkCount = statbuf->st_nlink;
200 	strcpy(hlInfo->name, fileName);
201 }
202 
freeHardLinkInfo(HardLinkInfo ** hlInfoHeadPtr)203 static void freeHardLinkInfo(HardLinkInfo **hlInfoHeadPtr)
204 {
205 	HardLinkInfo *hlInfo;
206 	HardLinkInfo *hlInfoNext;
207 
208 	if (hlInfoHeadPtr) {
209 		hlInfo = *hlInfoHeadPtr;
210 		while (hlInfo) {
211 			hlInfoNext = hlInfo->next;
212 			free(hlInfo);
213 			hlInfo = hlInfoNext;
214 		}
215 		*hlInfoHeadPtr = NULL;
216 	}
217 }
218 
219 /* Might be faster (and bigger) if the dev/ino were stored in numeric order ;) */
findHardLinkInfo(HardLinkInfo * hlInfo,struct stat * statbuf)220 static HardLinkInfo *findHardLinkInfo(HardLinkInfo *hlInfo, struct stat *statbuf)
221 {
222 	while (hlInfo) {
223 		if (statbuf->st_ino == hlInfo->ino
224 		 && statbuf->st_dev == hlInfo->dev
225 		) {
226 			DBG("found hardlink:'%s'", hlInfo->name);
227 			break;
228 		}
229 		hlInfo = hlInfo->next;
230 	}
231 	return hlInfo;
232 }
233 
234 /* Put an octal string into the specified buffer.
235  * The number is zero padded and possibly NUL terminated.
236  * Stores low-order bits only if whole value does not fit. */
putOctal(char * cp,int len,off_t value)237 static void putOctal(char *cp, int len, off_t value)
238 {
239 	char tempBuffer[sizeof(off_t)*3 + 1];
240 	char *tempString = tempBuffer;
241 	int width;
242 
243 	width = sprintf(tempBuffer, "%0*"OFF_FMT"o", len, value);
244 	tempString += (width - len);
245 
246 	/* If string has leading zeroes, we can drop one */
247 	/* and field will have trailing '\0' */
248 	/* (increases chances of compat with other tars) */
249 	if (tempString[0] == '0')
250 		tempString++;
251 
252 	/* Copy the string to the field */
253 	memcpy(cp, tempString, len);
254 }
255 #define PUT_OCTAL(a, b) putOctal((a), sizeof(a), (b))
256 
257 # if ENABLE_FEATURE_TAR_GNU_EXTENSIONS
writeLongname(int fd,int type,const char * name,int dir)258 static void writeLongname(int fd, int type, const char *name, int dir)
259 {
260 	struct prefilled {
261 		char mode[8];             /* 100-107 */
262 		char uid[8];              /* 108-115 */
263 		char gid[8];              /* 116-123 */
264 		char size[12];            /* 124-135 */
265 		char mtime[12];           /* 136-147 */
266 	};
267 	struct tar_header_t header;
268 	int size;
269 
270 	memset(&header, 0, sizeof(header));
271 	header.typeflag = type;
272 	strcpy(header.name, "././@LongLink");
273 	/* This sets mode/uid/gid/mtime to "00...00<NUL>" strings */
274 	memset((char*)&header + offsetof(struct tar_header_t, mode), /* make gcc-9.x happy */
275 			'0', sizeof(struct prefilled));
276 	header.mode [sizeof(header.mode ) - 1] = '\0';
277 	header.uid  [sizeof(header.uid  ) - 1] = '\0';
278 	header.gid  [sizeof(header.gid  ) - 1] = '\0';
279 	/* header.size is filled by '0' now, will be corrected below */
280 	header.mtime[sizeof(header.mtime) - 1] = '\0';
281 
282 	dir = !!dir; /* normalize: 0/1 */
283 	size = strlen(name) + 1 + dir; /* GNU tar uses strlen+1 */
284 	/* + dir: account for possible '/' */
285 
286 	PUT_OCTAL(header.size, size);
287 	chksum_and_xwrite_tar_header(fd, &header);
288 
289 	/* Write filename[/] and pad the block. */
290 	/* dir=0: writes 'name<NUL>', pads */
291 	/* dir=1: writes 'name', writes '/<NUL>', pads */
292 	dir *= 2;
293 	xwrite(fd, name, size - dir);
294 	xwrite(fd, "/", dir);
295 	size = (-size) & (TAR_BLOCK_SIZE-1);
296 	memset(&header, 0, size);
297 	xwrite(fd, &header, size);
298 }
299 # endif
300 
301 /* Write out a tar header for the specified file/directory/whatever */
writeTarHeader(struct TarBallInfo * tbInfo,const char * header_name,const char * fileName,struct stat * statbuf)302 static int writeTarHeader(struct TarBallInfo *tbInfo,
303 		const char *header_name, const char *fileName, struct stat *statbuf)
304 {
305 	struct tar_header_t header;
306 
307 	memset(&header, 0, sizeof(header));
308 
309 	strncpy(header.name, header_name, sizeof(header.name));
310 
311 	/* POSIX says to mask mode with 07777. */
312 	PUT_OCTAL(header.mode, statbuf->st_mode & 07777);
313 	PUT_OCTAL(header.uid, statbuf->st_uid);
314 	PUT_OCTAL(header.gid, statbuf->st_gid);
315 	memset(header.size, '0', sizeof(header.size)-1); /* Regular file size is handled later */
316 	/* users report that files with negative st_mtime cause trouble, so: */
317 	PUT_OCTAL(header.mtime, statbuf->st_mtime >= 0 ? statbuf->st_mtime : 0);
318 
319 	/* Enter the user and group names */
320 	safe_strncpy(header.uname, get_cached_username(statbuf->st_uid), sizeof(header.uname));
321 	safe_strncpy(header.gname, get_cached_groupname(statbuf->st_gid), sizeof(header.gname));
322 
323 	if (tbInfo->hlInfo) {
324 		/* This is a hard link */
325 		header.typeflag = LNKTYPE;
326 		strncpy(header.linkname, tbInfo->hlInfo->name,
327 				sizeof(header.linkname));
328 # if ENABLE_FEATURE_TAR_GNU_EXTENSIONS
329 		/* Write out long linkname if needed */
330 		if (header.linkname[sizeof(header.linkname)-1])
331 			writeLongname(tbInfo->tarFd, GNULONGLINK,
332 					tbInfo->hlInfo->name, 0);
333 # endif
334 	} else if (S_ISLNK(statbuf->st_mode)) {
335 		char *lpath = xmalloc_readlink_or_warn(fileName);
336 		if (!lpath)
337 			return FALSE;
338 		header.typeflag = SYMTYPE;
339 		strncpy(header.linkname, lpath, sizeof(header.linkname));
340 # if ENABLE_FEATURE_TAR_GNU_EXTENSIONS
341 		/* Write out long linkname if needed */
342 		if (header.linkname[sizeof(header.linkname)-1])
343 			writeLongname(tbInfo->tarFd, GNULONGLINK, lpath, 0);
344 # else
345 		/* If it is larger than 100 bytes, bail out */
346 		if (header.linkname[sizeof(header.linkname)-1]) {
347 			free(lpath);
348 			bb_simple_error_msg("names longer than "NAME_SIZE_STR" chars not supported");
349 			return FALSE;
350 		}
351 # endif
352 		free(lpath);
353 	} else if (S_ISDIR(statbuf->st_mode)) {
354 		header.typeflag = DIRTYPE;
355 		/* Append '/' only if there is a space for it */
356 		if (!header.name[sizeof(header.name)-1])
357 			header.name[strlen(header.name)] = '/';
358 	} else if (S_ISCHR(statbuf->st_mode)) {
359 		header.typeflag = CHRTYPE;
360 		PUT_OCTAL(header.devmajor, major(statbuf->st_rdev));
361 		PUT_OCTAL(header.devminor, minor(statbuf->st_rdev));
362 	} else if (S_ISBLK(statbuf->st_mode)) {
363 		header.typeflag = BLKTYPE;
364 		PUT_OCTAL(header.devmajor, major(statbuf->st_rdev));
365 		PUT_OCTAL(header.devminor, minor(statbuf->st_rdev));
366 	} else if (S_ISFIFO(statbuf->st_mode)) {
367 		header.typeflag = FIFOTYPE;
368 	} else if (S_ISREG(statbuf->st_mode)) {
369 		/* header.size field is 12 bytes long */
370 		/* Does octal-encoded size fit? */
371 		uoff_t filesize = statbuf->st_size;
372 		if (sizeof(filesize) <= 4
373 		 || filesize <= (uoff_t)0777777777777LL
374 		) {
375 			PUT_OCTAL(header.size, filesize);
376 		}
377 		/* Does base256-encoded size fit?
378 		 * It always does unless off_t is wider than 64 bits.
379 		 */
380 		else if (ENABLE_FEATURE_TAR_GNU_EXTENSIONS
381 # if ULLONG_MAX > 0xffffffffffffffffLL /* 2^64-1 */
382 		 && (filesize <= 0x3fffffffffffffffffffffffLL)
383 # endif
384 		) {
385 			/* GNU tar uses "base-256 encoding" for very large numbers.
386 			 * Encoding is binary, with highest bit always set as a marker
387 			 * and sign in next-highest bit:
388 			 * 80 00 .. 00 - zero
389 			 * bf ff .. ff - largest positive number
390 			 * ff ff .. ff - minus 1
391 			 * c0 00 .. 00 - smallest negative number
392 			 */
393 			char *p8 = header.size + sizeof(header.size);
394 			do {
395 				*--p8 = (uint8_t)filesize;
396 				filesize >>= 8;
397 			} while (p8 != header.size);
398 			*p8 |= 0x80;
399 		} else {
400 			bb_error_msg_and_die("can't store file '%s' "
401 				"of size %"OFF_FMT"u, aborting",
402 				fileName, statbuf->st_size);
403 		}
404 		header.typeflag = REGTYPE;
405 	} else {
406 		bb_error_msg("%s: unknown file type", fileName);
407 		return FALSE;
408 	}
409 
410 # if ENABLE_FEATURE_TAR_GNU_EXTENSIONS
411 	/* Write out long name if needed */
412 	/* (we, like GNU tar, output long linkname *before* long name) */
413 	if (header.name[sizeof(header.name)-1])
414 		writeLongname(tbInfo->tarFd, GNULONGNAME,
415 				header_name, S_ISDIR(statbuf->st_mode));
416 # endif
417 
418 	chksum_and_xwrite_tar_header(tbInfo->tarFd, &header);
419 
420 	/* Now do the verbose thing (or not) */
421 	if (tbInfo->verboseFlag) {
422 		FILE *vbFd = stdout;
423 
424 		/* If archive goes to stdout, verbose goes to stderr */
425 		if (tbInfo->tarFd == STDOUT_FILENO)
426 			vbFd = stderr;
427 		/* GNU "tar cvvf" prints "extended" listing a-la "ls -l" */
428 		/* We don't have such excesses here: for us "v" == "vv" */
429 		/* '/' is probably a GNUism */
430 		fprintf(vbFd, "%s%s\n", header_name,
431 				S_ISDIR(statbuf->st_mode) ? "/" : "");
432 	}
433 
434 	return TRUE;
435 }
436 
437 # if ENABLE_FEATURE_TAR_FROM
exclude_file(const llist_t * excluded_files,const char * file)438 static int exclude_file(const llist_t *excluded_files, const char *file)
439 {
440 	while (excluded_files) {
441 		if (excluded_files->data[0] == '/') {
442 			if (fnmatch(excluded_files->data, file,
443 					FNM_PATHNAME | FNM_LEADING_DIR) == 0)
444 				return 1;
445 		} else {
446 			const char *p;
447 
448 			for (p = file; p[0] != '\0'; p++) {
449 				if ((p == file || p[-1] == '/')
450 				 && p[0] != '/'
451 				 && fnmatch(excluded_files->data, p,
452 						FNM_PATHNAME | FNM_LEADING_DIR) == 0
453 				) {
454 					return 1;
455 				}
456 			}
457 		}
458 		excluded_files = excluded_files->link;
459 	}
460 
461 	return 0;
462 }
463 # else
464 #  define exclude_file(excluded_files, file) 0
465 # endif
466 
writeFileToTarball(struct recursive_state * state,const char * fileName,struct stat * statbuf)467 static int FAST_FUNC writeFileToTarball(struct recursive_state *state,
468 		const char *fileName,
469 		struct stat *statbuf)
470 {
471 	struct TarBallInfo *tbInfo = (struct TarBallInfo *) state->userData;
472 	const char *header_name;
473 	int inputFileFd = -1;
474 
475 	DBG("writeFileToTarball('%s')", fileName);
476 
477 	/* Strip leading '/' and such (must be before memorizing hardlink's name) */
478 	header_name = strip_unsafe_prefix(fileName);
479 
480 	if (header_name[0] == '\0')
481 		return TRUE;
482 
483 	if (exclude_file(tbInfo->excludeList, header_name))
484 		return SKIP; /* "do not recurse on this directory", no error message printed */
485 
486 	/* It is against the rules to archive a socket */
487 	if (S_ISSOCK(statbuf->st_mode)) {
488 		bb_error_msg("%s: socket ignored", fileName);
489 		return TRUE;
490 	}
491 
492 	/*
493 	 * Check to see if we are dealing with a hard link.
494 	 * If so -
495 	 * Treat the first occurrence of a given dev/inode as a file while
496 	 * treating any additional occurrences as hard links.  This is done
497 	 * by adding the file information to the HardLinkInfo linked list.
498 	 */
499 	tbInfo->hlInfo = NULL;
500 	if (!S_ISDIR(statbuf->st_mode) && statbuf->st_nlink > 1) {
501 		DBG("'%s': st_nlink > 1", header_name);
502 		tbInfo->hlInfo = findHardLinkInfo(tbInfo->hlInfoHead, statbuf);
503 		if (tbInfo->hlInfo == NULL) {
504 			DBG("'%s': addHardLinkInfo", header_name);
505 			addHardLinkInfo(&tbInfo->hlInfoHead, statbuf, header_name);
506 		}
507 	}
508 
509 	/* It is a bad idea to store the archive we are in the process of creating,
510 	 * so check the device and inode to be sure that this particular file isn't
511 	 * the new tarball */
512 	if (tbInfo->tarFileStatBuf.st_dev == statbuf->st_dev
513 	 && tbInfo->tarFileStatBuf.st_ino == statbuf->st_ino
514 	) {
515 		bb_error_msg("%s: file is the archive; skipping", fileName);
516 		return TRUE;
517 	}
518 
519 # if !ENABLE_FEATURE_TAR_GNU_EXTENSIONS
520 	if (strlen(header_name) >= NAME_SIZE) {
521 		bb_simple_error_msg("names longer than "NAME_SIZE_STR" chars not supported");
522 		return TRUE;
523 	}
524 # endif
525 
526 	/* Is this a regular file? */
527 	if (tbInfo->hlInfo == NULL && S_ISREG(statbuf->st_mode)) {
528 		/* open the file we want to archive, and make sure all is well */
529 		inputFileFd = open_or_warn(fileName, O_RDONLY);
530 		if (inputFileFd < 0) {
531 			return FALSE; /* make recursive_action() return FALSE */
532 		}
533 	}
534 
535 	/* Add an entry to the tarball */
536 	if (writeTarHeader(tbInfo, header_name, fileName, statbuf) == FALSE) {
537 		return FALSE; /* make recursive_action() return FALSE */
538 	}
539 
540 	/* If it was a regular file, write out the body */
541 	if (inputFileFd >= 0) {
542 		size_t readSize;
543 		/* Write the file to the archive. */
544 		/* We record size into header first, */
545 		/* and then write out file. If file shrinks in between, */
546 		/* tar will be corrupted. So we don't allow for that. */
547 		/* NB: GNU tar 1.16 warns and pads with zeroes */
548 		/* or even seeks back and updates header */
549 		bb_copyfd_exact_size(inputFileFd, tbInfo->tarFd, statbuf->st_size);
550 		////off_t readSize;
551 		////readSize = bb_copyfd_size(inputFileFd, tbInfo->tarFd, statbuf->st_size);
552 		////if (readSize != statbuf->st_size && readSize >= 0) {
553 		////	bb_error_msg_and_die("short read from %s, aborting", fileName);
554 		////}
555 
556 		/* Check that file did not grow in between? */
557 		/* if (safe_read(inputFileFd, 1) == 1) warn but continue? */
558 
559 		close(inputFileFd);
560 
561 		/* Pad the file up to the tar block size */
562 		/* (a few tricks here in the name of code size) */
563 		readSize = (-(int)statbuf->st_size) & (TAR_BLOCK_SIZE-1);
564 		memset(block_buf, 0, readSize);
565 		xwrite(tbInfo->tarFd, block_buf, readSize);
566 	}
567 
568 	return TRUE;
569 }
570 
571 # if SEAMLESS_COMPRESSION
572 /* Don't inline: vfork scares gcc and pessimizes code */
vfork_compressor(int tar_fd,const char * gzip)573 static void NOINLINE vfork_compressor(int tar_fd, const char *gzip)
574 {
575 	// On Linux, vfork never unpauses parent early, although standard
576 	// allows for that. Do we want to waste bytes checking for it?
577 #  define WAIT_FOR_CHILD 0
578 	volatile int vfork_exec_errno = 0;
579 	struct fd_pair data;
580 #  if WAIT_FOR_CHILD
581 	struct fd_pair status;
582 	xpiped_pair(status);
583 #  endif
584 	xpiped_pair(data);
585 
586 	signal(SIGPIPE, SIG_IGN); /* we only want EPIPE on errors */
587 
588 	if (xvfork() == 0) {
589 		/* child */
590 		int tfd;
591 		/* NB: close _first_, then move fds! */
592 		close(data.wr);
593 #  if WAIT_FOR_CHILD
594 		close(status.rd);
595 		/* status.wr will close only on exec -
596 		 * parent waits for this close to happen */
597 		fcntl(status.wr, F_SETFD, FD_CLOEXEC);
598 #  endif
599 		/* copy it: parent's tar_fd variable must not change */
600 		tfd = tar_fd;
601 		if (tfd == 0) {
602 			/* Output tar fd may be zero.
603 			 * xmove_fd(data.rd, 0) would destroy it.
604 			 * Reproducer:
605 			 *  exec 0>&-
606 			 *  exec 1>&-
607 			 *  tar czf Z.tar.gz FILE
608 			 * Swapping move_fd's order wouldn't work:
609 			 * data.rd is 1 and _it_ would be destroyed.
610 			 */
611 			tfd = dup(tfd);
612 		}
613 		xmove_fd(data.rd, 0);
614 		xmove_fd(tfd, 1);
615 
616 		/* exec gzip/bzip2/... program */
617 		//BB_EXECLP(gzip, gzip, "-f", (char *)0); - WRONG for "xz",
618 		// if xz is an enabled applet, it'll be a version which
619 		// can only decompress. We do need to execute external
620 		// program, not applet.
621 		execlp(gzip, gzip, "-f", (char *)0);
622 
623 		vfork_exec_errno = errno;
624 		_exit(EXIT_FAILURE);
625 	}
626 
627 	/* parent */
628 	xmove_fd(data.wr, tar_fd);
629 	close(data.rd);
630 #  if WAIT_FOR_CHILD
631 	close(status.wr);
632 	while (1) {
633 		/* Wait until child execs (or fails to) */
634 		char buf;
635 		int n = full_read(status.rd, &buf, 1);
636 		if (n < 0 /* && errno == EAGAIN */)
637 			continue;	/* try it again */
638 	}
639 	close(status.rd);
640 #  endif
641 	if (vfork_exec_errno) {
642 		errno = vfork_exec_errno;
643 		bb_perror_msg_and_die("can't execute '%s'", gzip);
644 	}
645 }
646 # endif /* SEAMLESS_COMPRESSION */
647 
648 
649 # if !SEAMLESS_COMPRESSION
650 /* Do not pass gzip flag to writeTarFile() */
651 #define writeTarFile(tbInfo, recurseFlags, filelist, gzip) \
652 	writeTarFile(tbInfo, recurseFlags, filelist)
653 # endif
654 /* gcc 4.2.1 inlines it, making code bigger */
writeTarFile(struct TarBallInfo * tbInfo,int recurseFlags,const llist_t * filelist,const char * gzip)655 static NOINLINE int writeTarFile(
656 	struct TarBallInfo *tbInfo,
657 	int recurseFlags,
658 	const llist_t *filelist,
659 	const char *gzip)
660 {
661 	int errorFlag = FALSE;
662 
663 	/*tbInfo->hlInfoHead = NULL; - already is */
664 
665 	/* Store the stat info for the tarball's file, so
666 	 * can avoid including the tarball into itself....  */
667 	xfstat(tbInfo->tarFd, &tbInfo->tarFileStatBuf, "can't stat tar file");
668 
669 # if SEAMLESS_COMPRESSION
670 	if (gzip)
671 		vfork_compressor(tbInfo->tarFd, gzip);
672 # endif
673 
674 	/* Read the directory/files and iterate over them one at a time */
675 	while (filelist) {
676 		if (!recursive_action(filelist->data, recurseFlags,
677 				writeFileToTarball, writeFileToTarball, tbInfo)
678 		) {
679 			errorFlag = TRUE;
680 		}
681 		filelist = filelist->link;
682 	}
683 	/* Write two empty blocks to the end of the archive */
684 	memset(block_buf, 0, 2*TAR_BLOCK_SIZE);
685 	xwrite(tbInfo->tarFd, block_buf, 2*TAR_BLOCK_SIZE);
686 
687 	/* To be pedantically correct, we would check if the tarball
688 	 * is smaller than 20 tar blocks, and pad it if it was smaller,
689 	 * but that isn't necessary for GNU tar interoperability, and
690 	 * so is considered a waste of space */
691 
692 	/* Close so the child process (if any) will exit */
693 	close(tbInfo->tarFd);
694 
695 	/* Hang up the tools, close up shop, head home */
696 	if (ENABLE_FEATURE_CLEAN_UP)
697 		freeHardLinkInfo(&tbInfo->hlInfoHead);
698 
699 	if (errorFlag)
700 		bb_simple_error_msg("error exit delayed from previous errors");
701 
702 # if SEAMLESS_COMPRESSION
703 	if (gzip) {
704 		int status;
705 		if (safe_waitpid(-1, &status, 0) == -1)
706 			bb_simple_perror_msg("waitpid");
707 		else if (!WIFEXITED(status) || WEXITSTATUS(status))
708 			/* gzip was killed or has exited with nonzero! */
709 			errorFlag = TRUE;
710 	}
711 # endif
712 	return errorFlag;
713 }
714 
715 #endif /* FEATURE_TAR_CREATE */
716 
717 #if ENABLE_FEATURE_TAR_FROM
append_file_list_to_list(llist_t * list)718 static llist_t *append_file_list_to_list(llist_t *list)
719 {
720 	llist_t *newlist = NULL;
721 
722 	while (list) {
723 		FILE *src_stream;
724 		char *line;
725 
726 		src_stream = xfopen_stdin(llist_pop(&list));
727 		while ((line = xmalloc_fgetline(src_stream)) != NULL) {
728 			/* kill trailing '/' unless the string is just "/" */
729 			char *cp = last_char_is(line, '/');
730 			if (cp > line)
731 				*cp = '\0';
732 			llist_add_to_end(&newlist, line);
733 		}
734 		fclose(src_stream);
735 	}
736 	return newlist;
737 }
738 #endif
739 
740 //usage:#define tar_trivial_usage
741 //usage:	IF_FEATURE_TAR_CREATE("c|") "x|t [-"
742 //usage:	IF_FEATURE_SEAMLESS_Z("Z")
743 //usage:	IF_FEATURE_SEAMLESS_GZ("z")
744 //usage:	IF_FEATURE_SEAMLESS_XZ("J")
745 //usage:	IF_FEATURE_SEAMLESS_BZ2("j")
746 //usage:	"a"
747 //usage:	IF_FEATURE_TAR_CREATE("h")
748 //usage:	IF_FEATURE_TAR_NOPRESERVE_TIME("m")
749 //usage:	"vokO] "
750 //usage:	"[-f TARFILE] [-C DIR] "
751 //usage:	IF_FEATURE_TAR_FROM("[-T FILE] [-X FILE] "IF_FEATURE_TAR_LONG_OPTIONS("[LONGOPT]... "))
752 //usage:	"[FILE]..."
753 //usage:#define tar_full_usage "\n\n"
754 //usage:	IF_FEATURE_TAR_CREATE("Create, extract, ")
755 //usage:	IF_NOT_FEATURE_TAR_CREATE("Extract ")
756 //usage:	"or list files from a tar file"
757 //usage:     "\n"
758 //usage:	IF_FEATURE_TAR_CREATE(
759 //usage:     "\n	c	Create"
760 //usage:	)
761 //usage:     "\n	x	Extract"
762 //usage:     "\n	t	List"
763 //usage:     "\n	-f FILE	Name of TARFILE ('-' for stdin/out)"
764 //usage:     "\n	-C DIR	Change to DIR before operation"
765 //usage:     "\n	-v	Verbose"
766 //usage:     "\n	-O	Extract to stdout"
767 //usage:	IF_FEATURE_TAR_NOPRESERVE_TIME(
768 //usage:     "\n	-m	Don't restore mtime"
769 //usage:	)
770 //usage:     "\n	-o	Don't restore user:group"
771 ///////:-p - accepted but ignored, restores mode (aliases in GNU tar: --preserve-permissions, --same-permissions)
772 //usage:     "\n	-k	Don't replace existing files"
773 //usage:	IF_FEATURE_SEAMLESS_Z(
774 //usage:     "\n	-Z	(De)compress using compress"
775 //usage:	)
776 //usage:	IF_FEATURE_SEAMLESS_GZ(
777 //usage:     "\n	-z	(De)compress using gzip"
778 //usage:	)
779 //usage:	IF_FEATURE_SEAMLESS_XZ(
780 //usage:     "\n	-J	(De)compress using xz"
781 //usage:	)
782 //usage:	IF_FEATURE_SEAMLESS_BZ2(
783 //usage:     "\n	-j	(De)compress using bzip2"
784 //usage:	)
785 //usage:	IF_FEATURE_SEAMLESS_LZMA(
786 //usage:	IF_FEATURE_TAR_LONG_OPTIONS(
787 //usage:     "\n	--lzma	(De)compress using lzma"
788 //usage:	)
789 //usage:	)
790 //usage:     "\n	-a	(De)compress based on extension"
791 //usage:	IF_FEATURE_TAR_CREATE(
792 //usage:     "\n	-h	Follow symlinks"
793 //usage:	)
794 //usage:	IF_FEATURE_TAR_FROM(
795 //usage:     "\n	-T FILE	File with names to include"
796 //usage:     "\n	-X FILE	File with glob patterns to exclude"
797 //usage:	IF_FEATURE_TAR_LONG_OPTIONS(
798 //usage:     "\n	--exclude PATTERN	Glob pattern to exclude"
799 //usage:	)
800 //usage:	)
801 //usage:	IF_FEATURE_TAR_LONG_OPTIONS(
802 //usage:     "\n	--overwrite		Replace existing files"
803 //usage:     "\n	--strip-components NUM	NUM of leading components to strip"
804 //usage:     "\n	--no-recursion		Don't descend in directories"
805 //usage:     "\n	--numeric-owner		Use numeric user:group"
806 //usage:     "\n	--no-same-permissions	Don't restore access permissions"
807 //usage:	IF_FEATURE_TAR_TO_COMMAND(
808 //usage:     "\n	--to-command COMMAND	Pipe files to COMMAND"
809 //usage:	)
810 //usage:	)
811 //usage:
812 //usage:#define tar_example_usage
813 //usage:       "$ zcat /tmp/tarball.tar.gz | tar -xf -\n"
814 //usage:       "$ tar -cf /tmp/tarball.tar /usr/local\n"
815 
816 enum {
817 	OPTBIT_KEEP_OLD = 8,
818 	IF_FEATURE_TAR_CREATE(   OPTBIT_CREATE      ,)
819 	IF_FEATURE_TAR_CREATE(   OPTBIT_DEREFERENCE ,)
820 	IF_FEATURE_SEAMLESS_BZ2( OPTBIT_BZIP2       ,)
821 	IF_FEATURE_TAR_FROM(     OPTBIT_INCLUDE_FROM,)
822 	IF_FEATURE_TAR_FROM(     OPTBIT_EXCLUDE_FROM,)
823 	IF_FEATURE_SEAMLESS_GZ(  OPTBIT_GZIP        ,)
824 	IF_FEATURE_SEAMLESS_XZ(  OPTBIT_XZ          ,)
825 	IF_FEATURE_SEAMLESS_Z(   OPTBIT_COMPRESS    ,) // 16th bit
826 	OPTBIT_AUTOCOMPRESS_BY_EXT,
827 	IF_FEATURE_TAR_NOPRESERVE_TIME(OPTBIT_NOPRESERVE_TIME,)
828 #if ENABLE_FEATURE_TAR_LONG_OPTIONS
829 	OPTBIT_STRIP_COMPONENTS,
830 	IF_FEATURE_SEAMLESS_LZMA(OPTBIT_LZMA        ,)
831 	OPTBIT_NORECURSION,
832 	IF_FEATURE_TAR_TO_COMMAND(OPTBIT_2COMMAND   ,)
833 	OPTBIT_NUMERIC_OWNER,
834 	OPTBIT_NOPRESERVE_PERM,
835 	OPTBIT_OVERWRITE,
836 #endif
837 	OPT_TEST         = 1 << 0, // t
838 	OPT_EXTRACT      = 1 << 1, // x
839 	OPT_BASEDIR      = 1 << 2, // C
840 	OPT_TARNAME      = 1 << 3, // f
841 	OPT_2STDOUT      = 1 << 4, // O
842 	OPT_NOPRESERVE_OWNER = 1 << 5, // o == no-same-owner
843 	OPT_P            = 1 << 6, // p
844 	OPT_VERBOSE      = 1 << 7, // v
845 	OPT_KEEP_OLD     = 1 << 8, // k
846 	OPT_CREATE       = IF_FEATURE_TAR_CREATE(   (1 << OPTBIT_CREATE      )) + 0, // c
847 	OPT_DEREFERENCE  = IF_FEATURE_TAR_CREATE(   (1 << OPTBIT_DEREFERENCE )) + 0, // h
848 	OPT_BZIP2        = IF_FEATURE_SEAMLESS_BZ2( (1 << OPTBIT_BZIP2       )) + 0, // j
849 	OPT_INCLUDE_FROM = IF_FEATURE_TAR_FROM(     (1 << OPTBIT_INCLUDE_FROM)) + 0, // T
850 	OPT_EXCLUDE_FROM = IF_FEATURE_TAR_FROM(     (1 << OPTBIT_EXCLUDE_FROM)) + 0, // X
851 	OPT_GZIP         = IF_FEATURE_SEAMLESS_GZ(  (1 << OPTBIT_GZIP        )) + 0, // z
852 	OPT_XZ           = IF_FEATURE_SEAMLESS_XZ(  (1 << OPTBIT_XZ          )) + 0, // J
853 	OPT_COMPRESS     = IF_FEATURE_SEAMLESS_Z(   (1 << OPTBIT_COMPRESS    )) + 0, // Z
854 	OPT_AUTOCOMPRESS_BY_EXT = 1 << OPTBIT_AUTOCOMPRESS_BY_EXT,                   // a
855 	OPT_NOPRESERVE_TIME  = IF_FEATURE_TAR_NOPRESERVE_TIME((1 << OPTBIT_NOPRESERVE_TIME)) + 0, // m
856 	OPT_STRIP_COMPONENTS = IF_FEATURE_TAR_LONG_OPTIONS((1 << OPTBIT_STRIP_COMPONENTS)) + 0, // strip-components
857 	OPT_LZMA             = IF_FEATURE_TAR_LONG_OPTIONS(IF_FEATURE_SEAMLESS_LZMA((1 << OPTBIT_LZMA))) + 0, // lzma
858 	OPT_NORECURSION      = IF_FEATURE_TAR_LONG_OPTIONS((1 << OPTBIT_NORECURSION    )) + 0, // no-recursion
859 	OPT_2COMMAND         = IF_FEATURE_TAR_TO_COMMAND(  (1 << OPTBIT_2COMMAND       )) + 0, // to-command
860 	OPT_NUMERIC_OWNER    = IF_FEATURE_TAR_LONG_OPTIONS((1 << OPTBIT_NUMERIC_OWNER  )) + 0, // numeric-owner
861 	OPT_NOPRESERVE_PERM  = IF_FEATURE_TAR_LONG_OPTIONS((1 << OPTBIT_NOPRESERVE_PERM)) + 0, // no-same-permissions
862 	OPT_OVERWRITE        = IF_FEATURE_TAR_LONG_OPTIONS((1 << OPTBIT_OVERWRITE      )) + 0, // overwrite
863 
864 	OPT_ANY_COMPRESS = (OPT_BZIP2 | OPT_LZMA | OPT_GZIP | OPT_XZ | OPT_COMPRESS),
865 };
866 #if ENABLE_FEATURE_TAR_LONG_OPTIONS
867 static const char tar_longopts[] ALIGN1 =
868 	"list\0"                No_argument       "t"
869 	"extract\0"             No_argument       "x"
870 	"directory\0"           Required_argument "C"
871 	"file\0"                Required_argument "f"
872 	"to-stdout\0"           No_argument       "O"
873 	/* do not restore owner */
874 	/* Note: GNU tar handles 'o' as no-same-owner only on extract,
875 	 * on create, 'o' is --old-archive. We do not support --old-archive. */
876 	"no-same-owner\0"       No_argument       "o"
877 	"same-permissions\0"    No_argument       "p"
878 	"verbose\0"             No_argument       "v"
879 	"keep-old\0"            No_argument       "k"
880 # if ENABLE_FEATURE_TAR_CREATE
881 	"create\0"              No_argument       "c"
882 	"dereference\0"         No_argument       "h"
883 # endif
884 # if ENABLE_FEATURE_SEAMLESS_BZ2
885 	"bzip2\0"               No_argument       "j"
886 # endif
887 # if ENABLE_FEATURE_TAR_FROM
888 	"files-from\0"          Required_argument "T"
889 	"exclude-from\0"        Required_argument "X"
890 # endif
891 # if ENABLE_FEATURE_SEAMLESS_GZ
892 	"gzip\0"                No_argument       "z"
893 # endif
894 # if ENABLE_FEATURE_SEAMLESS_XZ
895 	"xz\0"                  No_argument       "J"
896 # endif
897 # if ENABLE_FEATURE_SEAMLESS_Z
898 	"compress\0"            No_argument       "Z"
899 # endif
900 	"auto-compress\0"       No_argument       "a"
901 # if ENABLE_FEATURE_TAR_NOPRESERVE_TIME
902 	"touch\0"               No_argument       "m"
903 # endif
904 	"strip-components\0"	Required_argument "\xf8"
905 # if ENABLE_FEATURE_SEAMLESS_LZMA
906 	"lzma\0"                No_argument       "\xf9"
907 # endif
908 	"no-recursion\0"	No_argument       "\xfa"
909 # if ENABLE_FEATURE_TAR_TO_COMMAND
910 	"to-command\0"		Required_argument "\xfb"
911 # endif
912 	/* use numeric uid/gid from tar header, not textual */
913 	"numeric-owner\0"       No_argument       "\xfc"
914 	/* do not restore mode */
915 	"no-same-permissions\0" No_argument       "\xfd"
916 	/* on unpack, open with O_TRUNC and !O_EXCL */
917 	"overwrite\0"           No_argument       "\xfe"
918 	/* --exclude takes next bit position in option mask, */
919 	/* therefore we have to put it _after_ --no-same-permissions */
920 # if ENABLE_FEATURE_TAR_FROM
921 	"exclude\0"             Required_argument "\xff"
922 # endif
923 	;
924 # define GETOPT32 getopt32long
925 # define LONGOPTS ,tar_longopts
926 #else
927 # define GETOPT32 getopt32
928 # define LONGOPTS
929 #endif
930 
931 int tar_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
tar_main(int argc UNUSED_PARAM,char ** argv)932 int tar_main(int argc UNUSED_PARAM, char **argv)
933 {
934 	archive_handle_t *tar_handle;
935 	char *base_dir = NULL;
936 	const char *tar_filename = "-";
937 	unsigned opt;
938 	int verboseFlag = 0;
939 #if ENABLE_FEATURE_TAR_LONG_OPTIONS && ENABLE_FEATURE_TAR_FROM
940 	llist_t *excludes = NULL;
941 #endif
942 	INIT_G();
943 
944 	/* Initialise default values */
945 	tar_handle = init_handle();
946 	tar_handle->ah_flags = ARCHIVE_CREATE_LEADING_DIRS
947 	                     | ARCHIVE_RESTORE_DATE
948 	                     | ARCHIVE_UNLINK_OLD;
949 
950 	/* Apparently only root's tar preserves perms (see bug 3844) */
951 	if (getuid() != 0)
952 		tar_handle->ah_flags |= ARCHIVE_DONT_RESTORE_PERM;
953 
954 #if ENABLE_DESKTOP
955 	/* Lie to buildroot when it starts asking stupid questions. */
956 	if (argv[1] && strcmp(argv[1], "--version") == 0) {
957 		// Output of 'tar --version' examples:
958 		// tar (GNU tar) 1.15.1
959 		// tar (GNU tar) 1.25
960 		// bsdtar 2.8.3 - libarchive 2.8.3
961 		puts("tar (busybox) " BB_VER);
962 		return 0;
963 	}
964 #endif
965 	if (argv[1] && argv[1][0] != '-' && argv[1][0] != '\0') {
966 		/* Compat:
967 		 * 1st argument without dash handles options with parameters
968 		 * differently from dashed one: it takes *next argv[i]*
969 		 * as parameter even if there are more chars in 1st argument:
970 		 *  "tar fx TARFILE" - "x" is not taken as f's param
971 		 *  but is interpreted as -x option
972 		 *  "tar -xf TARFILE" - dashed equivalent of the above
973 		 *  "tar -fx ..." - "x" is taken as f's param
974 		 * getopt32 wouldn't handle 1st command correctly.
975 		 * Unfortunately, people do use such commands.
976 		 * We massage argv[1] to work around it by moving 'f'
977 		 * to the end of the string.
978 		 * More contrived "tar fCx TARFILE DIR" still fails,
979 		 * but such commands are much less likely to be used.
980 		 */
981 		char *f = strchr(argv[1], 'f');
982 		if (f) {
983 			while (f[1] != '\0') {
984 				*f = f[1];
985 				f++;
986 			}
987 			*f = 'f';
988 		}
989 		/* Prepend '-' to the first argument  */
990 		argv[1] = xasprintf("-%s", argv[1]);
991 	}
992 	opt = GETOPT32(argv, "^"
993 		"txC:f:Oopvk"
994 		IF_FEATURE_TAR_CREATE(   "ch"    )
995 		IF_FEATURE_SEAMLESS_BZ2( "j"     )
996 		IF_FEATURE_TAR_FROM(     "T:*X:*")
997 		IF_FEATURE_SEAMLESS_GZ(  "z"     )
998 		IF_FEATURE_SEAMLESS_XZ(  "J"     )
999 		IF_FEATURE_SEAMLESS_Z(   "Z"     )
1000 		"a"
1001 		IF_FEATURE_TAR_NOPRESERVE_TIME("m")
1002 		IF_FEATURE_TAR_LONG_OPTIONS("\xf8:") // --strip-components
1003 		"\0"
1004 		"tt:vv:" // count -t,-v
1005 #if ENABLE_FEATURE_TAR_LONG_OPTIONS && ENABLE_FEATURE_TAR_FROM
1006 		"\xff::" // --exclude=PATTERN is a list
1007 #endif
1008 		IF_FEATURE_TAR_CREATE("c:") "t:x:" // at least one of these is reqd
1009 		IF_FEATURE_TAR_CREATE("c--tx:t--cx:x--ct") // mutually exclusive
1010 		IF_NOT_FEATURE_TAR_CREATE("t--x:x--t") // mutually exclusive
1011 #if ENABLE_FEATURE_TAR_LONG_OPTIONS
1012 		":\xf8+" // --strip-components=NUM
1013 #endif
1014 		LONGOPTS
1015 		, &base_dir // -C dir
1016 		, &tar_filename // -f filename
1017 		IF_FEATURE_TAR_FROM(, &(tar_handle->accept)) // T
1018 		IF_FEATURE_TAR_FROM(, &(tar_handle->reject)) // X
1019 #if ENABLE_FEATURE_TAR_LONG_OPTIONS
1020 		, &tar_handle->tar__strip_components // --strip-components
1021 #endif
1022 		IF_FEATURE_TAR_TO_COMMAND(, &(tar_handle->tar__to_command)) // --to-command
1023 #if ENABLE_FEATURE_TAR_LONG_OPTIONS && ENABLE_FEATURE_TAR_FROM
1024 		, &excludes // --exclude
1025 #endif
1026 		, &verboseFlag // combined count for -t and -v
1027 		, &verboseFlag // combined count for -t and -v
1028 		);
1029 #if DBG_OPTION_PARSING
1030 	bb_error_msg("opt: 0x%08x", opt);
1031 # define showopt(o) bb_error_msg("opt & %s(%x):\t%x", #o, o, opt & o);
1032 	showopt(OPT_TEST            );
1033 	showopt(OPT_EXTRACT         );
1034 	showopt(OPT_BASEDIR         );
1035 	showopt(OPT_TARNAME         );
1036 	showopt(OPT_2STDOUT         );
1037 	showopt(OPT_NOPRESERVE_OWNER);
1038 	showopt(OPT_P               );
1039 	showopt(OPT_VERBOSE         );
1040 	showopt(OPT_KEEP_OLD        );
1041 	showopt(OPT_CREATE          );
1042 	showopt(OPT_DEREFERENCE     );
1043 	showopt(OPT_BZIP2           );
1044 	showopt(OPT_INCLUDE_FROM    );
1045 	showopt(OPT_EXCLUDE_FROM    );
1046 	showopt(OPT_GZIP            );
1047 	showopt(OPT_XZ              );
1048 	showopt(OPT_COMPRESS        );
1049 	showopt(OPT_AUTOCOMPRESS_BY_EXT);
1050 	showopt(OPT_NOPRESERVE_TIME );
1051 	showopt(OPT_STRIP_COMPONENTS);
1052 	showopt(OPT_LZMA            );
1053 	showopt(OPT_NORECURSION     );
1054 	showopt(OPT_2COMMAND        );
1055 	showopt(OPT_NUMERIC_OWNER   );
1056 	showopt(OPT_NOPRESERVE_PERM );
1057 	showopt(OPT_OVERWRITE       );
1058 	showopt(OPT_ANY_COMPRESS    );
1059 	bb_error_msg("base_dir:'%s'", base_dir);
1060 	bb_error_msg("tar_filename:'%s'", tar_filename);
1061 	bb_error_msg("verboseFlag:%d", verboseFlag);
1062 	bb_error_msg("tar_handle->tar__to_command:'%s'", tar_handle->tar__to_command);
1063 	bb_error_msg("tar_handle->tar__strip_components:%u", tar_handle->tar__strip_components);
1064 	return 0;
1065 # undef showopt
1066 #endif
1067 	argv += optind;
1068 
1069 	if (verboseFlag)
1070 		tar_handle->action_header = header_verbose_list;
1071 	if (verboseFlag == 1)
1072 		tar_handle->action_header = header_list;
1073 
1074 	if (opt & OPT_EXTRACT)
1075 		tar_handle->action_data = data_extract_all;
1076 
1077 	if (opt & OPT_2STDOUT)
1078 		tar_handle->action_data = data_extract_to_stdout;
1079 
1080 	if (opt & OPT_2COMMAND) {
1081 		putenv((char*)"TAR_FILETYPE=f");
1082 		signal(SIGPIPE, SIG_IGN);
1083 		tar_handle->action_data = data_extract_to_command;
1084 		IF_FEATURE_TAR_TO_COMMAND(tar_handle->tar__to_command_shell = xstrdup(get_shell_name());)
1085 	}
1086 
1087 	if (opt & OPT_KEEP_OLD)
1088 		tar_handle->ah_flags &= ~ARCHIVE_UNLINK_OLD;
1089 
1090 	if (opt & OPT_NUMERIC_OWNER)
1091 		tar_handle->ah_flags |= ARCHIVE_NUMERIC_OWNER;
1092 
1093 	if (opt & OPT_NOPRESERVE_OWNER)
1094 		tar_handle->ah_flags |= ARCHIVE_DONT_RESTORE_OWNER;
1095 
1096 	if (opt & OPT_NOPRESERVE_PERM)
1097 		tar_handle->ah_flags |= ARCHIVE_DONT_RESTORE_PERM;
1098 
1099 	if (opt & OPT_OVERWRITE) {
1100 		tar_handle->ah_flags &= ~ARCHIVE_UNLINK_OLD;
1101 		tar_handle->ah_flags |= ARCHIVE_O_TRUNC;
1102 	}
1103 
1104 	if (opt & OPT_NOPRESERVE_TIME)
1105 		tar_handle->ah_flags &= ~ARCHIVE_RESTORE_DATE;
1106 
1107 #if ENABLE_FEATURE_TAR_FROM
1108 	/* Convert each -X EXCLFILE to list of to-be-rejected glob patterns */
1109 	tar_handle->reject = append_file_list_to_list(tar_handle->reject);
1110 # if ENABLE_FEATURE_TAR_LONG_OPTIONS
1111 	/* Append --exclude=GLOBPATTERNs to reject */
1112 	if (excludes) {
1113 		llist_t **p2next = &tar_handle->reject;
1114 		while (*p2next)
1115 			p2next = &((*p2next)->link);
1116 		*p2next = excludes;
1117 	}
1118 # endif
1119 	tar_handle->accept = append_file_list_to_list(tar_handle->accept);
1120 #endif
1121 
1122 	/* Setup an array of filenames to work with */
1123 	/* TODO: This is the same as in ar, make a separate function? */
1124 	while (*argv) {
1125 		/* kill trailing '/' unless the string is just "/" */
1126 		char *cp = last_char_is(*argv, '/');
1127 		if (cp > *argv)
1128 			*cp = '\0';
1129 		llist_add_to_end(&tar_handle->accept, *argv);
1130 		argv++;
1131 	}
1132 
1133 	if (tar_handle->accept || tar_handle->reject)
1134 		tar_handle->filter = filter_accept_reject_list;
1135 
1136 	/* Open the tar file */
1137 	{
1138 		int tar_fd = STDIN_FILENO;
1139 		int flags = O_RDONLY;
1140 
1141 		if (opt & OPT_CREATE) {
1142 			/* Make sure there is at least one file to tar up */
1143 			if (tar_handle->accept == NULL)
1144 				bb_simple_error_msg_and_die("empty archive");
1145 
1146 			tar_fd = STDOUT_FILENO;
1147 			/* Mimicking GNU tar 1.15.1: */
1148 			flags = O_WRONLY | O_CREAT | O_TRUNC;
1149 		}
1150 
1151 		if (LONE_DASH(tar_filename)) {
1152 			tar_handle->src_fd = tar_fd;
1153 			tar_handle->seek = seek_by_read;
1154 		} else
1155 		if (ENABLE_FEATURE_TAR_AUTODETECT
1156 		 && ENABLE_FEATURE_SEAMLESS_LZMA
1157 		 && flags == O_RDONLY
1158 		 && !(opt & OPT_ANY_COMPRESS)
1159 		 && is_suffixed_with(tar_filename, ".lzma")
1160 		/* We do this only for .lzma files, they have no signature.
1161 		 * All other compression formats are recognized in
1162 		 * get_header_tar() when first tar block has invalid format.
1163 		 * Doing it here for all filenames would falsely trigger
1164 		 * on e.g. tarball with 1st file named "BZh5".
1165 		 */
1166 		) {
1167 			tar_handle->src_fd = open_zipped(tar_filename, /*fail_if_not_compressed:*/ 0);
1168 			if (tar_handle->src_fd < 0)
1169 				bb_perror_msg_and_die("can't open '%s'", tar_filename);
1170 		} else {
1171 			tar_handle->src_fd = xopen(tar_filename, flags);
1172 #if ENABLE_FEATURE_TAR_CREATE
1173 			if ((OPT_GZIP | OPT_BZIP2 | OPT_XZ | OPT_LZMA) != 0 /* at least one is config-enabled */
1174 			 && (opt & OPT_AUTOCOMPRESS_BY_EXT)
1175 			 && flags != O_RDONLY
1176 			) {
1177 				if (OPT_GZIP != 0 && is_suffixed_with(tar_filename, "gz"))
1178 					opt |= OPT_GZIP;
1179 				if (OPT_BZIP2 != 0 && is_suffixed_with(tar_filename, "bz2"))
1180 					opt |= OPT_BZIP2;
1181 				if (OPT_XZ != 0 && is_suffixed_with(tar_filename, "xz"))
1182 					opt |= OPT_XZ;
1183 				if (OPT_LZMA != 0 && is_suffixed_with(tar_filename, "lzma"))
1184 					opt |= OPT_LZMA;
1185 			}
1186 #endif
1187 		}
1188 	}
1189 
1190 	if (base_dir)
1191 		xchdir(base_dir);
1192 
1193 #if ENABLE_FEATURE_TAR_CREATE
1194 	/* Create an archive */
1195 	if (opt & OPT_CREATE) {
1196 		struct TarBallInfo *tbInfo;
1197 # if SEAMLESS_COMPRESSION
1198 		const char *zipMode = NULL;
1199 		if (opt & OPT_COMPRESS)
1200 			zipMode = "compress";
1201 		if (opt & OPT_GZIP)
1202 			zipMode = "gzip";
1203 		if (opt & OPT_BZIP2)
1204 			zipMode = "bzip2";
1205 		if (opt & OPT_LZMA)
1206 			zipMode = "lzma";
1207 		if (opt & OPT_XZ)
1208 			zipMode = "xz";
1209 # endif
1210 		tbInfo = xzalloc(sizeof(*tbInfo));
1211 		tbInfo->tarFd = tar_handle->src_fd;
1212 		tbInfo->verboseFlag = verboseFlag;
1213 # if ENABLE_FEATURE_TAR_FROM
1214 		tbInfo->excludeList = tar_handle->reject;
1215 # endif
1216 		/* NB: writeTarFile() closes tar_handle->src_fd */
1217 		return writeTarFile(tbInfo,
1218 				(opt & OPT_DEREFERENCE ? ACTION_FOLLOWLINKS : 0)
1219 				| (opt & OPT_NORECURSION ? 0 : ACTION_RECURSE),
1220 				tar_handle->accept,
1221 				zipMode);
1222 	}
1223 #endif
1224 
1225 	if (opt & OPT_ANY_COMPRESS) {
1226 		USE_FOR_MMU(IF_DESKTOP(long long) int FAST_FUNC (*xformer)(transformer_state_t *xstate);)
1227 		USE_FOR_NOMMU(const char *xformer_prog;)
1228 
1229 		if (opt & OPT_COMPRESS) {
1230 			USE_FOR_MMU(IF_FEATURE_SEAMLESS_Z(xformer = unpack_Z_stream;))
1231 			USE_FOR_NOMMU(xformer_prog = "uncompress";)
1232 		}
1233 		if (opt & OPT_GZIP) {
1234 			USE_FOR_MMU(IF_FEATURE_SEAMLESS_GZ(xformer = unpack_gz_stream;))
1235 			USE_FOR_NOMMU(xformer_prog = "gunzip";)
1236 		}
1237 		if (opt & OPT_BZIP2) {
1238 			USE_FOR_MMU(IF_FEATURE_SEAMLESS_BZ2(xformer = unpack_bz2_stream;))
1239 			USE_FOR_NOMMU(xformer_prog = "bunzip2";)
1240 		}
1241 		if (opt & OPT_LZMA) {
1242 			USE_FOR_MMU(IF_FEATURE_SEAMLESS_LZMA(xformer = unpack_lzma_stream;))
1243 			USE_FOR_NOMMU(xformer_prog = "unlzma";)
1244 		}
1245 		if (opt & OPT_XZ) {
1246 			USE_FOR_MMU(IF_FEATURE_SEAMLESS_XZ(xformer = unpack_xz_stream;))
1247 			USE_FOR_NOMMU(xformer_prog = "unxz";)
1248 		}
1249 
1250 		fork_transformer_with_sig(tar_handle->src_fd, xformer, xformer_prog);
1251 		/* Can't lseek over pipes */
1252 		tar_handle->seek = seek_by_read;
1253 		/*tar_handle->offset = 0; - already is */
1254 	}
1255 
1256 	/* Zero processed headers (== empty file) is not a valid tarball.
1257 	 * We (ab)use bb_got_signal as exitcode here,
1258 	 * because check_errors_in_children() uses _it_ as error indicator.
1259 	 */
1260 	bb_got_signal = EXIT_FAILURE;
1261 
1262 	while (get_header_tar(tar_handle) == EXIT_SUCCESS)
1263 		bb_got_signal = EXIT_SUCCESS; /* saw at least one header, good */
1264 
1265 	create_links_from_list(tar_handle->link_placeholders);
1266 
1267 	/* Check that every file that should have been extracted was */
1268 	while (tar_handle->accept) {
1269 		if (!find_list_entry(tar_handle->reject, tar_handle->accept->data)
1270 		 && !find_list_entry(tar_handle->passed, tar_handle->accept->data)
1271 		) {
1272 			bb_error_msg_and_die("%s: not found in archive",
1273 				tar_handle->accept->data);
1274 		}
1275 		tar_handle->accept = tar_handle->accept->link;
1276 	}
1277 	if (ENABLE_FEATURE_CLEAN_UP /* && tar_handle->src_fd != STDIN_FILENO */)
1278 		close(tar_handle->src_fd);
1279 
1280 	if (SEAMLESS_COMPRESSION || OPT_COMPRESS) {
1281 		/* Set bb_got_signal to 1 if a child died with !0 exitcode */
1282 		check_errors_in_children(0);
1283 	}
1284 
1285 	return bb_got_signal;
1286 }
1287