xref: /dragonfly/contrib/libarchive/tar/bsdtar.c (revision 38c2ea22)
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: src/usr.bin/tar/bsdtar.c,v 1.93 2008/11/08 04:43:24 kientzle Exp $");
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 /* External function to parse a date/time string */
122 time_t get_date(time_t, const char *);
123 
124 static void		 long_help(void);
125 static void		 only_mode(struct bsdtar *, const char *opt,
126 			     const char *valid);
127 static void		 set_mode(struct bsdtar *, char opt);
128 static void		 version(void);
129 
130 /* A basic set of security flags to request from libarchive. */
131 #define	SECURITY					\
132 	(ARCHIVE_EXTRACT_SECURE_SYMLINKS		\
133 	 | ARCHIVE_EXTRACT_SECURE_NODOTDOT)
134 
135 int
136 main(int argc, char **argv)
137 {
138 	struct bsdtar		*bsdtar, bsdtar_storage;
139 	int			 opt, t;
140 	char			 option_o;
141 	char			 possible_help_request;
142 	char			 buff[16];
143 	time_t			 now;
144 
145 	/*
146 	 * Use a pointer for consistency, but stack-allocated storage
147 	 * for ease of cleanup.
148 	 */
149 	bsdtar = &bsdtar_storage;
150 	memset(bsdtar, 0, sizeof(*bsdtar));
151 	bsdtar->fd = -1; /* Mark as "unused" */
152 	bsdtar->gid = -1;
153 	bsdtar->uid = -1;
154 	option_o = 0;
155 
156 #if defined(HAVE_SIGACTION)
157 	{ /* Set up signal handling. */
158 		struct sigaction sa;
159 		sa.sa_handler = siginfo_handler;
160 		sigemptyset(&sa.sa_mask);
161 		sa.sa_flags = 0;
162 #ifdef SIGINFO
163 		if (sigaction(SIGINFO, &sa, NULL))
164 			lafe_errc(1, errno, "sigaction(SIGINFO) failed");
165 #endif
166 #ifdef SIGUSR1
167 		/* ... and treat SIGUSR1 the same way as SIGINFO. */
168 		if (sigaction(SIGUSR1, &sa, NULL))
169 			lafe_errc(1, errno, "sigaction(SIGUSR1) failed");
170 #endif
171 #ifdef SIGPIPE
172 		/* Ignore SIGPIPE signals. */
173 		sa.sa_handler = SIG_IGN;
174 		sigaction(SIGPIPE, &sa, NULL);
175 #endif
176 	}
177 #endif
178 
179 
180 	/* Need lafe_progname before calling lafe_warnc. */
181 	if (*argv == NULL)
182 		lafe_progname = "bsdtar";
183 	else {
184 #if defined(_WIN32) && !defined(__CYGWIN__)
185 		lafe_progname = strrchr(*argv, '\\');
186 #else
187 		lafe_progname = strrchr(*argv, '/');
188 #endif
189 		if (lafe_progname != NULL)
190 			lafe_progname++;
191 		else
192 			lafe_progname = *argv;
193 	}
194 
195 	time(&now);
196 
197 #if HAVE_SETLOCALE
198 	if (setlocale(LC_ALL, "") == NULL)
199 		lafe_warnc(0, "Failed to set default locale");
200 #endif
201 #if defined(HAVE_NL_LANGINFO) && defined(HAVE_D_MD_ORDER)
202 	bsdtar->day_first = (*nl_langinfo(D_MD_ORDER) == 'd');
203 #endif
204 	possible_help_request = 0;
205 
206 	/* Look up uid of current user for future reference */
207 	bsdtar->user_uid = geteuid();
208 
209 	/* Default: open tape drive. */
210 	bsdtar->filename = getenv("TAPE");
211 	if (bsdtar->filename == NULL)
212 		bsdtar->filename = _PATH_DEFTAPE;
213 
214 	/* Default block size settings. */
215 	bsdtar->bytes_per_block = DEFAULT_BYTES_PER_BLOCK;
216 	/* Allow library to default this unless user specifies -b. */
217 	bsdtar->bytes_in_last_block = -1;
218 
219 	/* Default: preserve mod time on extract */
220 	bsdtar->extract_flags = ARCHIVE_EXTRACT_TIME;
221 
222 	/* Default: Perform basic security checks. */
223 	bsdtar->extract_flags |= SECURITY;
224 
225 #ifndef _WIN32
226 	/* On POSIX systems, assume --same-owner and -p when run by
227 	 * the root user.  This doesn't make any sense on Windows. */
228 	if (bsdtar->user_uid == 0) {
229 		/* --same-owner */
230 		bsdtar->extract_flags |= ARCHIVE_EXTRACT_OWNER;
231 		/* -p */
232 		bsdtar->extract_flags |= ARCHIVE_EXTRACT_PERM;
233 		bsdtar->extract_flags |= ARCHIVE_EXTRACT_ACL;
234 		bsdtar->extract_flags |= ARCHIVE_EXTRACT_XATTR;
235 		bsdtar->extract_flags |= ARCHIVE_EXTRACT_FFLAGS;
236 		bsdtar->extract_flags |= ARCHIVE_EXTRACT_MAC_METADATA;
237 	}
238 #endif
239 
240 	/*
241 	 * Enable Mac OS "copyfile()" extension by default.
242 	 * This has no effect on other platforms.
243 	 */
244 	bsdtar->enable_copyfile = 1;
245 #ifdef COPYFILE_DISABLE_VAR
246 	if (getenv(COPYFILE_DISABLE_VAR))
247 		bsdtar->enable_copyfile = 0;
248 #endif
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 'B': /* GNU tar */
262 			/* libarchive doesn't need this; just ignore it. */
263 			break;
264 		case 'b': /* SUSv2 */
265 			t = atoi(bsdtar->argument);
266 			if (t <= 0 || t > 8192)
267 				lafe_errc(1, 0,
268 				    "Argument to -b is out of range (1..8192)");
269 			bsdtar->bytes_per_block = 512 * t;
270 			/* Explicit -b forces last block size. */
271 			bsdtar->bytes_in_last_block = bsdtar->bytes_per_block;
272 			break;
273 		case 'C': /* GNU tar */
274 			if (strlen(bsdtar->argument) == 0)
275 				lafe_errc(1, 0,
276 				    "Meaningless option: -C ''");
277 
278 			set_chdir(bsdtar, bsdtar->argument);
279 			break;
280 		case 'c': /* SUSv2 */
281 			set_mode(bsdtar, opt);
282 			break;
283 		case OPTION_CHECK_LINKS: /* GNU tar */
284 			bsdtar->option_warn_links = 1;
285 			break;
286 		case OPTION_CHROOT: /* NetBSD */
287 			bsdtar->option_chroot = 1;
288 			break;
289 		case OPTION_DISABLE_COPYFILE: /* Mac OS X */
290 			bsdtar->enable_copyfile = 0;
291 			break;
292 		case OPTION_EXCLUDE: /* GNU tar */
293 			if (lafe_exclude(&bsdtar->matching, bsdtar->argument))
294 				lafe_errc(1, 0,
295 				    "Couldn't exclude %s\n", bsdtar->argument);
296 			break;
297 		case OPTION_FORMAT: /* GNU tar, others */
298 			bsdtar->create_format = bsdtar->argument;
299 			break;
300 		case 'f': /* SUSv2 */
301 			bsdtar->filename = bsdtar->argument;
302 			break;
303 		case OPTION_GID: /* cpio */
304 			t = atoi(bsdtar->argument);
305 			if (t < 0)
306 				lafe_errc(1, 0,
307 				    "Argument to --gid must be positive");
308 			bsdtar->gid = t;
309 			break;
310 		case OPTION_GNAME: /* cpio */
311 			bsdtar->gname = bsdtar->argument;
312 			break;
313 		case 'H': /* BSD convention */
314 			bsdtar->symlink_mode = 'H';
315 			break;
316 		case 'h': /* Linux Standards Base, gtar; synonym for -L */
317 			bsdtar->symlink_mode = 'L';
318 			/* Hack: -h by itself is the "help" command. */
319 			possible_help_request = 1;
320 			break;
321 		case OPTION_HELP: /* GNU tar, others */
322 			long_help();
323 			exit(0);
324 			break;
325 		case 'I': /* GNU tar */
326 			/*
327 			 * TODO: Allow 'names' to come from an archive,
328 			 * not just a text file.  Design a good UI for
329 			 * allowing names and mode/owner to be read
330 			 * from an archive, with contents coming from
331 			 * disk.  This can be used to "refresh" an
332 			 * archive or to design archives with special
333 			 * permissions without having to create those
334 			 * permissions on disk.
335 			 */
336 			bsdtar->names_from_file = bsdtar->argument;
337 			break;
338 		case OPTION_INCLUDE:
339 			/*
340 			 * No one else has the @archive extension, so
341 			 * no one else needs this to filter entries
342 			 * when transforming archives.
343 			 */
344 			if (lafe_include(&bsdtar->matching, bsdtar->argument))
345 				lafe_errc(1, 0,
346 				    "Failed to add %s to inclusion list",
347 				    bsdtar->argument);
348 			break;
349 		case 'j': /* GNU tar */
350 			if (bsdtar->create_compression != '\0')
351 				lafe_errc(1, 0,
352 				    "Can't specify both -%c and -%c", opt,
353 				    bsdtar->create_compression);
354 			bsdtar->create_compression = opt;
355 			break;
356 		case 'J': /* GNU tar 1.21 and later */
357 			if (bsdtar->create_compression != '\0')
358 				lafe_errc(1, 0,
359 				    "Can't specify both -%c and -%c", opt,
360 				    bsdtar->create_compression);
361 			bsdtar->create_compression = opt;
362 			break;
363 		case 'k': /* GNU tar */
364 			bsdtar->extract_flags |= ARCHIVE_EXTRACT_NO_OVERWRITE;
365 			break;
366 		case OPTION_KEEP_NEWER_FILES: /* GNU tar */
367 			bsdtar->extract_flags |= ARCHIVE_EXTRACT_NO_OVERWRITE_NEWER;
368 			break;
369 		case 'L': /* BSD convention */
370 			bsdtar->symlink_mode = 'L';
371 			break;
372 	        case 'l': /* SUSv2 and GNU tar beginning with 1.16 */
373 			/* GNU tar 1.13  used -l for --one-file-system */
374 			bsdtar->option_warn_links = 1;
375 			break;
376 		case OPTION_LZIP: /* GNU tar beginning with 1.23 */
377 		case OPTION_LZMA: /* GNU tar beginning with 1.20 */
378 			if (bsdtar->create_compression != '\0')
379 				lafe_errc(1, 0,
380 				    "Can't specify both -%c and -%c", opt,
381 				    bsdtar->create_compression);
382 			bsdtar->create_compression = opt;
383 			break;
384 		case 'm': /* SUSv2 */
385 			bsdtar->extract_flags &= ~ARCHIVE_EXTRACT_TIME;
386 			break;
387 		case 'n': /* GNU tar */
388 			bsdtar->option_no_subdirs = 1;
389 			break;
390 	        /*
391 		 * Selecting files by time:
392 		 *    --newer-?time='date' Only files newer than 'date'
393 		 *    --newer-?time-than='file' Only files newer than time
394 		 *         on specified file (useful for incremental backups)
395 		 * TODO: Add corresponding "older" options to reverse these.
396 		 */
397 		case OPTION_NEWER_CTIME: /* GNU tar */
398 			bsdtar->newer_ctime_filter = 1;
399 			bsdtar->newer_ctime_sec = get_date(now, bsdtar->argument);
400 			break;
401 		case OPTION_NEWER_CTIME_THAN:
402 			{
403 				struct stat st;
404 				if (stat(bsdtar->argument, &st) != 0)
405 					lafe_errc(1, 0,
406 					    "Can't open file %s", bsdtar->argument);
407 				bsdtar->newer_ctime_filter = 1;
408 				bsdtar->newer_ctime_sec = st.st_ctime;
409 				bsdtar->newer_ctime_nsec =
410 				    ARCHIVE_STAT_CTIME_NANOS(&st);
411 			}
412 			break;
413 		case OPTION_NEWER_MTIME: /* GNU tar */
414 			bsdtar->newer_mtime_filter = 1;
415 			bsdtar->newer_mtime_sec = get_date(now, bsdtar->argument);
416 			break;
417 		case OPTION_NEWER_MTIME_THAN:
418 			{
419 				struct stat st;
420 				if (stat(bsdtar->argument, &st) != 0)
421 					lafe_errc(1, 0,
422 					    "Can't open file %s", bsdtar->argument);
423 				bsdtar->newer_mtime_filter = 1;
424 				bsdtar->newer_mtime_sec = st.st_mtime;
425 				bsdtar->newer_mtime_nsec =
426 				    ARCHIVE_STAT_MTIME_NANOS(&st);
427 			}
428 			break;
429 		case OPTION_NODUMP: /* star */
430 			bsdtar->option_honor_nodump = 1;
431 			break;
432 		case OPTION_NO_SAME_OWNER: /* GNU tar */
433 			bsdtar->extract_flags &= ~ARCHIVE_EXTRACT_OWNER;
434 			break;
435 		case OPTION_NO_SAME_PERMISSIONS: /* GNU tar */
436 			bsdtar->extract_flags &= ~ARCHIVE_EXTRACT_PERM;
437 			bsdtar->extract_flags &= ~ARCHIVE_EXTRACT_ACL;
438 			bsdtar->extract_flags &= ~ARCHIVE_EXTRACT_XATTR;
439 			bsdtar->extract_flags &= ~ARCHIVE_EXTRACT_FFLAGS;
440 			bsdtar->extract_flags &= ~ARCHIVE_EXTRACT_MAC_METADATA;
441 			break;
442 		case OPTION_NULL: /* GNU tar */
443 			bsdtar->option_null++;
444 			break;
445 		case OPTION_NUMERIC_OWNER: /* GNU tar */
446 			bsdtar->uname = "";
447 			bsdtar->gname = "";
448 			bsdtar->option_numeric_owner++;
449 			break;
450 		case 'O': /* GNU tar */
451 			bsdtar->option_stdout = 1;
452 			break;
453 		case 'o': /* SUSv2 and GNU conflict here, but not fatally */
454 			option_o = 1; /* Record it and resolve it later. */
455 			break;
456 		case OPTION_ONE_FILE_SYSTEM: /* GNU tar */
457 			bsdtar->option_dont_traverse_mounts = 1;
458 			break;
459 		case OPTION_OPTIONS:
460 			bsdtar->option_options = bsdtar->argument;
461 			break;
462 #if 0
463 		/*
464 		 * The common BSD -P option is not necessary, since
465 		 * our default is to archive symlinks, not follow
466 		 * them.  This is convenient, as -P conflicts with GNU
467 		 * tar anyway.
468 		 */
469 		case 'P': /* BSD convention */
470 			/* Default behavior, no option necessary. */
471 			break;
472 #endif
473 		case 'P': /* GNU tar */
474 			bsdtar->extract_flags &= ~SECURITY;
475 			bsdtar->option_absolute_paths = 1;
476 			break;
477 		case 'p': /* GNU tar, star */
478 			bsdtar->extract_flags |= ARCHIVE_EXTRACT_PERM;
479 			bsdtar->extract_flags |= ARCHIVE_EXTRACT_ACL;
480 			bsdtar->extract_flags |= ARCHIVE_EXTRACT_XATTR;
481 			bsdtar->extract_flags |= ARCHIVE_EXTRACT_FFLAGS;
482 			bsdtar->extract_flags |= ARCHIVE_EXTRACT_MAC_METADATA;
483 			break;
484 		case OPTION_POSIX: /* GNU tar */
485 			bsdtar->create_format = "pax";
486 			break;
487 		case 'q': /* FreeBSD GNU tar --fast-read, NetBSD -q */
488 			bsdtar->option_fast_read = 1;
489 			break;
490 		case 'r': /* SUSv2 */
491 			set_mode(bsdtar, opt);
492 			break;
493 		case 'S': /* NetBSD pax-as-tar */
494 			bsdtar->extract_flags |= ARCHIVE_EXTRACT_SPARSE;
495 			break;
496 		case 's': /* NetBSD pax-as-tar */
497 #if HAVE_REGEX_H
498 			add_substitution(bsdtar, bsdtar->argument);
499 #else
500 			lafe_warnc(0,
501 			    "-s is not supported by this version of bsdtar");
502 			usage();
503 #endif
504 			break;
505 		case OPTION_SAME_OWNER: /* GNU tar */
506 			bsdtar->extract_flags |= ARCHIVE_EXTRACT_OWNER;
507 			break;
508 		case OPTION_STRIP_COMPONENTS: /* GNU tar 1.15 */
509 			errno = 0;
510 			bsdtar->strip_components = strtol(bsdtar->argument,
511 			    NULL, 0);
512 			if (errno)
513 				lafe_errc(1, 0,
514 				    "Invalid --strip-components argument: %s",
515 				    bsdtar->argument);
516 			break;
517 		case 'T': /* GNU tar */
518 			bsdtar->names_from_file = bsdtar->argument;
519 			break;
520 		case 't': /* SUSv2 */
521 			set_mode(bsdtar, opt);
522 			bsdtar->verbose++;
523 			break;
524 		case OPTION_TOTALS: /* GNU tar */
525 			bsdtar->option_totals++;
526 			break;
527 		case 'U': /* GNU tar */
528 			bsdtar->extract_flags |= ARCHIVE_EXTRACT_UNLINK;
529 			bsdtar->option_unlink_first = 1;
530 			break;
531 		case 'u': /* SUSv2 */
532 			set_mode(bsdtar, opt);
533 			break;
534 		case OPTION_UID: /* cpio */
535 			t = atoi(bsdtar->argument);
536 			if (t < 0)
537 				lafe_errc(1, 0,
538 				    "Argument to --uid must be positive");
539 			bsdtar->uid = t;
540 			break;
541 		case OPTION_UNAME: /* cpio */
542 			bsdtar->uname = bsdtar->argument;
543 			break;
544 		case 'v': /* SUSv2 */
545 			bsdtar->verbose++;
546 			break;
547 		case OPTION_VERSION: /* GNU convention */
548 			version();
549 			break;
550 #if 0
551 		/*
552 		 * The -W longopt feature is handled inside of
553 		 * bsdtar_getopt(), so -W is not available here.
554 		 */
555 		case 'W': /* Obscure GNU convention. */
556 			break;
557 #endif
558 		case 'w': /* SUSv2 */
559 			bsdtar->option_interactive = 1;
560 			break;
561 		case 'X': /* GNU tar */
562 			if (lafe_exclude_from_file(&bsdtar->matching, bsdtar->argument))
563 				lafe_errc(1, 0,
564 				    "failed to process exclusions from file %s",
565 				    bsdtar->argument);
566 			break;
567 		case 'x': /* SUSv2 */
568 			set_mode(bsdtar, opt);
569 			break;
570 		case 'y': /* FreeBSD version of GNU tar */
571 			if (bsdtar->create_compression != '\0')
572 				lafe_errc(1, 0,
573 				    "Can't specify both -%c and -%c", opt,
574 				    bsdtar->create_compression);
575 			bsdtar->create_compression = opt;
576 			break;
577 		case 'Z': /* GNU tar */
578 			if (bsdtar->create_compression != '\0')
579 				lafe_errc(1, 0,
580 				    "Can't specify both -%c and -%c", opt,
581 				    bsdtar->create_compression);
582 			bsdtar->create_compression = opt;
583 			break;
584 		case 'z': /* GNU tar, star, many others */
585 			if (bsdtar->create_compression != '\0')
586 				lafe_errc(1, 0,
587 				    "Can't specify both -%c and -%c", opt,
588 				    bsdtar->create_compression);
589 			bsdtar->create_compression = opt;
590 			break;
591 		case OPTION_USE_COMPRESS_PROGRAM:
592 			bsdtar->compress_program = bsdtar->argument;
593 			break;
594 		default:
595 			usage();
596 		}
597 	}
598 
599 	/*
600 	 * Sanity-check options.
601 	 */
602 
603 	/* If no "real" mode was specified, treat -h as --help. */
604 	if ((bsdtar->mode == '\0') && possible_help_request) {
605 		long_help();
606 		exit(0);
607 	}
608 
609 	/* Otherwise, a mode is required. */
610 	if (bsdtar->mode == '\0')
611 		lafe_errc(1, 0,
612 		    "Must specify one of -c, -r, -t, -u, -x");
613 
614 	/* Check boolean options only permitted in certain modes. */
615 	if (bsdtar->option_dont_traverse_mounts)
616 		only_mode(bsdtar, "--one-file-system", "cru");
617 	if (bsdtar->option_fast_read)
618 		only_mode(bsdtar, "--fast-read", "xt");
619 	if (bsdtar->option_honor_nodump)
620 		only_mode(bsdtar, "--nodump", "cru");
621 	if (option_o > 0) {
622 		switch (bsdtar->mode) {
623 		case 'c':
624 			/*
625 			 * In GNU tar, -o means "old format."  The
626 			 * "ustar" format is the closest thing
627 			 * supported by libarchive.
628 			 */
629 			bsdtar->create_format = "ustar";
630 			/* TODO: bsdtar->create_format = "v7"; */
631 			break;
632 		case 'x':
633 			/* POSIX-compatible behavior. */
634 			bsdtar->option_no_owner = 1;
635 			bsdtar->extract_flags &= ~ARCHIVE_EXTRACT_OWNER;
636 			break;
637 		default:
638 			only_mode(bsdtar, "-o", "xc");
639 			break;
640 		}
641 	}
642 	if (bsdtar->option_no_subdirs)
643 		only_mode(bsdtar, "-n", "cru");
644 	if (bsdtar->option_stdout)
645 		only_mode(bsdtar, "-O", "xt");
646 	if (bsdtar->option_unlink_first)
647 		only_mode(bsdtar, "-U", "x");
648 	if (bsdtar->option_warn_links)
649 		only_mode(bsdtar, "--check-links", "cr");
650 
651 	/* Check other parameters only permitted in certain modes. */
652 	if (bsdtar->create_compression != '\0') {
653 		strcpy(buff, "-?");
654 		buff[1] = bsdtar->create_compression;
655 		only_mode(bsdtar, buff, "cxt");
656 	}
657 	if (bsdtar->create_format != NULL)
658 		only_mode(bsdtar, "--format", "cru");
659 	if (bsdtar->symlink_mode != '\0') {
660 		strcpy(buff, "-?");
661 		buff[1] = bsdtar->symlink_mode;
662 		only_mode(bsdtar, buff, "cru");
663 	}
664 
665 	/* Filename "-" implies stdio. */
666 	if (strcmp(bsdtar->filename, "-") == 0)
667 		bsdtar->filename = NULL;
668 
669 	switch(bsdtar->mode) {
670 	case 'c':
671 		tar_mode_c(bsdtar);
672 		break;
673 	case 'r':
674 		tar_mode_r(bsdtar);
675 		break;
676 	case 't':
677 		tar_mode_t(bsdtar);
678 		break;
679 	case 'u':
680 		tar_mode_u(bsdtar);
681 		break;
682 	case 'x':
683 		tar_mode_x(bsdtar);
684 		break;
685 	}
686 
687 	lafe_cleanup_exclusions(&bsdtar->matching);
688 #if HAVE_REGEX_H
689 	cleanup_substitution(bsdtar);
690 #endif
691 
692 	if (bsdtar->return_value != 0)
693 		lafe_warnc(0,
694 		    "Error exit delayed from previous errors.");
695 	return (bsdtar->return_value);
696 }
697 
698 static void
699 set_mode(struct bsdtar *bsdtar, char opt)
700 {
701 	if (bsdtar->mode != '\0' && bsdtar->mode != opt)
702 		lafe_errc(1, 0,
703 		    "Can't specify both -%c and -%c", opt, bsdtar->mode);
704 	bsdtar->mode = opt;
705 }
706 
707 /*
708  * Verify that the mode is correct.
709  */
710 static void
711 only_mode(struct bsdtar *bsdtar, const char *opt, const char *valid_modes)
712 {
713 	if (strchr(valid_modes, bsdtar->mode) == NULL)
714 		lafe_errc(1, 0,
715 		    "Option %s is not permitted in mode -%c",
716 		    opt, bsdtar->mode);
717 }
718 
719 
720 void
721 usage(void)
722 {
723 	const char	*p;
724 
725 	p = lafe_progname;
726 
727 	fprintf(stderr, "Usage:\n");
728 	fprintf(stderr, "  List:    %s -tf <archive-filename>\n", p);
729 	fprintf(stderr, "  Extract: %s -xf <archive-filename>\n", p);
730 	fprintf(stderr, "  Create:  %s -cf <archive-filename> [filenames...]\n", p);
731 	fprintf(stderr, "  Help:    %s --help\n", p);
732 	exit(1);
733 }
734 
735 static void
736 version(void)
737 {
738 	printf("bsdtar %s - %s\n",
739 	    BSDTAR_VERSION_STRING,
740 	    archive_version_string());
741 	exit(0);
742 }
743 
744 static const char *long_help_msg =
745 	"First option must be a mode specifier:\n"
746 	"  -c Create  -r Add/Replace  -t List  -u Update  -x Extract\n"
747 	"Common Options:\n"
748 	"  -b #  Use # 512-byte records per I/O block\n"
749 	"  -f <filename>  Location of archive (default " _PATH_DEFTAPE ")\n"
750 	"  -v    Verbose\n"
751 	"  -w    Interactive\n"
752 	"Create: %p -c [options] [<file> | <dir> | @<archive> | -C <dir> ]\n"
753 	"  <file>, <dir>  add these items to archive\n"
754 	"  -z, -j, -J, --lzma  Compress archive with gzip/bzip2/xz/lzma\n"
755 	"  --format {ustar|pax|cpio|shar}  Select archive format\n"
756 	"  --exclude <pattern>  Skip files that match pattern\n"
757 	"  -C <dir>  Change to <dir> before processing remaining files\n"
758 	"  @<archive>  Add entries from <archive> to output\n"
759 	"List: %p -t [options] [<patterns>]\n"
760 	"  <patterns>  If specified, list only entries that match\n"
761 	"Extract: %p -x [options] [<patterns>]\n"
762 	"  <patterns>  If specified, extract only entries that match\n"
763 	"  -k    Keep (don't overwrite) existing files\n"
764 	"  -m    Don't restore modification times\n"
765 	"  -O    Write entries to stdout, don't restore to disk\n"
766 	"  -p    Restore permissions (including ACLs, owner, file flags)\n";
767 
768 
769 /*
770  * Note that the word 'bsdtar' will always appear in the first line
771  * of output.
772  *
773  * In particular, /bin/sh scripts that need to test for the presence
774  * of bsdtar can use the following template:
775  *
776  * if (tar --help 2>&1 | grep bsdtar >/dev/null 2>&1 ) then \
777  *          echo bsdtar; else echo not bsdtar; fi
778  */
779 static void
780 long_help(void)
781 {
782 	const char	*prog;
783 	const char	*p;
784 
785 	prog = lafe_progname;
786 
787 	fflush(stderr);
788 
789 	p = (strcmp(prog,"bsdtar") != 0) ? "(bsdtar)" : "";
790 	printf("%s%s: manipulate archive files\n", prog, p);
791 
792 	for (p = long_help_msg; *p != '\0'; p++) {
793 		if (*p == '%') {
794 			if (p[1] == 'p') {
795 				fputs(prog, stdout);
796 				p++;
797 			} else
798 				putchar('%');
799 		} else
800 			putchar(*p);
801 	}
802 	version();
803 }
804