Import libarchive-2.2.5 which fixes a forgotten 'break'. Without this,
[dragonfly.git] / contrib / libarchive-2 / tar / bsdtar.c
1 /*-
2  * Copyright (c) 2003-2007 Tim Kientzle
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS OR
15  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
16  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
17  * IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY DIRECT, INDIRECT,
18  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
19  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
20  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
21  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
22  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
23  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
24  */
25
26 #include "bsdtar_platform.h"
27 __FBSDID("$FreeBSD: src/usr.bin/tar/bsdtar.c,v 1.75 2007/05/29 05:39:10 kientzle Exp $");
28
29 #ifdef HAVE_SYS_PARAM_H
30 #include <sys/param.h>
31 #endif
32 #ifdef HAVE_SYS_STAT_H
33 #include <sys/stat.h>
34 #endif
35 #ifdef HAVE_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;
49 };
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
78
79 #include "bsdtar.h"
80
81 /*
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.
84  */
85 #ifdef __linux
86 #define _PATH_DEFTAPE "/dev/st0"
87 #endif
88
89 #ifndef _PATH_DEFTAPE
90 #define _PATH_DEFTAPE "/dev/tape"
91 #endif
92
93 /* External function to parse a date/time string (from getdate.y) */
94 time_t get_date(const char *);
95
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);
106
107 /*
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.
112  */
113 static const char *tar_opts = "+Bb:C:cf:HhI:jkLlmnOoPprtT:UuvW:wX:xyZz";
114
115 /*
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.
121  *
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().
127  */
128
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_USE_COMPRESS_PROGRAM,
149         OPTION_VERSION
150 };
151
152 /*
153  * If you add anything, be very careful to keep this list properly
154  * sorted, as the -W logic relies on it.
155  */
156 static const struct option tar_longopts[] = {
157         { "absolute-paths",     no_argument,       NULL, 'P' },
158         { "append",             no_argument,       NULL, 'r' },
159         { "block-size",         required_argument, NULL, 'b' },
160         { "bunzip2",            no_argument,       NULL, 'j' },
161         { "bzip",               no_argument,       NULL, 'j' },
162         { "bzip2",              no_argument,       NULL, 'j' },
163         { "cd",                 required_argument, NULL, 'C' },
164         { "check-links",        no_argument,       NULL, OPTION_CHECK_LINKS },
165         { "confirmation",       no_argument,       NULL, 'w' },
166         { "create",             no_argument,       NULL, 'c' },
167         { "dereference",        no_argument,       NULL, 'L' },
168         { "directory",          required_argument, NULL, 'C' },
169         { "exclude",            required_argument, NULL, OPTION_EXCLUDE },
170         { "exclude-from",       required_argument, NULL, 'X' },
171         { "extract",            no_argument,       NULL, 'x' },
172         { "fast-read",          no_argument,       NULL, OPTION_FAST_READ },
173         { "file",               required_argument, NULL, 'f' },
174         { "files-from",         required_argument, NULL, 'T' },
175         { "format",             required_argument, NULL, OPTION_FORMAT },
176         { "gunzip",             no_argument,       NULL, 'z' },
177         { "gzip",               no_argument,       NULL, 'z' },
178         { "help",               no_argument,       NULL, OPTION_HELP },
179         { "include",            required_argument, NULL, OPTION_INCLUDE },
180         { "interactive",        no_argument,       NULL, 'w' },
181         { "keep-old-files",     no_argument,       NULL, 'k' },
182         { "list",               no_argument,       NULL, 't' },
183         { "modification-time",  no_argument,       NULL, 'm' },
184         { "newer",              required_argument, NULL, OPTION_NEWER_CTIME },
185         { "newer-ctime",        required_argument, NULL, OPTION_NEWER_CTIME },
186         { "newer-ctime-than",   required_argument, NULL, OPTION_NEWER_CTIME_THAN },
187         { "newer-mtime",        required_argument, NULL, OPTION_NEWER_MTIME },
188         { "newer-mtime-than",   required_argument, NULL, OPTION_NEWER_MTIME_THAN },
189         { "newer-than",         required_argument, NULL, OPTION_NEWER_CTIME_THAN },
190         { "nodump",             no_argument,       NULL, OPTION_NODUMP },
191         { "norecurse",          no_argument,       NULL, 'n' },
192         { "no-recursion",       no_argument,       NULL, 'n' },
193         { "no-same-owner",      no_argument,       NULL, OPTION_NO_SAME_OWNER },
194         { "no-same-permissions",no_argument,       NULL, OPTION_NO_SAME_PERMISSIONS },
195         { "null",               no_argument,       NULL, OPTION_NULL },
196         { "one-file-system",    no_argument,       NULL, OPTION_ONE_FILE_SYSTEM },
197         { "preserve-permissions", no_argument,     NULL, 'p' },
198         { "read-full-blocks",   no_argument,       NULL, 'B' },
199         { "same-permissions",   no_argument,       NULL, 'p' },
200         { "strip-components",   required_argument, NULL, OPTION_STRIP_COMPONENTS },
201         { "to-stdout",          no_argument,       NULL, 'O' },
202         { "totals",             no_argument,       NULL, OPTION_TOTALS },
203         { "unlink",             no_argument,       NULL, 'U' },
204         { "unlink-first",       no_argument,       NULL, 'U' },
205         { "update",             no_argument,       NULL, 'u' },
206         { "use-compress-program",
207                                 required_argument, NULL, OPTION_USE_COMPRESS_PROGRAM },
208         { "verbose",            no_argument,       NULL, 'v' },
209         { "version",            no_argument,       NULL, OPTION_VERSION },
210         { NULL, 0, NULL, 0 }
211 };
212
213 /* A basic set of security flags to request from libarchive. */
214 #define SECURITY                                        \
215         (ARCHIVE_EXTRACT_SECURE_SYMLINKS                \
216          | ARCHIVE_EXTRACT_SECURE_NODOTDOT)
217
218 int
219 main(int argc, char **argv)
220 {
221         struct bsdtar           *bsdtar, bsdtar_storage;
222         const struct option     *option;
223         int                      opt, t;
224         char                     option_o;
225         char                     possible_help_request;
226         char                     buff[16];
227
228         /*
229          * Use a pointer for consistency, but stack-allocated storage
230          * for ease of cleanup.
231          */
232         bsdtar = &bsdtar_storage;
233         memset(bsdtar, 0, sizeof(*bsdtar));
234         bsdtar->fd = -1; /* Mark as "unused" */
235         option_o = 0;
236
237         /* Need bsdtar->progname before calling bsdtar_warnc. */
238         if (*argv == NULL)
239                 bsdtar->progname = "bsdtar";
240         else {
241                 bsdtar->progname = strrchr(*argv, '/');
242                 if (bsdtar->progname != NULL)
243                         bsdtar->progname++;
244                 else
245                         bsdtar->progname = *argv;
246         }
247
248         if (setlocale(LC_ALL, "") == NULL)
249                 bsdtar_warnc(bsdtar, 0, "Failed to set default locale");
250 #if defined(HAVE_NL_LANGINFO) && defined(HAVE_D_MD_ORDER)
251         bsdtar->day_first = (*nl_langinfo(D_MD_ORDER) == 'd');
252 #endif
253         possible_help_request = 0;
254
255         /* Look up uid of current user for future reference */
256         bsdtar->user_uid = geteuid();
257
258         /* Default: open tape drive. */
259         bsdtar->filename = getenv("TAPE");
260         if (bsdtar->filename == NULL)
261                 bsdtar->filename = _PATH_DEFTAPE;
262
263         /* Default: preserve mod time on extract */
264         bsdtar->extract_flags = ARCHIVE_EXTRACT_TIME;
265
266         /* Default: Perform basic security checks. */
267         bsdtar->extract_flags |= SECURITY;
268
269         /* Defaults for root user: */
270         if (bsdtar->user_uid == 0) {
271                 /* --same-owner */
272                 bsdtar->extract_flags |= ARCHIVE_EXTRACT_OWNER;
273                 /* -p */
274                 bsdtar->extract_flags |= ARCHIVE_EXTRACT_PERM;
275                 bsdtar->extract_flags |= ARCHIVE_EXTRACT_ACL;
276                 bsdtar->extract_flags |= ARCHIVE_EXTRACT_XATTR;
277                 bsdtar->extract_flags |= ARCHIVE_EXTRACT_FFLAGS;
278         }
279
280         /* Rewrite traditional-style tar arguments, if used. */
281         argv = rewrite_argv(bsdtar, &argc, argv, tar_opts);
282
283         bsdtar->argv = argv;
284         bsdtar->argc = argc;
285
286         /* Process all remaining arguments now. */
287         /*
288          * Comments following each option indicate where that option
289          * originated:  SUSv2, POSIX, GNU tar, star, etc.  If there's
290          * no such comment, then I don't know of anyone else who
291          * implements that option.
292          */
293         while ((opt = bsdtar_getopt(bsdtar, tar_opts, &option)) != -1) {
294                 switch (opt) {
295                 case 'B': /* GNU tar */
296                         /* libarchive doesn't need this; just ignore it. */
297                         break;
298                 case 'b': /* SUSv2 */
299                         t = atoi(optarg);
300                         if (t <= 0 || t > 1024)
301                                 bsdtar_errc(bsdtar, 1, 0,
302                                     "Argument to -b is out of range (1..1024)");
303                         bsdtar->bytes_per_block = 512 * t;
304                         break;
305                 case 'C': /* GNU tar */
306                         set_chdir(bsdtar, optarg);
307                         break;
308                 case 'c': /* SUSv2 */
309                         set_mode(bsdtar, opt);
310                         break;
311                 case OPTION_CHECK_LINKS: /* GNU tar */
312                         bsdtar->option_warn_links = 1;
313                         break;
314                 case OPTION_EXCLUDE: /* GNU tar */
315                         if (exclude(bsdtar, optarg))
316                                 bsdtar_errc(bsdtar, 1, 0,
317                                     "Couldn't exclude %s\n", optarg);
318                         break;
319                 case OPTION_FORMAT: /* GNU tar, others */
320                         bsdtar->create_format = optarg;
321                         break;
322                 case 'f': /* SUSv2 */
323                         bsdtar->filename = optarg;
324                         if (strcmp(bsdtar->filename, "-") == 0)
325                                 bsdtar->filename = NULL;
326                         break;
327                 case OPTION_FAST_READ: /* GNU tar */
328                         bsdtar->option_fast_read = 1;
329                         break;
330                 case 'H': /* BSD convention */
331                         bsdtar->symlink_mode = 'H';
332                         break;
333                 case 'h': /* Linux Standards Base, gtar; synonym for -L */
334                         bsdtar->symlink_mode = 'L';
335                         /* Hack: -h by itself is the "help" command. */
336                         possible_help_request = 1;
337                         break;
338                 case OPTION_HELP: /* GNU tar, others */
339                         long_help(bsdtar);
340                         exit(0);
341                         break;
342                 case 'I': /* GNU tar */
343                         /*
344                          * TODO: Allow 'names' to come from an archive,
345                          * not just a text file.  Design a good UI for
346                          * allowing names and mode/owner to be read
347                          * from an archive, with contents coming from
348                          * disk.  This can be used to "refresh" an
349                          * archive or to design archives with special
350                          * permissions without having to create those
351                          * permissions on disk.
352                          */
353                         bsdtar->names_from_file = optarg;
354                         break;
355                 case OPTION_INCLUDE:
356                         /*
357                          * Noone else has the @archive extension, so
358                          * noone else needs this to filter entries
359                          * when transforming archives.
360                          */
361                         if (include(bsdtar, optarg))
362                                 bsdtar_errc(bsdtar, 1, 0,
363                                     "Failed to add %s to inclusion list",
364                                     optarg);
365                         break;
366                 case 'j': /* GNU tar */
367 #if HAVE_LIBBZ2
368                         if (bsdtar->create_compression != '\0')
369                                 bsdtar_errc(bsdtar, 1, 0,
370                                     "Can't specify both -%c and -%c", opt,
371                                     bsdtar->create_compression);
372                         bsdtar->create_compression = opt;
373 #else
374                         bsdtar_warnc(bsdtar, 0, "-j compression not supported by this version of bsdtar");
375                         usage(bsdtar);
376 #endif
377                         break;
378                 case 'k': /* GNU tar */
379                         bsdtar->extract_flags |= ARCHIVE_EXTRACT_NO_OVERWRITE;
380                         break;
381                 case 'L': /* BSD convention */
382                         bsdtar->symlink_mode = 'L';
383                         break;
384                 case 'l': /* SUSv2 and GNU conflict badly here */
385                         if (getenv("POSIXLY_CORRECT") != NULL) {
386                                 /* User has asked for POSIX/SUS behavior. */
387                                 bsdtar->option_warn_links = 1;
388                         } else {
389                                 fprintf(stderr,
390 "Error: -l has different behaviors in different tar programs.\n");
391                                 fprintf(stderr,
392 "  For the GNU behavior, use --one-file-system instead.\n");
393                                 fprintf(stderr,
394 "  For the POSIX behavior, use --check-links instead.\n");
395                                 usage(bsdtar);
396                         }
397                         break;
398                 case 'm': /* SUSv2 */
399                         bsdtar->extract_flags &= ~ARCHIVE_EXTRACT_TIME;
400                         break;
401                 case 'n': /* GNU tar */
402                         bsdtar->option_no_subdirs = 1;
403                         break;
404                 /*
405                  * Selecting files by time:
406                  *    --newer-?time='date' Only files newer than 'date'
407                  *    --newer-?time-than='file' Only files newer than time
408                  *         on specified file (useful for incremental backups)
409                  * TODO: Add corresponding "older" options to reverse these.
410                  */
411                 case OPTION_NEWER_CTIME: /* GNU tar */
412                         bsdtar->newer_ctime_sec = get_date(optarg);
413                         break;
414                 case OPTION_NEWER_CTIME_THAN:
415                         {
416                                 struct stat st;
417                                 if (stat(optarg, &st) != 0)
418                                         bsdtar_errc(bsdtar, 1, 0,
419                                             "Can't open file %s", optarg);
420                                 bsdtar->newer_ctime_sec = st.st_ctime;
421                                 bsdtar->newer_ctime_nsec =
422                                     ARCHIVE_STAT_CTIME_NANOS(&st);
423                         }
424                         break;
425                 case OPTION_NEWER_MTIME: /* GNU tar */
426                         bsdtar->newer_mtime_sec = get_date(optarg);
427                         break;
428                 case OPTION_NEWER_MTIME_THAN:
429                         {
430                                 struct stat st;
431                                 if (stat(optarg, &st) != 0)
432                                         bsdtar_errc(bsdtar, 1, 0,
433                                             "Can't open file %s", optarg);
434                                 bsdtar->newer_mtime_sec = st.st_mtime;
435                                 bsdtar->newer_mtime_nsec =
436                                     ARCHIVE_STAT_MTIME_NANOS(&st);
437                         }
438                         break;
439                 case OPTION_NODUMP: /* star */
440                         bsdtar->option_honor_nodump = 1;
441                         break;
442                 case OPTION_NO_SAME_OWNER: /* GNU tar */
443                         bsdtar->extract_flags &= ~ARCHIVE_EXTRACT_OWNER;
444                         break;
445                 case OPTION_NO_SAME_PERMISSIONS: /* GNU tar */
446                         bsdtar->extract_flags &= ~ARCHIVE_EXTRACT_PERM;
447                         bsdtar->extract_flags &= ~ARCHIVE_EXTRACT_ACL;
448                         bsdtar->extract_flags &= ~ARCHIVE_EXTRACT_XATTR;
449                         bsdtar->extract_flags &= ~ARCHIVE_EXTRACT_FFLAGS;
450                         break;
451                 case OPTION_NULL: /* GNU tar */
452                         bsdtar->option_null++;
453                         break;
454                 case 'O': /* GNU tar */
455                         bsdtar->option_stdout = 1;
456                         break;
457                 case 'o': /* SUSv2 and GNU conflict here, but not fatally */
458                         option_o = 1; /* Record it and resolve it later. */
459                         break;
460                 case OPTION_ONE_FILE_SYSTEM: /* GNU tar */
461                         bsdtar->option_dont_traverse_mounts = 1;
462                         break;
463 #if 0
464                 /*
465                  * The common BSD -P option is not necessary, since
466                  * our default is to archive symlinks, not follow
467                  * them.  This is convenient, as -P conflicts with GNU
468                  * tar anyway.
469                  */
470                 case 'P': /* BSD convention */
471                         /* Default behavior, no option necessary. */
472                         break;
473 #endif
474                 case 'P': /* GNU tar */
475                         bsdtar->extract_flags &= ~SECURITY;
476                         bsdtar->option_absolute_paths = 1;
477                         break;
478                 case 'p': /* GNU tar, star */
479                         bsdtar->extract_flags |= ARCHIVE_EXTRACT_PERM;
480                         bsdtar->extract_flags |= ARCHIVE_EXTRACT_ACL;
481                         bsdtar->extract_flags |= ARCHIVE_EXTRACT_XATTR;
482                         bsdtar->extract_flags |= ARCHIVE_EXTRACT_FFLAGS;
483                         break;
484                 case 'r': /* SUSv2 */
485                         set_mode(bsdtar, opt);
486                         break;
487                 case OPTION_STRIP_COMPONENTS: /* GNU tar 1.15 */
488                         bsdtar->strip_components = atoi(optarg);
489                         break;
490                 case 'T': /* GNU tar */
491                         bsdtar->names_from_file = optarg;
492                         break;
493                 case 't': /* SUSv2 */
494                         set_mode(bsdtar, opt);
495                         bsdtar->verbose++;
496                         break;
497                 case OPTION_TOTALS: /* GNU tar */
498                         bsdtar->option_totals++;
499                         break;
500                 case 'U': /* GNU tar */
501                         bsdtar->extract_flags |= ARCHIVE_EXTRACT_UNLINK;
502                         bsdtar->option_unlink_first = 1;
503                         break;
504                 case 'u': /* SUSv2 */
505                         set_mode(bsdtar, opt);
506                         break;
507                 case 'v': /* SUSv2 */
508                         bsdtar->verbose++;
509                         break;
510                 case OPTION_VERSION: /* GNU convention */
511                         version();
512                         break;
513 #if 0
514                 /*
515                  * The -W longopt feature is handled inside of
516                  * bsdtar_getop(), so -W is not available here.
517                  */
518                 case 'W': /* Obscure, but useful GNU convention. */
519                         break;
520 #endif
521                 case 'w': /* SUSv2 */
522                         bsdtar->option_interactive = 1;
523                         break;
524                 case 'X': /* GNU tar */
525                         if (exclude_from_file(bsdtar, optarg))
526                                 bsdtar_errc(bsdtar, 1, 0,
527                                     "failed to process exclusions from file %s",
528                                     optarg);
529                         break;
530                 case 'x': /* SUSv2 */
531                         set_mode(bsdtar, opt);
532                         break;
533                 case 'y': /* FreeBSD version of GNU tar */
534 #if HAVE_LIBBZ2
535                         if (bsdtar->create_compression != '\0')
536                                 bsdtar_errc(bsdtar, 1, 0,
537                                     "Can't specify both -%c and -%c", opt,
538                                     bsdtar->create_compression);
539                         bsdtar->create_compression = opt;
540 #else
541                         bsdtar_warnc(bsdtar, 0, "-y compression not supported by this version of bsdtar");
542                         usage(bsdtar);
543 #endif
544                         break;
545                 case 'Z': /* GNU tar */
546                         if (bsdtar->create_compression != '\0')
547                                 bsdtar_errc(bsdtar, 1, 0,
548                                     "Can't specify both -%c and -%c", opt,
549                                     bsdtar->create_compression);
550                         bsdtar->create_compression = opt;
551                         break;
552                 case 'z': /* GNU tar, star, many others */
553 #if HAVE_LIBZ
554                         if (bsdtar->create_compression != '\0')
555                                 bsdtar_errc(bsdtar, 1, 0,
556                                     "Can't specify both -%c and -%c", opt,
557                                     bsdtar->create_compression);
558                         bsdtar->create_compression = opt;
559 #else
560                         bsdtar_warnc(bsdtar, 0, "-z compression not supported by this version of bsdtar");
561                         usage(bsdtar);
562 #endif
563                         break;
564                 case OPTION_USE_COMPRESS_PROGRAM:
565                         bsdtar->compress_program = optarg;
566                         break;
567                 default:
568                         usage(bsdtar);
569                 }
570         }
571
572         /*
573          * Sanity-check options.
574          */
575
576         /* If no "real" mode was specified, treat -h as --help. */
577         if ((bsdtar->mode == '\0') && possible_help_request) {
578                 long_help(bsdtar);
579                 exit(0);
580         }
581
582         /* Otherwise, a mode is required. */
583         if (bsdtar->mode == '\0')
584                 bsdtar_errc(bsdtar, 1, 0,
585                     "Must specify one of -c, -r, -t, -u, -x");
586
587         /* Check boolean options only permitted in certain modes. */
588         if (bsdtar->option_dont_traverse_mounts)
589                 only_mode(bsdtar, "--one-file-system", "cru");
590         if (bsdtar->option_fast_read)
591                 only_mode(bsdtar, "--fast-read", "xt");
592         if (bsdtar->option_honor_nodump)
593                 only_mode(bsdtar, "--nodump", "cru");
594         if (option_o > 0) {
595                 switch (bsdtar->mode) {
596                 case 'c':
597                         /*
598                          * In GNU tar, -o means "old format."  The
599                          * "ustar" format is the closest thing
600                          * supported by libarchive.
601                          */
602                         bsdtar->create_format = "ustar";
603                         /* TODO: bsdtar->create_format = "v7"; */
604                         break;
605                 case 'x':
606                         /* POSIX-compatible behavior. */
607                         bsdtar->option_no_owner = 1;
608                         bsdtar->extract_flags &= ~ARCHIVE_EXTRACT_OWNER;
609                         break;
610                 default:
611                         only_mode(bsdtar, "-o", "xc");
612                         break;
613                 }
614         }
615         if (bsdtar->option_no_subdirs)
616                 only_mode(bsdtar, "-n", "cru");
617         if (bsdtar->option_stdout)
618                 only_mode(bsdtar, "-O", "xt");
619         if (bsdtar->option_unlink_first)
620                 only_mode(bsdtar, "-U", "x");
621         if (bsdtar->option_warn_links)
622                 only_mode(bsdtar, "--check-links", "cr");
623
624         /* Check other parameters only permitted in certain modes. */
625         if (bsdtar->create_compression == 'Z' && bsdtar->mode == 'c') {
626                 bsdtar_warnc(bsdtar, 0, ".Z compression not supported");
627                 usage(bsdtar);
628         }
629         if (bsdtar->create_compression != '\0') {
630                 strcpy(buff, "-?");
631                 buff[1] = bsdtar->create_compression;
632                 only_mode(bsdtar, buff, "cxt");
633         }
634         if (bsdtar->create_format != NULL)
635                 only_mode(bsdtar, "--format", "c");
636         if (bsdtar->symlink_mode != '\0') {
637                 strcpy(buff, "-?");
638                 buff[1] = bsdtar->symlink_mode;
639                 only_mode(bsdtar, buff, "cru");
640         }
641         if (bsdtar->strip_components != 0)
642                 only_mode(bsdtar, "--strip-components", "xt");
643
644         bsdtar->argc -= optind;
645         bsdtar->argv += optind;
646
647         switch(bsdtar->mode) {
648         case 'c':
649                 tar_mode_c(bsdtar);
650                 break;
651         case 'r':
652                 tar_mode_r(bsdtar);
653                 break;
654         case 't':
655                 tar_mode_t(bsdtar);
656                 break;
657         case 'u':
658                 tar_mode_u(bsdtar);
659                 break;
660         case 'x':
661                 tar_mode_x(bsdtar);
662                 break;
663         }
664
665         cleanup_exclusions(bsdtar);
666         if (bsdtar->return_value != 0)
667                 bsdtar_warnc(bsdtar, 0,
668                     "Error exit delayed from previous errors.");
669         return (bsdtar->return_value);
670 }
671
672 static void
673 set_mode(struct bsdtar *bsdtar, char opt)
674 {
675         if (bsdtar->mode != '\0' && bsdtar->mode != opt)
676                 bsdtar_errc(bsdtar, 1, 0,
677                     "Can't specify both -%c and -%c", opt, bsdtar->mode);
678         bsdtar->mode = opt;
679 }
680
681 /*
682  * Verify that the mode is correct.
683  */
684 static void
685 only_mode(struct bsdtar *bsdtar, const char *opt, const char *valid_modes)
686 {
687         if (strchr(valid_modes, bsdtar->mode) == NULL)
688                 bsdtar_errc(bsdtar, 1, 0,
689                     "Option %s is not permitted in mode -%c",
690                     opt, bsdtar->mode);
691 }
692
693
694 /*-
695  * Convert traditional tar arguments into new-style.
696  * For example,
697  *     tar tvfb file.tar 32 --exclude FOO
698  * will be converted to
699  *     tar -t -v -f file.tar -b 32 --exclude FOO
700  *
701  * This requires building a new argv array.  The initial bundled word
702  * gets expanded into a new string that looks like "-t\0-v\0-f\0-b\0".
703  * The new argv array has pointers into this string intermingled with
704  * pointers to the existing arguments.  Arguments are moved to
705  * immediately follow their options.
706  *
707  * The optstring argument here is the same one passed to getopt(3).
708  * It is used to determine which option letters have trailing arguments.
709  */
710 char **
711 rewrite_argv(struct bsdtar *bsdtar, int *argc, char **src_argv,
712     const char *optstring)
713 {
714         char **new_argv, **dest_argv;
715         const char *p;
716         char *src, *dest;
717
718         if (src_argv[0] == NULL ||
719             src_argv[1] == NULL || src_argv[1][0] == '-')
720                 return (src_argv);
721
722         *argc += strlen(src_argv[1]) - 1;
723         new_argv = malloc((*argc + 1) * sizeof(new_argv[0]));
724         if (new_argv == NULL)
725                 bsdtar_errc(bsdtar, 1, errno, "No Memory");
726
727         dest_argv = new_argv;
728         *dest_argv++ = *src_argv++;
729
730         dest = malloc(strlen(*src_argv) * 3);
731         if (dest == NULL)
732                 bsdtar_errc(bsdtar, 1, errno, "No memory");
733         for (src = *src_argv++; *src != '\0'; src++) {
734                 *dest_argv++ = dest;
735                 *dest++ = '-';
736                 *dest++ = *src;
737                 *dest++ = '\0';
738                 /* If option takes an argument, insert that into the list. */
739                 for (p = optstring; p != NULL && *p != '\0'; p++) {
740                         if (*p != *src)
741                                 continue;
742                         if (p[1] != ':')        /* No arg required, done. */
743                                 break;
744                         if (*src_argv == NULL)  /* No arg available? Error. */
745                                 bsdtar_errc(bsdtar, 1, 0,
746                                     "Option %c requires an argument",
747                                     *src);
748                         *dest_argv++ = *src_argv++;
749                         break;
750                 }
751         }
752
753         /* Copy remaining arguments, including trailing NULL. */
754         while ((*dest_argv++ = *src_argv++) != NULL)
755                 ;
756
757         return (new_argv);
758 }
759
760 void
761 usage(struct bsdtar *bsdtar)
762 {
763         const char      *p;
764
765         p = bsdtar->progname;
766
767         fprintf(stderr, "Usage:\n");
768         fprintf(stderr, "  List:    %s -tf <archive-filename>\n", p);
769         fprintf(stderr, "  Extract: %s -xf <archive-filename>\n", p);
770         fprintf(stderr, "  Create:  %s -cf <archive-filename> [filenames...]\n", p);
771 #ifdef HAVE_GETOPT_LONG
772         fprintf(stderr, "  Help:    %s --help\n", p);
773 #else
774         fprintf(stderr, "  Help:    %s -h\n", p);
775 #endif
776         exit(1);
777 }
778
779 static void
780 version(void)
781 {
782         printf("bsdtar %s - %s\n", PACKAGE_VERSION, archive_version());
783         exit(1);
784 }
785
786 static const char *long_help_msg =
787         "First option must be a mode specifier:\n"
788         "  -c Create  -r Add/Replace  -t List  -u Update  -x Extract\n"
789         "Common Options:\n"
790         "  -b #  Use # 512-byte records per I/O block\n"
791         "  -f <filename>  Location of archive (default " _PATH_DEFTAPE ")\n"
792         "  -v    Verbose\n"
793         "  -w    Interactive\n"
794         "Create: %p -c [options] [<file> | <dir> | @<archive> | -C <dir> ]\n"
795         "  <file>, <dir>  add these items to archive\n"
796         "  -z, -j  Compress archive with gzip/bzip2\n"
797         "  --format {ustar|pax|cpio|shar}  Select archive format\n"
798 #ifdef HAVE_GETOPT_LONG
799         "  --exclude <pattern>  Skip files that match pattern\n"
800 #else
801         "  -W exclude=<pattern>  Skip files that match pattern\n"
802 #endif
803         "  -C <dir>  Change to <dir> before processing remaining files\n"
804         "  @<archive>  Add entries from <archive> to output\n"
805         "List: %p -t [options] [<patterns>]\n"
806         "  <patterns>  If specified, list only entries that match\n"
807         "Extract: %p -x [options] [<patterns>]\n"
808         "  <patterns>  If specified, extract only entries that match\n"
809         "  -k    Keep (don't overwrite) existing files\n"
810         "  -m    Don't restore modification times\n"
811         "  -O    Write entries to stdout, don't restore to disk\n"
812         "  -p    Restore permissions (including ACLs, owner, file flags)\n";
813
814
815 /*
816  * Note that the word 'bsdtar' will always appear in the first line
817  * of output.
818  *
819  * In particular, /bin/sh scripts that need to test for the presence
820  * of bsdtar can use the following template:
821  *
822  * if (tar --help 2>&1 | grep bsdtar >/dev/null 2>&1 ) then \
823  *          echo bsdtar; else echo not bsdtar; fi
824  */
825 static void
826 long_help(struct bsdtar *bsdtar)
827 {
828         const char      *prog;
829         const char      *p;
830
831         prog = bsdtar->progname;
832
833         fflush(stderr);
834
835         p = (strcmp(prog,"bsdtar") != 0) ? "(bsdtar)" : "";
836         printf("%s%s: manipulate archive files\n", prog, p);
837
838         for (p = long_help_msg; *p != '\0'; p++) {
839                 if (*p == '%') {
840                         if (p[1] == 'p') {
841                                 fputs(prog, stdout);
842                                 p++;
843                         } else
844                                 putchar('%');
845                 } else
846                         putchar(*p);
847         }
848         version();
849 }
850
851 static int
852 bsdtar_getopt(struct bsdtar *bsdtar, const char *optstring,
853     const struct option **poption)
854 {
855         char *p, *q;
856         const struct option *option;
857         int opt;
858         int option_index;
859         size_t option_length;
860
861         option_index = -1;
862         *poption = NULL;
863
864 #ifdef HAVE_GETOPT_LONG
865         opt = getopt_long(bsdtar->argc, bsdtar->argv, optstring,
866             tar_longopts, &option_index);
867         if (option_index > -1)
868                 *poption = tar_longopts + option_index;
869 #else
870         opt = getopt(bsdtar->argc, bsdtar->argv, optstring);
871 #endif
872
873         /* Support long options through -W longopt=value */
874         if (opt == 'W') {
875                 p = optarg;
876                 q = strchr(optarg, '=');
877                 if (q != NULL) {
878                         option_length = (size_t)(q - p);
879                         optarg = q + 1;
880                 } else {
881                         option_length = strlen(p);
882                         optarg = NULL;
883                 }
884                 option = tar_longopts;
885                 while (option->name != NULL &&
886                     (strlen(option->name) < option_length ||
887                     strncmp(p, option->name, option_length) != 0 )) {
888                         option++;
889                 }
890
891                 if (option->name != NULL) {
892                         *poption = option;
893                         opt = option->val;
894
895                         /* If the first match was exact, we're done. */
896                         if (strncmp(p, option->name, strlen(option->name)) == 0) {
897                                 while (option->name != NULL)
898                                         option++;
899                         } else {
900                                 /* Check if there's another match. */
901                                 option++;
902                                 while (option->name != NULL &&
903                                     (strlen(option->name) < option_length ||
904                                     strncmp(p, option->name, option_length) != 0)) {
905                                         option++;
906                                 }
907                         }
908                         if (option->name != NULL)
909                                 bsdtar_errc(bsdtar, 1, 0,
910                                     "Ambiguous option %s "
911                                     "(matches both %s and %s)",
912                                     p, (*poption)->name, option->name);
913
914                 } else {
915                         opt = '?';
916                         /* TODO: Set up a fake 'struct option' for
917                          * error reporting... ? ? ? */
918                 }
919         }
920
921         return (opt);
922 }