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