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