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