2 * Copyright (c) 2003-2004 Tim Kientzle
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer
10 * in this position and unchanged.
11 * 2. Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
15 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS OR
16 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
17 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
18 * IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY DIRECT, INDIRECT,
19 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
20 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
21 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
22 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
24 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27 #include "bsdtar_platform.h"
28 __FBSDID("$FreeBSD: src/usr.bin/tar/bsdtar.c,v 1.56 2004/10/17 23:58:17 kientzle Exp $");
30 #include <sys/param.h>
33 #include <archive_entry.h>
38 #ifdef HAVE_GETOPT_LONG
48 #define required_argument 1
50 #ifdef HAVE_LANGINFO_H
69 #define _PATH_DEFTAPE "/dev/st0"
73 #define _PATH_DEFTAPE "/dev/tape"
76 static int bsdtar_getopt(struct bsdtar *, const char *optstring,
77 const struct option **poption);
78 static void long_help(struct bsdtar *);
79 static void only_mode(struct bsdtar *, const char *opt,
81 static char ** rewrite_argv(struct bsdtar *,
82 int *argc, char ** src_argv,
83 const char *optstring);
84 static void set_mode(struct bsdtar *, char opt);
85 static void version(void);
88 * The leading '+' here forces the GNU version of getopt() (as well as
89 * both the GNU and BSD versions of getopt_long) to stop at the first
90 * non-option. Otherwise, GNU getopt() permutes the arguments and
91 * screws up -C processing.
93 static const char *tar_opts = "+Bb:C:cF:f:HhI:jkLlmnOoPprtT:UuvW:wX:xyZz";
96 * Most of these long options are deliberately not documented. They
97 * are provided only to make life easier for people who also use GNU tar.
98 * The only long options documented in the manual page are the ones
99 * with no corresponding short option, such as --exclude, --nodump,
102 * On systems that lack getopt_long, long options can be specified
103 * using -W longopt and -W longopt=value, e.g. "-W nodump" is the same
104 * as "--nodump" and "-W exclude=pattern" is the same as "--exclude
105 * pattern". This does not rely the GNU getopt() "W;" extension, so
106 * should work correctly on any system with a POSIX-compliant getopt().
109 /* Fake short equivalents for long options that otherwise lack them. */
110 #define OPTION_CHECK_LINKS 3
111 #define OPTION_EXCLUDE 6
112 #define OPTION_FAST_READ 9
113 #define OPTION_FORMAT 10
114 #define OPTION_HELP 12
115 #define OPTION_INCLUDE 15
116 #define OPTION_NODUMP 18
117 #define OPTION_NO_SAME_PERMISSIONS 21
118 #define OPTION_NULL 24
119 #define OPTION_ONE_FILE_SYSTEM 27
120 #define OPTION_TOTALS 28
121 #define OPTION_VERSION 30
123 static const struct option tar_longopts[] = {
124 { "absolute-paths", no_argument, NULL, 'P' },
125 { "append", no_argument, NULL, 'r' },
126 { "block-size", required_argument, NULL, 'b' },
127 { "bunzip2", no_argument, NULL, 'j' },
128 { "bzip", no_argument, NULL, 'j' },
129 { "bzip2", no_argument, NULL, 'j' },
130 { "cd", required_argument, NULL, 'C' },
131 { "check-links", no_argument, NULL, OPTION_CHECK_LINKS },
132 { "confirmation", no_argument, NULL, 'w' },
133 { "create", no_argument, NULL, 'c' },
134 { "dereference", no_argument, NULL, 'L' },
135 { "directory", required_argument, NULL, 'C' },
136 { "exclude", required_argument, NULL, OPTION_EXCLUDE },
137 { "exclude-from", required_argument, NULL, 'X' },
138 { "extract", no_argument, NULL, 'x' },
139 { "fast-read", no_argument, NULL, OPTION_FAST_READ },
140 { "file", required_argument, NULL, 'f' },
141 { "files-from", required_argument, NULL, 'T' },
142 { "format", required_argument, NULL, OPTION_FORMAT },
143 { "gunzip", no_argument, NULL, 'z' },
144 { "gzip", no_argument, NULL, 'z' },
145 { "help", no_argument, NULL, OPTION_HELP },
146 { "include", required_argument, NULL, OPTION_INCLUDE },
147 { "interactive", no_argument, NULL, 'w' },
148 { "keep-old-files", no_argument, NULL, 'k' },
149 { "list", no_argument, NULL, 't' },
150 { "modification-time", no_argument, NULL, 'm' },
151 { "nodump", no_argument, NULL, OPTION_NODUMP },
152 { "norecurse", no_argument, NULL, 'n' },
153 { "no-recursion", no_argument, NULL, 'n' },
154 { "no-same-owner", no_argument, NULL, 'o' },
155 { "no-same-permissions",no_argument, NULL, OPTION_NO_SAME_PERMISSIONS },
156 { "null", no_argument, NULL, OPTION_NULL },
157 { "one-file-system", no_argument, NULL, OPTION_ONE_FILE_SYSTEM },
158 { "preserve-permissions", no_argument, NULL, 'p' },
159 { "read-full-blocks", no_argument, NULL, 'B' },
160 { "same-permissions", no_argument, NULL, 'p' },
161 { "to-stdout", no_argument, NULL, 'O' },
162 { "totals", no_argument, NULL, OPTION_TOTALS },
163 { "unlink", no_argument, NULL, 'U' },
164 { "unlink-first", no_argument, NULL, 'U' },
165 { "update", no_argument, NULL, 'u' },
166 { "verbose", no_argument, NULL, 'v' },
167 { "version", no_argument, NULL, OPTION_VERSION },
172 main(int argc, char **argv)
174 struct bsdtar *bsdtar, bsdtar_storage;
175 const struct option *option;
178 char possible_help_request;
182 * Use a pointer for consistency, but stack-allocated storage
183 * for ease of cleanup.
185 bsdtar = &bsdtar_storage;
186 memset(bsdtar, 0, sizeof(*bsdtar));
187 bsdtar->fd = -1; /* Mark as "unused" */
190 if (setlocale(LC_ALL, "") == NULL)
191 bsdtar_warnc(bsdtar, 0, "Failed to set default locale");
192 #if defined(HAVE_NL_LANGINFO) && defined(HAVE_D_MD_ORDER)
193 bsdtar->day_first = (*nl_langinfo(D_MD_ORDER) == 'd');
195 possible_help_request = 0;
197 /* Look up uid of current user for future reference */
198 bsdtar->user_uid = geteuid();
200 /* Default: open tape drive. */
201 bsdtar->filename = getenv("TAPE");
202 if (bsdtar->filename == NULL)
203 bsdtar->filename = _PATH_DEFTAPE;
205 /* Default: preserve mod time on extract */
206 bsdtar->extract_flags = ARCHIVE_EXTRACT_TIME;
208 if (bsdtar->user_uid == 0)
209 bsdtar->extract_flags |= ARCHIVE_EXTRACT_OWNER;
212 bsdtar->progname = "bsdtar";
214 bsdtar->progname = strrchr(*argv, '/');
215 if (bsdtar->progname != NULL)
218 bsdtar->progname = *argv;
221 /* Rewrite traditional-style tar arguments, if used. */
222 argv = rewrite_argv(bsdtar, &argc, argv, tar_opts);
227 /* Process all remaining arguments now. */
228 while ((opt = bsdtar_getopt(bsdtar, tar_opts, &option)) != -1) {
230 case 'B': /* GNU tar */
231 /* libarchive doesn't need this; just ignore it. */
233 case 'b': /* SUSv2 */
235 if (t <= 0 || t > 1024)
236 bsdtar_errc(bsdtar, 1, 0,
237 "Argument to -b is out of range (1..1024)");
238 bsdtar->bytes_per_block = 512 * t;
240 case 'C': /* GNU tar */
241 set_chdir(bsdtar, optarg);
243 case 'c': /* SUSv2 */
244 set_mode(bsdtar, opt);
246 case OPTION_CHECK_LINKS: /* GNU tar */
247 bsdtar->option_warn_links = 1;
249 case OPTION_EXCLUDE: /* GNU tar */
250 if (exclude(bsdtar, optarg))
251 bsdtar_errc(bsdtar, 1, 0,
252 "Couldn't exclude %s\n", optarg);
255 bsdtar->create_format = optarg;
257 case 'f': /* SUSv2 */
258 bsdtar->filename = optarg;
259 if (strcmp(bsdtar->filename, "-") == 0)
260 bsdtar->filename = NULL;
262 case OPTION_FAST_READ: /* GNU tar */
263 bsdtar->option_fast_read = 1;
265 case 'H': /* BSD convention */
266 bsdtar->symlink_mode = 'H';
268 case 'h': /* Linux Standards Base, gtar; synonym for -L */
269 bsdtar->symlink_mode = 'L';
270 /* Hack: -h by itself is the "help" command. */
271 possible_help_request = 1;
277 case 'I': /* GNU tar */
278 bsdtar->names_from_file = optarg;
281 if (include(bsdtar, optarg))
282 bsdtar_errc(bsdtar, 1, 0,
283 "Failed to add %s to inclusion list",
286 case 'j': /* GNU tar */
288 if (bsdtar->create_compression != '\0')
289 bsdtar_errc(bsdtar, 1, 0,
290 "Can't specify both -%c and -%c", opt,
291 bsdtar->create_compression);
292 bsdtar->create_compression = opt;
294 bsdtar_warnc(bsdtar, 0, "-j compression not supported by this version of bsdtar");
298 case 'k': /* GNU tar */
299 bsdtar->extract_flags |= ARCHIVE_EXTRACT_NO_OVERWRITE;
301 case 'L': /* BSD convention */
302 bsdtar->symlink_mode = 'L';
304 case 'l': /* SUSv2 and GNU conflict badly here */
305 if (getenv("POSIXLY_CORRECT") != NULL) {
306 /* User has asked for POSIX/SUS behavior. */
307 bsdtar->option_warn_links = 1;
310 "Error: -l has different behaviors in different tar programs.\n");
312 " For the GNU behavior, use --one-file-system instead.\n");
314 " For the POSIX behavior, use --check-links instead.\n");
318 case 'm': /* SUSv2 */
319 bsdtar->extract_flags &= ~ARCHIVE_EXTRACT_TIME;
321 case 'n': /* GNU tar */
322 bsdtar->option_no_subdirs = 1;
324 case OPTION_NODUMP: /* star */
325 bsdtar->option_honor_nodump = 1;
327 case OPTION_NO_SAME_PERMISSIONS: /* GNU tar */
329 * This is always the default in FreeBSD's
330 * version of GNU tar; it's also the default
331 * behavior for bsdtar, so treat the
332 * command-line option as a no-op.
335 case OPTION_NULL: /* GNU tar */
336 bsdtar->option_null++;
338 case 'O': /* GNU tar */
339 bsdtar->option_stdout = 1;
341 case 'o': /* SUSv2 and GNU conflict here */
342 option_o = 1; /* Record it and resolve it later. */
344 case OPTION_ONE_FILE_SYSTEM: /* -l in GNU tar */
345 bsdtar->option_dont_traverse_mounts = 1;
349 * The common BSD -P option is not necessary, since
350 * our default is to archive symlinks, not follow
351 * them. This is convenient, as -P conflicts with GNU
354 case 'P': /* BSD convention */
355 /* Default behavior, no option necessary. */
358 case 'P': /* GNU tar */
359 bsdtar->option_absolute_paths = 1;
361 case 'p': /* GNU tar, star */
362 bsdtar->extract_flags |= ARCHIVE_EXTRACT_PERM;
363 bsdtar->extract_flags |= ARCHIVE_EXTRACT_ACL;
364 bsdtar->extract_flags |= ARCHIVE_EXTRACT_FFLAGS;
366 case 'r': /* SUSv2 */
367 set_mode(bsdtar, opt);
369 case 'T': /* GNU tar */
370 bsdtar->names_from_file = optarg;
372 case 't': /* SUSv2 */
373 set_mode(bsdtar, opt);
376 case OPTION_TOTALS: /* GNU tar */
377 bsdtar->option_totals++;
379 case 'U': /* GNU tar */
380 bsdtar->extract_flags |= ARCHIVE_EXTRACT_UNLINK;
381 bsdtar->option_unlink_first = 1;
383 case 'u': /* SUSv2 */
384 set_mode(bsdtar, opt);
386 case 'v': /* SUSv2 */
392 case 'w': /* SUSv2 */
393 bsdtar->option_interactive = 1;
395 case 'X': /* GNU tar */
396 if (exclude_from_file(bsdtar, optarg))
397 bsdtar_errc(bsdtar, 1, 0,
398 "failed to process exclusions from file %s",
401 case 'x': /* SUSv2 */
402 set_mode(bsdtar, opt);
404 case 'y': /* FreeBSD version of GNU tar */
406 if (bsdtar->create_compression != '\0')
407 bsdtar_errc(bsdtar, 1, 0,
408 "Can't specify both -%c and -%c", opt,
409 bsdtar->create_compression);
410 bsdtar->create_compression = opt;
412 bsdtar_warnc(bsdtar, 0, "-y compression not supported by this version of bsdtar");
416 case 'Z': /* GNU tar */
417 if (bsdtar->create_compression != '\0')
418 bsdtar_errc(bsdtar, 1, 0,
419 "Can't specify both -%c and -%c", opt,
420 bsdtar->create_compression);
421 bsdtar->create_compression = opt;
423 case 'z': /* GNU tar, star, many others */
425 if (bsdtar->create_compression != '\0')
426 bsdtar_errc(bsdtar, 1, 0,
427 "Can't specify both -%c and -%c", opt,
428 bsdtar->create_compression);
429 bsdtar->create_compression = opt;
431 bsdtar_warnc(bsdtar, 0, "-z compression not supported by this version of bsdtar");
441 * Sanity-check options.
443 if ((bsdtar->mode == '\0') && possible_help_request) {
448 if (bsdtar->mode == '\0')
449 bsdtar_errc(bsdtar, 1, 0,
450 "Must specify one of -c, -r, -t, -u, -x");
452 /* Check boolean options only permitted in certain modes. */
453 if (bsdtar->option_dont_traverse_mounts)
454 only_mode(bsdtar, "-X", "cru");
455 if (bsdtar->option_fast_read)
456 only_mode(bsdtar, "--fast-read", "xt");
457 if (bsdtar->option_honor_nodump)
458 only_mode(bsdtar, "--nodump", "cru");
460 switch (bsdtar->mode) {
463 * In GNU tar, -o means "old format." The
464 * "ustar" format is the closest thing
465 * supported by libarchive.
467 bsdtar->create_format = "ustar";
468 /* TODO: bsdtar->create_format = "v7"; */
471 /* POSIX-compatible behavior. */
472 bsdtar->option_no_owner = 1;
473 bsdtar->extract_flags &= ~ARCHIVE_EXTRACT_OWNER;
476 only_mode(bsdtar, "-o", "xc");
480 if (bsdtar->option_no_subdirs)
481 only_mode(bsdtar, "-n", "cru");
482 if (bsdtar->option_stdout)
483 only_mode(bsdtar, "-O", "xt");
484 if (bsdtar->option_warn_links)
485 only_mode(bsdtar, "--check-links", "cr");
487 /* Check other parameters only permitted in certain modes. */
488 if (bsdtar->create_compression == 'Z' && bsdtar->mode == 'c') {
489 bsdtar_warnc(bsdtar, 0, ".Z compression not supported");
492 if (bsdtar->create_compression != '\0') {
494 buff[1] = bsdtar->create_compression;
495 only_mode(bsdtar, buff, "cxt");
497 if (bsdtar->create_format != NULL)
498 only_mode(bsdtar, "-F", "c");
499 if (bsdtar->symlink_mode != '\0') {
501 buff[1] = bsdtar->symlink_mode;
502 only_mode(bsdtar, buff, "cru");
505 bsdtar->argc -= optind;
506 bsdtar->argv += optind;
508 switch(bsdtar->mode) {
526 cleanup_exclusions(bsdtar);
527 return (bsdtar->return_value);
531 set_mode(struct bsdtar *bsdtar, char opt)
533 if (bsdtar->mode != '\0' && bsdtar->mode != opt)
534 bsdtar_errc(bsdtar, 1, 0,
535 "Can't specify both -%c and -%c", opt, bsdtar->mode);
540 * Verify that the mode is correct.
543 only_mode(struct bsdtar *bsdtar, const char *opt, const char *valid_modes)
545 if (strchr(valid_modes, bsdtar->mode) == NULL)
546 bsdtar_errc(bsdtar, 1, 0,
547 "Option %s is not permitted in mode -%c",
553 * Convert traditional tar arguments into new-style.
555 * tar tvfb file.tar 32 --exclude FOO
556 * will be converted to
557 * tar -t -v -f file.tar -b 32 --exclude FOO
559 * This requires building a new argv array. The initial bundled word
560 * gets expanded into a new string that looks like "-t\0-v\0-f\0-b\0".
561 * The new argv array has pointers into this string intermingled with
562 * pointers to the existing arguments. Arguments are moved to
563 * immediately follow their options.
565 * The optstring argument here is the same one passed to getopt(3).
566 * It is used to determine which option letters have trailing arguments.
569 rewrite_argv(struct bsdtar *bsdtar, int *argc, char **src_argv,
570 const char *optstring)
572 char **new_argv, **dest_argv;
576 if (src_argv[0] == NULL ||
577 src_argv[1] == NULL || src_argv[1][0] == '-')
580 *argc += strlen(src_argv[1]) - 1;
581 new_argv = malloc((*argc + 1) * sizeof(new_argv[0]));
582 if (new_argv == NULL)
583 bsdtar_errc(bsdtar, 1, errno, "No Memory");
585 dest_argv = new_argv;
586 *dest_argv++ = *src_argv++;
588 dest = malloc(strlen(*src_argv) * 3);
590 bsdtar_errc(bsdtar, 1, errno, "No memory");
591 for (src = *src_argv++; *src != '\0'; src++) {
596 /* If option takes an argument, insert that into the list. */
597 for (p = optstring; p != NULL && *p != '\0'; p++) {
600 if (p[1] != ':') /* No arg required, done. */
602 if (*src_argv == NULL) /* No arg available? Error. */
603 bsdtar_errc(bsdtar, 1, 0,
604 "Option %c requires an argument",
606 *dest_argv++ = *src_argv++;
611 /* Copy remaining arguments, including trailing NULL. */
612 while ((*dest_argv++ = *src_argv++) != NULL)
619 usage(struct bsdtar *bsdtar)
623 p = bsdtar->progname;
625 fprintf(stderr, "Usage:\n");
626 fprintf(stderr, " List: %s -tf <archive-filename>\n", p);
627 fprintf(stderr, " Extract: %s -xf <archive-filename>\n", p);
628 fprintf(stderr, " Create: %s -cf <archive-filename> [filenames...]\n", p);
629 #ifdef HAVE_GETOPT_LONG
630 fprintf(stderr, " Help: %s --help\n", p);
632 fprintf(stderr, " Help: %s -h\n", p);
640 printf("bsdtar %s, ", PACKAGE_VERSION);
641 printf("%s\n", archive_version());
642 printf("Copyright (C) 2003-2004 Tim Kientzle\n");
646 static const char *long_help_msg =
647 "First option must be a mode specifier:\n"
648 " -c Create -r Add/Replace -t List -u Update -x Extract\n"
650 " -b # Use # 512-byte records per I/O block\n"
651 " -f <filename> Location of archive (default " _PATH_DEFTAPE ")\n"
654 "Create: %p -c [options] [<file> | <dir> | @<archive> | -C <dir> ]\n"
655 " <file>, <dir> add these items to archive\n"
656 " -z, -j Compress archive with gzip/bzip2\n"
657 " --format {ustar|pax|cpio|shar} Select archive format\n"
658 #ifdef HAVE_GETOPT_LONG
659 " --exclude <pattern> Skip files that match pattern\n"
661 " -W exclude=<pattern> Skip files that match pattern\n"
663 " -C <dir> Change to <dir> before processing remaining files\n"
664 " @<archive> Add entries from <archive> to output\n"
665 "List: %p -t [options] [<patterns>]\n"
666 " <patterns> If specified, list only entries that match\n"
667 "Extract: %p -x [options] [<patterns>]\n"
668 " <patterns> If specified, extract only entries that match\n"
669 " -k Keep (don't overwrite) existing files\n"
670 " -m Don't restore modification times\n"
671 " -O Write entries to stdout, don't restore to disk\n"
672 " -p Restore permissions (including ACLs, owner, file flags)\n";
676 * Note that the word 'bsdtar' will always appear in the first line
679 * In particular, /bin/sh scripts that need to test for the presence
680 * of bsdtar can use the following template:
682 * if (tar --help 2>&1 | grep bsdtar >/dev/null 2>&1 ) then \
683 * echo bsdtar; else echo not bsdtar; fi
686 long_help(struct bsdtar *bsdtar)
691 prog = bsdtar->progname;
695 p = (strcmp(prog,"bsdtar") != 0) ? "(bsdtar)" : "";
696 printf("%s%s: manipulate archive files\n", prog, p);
698 for (p = long_help_msg; *p != '\0'; p++) {
708 fprintf(stdout, "\n%s %s\n", PACKAGE_NAME, PACKAGE_VERSION);
709 fprintf(stdout, "%s\n", archive_version());
713 bsdtar_getopt(struct bsdtar *bsdtar, const char *optstring,
714 const struct option **poption)
717 const struct option *option;
720 size_t option_length;
725 #ifdef HAVE_GETOPT_LONG
726 opt = getopt_long(bsdtar->argc, bsdtar->argv, optstring,
727 tar_longopts, &option_index);
728 if (option_index > -1)
729 *poption = tar_longopts + option_index;
731 opt = getopt(bsdtar->argc, bsdtar->argv, optstring);
734 /* Support long options through -W longopt=value */
737 q = strchr(optarg, '=');
739 option_length = (size_t)(q - p);
742 option_length = strlen(p);
745 option = tar_longopts;
746 while (option->name != NULL &&
747 (strlen(option->name) < option_length ||
748 strncmp(p, option->name, option_length) != 0 )) {
752 if (option->name != NULL) {
756 /* Check if there's another match. */
758 while (option->name != NULL &&
759 (strlen(option->name) < option_length ||
760 strncmp(p, option->name, option_length) != 0)) {
763 if (option->name != NULL)
764 bsdtar_errc(bsdtar, 1, 0,
765 "Ambiguous option %s "
766 "(matches both %s and %s)",
767 p, (*poption)->name, option->name);
771 /* TODO: Set up a fake 'struct option' for
772 * error reporting... ? ? ? */