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