bsdtar.c revision 342361
1/*-
2 * Copyright (c) 2003-2008 Tim Kientzle
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * 1. Redistributions of source code must retain the above copyright
9 *    notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 *    notice, this list of conditions and the following disclaimer in the
12 *    documentation and/or other materials provided with the distribution.
13 *
14 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS OR
15 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
16 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
17 * IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY DIRECT, INDIRECT,
18 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
19 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
20 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
21 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
22 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
23 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
24 */
25
26#include "bsdtar_platform.h"
27__FBSDID("$FreeBSD: stable/10/contrib/libarchive/tar/bsdtar.c 342361 2018-12-21 23:33:28Z mm $");
28
29#ifdef HAVE_SYS_PARAM_H
30#include <sys/param.h>
31#endif
32#ifdef HAVE_SYS_STAT_H
33#include <sys/stat.h>
34#endif
35#ifdef HAVE_COPYFILE_H
36#include <copyfile.h>
37#endif
38#ifdef HAVE_ERRNO_H
39#include <errno.h>
40#endif
41#ifdef HAVE_FCNTL_H
42#include <fcntl.h>
43#endif
44#ifdef HAVE_LANGINFO_H
45#include <langinfo.h>
46#endif
47#ifdef HAVE_LOCALE_H
48#include <locale.h>
49#endif
50#ifdef HAVE_PATHS_H
51#include <paths.h>
52#endif
53#ifdef HAVE_SIGNAL_H
54#include <signal.h>
55#endif
56#include <stdio.h>
57#ifdef HAVE_STDLIB_H
58#include <stdlib.h>
59#endif
60#ifdef HAVE_STRING_H
61#include <string.h>
62#endif
63#ifdef HAVE_TIME_H
64#include <time.h>
65#endif
66#ifdef HAVE_UNISTD_H
67#include <unistd.h>
68#endif
69
70#include "bsdtar.h"
71#include "err.h"
72
73/*
74 * Per POSIX.1-1988, tar defaults to reading/writing archives to/from
75 * the default tape device for the system.  Pick something reasonable here.
76 */
77#ifdef __linux
78#define	_PATH_DEFTAPE "/dev/st0"
79#endif
80#if defined(_WIN32) && !defined(__CYGWIN__)
81#define	_PATH_DEFTAPE "\\\\.\\tape0"
82#endif
83#if defined(__APPLE__)
84#undef _PATH_DEFTAPE
85#define	_PATH_DEFTAPE "-"  /* Mac OS has no tape support, default to stdio. */
86#endif
87
88#ifndef _PATH_DEFTAPE
89#define	_PATH_DEFTAPE "/dev/tape"
90#endif
91
92#ifdef __MINGW32__
93int _CRT_glob = 0; /* Disable broken CRT globbing. */
94#endif
95
96#if defined(HAVE_SIGACTION) && (defined(SIGINFO) || defined(SIGUSR1))
97static volatile int siginfo_occurred;
98
99static void
100siginfo_handler(int sig)
101{
102	(void)sig; /* UNUSED */
103	siginfo_occurred = 1;
104}
105
106int
107need_report(void)
108{
109	int r = siginfo_occurred;
110	siginfo_occurred = 0;
111	return (r);
112}
113#else
114int
115need_report(void)
116{
117	return (0);
118}
119#endif
120
121static void		 long_help(void) __LA_DEAD;
122static void		 only_mode(struct bsdtar *, const char *opt,
123			     const char *valid);
124static void		 set_mode(struct bsdtar *, char opt);
125static void		 version(void) __LA_DEAD;
126
127/* A basic set of security flags to request from libarchive. */
128#define	SECURITY					\
129	(ARCHIVE_EXTRACT_SECURE_SYMLINKS		\
130	 | ARCHIVE_EXTRACT_SECURE_NODOTDOT)
131
132int
133main(int argc, char **argv)
134{
135	struct bsdtar		*bsdtar, bsdtar_storage;
136	int			 opt, t;
137	char			 compression, compression2;
138	const char		*compression_name, *compression2_name;
139	const char		*compress_program;
140	char			*tptr;
141	char			 possible_help_request;
142	char			 buff[16];
143
144	/*
145	 * Use a pointer for consistency, but stack-allocated storage
146	 * for ease of cleanup.
147	 */
148	bsdtar = &bsdtar_storage;
149	memset(bsdtar, 0, sizeof(*bsdtar));
150	bsdtar->fd = -1; /* Mark as "unused" */
151	bsdtar->gid = -1;
152	bsdtar->uid = -1;
153	bsdtar->flags = 0;
154	compression = compression2 = '\0';
155	compression_name = compression2_name = NULL;
156	compress_program = NULL;
157
158#if defined(HAVE_SIGACTION)
159	{ /* Set up signal handling. */
160		struct sigaction sa;
161		sa.sa_handler = siginfo_handler;
162		sigemptyset(&sa.sa_mask);
163		sa.sa_flags = 0;
164#ifdef SIGINFO
165		if (sigaction(SIGINFO, &sa, NULL))
166			lafe_errc(1, errno, "sigaction(SIGINFO) failed");
167#endif
168#ifdef SIGUSR1
169		/* ... and treat SIGUSR1 the same way as SIGINFO. */
170		if (sigaction(SIGUSR1, &sa, NULL))
171			lafe_errc(1, errno, "sigaction(SIGUSR1) failed");
172#endif
173#ifdef SIGPIPE
174		/* Ignore SIGPIPE signals. */
175		sa.sa_handler = SIG_IGN;
176		sigaction(SIGPIPE, &sa, NULL);
177#endif
178	}
179#endif
180
181	/* Set lafe_progname before calling lafe_warnc. */
182	lafe_setprogname(*argv, "bsdtar");
183
184#if HAVE_SETLOCALE
185	if (setlocale(LC_ALL, "") == NULL)
186		lafe_warnc(0, "Failed to set default locale");
187#endif
188#if defined(HAVE_NL_LANGINFO) && defined(HAVE_D_MD_ORDER)
189	bsdtar->day_first = (*nl_langinfo(D_MD_ORDER) == 'd');
190#endif
191	possible_help_request = 0;
192
193	/* Look up uid of current user for future reference */
194	bsdtar->user_uid = geteuid();
195
196	/* Default: open tape drive. */
197	bsdtar->filename = getenv("TAPE");
198	if (bsdtar->filename == NULL)
199		bsdtar->filename = _PATH_DEFTAPE;
200
201	/* Default block size settings. */
202	bsdtar->bytes_per_block = DEFAULT_BYTES_PER_BLOCK;
203	/* Allow library to default this unless user specifies -b. */
204	bsdtar->bytes_in_last_block = -1;
205
206	/* Default: preserve mod time on extract */
207	bsdtar->extract_flags = ARCHIVE_EXTRACT_TIME;
208
209	/* Default: Perform basic security checks. */
210	bsdtar->extract_flags |= SECURITY;
211
212#ifndef _WIN32
213	/* On POSIX systems, assume --same-owner and -p when run by
214	 * the root user.  This doesn't make any sense on Windows. */
215	if (bsdtar->user_uid == 0) {
216		/* --same-owner */
217		bsdtar->extract_flags |= ARCHIVE_EXTRACT_OWNER;
218		/* -p */
219		bsdtar->extract_flags |= ARCHIVE_EXTRACT_PERM;
220		bsdtar->extract_flags |= ARCHIVE_EXTRACT_ACL;
221		bsdtar->extract_flags |= ARCHIVE_EXTRACT_XATTR;
222		bsdtar->extract_flags |= ARCHIVE_EXTRACT_FFLAGS;
223		bsdtar->extract_flags |= ARCHIVE_EXTRACT_MAC_METADATA;
224	}
225#endif
226
227	/*
228	 * Enable Mac OS "copyfile()" extension by default.
229	 * This has no effect on other platforms.
230	 */
231	bsdtar->readdisk_flags |= ARCHIVE_READDISK_MAC_COPYFILE;
232#ifdef COPYFILE_DISABLE_VAR
233	if (getenv(COPYFILE_DISABLE_VAR))
234		bsdtar->readdisk_flags &= ~ARCHIVE_READDISK_MAC_COPYFILE;
235#endif
236#if defined(__APPLE__)
237	/*
238	 * On Mac OS ACLs are archived with copyfile() (--mac-metadata)
239	 * Translation to NFSv4 ACLs has to be requested explicitly with --acls
240	 */
241	bsdtar->readdisk_flags |= ARCHIVE_READDISK_NO_ACL;
242#endif
243
244	bsdtar->matching = archive_match_new();
245	if (bsdtar->matching == NULL)
246		lafe_errc(1, errno, "Out of memory");
247	bsdtar->cset = cset_new();
248	if (bsdtar->cset == NULL)
249		lafe_errc(1, errno, "Out of memory");
250
251	bsdtar->argv = argv;
252	bsdtar->argc = argc;
253
254	/*
255	 * Comments following each option indicate where that option
256	 * originated:  SUSv2, POSIX, GNU tar, star, etc.  If there's
257	 * no such comment, then I don't know of anyone else who
258	 * implements that option.
259	 */
260	while ((opt = bsdtar_getopt(bsdtar)) != -1) {
261		switch (opt) {
262		case 'a': /* GNU tar */
263			bsdtar->flags |= OPTFLAG_AUTO_COMPRESS;
264			break;
265		case OPTION_ACLS: /* GNU tar */
266			bsdtar->extract_flags |= ARCHIVE_EXTRACT_ACL;
267			bsdtar->readdisk_flags &= ~ARCHIVE_READDISK_NO_ACL;
268			bsdtar->flags |= OPTFLAG_ACLS;
269			break;
270		case 'B': /* GNU tar */
271			/* libarchive doesn't need this; just ignore it. */
272			break;
273		case 'b': /* SUSv2 */
274			errno = 0;
275			tptr = NULL;
276			t = (int)strtol(bsdtar->argument, &tptr, 10);
277			if (errno || t <= 0 || t > 8192 ||
278			    *(bsdtar->argument) == '\0' || tptr == NULL ||
279			    *tptr != '\0') {
280				lafe_errc(1, 0, "Invalid or out of range "
281				    "(1..8192) argument to -b");
282			}
283			bsdtar->bytes_per_block = 512 * t;
284			/* Explicit -b forces last block size. */
285			bsdtar->bytes_in_last_block = bsdtar->bytes_per_block;
286			break;
287		case OPTION_B64ENCODE:
288			if (compression2 != '\0')
289				lafe_errc(1, 0,
290				    "Can't specify both --uuencode and "
291				    "--b64encode");
292			compression2 = opt;
293			compression2_name = "b64encode";
294			break;
295		case 'C': /* GNU tar */
296			if (strlen(bsdtar->argument) == 0)
297				lafe_errc(1, 0,
298				    "Meaningless option: -C ''");
299
300			set_chdir(bsdtar, bsdtar->argument);
301			break;
302		case 'c': /* SUSv2 */
303			set_mode(bsdtar, opt);
304			break;
305		case OPTION_CHECK_LINKS: /* GNU tar */
306			bsdtar->flags |= OPTFLAG_WARN_LINKS;
307			break;
308		case OPTION_CHROOT: /* NetBSD */
309			bsdtar->flags |= OPTFLAG_CHROOT;
310			break;
311		case OPTION_CLEAR_NOCHANGE_FFLAGS:
312			bsdtar->extract_flags |=
313			    ARCHIVE_EXTRACT_CLEAR_NOCHANGE_FFLAGS;
314			break;
315		case OPTION_EXCLUDE: /* GNU tar */
316			if (archive_match_exclude_pattern(
317			    bsdtar->matching, bsdtar->argument) != ARCHIVE_OK)
318				lafe_errc(1, 0,
319				    "Couldn't exclude %s\n", bsdtar->argument);
320			break;
321		case OPTION_FFLAGS:
322			bsdtar->extract_flags |= ARCHIVE_EXTRACT_FFLAGS;
323			bsdtar->readdisk_flags &= ~ARCHIVE_READDISK_NO_FFLAGS;
324			bsdtar->flags |= OPTFLAG_FFLAGS;
325			break;
326		case OPTION_FORMAT: /* GNU tar, others */
327			cset_set_format(bsdtar->cset, bsdtar->argument);
328			break;
329		case 'f': /* SUSv2 */
330			bsdtar->filename = bsdtar->argument;
331			break;
332		case OPTION_GID: /* cpio */
333			errno = 0;
334			tptr = NULL;
335			t = (int)strtol(bsdtar->argument, &tptr, 10);
336			if (errno || t < 0 || *(bsdtar->argument) == '\0' ||
337			    tptr == NULL || *tptr != '\0') {
338				lafe_errc(1, 0, "Invalid argument to --gid");
339			}
340			bsdtar->gid = t;
341			break;
342		case OPTION_GNAME: /* cpio */
343			bsdtar->gname = bsdtar->argument;
344			break;
345		case OPTION_GRZIP:
346			if (compression != '\0')
347				lafe_errc(1, 0,
348				    "Can't specify both -%c and -%c", opt,
349				    compression);
350			compression = opt;
351			compression_name = "grzip";
352			break;
353		case 'H': /* BSD convention */
354			bsdtar->symlink_mode = 'H';
355			break;
356		case 'h': /* Linux Standards Base, gtar; synonym for -L */
357			bsdtar->symlink_mode = 'L';
358			/* Hack: -h by itself is the "help" command. */
359			possible_help_request = 1;
360			break;
361		case OPTION_HELP: /* GNU tar, others */
362			long_help();
363			exit(0);
364			break;
365		case OPTION_HFS_COMPRESSION: /* Mac OS X v10.6 or later */
366			bsdtar->extract_flags |=
367			    ARCHIVE_EXTRACT_HFS_COMPRESSION_FORCED;
368			break;
369		case OPTION_IGNORE_ZEROS:
370			bsdtar->flags |= OPTFLAG_IGNORE_ZEROS;
371			break;
372		case 'I': /* GNU tar */
373			/*
374			 * TODO: Allow 'names' to come from an archive,
375			 * not just a text file.  Design a good UI for
376			 * allowing names and mode/owner to be read
377			 * from an archive, with contents coming from
378			 * disk.  This can be used to "refresh" an
379			 * archive or to design archives with special
380			 * permissions without having to create those
381			 * permissions on disk.
382			 */
383			bsdtar->names_from_file = bsdtar->argument;
384			break;
385		case OPTION_INCLUDE:
386			/*
387			 * No one else has the @archive extension, so
388			 * no one else needs this to filter entries
389			 * when transforming archives.
390			 */
391			if (archive_match_include_pattern(bsdtar->matching,
392			    bsdtar->argument) != ARCHIVE_OK)
393				lafe_errc(1, 0,
394				    "Failed to add %s to inclusion list",
395				    bsdtar->argument);
396			break;
397		case 'j': /* GNU tar */
398			if (compression != '\0')
399				lafe_errc(1, 0,
400				    "Can't specify both -%c and -%c", opt,
401				    compression);
402			compression = opt;
403			compression_name = "bzip2";
404			break;
405		case 'J': /* GNU tar 1.21 and later */
406			if (compression != '\0')
407				lafe_errc(1, 0,
408				    "Can't specify both -%c and -%c", opt,
409				    compression);
410			compression = opt;
411			compression_name = "xz";
412			break;
413		case 'k': /* GNU tar */
414			bsdtar->extract_flags |= ARCHIVE_EXTRACT_NO_OVERWRITE;
415			break;
416		case OPTION_KEEP_NEWER_FILES: /* GNU tar */
417			bsdtar->extract_flags |= ARCHIVE_EXTRACT_NO_OVERWRITE_NEWER;
418			break;
419		case 'L': /* BSD convention */
420			bsdtar->symlink_mode = 'L';
421			break;
422	        case 'l': /* SUSv2 and GNU tar beginning with 1.16 */
423			/* GNU tar 1.13  used -l for --one-file-system */
424			bsdtar->flags |= OPTFLAG_WARN_LINKS;
425			break;
426		case OPTION_LRZIP:
427		case OPTION_LZ4:
428		case OPTION_LZIP: /* GNU tar beginning with 1.23 */
429		case OPTION_LZMA: /* GNU tar beginning with 1.20 */
430		case OPTION_LZOP: /* GNU tar beginning with 1.21 */
431		case OPTION_ZSTD:
432			if (compression != '\0')
433				lafe_errc(1, 0,
434				    "Can't specify both -%c and -%c", opt,
435				    compression);
436			compression = opt;
437			switch (opt) {
438			case OPTION_LRZIP: compression_name = "lrzip"; break;
439			case OPTION_LZ4:  compression_name = "lz4"; break;
440			case OPTION_LZIP: compression_name = "lzip"; break;
441			case OPTION_LZMA: compression_name = "lzma"; break;
442			case OPTION_LZOP: compression_name = "lzop"; break;
443			case OPTION_ZSTD: compression_name = "zstd"; break;
444			}
445			break;
446		case 'm': /* SUSv2 */
447			bsdtar->extract_flags &= ~ARCHIVE_EXTRACT_TIME;
448			break;
449		case OPTION_MAC_METADATA: /* Mac OS X */
450			bsdtar->readdisk_flags |= ARCHIVE_READDISK_MAC_COPYFILE;
451			bsdtar->extract_flags |= ARCHIVE_EXTRACT_MAC_METADATA;
452			bsdtar->flags |= OPTFLAG_MAC_METADATA;
453			break;
454		case 'n': /* GNU tar */
455			bsdtar->flags |= OPTFLAG_NO_SUBDIRS;
456			break;
457	        /*
458		 * Selecting files by time:
459		 *    --newer-?time='date' Only files newer than 'date'
460		 *    --newer-?time-than='file' Only files newer than time
461		 *         on specified file (useful for incremental backups)
462		 */
463		case OPTION_NEWER_CTIME: /* GNU tar */
464			if (archive_match_include_date(bsdtar->matching,
465			    ARCHIVE_MATCH_CTIME | ARCHIVE_MATCH_NEWER,
466			    bsdtar->argument) != ARCHIVE_OK)
467				lafe_errc(1, 0, "Error : %s",
468				    archive_error_string(bsdtar->matching));
469			break;
470		case OPTION_NEWER_CTIME_THAN:
471			if (archive_match_include_file_time(bsdtar->matching,
472			    ARCHIVE_MATCH_CTIME | ARCHIVE_MATCH_NEWER,
473			    bsdtar->argument) != ARCHIVE_OK)
474				lafe_errc(1, 0, "Error : %s",
475				    archive_error_string(bsdtar->matching));
476			break;
477		case OPTION_NEWER_MTIME: /* GNU tar */
478			if (archive_match_include_date(bsdtar->matching,
479			    ARCHIVE_MATCH_MTIME | ARCHIVE_MATCH_NEWER,
480			    bsdtar->argument) != ARCHIVE_OK)
481				lafe_errc(1, 0, "Error : %s",
482				    archive_error_string(bsdtar->matching));
483			break;
484		case OPTION_NEWER_MTIME_THAN:
485			if (archive_match_include_file_time(bsdtar->matching,
486			    ARCHIVE_MATCH_MTIME | ARCHIVE_MATCH_NEWER,
487			    bsdtar->argument) != ARCHIVE_OK)
488				lafe_errc(1, 0, "Error : %s",
489				    archive_error_string(bsdtar->matching));
490			break;
491		case OPTION_NODUMP: /* star */
492			bsdtar->readdisk_flags |= ARCHIVE_READDISK_HONOR_NODUMP;
493			break;
494		case OPTION_NOPRESERVE_HFS_COMPRESSION:
495			/* Mac OS X v10.6 or later */
496			bsdtar->extract_flags |=
497			    ARCHIVE_EXTRACT_NO_HFS_COMPRESSION;
498			break;
499		case OPTION_NO_ACLS: /* GNU tar */
500			bsdtar->extract_flags &= ~ARCHIVE_EXTRACT_ACL;
501			bsdtar->readdisk_flags |= ARCHIVE_READDISK_NO_ACL;
502			bsdtar->flags |= OPTFLAG_NO_ACLS;
503			break;
504		case OPTION_NO_FFLAGS:
505			bsdtar->extract_flags &= ~ARCHIVE_EXTRACT_FFLAGS;
506			bsdtar->readdisk_flags |= ARCHIVE_READDISK_NO_FFLAGS;
507			bsdtar->flags |= OPTFLAG_NO_FFLAGS;
508			break;
509		case OPTION_NO_MAC_METADATA: /* Mac OS X */
510			bsdtar->readdisk_flags &= ~ARCHIVE_READDISK_MAC_COPYFILE;
511			bsdtar->extract_flags &= ~ARCHIVE_EXTRACT_MAC_METADATA;
512			bsdtar->flags |= OPTFLAG_NO_MAC_METADATA;
513			break;
514		case OPTION_NO_SAME_OWNER: /* GNU tar */
515			bsdtar->extract_flags &= ~ARCHIVE_EXTRACT_OWNER;
516			break;
517		case OPTION_NO_SAME_PERMISSIONS: /* GNU tar */
518			bsdtar->extract_flags &= ~ARCHIVE_EXTRACT_PERM;
519			bsdtar->extract_flags &= ~ARCHIVE_EXTRACT_ACL;
520			bsdtar->extract_flags &= ~ARCHIVE_EXTRACT_XATTR;
521			bsdtar->extract_flags &= ~ARCHIVE_EXTRACT_FFLAGS;
522			bsdtar->extract_flags &= ~ARCHIVE_EXTRACT_MAC_METADATA;
523			break;
524		case OPTION_NO_XATTRS: /* GNU tar */
525			bsdtar->extract_flags &= ~ARCHIVE_EXTRACT_XATTR;
526			bsdtar->readdisk_flags |= ARCHIVE_READDISK_NO_XATTR;
527			bsdtar->flags |= OPTFLAG_NO_XATTRS;
528			break;
529		case OPTION_NULL: /* GNU tar */
530			bsdtar->flags |= OPTFLAG_NULL;
531			break;
532		case OPTION_NUMERIC_OWNER: /* GNU tar */
533			bsdtar->uname = "";
534			bsdtar->gname = "";
535			bsdtar->flags |= OPTFLAG_NUMERIC_OWNER;
536			break;
537		case 'O': /* GNU tar */
538			bsdtar->flags |= OPTFLAG_STDOUT;
539			break;
540		case 'o': /* SUSv2 and GNU conflict here, but not fatally */
541			bsdtar->flags |= OPTFLAG_O;
542			break;
543	        /*
544		 * Selecting files by time:
545		 *    --older-?time='date' Only files older than 'date'
546		 *    --older-?time-than='file' Only files older than time
547		 *         on specified file
548		 */
549		case OPTION_OLDER_CTIME:
550			if (archive_match_include_date(bsdtar->matching,
551			    ARCHIVE_MATCH_CTIME | ARCHIVE_MATCH_OLDER,
552			    bsdtar->argument) != ARCHIVE_OK)
553				lafe_errc(1, 0, "Error : %s",
554				    archive_error_string(bsdtar->matching));
555			break;
556		case OPTION_OLDER_CTIME_THAN:
557			if (archive_match_include_file_time(bsdtar->matching,
558			    ARCHIVE_MATCH_CTIME | ARCHIVE_MATCH_OLDER,
559			    bsdtar->argument) != ARCHIVE_OK)
560				lafe_errc(1, 0, "Error : %s",
561				    archive_error_string(bsdtar->matching));
562			break;
563		case OPTION_OLDER_MTIME:
564			if (archive_match_include_date(bsdtar->matching,
565			    ARCHIVE_MATCH_MTIME | ARCHIVE_MATCH_OLDER,
566			    bsdtar->argument) != ARCHIVE_OK)
567				lafe_errc(1, 0, "Error : %s",
568				    archive_error_string(bsdtar->matching));
569			break;
570		case OPTION_OLDER_MTIME_THAN:
571			if (archive_match_include_file_time(bsdtar->matching,
572			    ARCHIVE_MATCH_MTIME | ARCHIVE_MATCH_OLDER,
573			    bsdtar->argument) != ARCHIVE_OK)
574				lafe_errc(1, 0, "Error : %s",
575				    archive_error_string(bsdtar->matching));
576			break;
577		case OPTION_ONE_FILE_SYSTEM: /* GNU tar */
578			bsdtar->readdisk_flags |=
579			    ARCHIVE_READDISK_NO_TRAVERSE_MOUNTS;
580			break;
581		case OPTION_OPTIONS:
582			bsdtar->option_options = bsdtar->argument;
583			break;
584#if 0
585		/*
586		 * The common BSD -P option is not necessary, since
587		 * our default is to archive symlinks, not follow
588		 * them.  This is convenient, as -P conflicts with GNU
589		 * tar anyway.
590		 */
591		case 'P': /* BSD convention */
592			/* Default behavior, no option necessary. */
593			break;
594#endif
595		case 'P': /* GNU tar */
596			bsdtar->extract_flags &= ~SECURITY;
597			bsdtar->flags |= OPTFLAG_ABSOLUTE_PATHS;
598			break;
599		case 'p': /* GNU tar, star */
600			bsdtar->extract_flags |= ARCHIVE_EXTRACT_PERM;
601			bsdtar->extract_flags |= ARCHIVE_EXTRACT_ACL;
602			bsdtar->extract_flags |= ARCHIVE_EXTRACT_XATTR;
603			bsdtar->extract_flags |= ARCHIVE_EXTRACT_FFLAGS;
604			bsdtar->extract_flags |= ARCHIVE_EXTRACT_MAC_METADATA;
605			break;
606		case OPTION_PASSPHRASE:
607			bsdtar->passphrase = bsdtar->argument;
608			break;
609		case OPTION_POSIX: /* GNU tar */
610			cset_set_format(bsdtar->cset, "pax");
611			break;
612		case 'q': /* FreeBSD GNU tar --fast-read, NetBSD -q */
613			bsdtar->flags |= OPTFLAG_FAST_READ;
614			break;
615		case 'r': /* SUSv2 */
616			set_mode(bsdtar, opt);
617			break;
618		case 'S': /* NetBSD pax-as-tar */
619			bsdtar->extract_flags |= ARCHIVE_EXTRACT_SPARSE;
620			break;
621		case 's': /* NetBSD pax-as-tar */
622#if defined(HAVE_REGEX_H) || defined(HAVE_PCREPOSIX_H)
623			add_substitution(bsdtar, bsdtar->argument);
624#else
625			lafe_warnc(0,
626			    "-s is not supported by this version of bsdtar");
627			usage();
628#endif
629			break;
630		case OPTION_SAME_OWNER: /* GNU tar */
631			bsdtar->extract_flags |= ARCHIVE_EXTRACT_OWNER;
632			break;
633		case OPTION_STRIP_COMPONENTS: /* GNU tar 1.15 */
634			errno = 0;
635			tptr = NULL;
636			t = (int)strtol(bsdtar->argument, &tptr, 10);
637			if (errno || t < 0 || *(bsdtar->argument) == '\0' ||
638			    tptr == NULL || *tptr != '\0') {
639				lafe_errc(1, 0, "Invalid argument to "
640				    "--strip-components");
641			}
642			bsdtar->strip_components = t;
643			break;
644		case 'T': /* GNU tar */
645			bsdtar->names_from_file = bsdtar->argument;
646			break;
647		case 't': /* SUSv2 */
648			set_mode(bsdtar, opt);
649			bsdtar->verbose++;
650			break;
651		case OPTION_TOTALS: /* GNU tar */
652			bsdtar->flags |= OPTFLAG_TOTALS;
653			break;
654		case 'U': /* GNU tar */
655			bsdtar->extract_flags |= ARCHIVE_EXTRACT_UNLINK;
656			bsdtar->flags |= OPTFLAG_UNLINK_FIRST;
657			break;
658		case 'u': /* SUSv2 */
659			set_mode(bsdtar, opt);
660			break;
661		case OPTION_UID: /* cpio */
662			errno = 0;
663			tptr = NULL;
664			t = (int)strtol(bsdtar->argument, &tptr, 10);
665			if (errno || t < 0 || *(bsdtar->argument) == '\0' ||
666			    tptr == NULL || *tptr != '\0') {
667				lafe_errc(1, 0, "Invalid argument to --uid");
668			}
669			bsdtar->uid = t;
670			break;
671		case OPTION_UNAME: /* cpio */
672			bsdtar->uname = bsdtar->argument;
673			break;
674		case OPTION_UUENCODE:
675			if (compression2 != '\0')
676				lafe_errc(1, 0,
677				    "Can't specify both --uuencode and "
678				    "--b64encode");
679			compression2 = opt;
680			compression2_name = "uuencode";
681			break;
682		case 'v': /* SUSv2 */
683			bsdtar->verbose++;
684			break;
685		case OPTION_VERSION: /* GNU convention */
686			version();
687			break;
688#if 0
689		/*
690		 * The -W longopt feature is handled inside of
691		 * bsdtar_getopt(), so -W is not available here.
692		 */
693		case 'W': /* Obscure GNU convention. */
694			break;
695#endif
696		case 'w': /* SUSv2 */
697			bsdtar->flags |= OPTFLAG_INTERACTIVE;
698			break;
699		case 'X': /* GNU tar */
700			if (archive_match_exclude_pattern_from_file(
701			    bsdtar->matching, bsdtar->argument, 0)
702			    != ARCHIVE_OK)
703				lafe_errc(1, 0, "Error : %s",
704				    archive_error_string(bsdtar->matching));
705			break;
706		case 'x': /* SUSv2 */
707			set_mode(bsdtar, opt);
708			break;
709		case OPTION_XATTRS: /* GNU tar */
710			bsdtar->extract_flags |= ARCHIVE_EXTRACT_XATTR;
711			bsdtar->readdisk_flags &= ~ARCHIVE_READDISK_NO_XATTR;
712			bsdtar->flags |= OPTFLAG_XATTRS;
713			break;
714		case 'y': /* FreeBSD version of GNU tar */
715			if (compression != '\0')
716				lafe_errc(1, 0,
717				    "Can't specify both -%c and -%c", opt,
718				    compression);
719			compression = opt;
720			compression_name = "bzip2";
721			break;
722		case 'Z': /* GNU tar */
723			if (compression != '\0')
724				lafe_errc(1, 0,
725				    "Can't specify both -%c and -%c", opt,
726				    compression);
727			compression = opt;
728			compression_name = "compress";
729			break;
730		case 'z': /* GNU tar, star, many others */
731			if (compression != '\0')
732				lafe_errc(1, 0,
733				    "Can't specify both -%c and -%c", opt,
734				    compression);
735			compression = opt;
736			compression_name = "gzip";
737			break;
738		case OPTION_USE_COMPRESS_PROGRAM:
739			compress_program = bsdtar->argument;
740			break;
741		default:
742			usage();
743		}
744	}
745
746	/*
747	 * Sanity-check options.
748	 */
749
750	/* If no "real" mode was specified, treat -h as --help. */
751	if ((bsdtar->mode == '\0') && possible_help_request) {
752		long_help();
753		exit(0);
754	}
755
756	/* Otherwise, a mode is required. */
757	if (bsdtar->mode == '\0')
758		lafe_errc(1, 0,
759		    "Must specify one of -c, -r, -t, -u, -x");
760
761	/* Check boolean options only permitted in certain modes. */
762	if (bsdtar->flags & OPTFLAG_AUTO_COMPRESS)
763		only_mode(bsdtar, "-a", "c");
764	if (bsdtar->readdisk_flags & ARCHIVE_READDISK_NO_TRAVERSE_MOUNTS)
765		only_mode(bsdtar, "--one-file-system", "cru");
766	if (bsdtar->flags & OPTFLAG_FAST_READ)
767		only_mode(bsdtar, "--fast-read", "xt");
768	if (bsdtar->extract_flags & ARCHIVE_EXTRACT_HFS_COMPRESSION_FORCED)
769		only_mode(bsdtar, "--hfsCompression", "x");
770	if (bsdtar->extract_flags & ARCHIVE_EXTRACT_NO_HFS_COMPRESSION)
771		only_mode(bsdtar, "--nopreserveHFSCompression", "x");
772	if (bsdtar->readdisk_flags & ARCHIVE_READDISK_HONOR_NODUMP)
773		only_mode(bsdtar, "--nodump", "cru");
774	if (bsdtar->flags & OPTFLAG_ACLS)
775		only_mode(bsdtar, "--acls", "crux");
776	if (bsdtar->flags & OPTFLAG_NO_ACLS)
777		only_mode(bsdtar, "--no-acls", "crux");
778	if (bsdtar->flags & OPTFLAG_XATTRS)
779		only_mode(bsdtar, "--xattrs", "crux");
780	if (bsdtar->flags & OPTFLAG_NO_XATTRS)
781		only_mode(bsdtar, "--no-xattrs", "crux");
782	if (bsdtar->flags & OPTFLAG_FFLAGS)
783		only_mode(bsdtar, "--fflags", "crux");
784	if (bsdtar->flags & OPTFLAG_NO_FFLAGS)
785		only_mode(bsdtar, "--no-fflags", "crux");
786	if (bsdtar->flags & OPTFLAG_MAC_METADATA)
787		only_mode(bsdtar, "--mac-metadata", "crux");
788	if (bsdtar->flags & OPTFLAG_NO_MAC_METADATA)
789		only_mode(bsdtar, "--no-mac-metadata", "crux");
790	if (bsdtar->flags & OPTFLAG_O) {
791		switch (bsdtar->mode) {
792		case 'c':
793			/*
794			 * In GNU tar, -o means "old format."  The
795			 * "ustar" format is the closest thing
796			 * supported by libarchive.
797			 */
798			cset_set_format(bsdtar->cset, "ustar");
799			/* TODO: bsdtar->create_format = "v7"; */
800			break;
801		case 'x':
802			/* POSIX-compatible behavior. */
803			bsdtar->flags |= OPTFLAG_NO_OWNER;
804			bsdtar->extract_flags &= ~ARCHIVE_EXTRACT_OWNER;
805			break;
806		default:
807			only_mode(bsdtar, "-o", "xc");
808			break;
809		}
810	}
811	if (bsdtar->flags & OPTFLAG_NO_SUBDIRS)
812		only_mode(bsdtar, "-n", "cru");
813	if (bsdtar->flags & OPTFLAG_STDOUT)
814		only_mode(bsdtar, "-O", "xt");
815	if (bsdtar->flags & OPTFLAG_UNLINK_FIRST)
816		only_mode(bsdtar, "-U", "x");
817	if (bsdtar->flags & OPTFLAG_WARN_LINKS)
818		only_mode(bsdtar, "--check-links", "cr");
819
820	if ((bsdtar->flags & OPTFLAG_AUTO_COMPRESS) &&
821	    cset_auto_compress(bsdtar->cset, bsdtar->filename)) {
822		/* Ignore specified compressions if auto-compress works. */
823		compression = '\0';
824		compression2 = '\0';
825	}
826	/* Check other parameters only permitted in certain modes. */
827	if (compress_program != NULL) {
828		only_mode(bsdtar, "--use-compress-program", "cxt");
829		cset_add_filter_program(bsdtar->cset, compress_program);
830		/* Ignore specified compressions. */
831		compression = '\0';
832		compression2 = '\0';
833	}
834	if (compression != '\0') {
835		switch (compression) {
836		case 'J': case 'j': case 'y': case 'Z': case 'z':
837			strcpy(buff, "-?");
838			buff[1] = compression;
839			break;
840		default:
841			strcpy(buff, "--");
842			strcat(buff, compression_name);
843			break;
844		}
845		only_mode(bsdtar, buff, "cxt");
846		cset_add_filter(bsdtar->cset, compression_name);
847	}
848	if (compression2 != '\0') {
849		strcpy(buff, "--");
850		strcat(buff, compression2_name);
851		only_mode(bsdtar, buff, "cxt");
852		cset_add_filter(bsdtar->cset, compression2_name);
853	}
854	if (cset_get_format(bsdtar->cset) != NULL)
855		only_mode(bsdtar, "--format", "cru");
856	if (bsdtar->symlink_mode != '\0') {
857		strcpy(buff, "-?");
858		buff[1] = bsdtar->symlink_mode;
859		only_mode(bsdtar, buff, "cru");
860	}
861
862	/* Filename "-" implies stdio. */
863	if (strcmp(bsdtar->filename, "-") == 0)
864		bsdtar->filename = NULL;
865
866	switch(bsdtar->mode) {
867	case 'c':
868		tar_mode_c(bsdtar);
869		break;
870	case 'r':
871		tar_mode_r(bsdtar);
872		break;
873	case 't':
874		tar_mode_t(bsdtar);
875		break;
876	case 'u':
877		tar_mode_u(bsdtar);
878		break;
879	case 'x':
880		tar_mode_x(bsdtar);
881		break;
882	}
883
884	archive_match_free(bsdtar->matching);
885#if defined(HAVE_REGEX_H) || defined(HAVE_PCREPOSIX_H)
886	cleanup_substitution(bsdtar);
887#endif
888	cset_free(bsdtar->cset);
889	passphrase_free(bsdtar->ppbuff);
890
891	if (bsdtar->return_value != 0)
892		lafe_warnc(0,
893		    "Error exit delayed from previous errors.");
894	return (bsdtar->return_value);
895}
896
897static void
898set_mode(struct bsdtar *bsdtar, char opt)
899{
900	if (bsdtar->mode != '\0' && bsdtar->mode != opt)
901		lafe_errc(1, 0,
902		    "Can't specify both -%c and -%c", opt, bsdtar->mode);
903	bsdtar->mode = opt;
904}
905
906/*
907 * Verify that the mode is correct.
908 */
909static void
910only_mode(struct bsdtar *bsdtar, const char *opt, const char *valid_modes)
911{
912	if (strchr(valid_modes, bsdtar->mode) == NULL)
913		lafe_errc(1, 0,
914		    "Option %s is not permitted in mode -%c",
915		    opt, bsdtar->mode);
916}
917
918
919void
920usage(void)
921{
922	const char	*p;
923
924	p = lafe_getprogname();
925
926	fprintf(stderr, "Usage:\n");
927	fprintf(stderr, "  List:    %s -tf <archive-filename>\n", p);
928	fprintf(stderr, "  Extract: %s -xf <archive-filename>\n", p);
929	fprintf(stderr, "  Create:  %s -cf <archive-filename> [filenames...]\n", p);
930	fprintf(stderr, "  Help:    %s --help\n", p);
931	exit(1);
932}
933
934static void
935version(void)
936{
937	printf("bsdtar %s - %s \n",
938	    BSDTAR_VERSION_STRING,
939	    archive_version_details());
940	exit(0);
941}
942
943static const char *long_help_msg =
944	"First option must be a mode specifier:\n"
945	"  -c Create  -r Add/Replace  -t List  -u Update  -x Extract\n"
946	"Common Options:\n"
947	"  -b #  Use # 512-byte records per I/O block\n"
948	"  -f <filename>  Location of archive (default " _PATH_DEFTAPE ")\n"
949	"  -v    Verbose\n"
950	"  -w    Interactive\n"
951	"Create: %p -c [options] [<file> | <dir> | @<archive> | -C <dir> ]\n"
952	"  <file>, <dir>  add these items to archive\n"
953	"  -z, -j, -J, --lzma  Compress archive with gzip/bzip2/xz/lzma\n"
954	"  --format {ustar|pax|cpio|shar}  Select archive format\n"
955	"  --exclude <pattern>  Skip files that match pattern\n"
956	"  -C <dir>  Change to <dir> before processing remaining files\n"
957	"  @<archive>  Add entries from <archive> to output\n"
958	"List: %p -t [options] [<patterns>]\n"
959	"  <patterns>  If specified, list only entries that match\n"
960	"Extract: %p -x [options] [<patterns>]\n"
961	"  <patterns>  If specified, extract only entries that match\n"
962	"  -k    Keep (don't overwrite) existing files\n"
963	"  -m    Don't restore modification times\n"
964	"  -O    Write entries to stdout, don't restore to disk\n"
965	"  -p    Restore permissions (including ACLs, owner, file flags)\n";
966
967
968/*
969 * Note that the word 'bsdtar' will always appear in the first line
970 * of output.
971 *
972 * In particular, /bin/sh scripts that need to test for the presence
973 * of bsdtar can use the following template:
974 *
975 * if (tar --help 2>&1 | grep bsdtar >/dev/null 2>&1 ) then \
976 *          echo bsdtar; else echo not bsdtar; fi
977 */
978static void
979long_help(void)
980{
981	const char	*prog;
982	const char	*p;
983
984	prog = lafe_getprogname();
985
986	fflush(stderr);
987
988	p = (strcmp(prog,"bsdtar") != 0) ? "(bsdtar)" : "";
989	printf("%s%s: manipulate archive files\n", prog, p);
990
991	for (p = long_help_msg; *p != '\0'; p++) {
992		if (*p == '%') {
993			if (p[1] == 'p') {
994				fputs(prog, stdout);
995				p++;
996			} else
997				putchar('%');
998		} else
999			putchar(*p);
1000	}
1001	version();
1002}
1003