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