Import libarchive and bsdtar version 2.0.25
[dragonfly/port-amd64.git] / contrib / libarchive-2.0 / tar / bsdtar.c
blob6e6ac9f3f7a80f08f07d31583b9ccab6dafaa845
1 /*-
2 * Copyright (c) 2003-2007 Tim Kientzle
3 * All rights reserved.
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.
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.
26 #include "bsdtar_platform.h"
27 __FBSDID("$FreeBSD: src/usr.bin/tar/bsdtar.c,v 1.73 2007/03/11 10:36:42 kientzle Exp $");
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_ERRNO_H
36 #include <errno.h>
37 #endif
38 #ifdef HAVE_FCNTL_H
39 #include <fcntl.h>
40 #endif
41 #ifdef HAVE_GETOPT_LONG
42 #include <getopt.h>
43 #else
44 struct option {
45 const char *name;
46 int has_arg;
47 int *flag;
48 int val;
50 #define no_argument 0
51 #define required_argument 1
52 #endif
53 #ifdef HAVE_LANGINFO_H
54 #include <langinfo.h>
55 #endif
56 #ifdef HAVE_LOCALE_H
57 #include <locale.h>
58 #endif
59 #ifdef HAVE_PATHS_H
60 #include <paths.h>
61 #endif
62 #include <stdio.h>
63 #ifdef HAVE_STDLIB_H
64 #include <stdlib.h>
65 #endif
66 #ifdef HAVE_STRING_H
67 #include <string.h>
68 #endif
69 #ifdef HAVE_TIME_H
70 #include <time.h>
71 #endif
72 #ifdef HAVE_UNISTD_H
73 #include <unistd.h>
74 #endif
75 #if HAVE_ZLIB_H
76 #include <zlib.h>
77 #endif
79 #include "bsdtar.h"
82 * Per POSIX.1-1988, tar defaults to reading/writing archives to/from
83 * the default tape device for the system. Pick something reasonable here.
85 #ifdef __linux
86 #define _PATH_DEFTAPE "/dev/st0"
87 #endif
89 #ifndef _PATH_DEFTAPE
90 #define _PATH_DEFTAPE "/dev/tape"
91 #endif
93 /* External function to parse a date/time string (from getdate.y) */
94 time_t get_date(const char *);
96 static int bsdtar_getopt(struct bsdtar *, const char *optstring,
97 const struct option **poption);
98 static void long_help(struct bsdtar *);
99 static void only_mode(struct bsdtar *, const char *opt,
100 const char *valid);
101 static char ** rewrite_argv(struct bsdtar *,
102 int *argc, char ** src_argv,
103 const char *optstring);
104 static void set_mode(struct bsdtar *, char opt);
105 static void version(void);
108 * The leading '+' here forces the GNU version of getopt() (as well as
109 * both the GNU and BSD versions of getopt_long) to stop at the first
110 * non-option. Otherwise, GNU getopt() permutes the arguments and
111 * screws up -C processing.
113 static const char *tar_opts = "+Bb:C:cf:HhI:jkLlmnOoPprtT:UuvW:wX:xyZz";
116 * Most of these long options are deliberately not documented. They
117 * are provided only to make life easier for people who also use GNU tar.
118 * The only long options documented in the manual page are the ones
119 * with no corresponding short option, such as --exclude, --nodump,
120 * and --fast-read.
122 * On systems that lack getopt_long, long options can be specified
123 * using -W longopt and -W longopt=value, e.g. "-W nodump" is the same
124 * as "--nodump" and "-W exclude=pattern" is the same as "--exclude
125 * pattern". This does not rely the GNU getopt() "W;" extension, so
126 * should work correctly on any system with a POSIX-compliant getopt().
129 /* Fake short equivalents for long options that otherwise lack them. */
130 enum {
131 OPTION_CHECK_LINKS=1,
132 OPTION_EXCLUDE,
133 OPTION_FAST_READ,
134 OPTION_FORMAT,
135 OPTION_HELP,
136 OPTION_INCLUDE,
137 OPTION_NEWER_CTIME,
138 OPTION_NEWER_CTIME_THAN,
139 OPTION_NEWER_MTIME,
140 OPTION_NEWER_MTIME_THAN,
141 OPTION_NODUMP,
142 OPTION_NO_SAME_OWNER,
143 OPTION_NO_SAME_PERMISSIONS,
144 OPTION_NULL,
145 OPTION_ONE_FILE_SYSTEM,
146 OPTION_STRIP_COMPONENTS,
147 OPTION_TOTALS,
148 OPTION_VERSION
152 * If you add anything, be very careful to keep this list properly
153 * sorted, as the -W logic relies on it.
155 static const struct option tar_longopts[] = {
156 { "absolute-paths", no_argument, NULL, 'P' },
157 { "append", no_argument, NULL, 'r' },
158 { "block-size", required_argument, NULL, 'b' },
159 { "bunzip2", no_argument, NULL, 'j' },
160 { "bzip", no_argument, NULL, 'j' },
161 { "bzip2", no_argument, NULL, 'j' },
162 { "cd", required_argument, NULL, 'C' },
163 { "check-links", no_argument, NULL, OPTION_CHECK_LINKS },
164 { "confirmation", no_argument, NULL, 'w' },
165 { "create", no_argument, NULL, 'c' },
166 { "dereference", no_argument, NULL, 'L' },
167 { "directory", required_argument, NULL, 'C' },
168 { "exclude", required_argument, NULL, OPTION_EXCLUDE },
169 { "exclude-from", required_argument, NULL, 'X' },
170 { "extract", no_argument, NULL, 'x' },
171 { "fast-read", no_argument, NULL, OPTION_FAST_READ },
172 { "file", required_argument, NULL, 'f' },
173 { "files-from", required_argument, NULL, 'T' },
174 { "format", required_argument, NULL, OPTION_FORMAT },
175 { "gunzip", no_argument, NULL, 'z' },
176 { "gzip", no_argument, NULL, 'z' },
177 { "help", no_argument, NULL, OPTION_HELP },
178 { "include", required_argument, NULL, OPTION_INCLUDE },
179 { "interactive", no_argument, NULL, 'w' },
180 { "keep-old-files", no_argument, NULL, 'k' },
181 { "list", no_argument, NULL, 't' },
182 { "modification-time", no_argument, NULL, 'm' },
183 { "newer", required_argument, NULL, OPTION_NEWER_CTIME },
184 { "newer-ctime", required_argument, NULL, OPTION_NEWER_CTIME },
185 { "newer-ctime-than", required_argument, NULL, OPTION_NEWER_CTIME_THAN },
186 { "newer-mtime", required_argument, NULL, OPTION_NEWER_MTIME },
187 { "newer-mtime-than", required_argument, NULL, OPTION_NEWER_MTIME_THAN },
188 { "newer-than", required_argument, NULL, OPTION_NEWER_CTIME_THAN },
189 { "nodump", no_argument, NULL, OPTION_NODUMP },
190 { "norecurse", no_argument, NULL, 'n' },
191 { "no-recursion", no_argument, NULL, 'n' },
192 { "no-same-owner", no_argument, NULL, OPTION_NO_SAME_OWNER },
193 { "no-same-permissions",no_argument, NULL, OPTION_NO_SAME_PERMISSIONS },
194 { "null", no_argument, NULL, OPTION_NULL },
195 { "one-file-system", no_argument, NULL, OPTION_ONE_FILE_SYSTEM },
196 { "preserve-permissions", no_argument, NULL, 'p' },
197 { "read-full-blocks", no_argument, NULL, 'B' },
198 { "same-permissions", no_argument, NULL, 'p' },
199 { "strip-components", required_argument, NULL, OPTION_STRIP_COMPONENTS },
200 { "to-stdout", no_argument, NULL, 'O' },
201 { "totals", no_argument, NULL, OPTION_TOTALS },
202 { "unlink", no_argument, NULL, 'U' },
203 { "unlink-first", no_argument, NULL, 'U' },
204 { "update", no_argument, NULL, 'u' },
205 { "verbose", no_argument, NULL, 'v' },
206 { "version", no_argument, NULL, OPTION_VERSION },
207 { NULL, 0, NULL, 0 }
210 /* A basic set of security flags to request from libarchive. */
211 #define SECURITY \
212 (ARCHIVE_EXTRACT_SECURE_SYMLINKS \
213 | ARCHIVE_EXTRACT_SECURE_NODOTDOT)
216 main(int argc, char **argv)
218 struct bsdtar *bsdtar, bsdtar_storage;
219 const struct option *option;
220 int opt, t;
221 char option_o;
222 char possible_help_request;
223 char buff[16];
226 * Use a pointer for consistency, but stack-allocated storage
227 * for ease of cleanup.
229 bsdtar = &bsdtar_storage;
230 memset(bsdtar, 0, sizeof(*bsdtar));
231 bsdtar->fd = -1; /* Mark as "unused" */
232 option_o = 0;
234 /* Need bsdtar->progname before calling bsdtar_warnc. */
235 if (*argv == NULL)
236 bsdtar->progname = "bsdtar";
237 else {
238 bsdtar->progname = strrchr(*argv, '/');
239 if (bsdtar->progname != NULL)
240 bsdtar->progname++;
241 else
242 bsdtar->progname = *argv;
245 if (setlocale(LC_ALL, "") == NULL)
246 bsdtar_warnc(bsdtar, 0, "Failed to set default locale");
247 #if defined(HAVE_NL_LANGINFO) && defined(HAVE_D_MD_ORDER)
248 bsdtar->day_first = (*nl_langinfo(D_MD_ORDER) == 'd');
249 #endif
250 possible_help_request = 0;
252 /* Look up uid of current user for future reference */
253 bsdtar->user_uid = geteuid();
255 /* Default: open tape drive. */
256 bsdtar->filename = getenv("TAPE");
257 if (bsdtar->filename == NULL)
258 bsdtar->filename = _PATH_DEFTAPE;
260 /* Default: preserve mod time on extract */
261 bsdtar->extract_flags = ARCHIVE_EXTRACT_TIME;
263 /* Default: Perform basic security checks. */
264 bsdtar->extract_flags |= SECURITY;
266 /* Defaults for root user: */
267 if (bsdtar->user_uid == 0) {
268 /* --same-owner */
269 bsdtar->extract_flags |= ARCHIVE_EXTRACT_OWNER;
270 /* -p */
271 bsdtar->extract_flags |= ARCHIVE_EXTRACT_PERM;
272 bsdtar->extract_flags |= ARCHIVE_EXTRACT_ACL;
273 bsdtar->extract_flags |= ARCHIVE_EXTRACT_XATTR;
274 bsdtar->extract_flags |= ARCHIVE_EXTRACT_FFLAGS;
277 /* Rewrite traditional-style tar arguments, if used. */
278 argv = rewrite_argv(bsdtar, &argc, argv, tar_opts);
280 bsdtar->argv = argv;
281 bsdtar->argc = argc;
283 /* Process all remaining arguments now. */
285 * Comments following each option indicate where that option
286 * originated: SUSv2, POSIX, GNU tar, star, etc. If there's
287 * no such comment, then I don't know of anyone else who
288 * implements that option.
290 while ((opt = bsdtar_getopt(bsdtar, tar_opts, &option)) != -1) {
291 switch (opt) {
292 case 'B': /* GNU tar */
293 /* libarchive doesn't need this; just ignore it. */
294 break;
295 case 'b': /* SUSv2 */
296 t = atoi(optarg);
297 if (t <= 0 || t > 1024)
298 bsdtar_errc(bsdtar, 1, 0,
299 "Argument to -b is out of range (1..1024)");
300 bsdtar->bytes_per_block = 512 * t;
301 break;
302 case 'C': /* GNU tar */
303 set_chdir(bsdtar, optarg);
304 break;
305 case 'c': /* SUSv2 */
306 set_mode(bsdtar, opt);
307 break;
308 case OPTION_CHECK_LINKS: /* GNU tar */
309 bsdtar->option_warn_links = 1;
310 break;
311 case OPTION_EXCLUDE: /* GNU tar */
312 if (exclude(bsdtar, optarg))
313 bsdtar_errc(bsdtar, 1, 0,
314 "Couldn't exclude %s\n", optarg);
315 break;
316 case OPTION_FORMAT: /* GNU tar, others */
317 bsdtar->create_format = optarg;
318 break;
319 case 'f': /* SUSv2 */
320 bsdtar->filename = optarg;
321 if (strcmp(bsdtar->filename, "-") == 0)
322 bsdtar->filename = NULL;
323 break;
324 case OPTION_FAST_READ: /* GNU tar */
325 bsdtar->option_fast_read = 1;
326 break;
327 case 'H': /* BSD convention */
328 bsdtar->symlink_mode = 'H';
329 break;
330 case 'h': /* Linux Standards Base, gtar; synonym for -L */
331 bsdtar->symlink_mode = 'L';
332 /* Hack: -h by itself is the "help" command. */
333 possible_help_request = 1;
334 break;
335 case OPTION_HELP: /* GNU tar, others */
336 long_help(bsdtar);
337 exit(0);
338 break;
339 case 'I': /* GNU tar */
341 * TODO: Allow 'names' to come from an archive,
342 * not just a text file. Design a good UI for
343 * allowing names and mode/owner to be read
344 * from an archive, with contents coming from
345 * disk. This can be used to "refresh" an
346 * archive or to design archives with special
347 * permissions without having to create those
348 * permissions on disk.
350 bsdtar->names_from_file = optarg;
351 break;
352 case OPTION_INCLUDE:
354 * Noone else has the @archive extension, so
355 * noone else needs this to filter entries
356 * when transforming archives.
358 if (include(bsdtar, optarg))
359 bsdtar_errc(bsdtar, 1, 0,
360 "Failed to add %s to inclusion list",
361 optarg);
362 break;
363 case 'j': /* GNU tar */
364 #if HAVE_LIBBZ2
365 if (bsdtar->create_compression != '\0')
366 bsdtar_errc(bsdtar, 1, 0,
367 "Can't specify both -%c and -%c", opt,
368 bsdtar->create_compression);
369 bsdtar->create_compression = opt;
370 #else
371 bsdtar_warnc(bsdtar, 0, "-j compression not supported by this version of bsdtar");
372 usage(bsdtar);
373 #endif
374 break;
375 case 'k': /* GNU tar */
376 bsdtar->extract_flags |= ARCHIVE_EXTRACT_NO_OVERWRITE;
377 break;
378 case 'L': /* BSD convention */
379 bsdtar->symlink_mode = 'L';
380 break;
381 case 'l': /* SUSv2 and GNU conflict badly here */
382 if (getenv("POSIXLY_CORRECT") != NULL) {
383 /* User has asked for POSIX/SUS behavior. */
384 bsdtar->option_warn_links = 1;
385 } else {
386 fprintf(stderr,
387 "Error: -l has different behaviors in different tar programs.\n");
388 fprintf(stderr,
389 " For the GNU behavior, use --one-file-system instead.\n");
390 fprintf(stderr,
391 " For the POSIX behavior, use --check-links instead.\n");
392 usage(bsdtar);
394 break;
395 case 'm': /* SUSv2 */
396 bsdtar->extract_flags &= ~ARCHIVE_EXTRACT_TIME;
397 break;
398 case 'n': /* GNU tar */
399 bsdtar->option_no_subdirs = 1;
400 break;
402 * Selecting files by time:
403 * --newer-?time='date' Only files newer than 'date'
404 * --newer-?time-than='file' Only files newer than time
405 * on specified file (useful for incremental backups)
406 * TODO: Add corresponding "older" options to reverse these.
408 case OPTION_NEWER_CTIME: /* GNU tar */
409 bsdtar->newer_ctime_sec = get_date(optarg);
410 break;
411 case OPTION_NEWER_CTIME_THAN:
413 struct stat st;
414 if (stat(optarg, &st) != 0)
415 bsdtar_errc(bsdtar, 1, 0,
416 "Can't open file %s", optarg);
417 bsdtar->newer_ctime_sec = st.st_ctime;
418 bsdtar->newer_ctime_nsec =
419 ARCHIVE_STAT_CTIME_NANOS(&st);
421 break;
422 case OPTION_NEWER_MTIME: /* GNU tar */
423 bsdtar->newer_mtime_sec = get_date(optarg);
424 break;
425 case OPTION_NEWER_MTIME_THAN:
427 struct stat st;
428 if (stat(optarg, &st) != 0)
429 bsdtar_errc(bsdtar, 1, 0,
430 "Can't open file %s", optarg);
431 bsdtar->newer_mtime_sec = st.st_mtime;
432 bsdtar->newer_mtime_nsec =
433 ARCHIVE_STAT_MTIME_NANOS(&st);
435 break;
436 case OPTION_NODUMP: /* star */
437 bsdtar->option_honor_nodump = 1;
438 break;
439 case OPTION_NO_SAME_OWNER: /* GNU tar */
440 bsdtar->extract_flags &= ~ARCHIVE_EXTRACT_OWNER;
441 break;
442 case OPTION_NO_SAME_PERMISSIONS: /* GNU tar */
443 bsdtar->extract_flags &= ~ARCHIVE_EXTRACT_PERM;
444 bsdtar->extract_flags &= ~ARCHIVE_EXTRACT_ACL;
445 bsdtar->extract_flags &= ~ARCHIVE_EXTRACT_XATTR;
446 bsdtar->extract_flags &= ~ARCHIVE_EXTRACT_FFLAGS;
447 break;
448 case OPTION_NULL: /* GNU tar */
449 bsdtar->option_null++;
450 break;
451 case 'O': /* GNU tar */
452 bsdtar->option_stdout = 1;
453 break;
454 case 'o': /* SUSv2 and GNU conflict here, but not fatally */
455 option_o = 1; /* Record it and resolve it later. */
456 break;
457 case OPTION_ONE_FILE_SYSTEM: /* GNU tar */
458 bsdtar->option_dont_traverse_mounts = 1;
459 break;
460 #if 0
462 * The common BSD -P option is not necessary, since
463 * our default is to archive symlinks, not follow
464 * them. This is convenient, as -P conflicts with GNU
465 * tar anyway.
467 case 'P': /* BSD convention */
468 /* Default behavior, no option necessary. */
469 break;
470 #endif
471 case 'P': /* GNU tar */
472 bsdtar->extract_flags &= ~SECURITY;
473 bsdtar->option_absolute_paths = 1;
474 break;
475 case 'p': /* GNU tar, star */
476 bsdtar->extract_flags |= ARCHIVE_EXTRACT_PERM;
477 bsdtar->extract_flags |= ARCHIVE_EXTRACT_ACL;
478 bsdtar->extract_flags |= ARCHIVE_EXTRACT_XATTR;
479 bsdtar->extract_flags |= ARCHIVE_EXTRACT_FFLAGS;
480 break;
481 case 'r': /* SUSv2 */
482 set_mode(bsdtar, opt);
483 break;
484 case OPTION_STRIP_COMPONENTS: /* GNU tar 1.15 */
485 bsdtar->strip_components = atoi(optarg);
486 break;
487 case 'T': /* GNU tar */
488 bsdtar->names_from_file = optarg;
489 break;
490 case 't': /* SUSv2 */
491 set_mode(bsdtar, opt);
492 bsdtar->verbose++;
493 break;
494 case OPTION_TOTALS: /* GNU tar */
495 bsdtar->option_totals++;
496 break;
497 case 'U': /* GNU tar */
498 bsdtar->extract_flags |= ARCHIVE_EXTRACT_UNLINK;
499 bsdtar->option_unlink_first = 1;
500 break;
501 case 'u': /* SUSv2 */
502 set_mode(bsdtar, opt);
503 break;
504 case 'v': /* SUSv2 */
505 bsdtar->verbose++;
506 break;
507 case OPTION_VERSION: /* GNU convention */
508 version();
509 break;
510 #if 0
512 * The -W longopt feature is handled inside of
513 * bsdtar_getop(), so -W is not available here.
515 case 'W': /* Obscure, but useful GNU convention. */
516 break;
517 #endif
518 case 'w': /* SUSv2 */
519 bsdtar->option_interactive = 1;
520 break;
521 case 'X': /* GNU tar */
522 if (exclude_from_file(bsdtar, optarg))
523 bsdtar_errc(bsdtar, 1, 0,
524 "failed to process exclusions from file %s",
525 optarg);
526 break;
527 case 'x': /* SUSv2 */
528 set_mode(bsdtar, opt);
529 break;
530 case 'y': /* FreeBSD version of GNU tar */
531 #if HAVE_LIBBZ2
532 if (bsdtar->create_compression != '\0')
533 bsdtar_errc(bsdtar, 1, 0,
534 "Can't specify both -%c and -%c", opt,
535 bsdtar->create_compression);
536 bsdtar->create_compression = opt;
537 #else
538 bsdtar_warnc(bsdtar, 0, "-y compression not supported by this version of bsdtar");
539 usage(bsdtar);
540 #endif
541 break;
542 case 'Z': /* GNU tar */
543 if (bsdtar->create_compression != '\0')
544 bsdtar_errc(bsdtar, 1, 0,
545 "Can't specify both -%c and -%c", opt,
546 bsdtar->create_compression);
547 bsdtar->create_compression = opt;
548 break;
549 case 'z': /* GNU tar, star, many others */
550 #if HAVE_LIBZ
551 if (bsdtar->create_compression != '\0')
552 bsdtar_errc(bsdtar, 1, 0,
553 "Can't specify both -%c and -%c", opt,
554 bsdtar->create_compression);
555 bsdtar->create_compression = opt;
556 #else
557 bsdtar_warnc(bsdtar, 0, "-z compression not supported by this version of bsdtar");
558 usage(bsdtar);
559 #endif
560 break;
561 default:
562 usage(bsdtar);
567 * Sanity-check options.
570 /* If no "real" mode was specified, treat -h as --help. */
571 if ((bsdtar->mode == '\0') && possible_help_request) {
572 long_help(bsdtar);
573 exit(0);
576 /* Otherwise, a mode is required. */
577 if (bsdtar->mode == '\0')
578 bsdtar_errc(bsdtar, 1, 0,
579 "Must specify one of -c, -r, -t, -u, -x");
581 /* Check boolean options only permitted in certain modes. */
582 if (bsdtar->option_dont_traverse_mounts)
583 only_mode(bsdtar, "--one-file-system", "cru");
584 if (bsdtar->option_fast_read)
585 only_mode(bsdtar, "--fast-read", "xt");
586 if (bsdtar->option_honor_nodump)
587 only_mode(bsdtar, "--nodump", "cru");
588 if (option_o > 0) {
589 switch (bsdtar->mode) {
590 case 'c':
592 * In GNU tar, -o means "old format." The
593 * "ustar" format is the closest thing
594 * supported by libarchive.
596 bsdtar->create_format = "ustar";
597 /* TODO: bsdtar->create_format = "v7"; */
598 break;
599 case 'x':
600 /* POSIX-compatible behavior. */
601 bsdtar->option_no_owner = 1;
602 bsdtar->extract_flags &= ~ARCHIVE_EXTRACT_OWNER;
603 break;
604 default:
605 only_mode(bsdtar, "-o", "xc");
606 break;
609 if (bsdtar->option_no_subdirs)
610 only_mode(bsdtar, "-n", "cru");
611 if (bsdtar->option_stdout)
612 only_mode(bsdtar, "-O", "xt");
613 if (bsdtar->option_unlink_first)
614 only_mode(bsdtar, "-U", "x");
615 if (bsdtar->option_warn_links)
616 only_mode(bsdtar, "--check-links", "cr");
618 /* Check other parameters only permitted in certain modes. */
619 if (bsdtar->create_compression == 'Z' && bsdtar->mode == 'c') {
620 bsdtar_warnc(bsdtar, 0, ".Z compression not supported");
621 usage(bsdtar);
623 if (bsdtar->create_compression != '\0') {
624 strcpy(buff, "-?");
625 buff[1] = bsdtar->create_compression;
626 only_mode(bsdtar, buff, "cxt");
628 if (bsdtar->create_format != NULL)
629 only_mode(bsdtar, "--format", "c");
630 if (bsdtar->symlink_mode != '\0') {
631 strcpy(buff, "-?");
632 buff[1] = bsdtar->symlink_mode;
633 only_mode(bsdtar, buff, "cru");
635 if (bsdtar->strip_components != 0)
636 only_mode(bsdtar, "--strip-components", "xt");
638 bsdtar->argc -= optind;
639 bsdtar->argv += optind;
641 switch(bsdtar->mode) {
642 case 'c':
643 tar_mode_c(bsdtar);
644 break;
645 case 'r':
646 tar_mode_r(bsdtar);
647 break;
648 case 't':
649 tar_mode_t(bsdtar);
650 break;
651 case 'u':
652 tar_mode_u(bsdtar);
653 break;
654 case 'x':
655 tar_mode_x(bsdtar);
656 break;
659 cleanup_exclusions(bsdtar);
660 return (bsdtar->return_value);
663 static void
664 set_mode(struct bsdtar *bsdtar, char opt)
666 if (bsdtar->mode != '\0' && bsdtar->mode != opt)
667 bsdtar_errc(bsdtar, 1, 0,
668 "Can't specify both -%c and -%c", opt, bsdtar->mode);
669 bsdtar->mode = opt;
673 * Verify that the mode is correct.
675 static void
676 only_mode(struct bsdtar *bsdtar, const char *opt, const char *valid_modes)
678 if (strchr(valid_modes, bsdtar->mode) == NULL)
679 bsdtar_errc(bsdtar, 1, 0,
680 "Option %s is not permitted in mode -%c",
681 opt, bsdtar->mode);
686 * Convert traditional tar arguments into new-style.
687 * For example,
688 * tar tvfb file.tar 32 --exclude FOO
689 * will be converted to
690 * tar -t -v -f file.tar -b 32 --exclude FOO
692 * This requires building a new argv array. The initial bundled word
693 * gets expanded into a new string that looks like "-t\0-v\0-f\0-b\0".
694 * The new argv array has pointers into this string intermingled with
695 * pointers to the existing arguments. Arguments are moved to
696 * immediately follow their options.
698 * The optstring argument here is the same one passed to getopt(3).
699 * It is used to determine which option letters have trailing arguments.
701 char **
702 rewrite_argv(struct bsdtar *bsdtar, int *argc, char **src_argv,
703 const char *optstring)
705 char **new_argv, **dest_argv;
706 const char *p;
707 char *src, *dest;
709 if (src_argv[0] == NULL ||
710 src_argv[1] == NULL || src_argv[1][0] == '-')
711 return (src_argv);
713 *argc += strlen(src_argv[1]) - 1;
714 new_argv = malloc((*argc + 1) * sizeof(new_argv[0]));
715 if (new_argv == NULL)
716 bsdtar_errc(bsdtar, 1, errno, "No Memory");
718 dest_argv = new_argv;
719 *dest_argv++ = *src_argv++;
721 dest = malloc(strlen(*src_argv) * 3);
722 if (dest == NULL)
723 bsdtar_errc(bsdtar, 1, errno, "No memory");
724 for (src = *src_argv++; *src != '\0'; src++) {
725 *dest_argv++ = dest;
726 *dest++ = '-';
727 *dest++ = *src;
728 *dest++ = '\0';
729 /* If option takes an argument, insert that into the list. */
730 for (p = optstring; p != NULL && *p != '\0'; p++) {
731 if (*p != *src)
732 continue;
733 if (p[1] != ':') /* No arg required, done. */
734 break;
735 if (*src_argv == NULL) /* No arg available? Error. */
736 bsdtar_errc(bsdtar, 1, 0,
737 "Option %c requires an argument",
738 *src);
739 *dest_argv++ = *src_argv++;
740 break;
744 /* Copy remaining arguments, including trailing NULL. */
745 while ((*dest_argv++ = *src_argv++) != NULL)
748 return (new_argv);
751 void
752 usage(struct bsdtar *bsdtar)
754 const char *p;
756 p = bsdtar->progname;
758 fprintf(stderr, "Usage:\n");
759 fprintf(stderr, " List: %s -tf <archive-filename>\n", p);
760 fprintf(stderr, " Extract: %s -xf <archive-filename>\n", p);
761 fprintf(stderr, " Create: %s -cf <archive-filename> [filenames...]\n", p);
762 #ifdef HAVE_GETOPT_LONG
763 fprintf(stderr, " Help: %s --help\n", p);
764 #else
765 fprintf(stderr, " Help: %s -h\n", p);
766 #endif
767 exit(1);
770 static void
771 version(void)
773 printf("bsdtar %s - %s\n", PACKAGE_VERSION, archive_version());
774 exit(1);
777 static const char *long_help_msg =
778 "First option must be a mode specifier:\n"
779 " -c Create -r Add/Replace -t List -u Update -x Extract\n"
780 "Common Options:\n"
781 " -b # Use # 512-byte records per I/O block\n"
782 " -f <filename> Location of archive (default " _PATH_DEFTAPE ")\n"
783 " -v Verbose\n"
784 " -w Interactive\n"
785 "Create: %p -c [options] [<file> | <dir> | @<archive> | -C <dir> ]\n"
786 " <file>, <dir> add these items to archive\n"
787 " -z, -j Compress archive with gzip/bzip2\n"
788 " --format {ustar|pax|cpio|shar} Select archive format\n"
789 #ifdef HAVE_GETOPT_LONG
790 " --exclude <pattern> Skip files that match pattern\n"
791 #else
792 " -W exclude=<pattern> Skip files that match pattern\n"
793 #endif
794 " -C <dir> Change to <dir> before processing remaining files\n"
795 " @<archive> Add entries from <archive> to output\n"
796 "List: %p -t [options] [<patterns>]\n"
797 " <patterns> If specified, list only entries that match\n"
798 "Extract: %p -x [options] [<patterns>]\n"
799 " <patterns> If specified, extract only entries that match\n"
800 " -k Keep (don't overwrite) existing files\n"
801 " -m Don't restore modification times\n"
802 " -O Write entries to stdout, don't restore to disk\n"
803 " -p Restore permissions (including ACLs, owner, file flags)\n";
807 * Note that the word 'bsdtar' will always appear in the first line
808 * of output.
810 * In particular, /bin/sh scripts that need to test for the presence
811 * of bsdtar can use the following template:
813 * if (tar --help 2>&1 | grep bsdtar >/dev/null 2>&1 ) then \
814 * echo bsdtar; else echo not bsdtar; fi
816 static void
817 long_help(struct bsdtar *bsdtar)
819 const char *prog;
820 const char *p;
822 prog = bsdtar->progname;
824 fflush(stderr);
826 p = (strcmp(prog,"bsdtar") != 0) ? "(bsdtar)" : "";
827 printf("%s%s: manipulate archive files\n", prog, p);
829 for (p = long_help_msg; *p != '\0'; p++) {
830 if (*p == '%') {
831 if (p[1] == 'p') {
832 fputs(prog, stdout);
833 p++;
834 } else
835 putchar('%');
836 } else
837 putchar(*p);
839 version();
842 static int
843 bsdtar_getopt(struct bsdtar *bsdtar, const char *optstring,
844 const struct option **poption)
846 char *p, *q;
847 const struct option *option;
848 int opt;
849 int option_index;
850 size_t option_length;
852 option_index = -1;
853 *poption = NULL;
855 #ifdef HAVE_GETOPT_LONG
856 opt = getopt_long(bsdtar->argc, bsdtar->argv, optstring,
857 tar_longopts, &option_index);
858 if (option_index > -1)
859 *poption = tar_longopts + option_index;
860 #else
861 opt = getopt(bsdtar->argc, bsdtar->argv, optstring);
862 #endif
864 /* Support long options through -W longopt=value */
865 if (opt == 'W') {
866 p = optarg;
867 q = strchr(optarg, '=');
868 if (q != NULL) {
869 option_length = (size_t)(q - p);
870 optarg = q + 1;
871 } else {
872 option_length = strlen(p);
873 optarg = NULL;
875 option = tar_longopts;
876 while (option->name != NULL &&
877 (strlen(option->name) < option_length ||
878 strncmp(p, option->name, option_length) != 0 )) {
879 option++;
882 if (option->name != NULL) {
883 *poption = option;
884 opt = option->val;
886 /* If the first match was exact, we're done. */
887 if (strncmp(p, option->name, strlen(option->name)) == 0) {
888 while (option->name != NULL)
889 option++;
890 } else {
891 /* Check if there's another match. */
892 option++;
893 while (option->name != NULL &&
894 (strlen(option->name) < option_length ||
895 strncmp(p, option->name, option_length) != 0)) {
896 option++;
899 if (option->name != NULL)
900 bsdtar_errc(bsdtar, 1, 0,
901 "Ambiguous option %s "
902 "(matches both %s and %s)",
903 p, (*poption)->name, option->name);
905 } else {
906 opt = '?';
907 /* TODO: Set up a fake 'struct option' for
908 * error reporting... ? ? ? */
912 return (opt);