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