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