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