- Add ral(4) for Ralink RT2500/RT2501/RT2600 chip based wireless NIC
[dragonfly.git] / contrib / bsdtar / 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.63 2005/04/17 19:43:37 kientzle Exp $");
29
30 #include <sys/param.h>
31 #include <sys/stat.h>
32 #include <archive.h>
33 #include <archive_entry.h>
34 #include <errno.h>
35 #include <fcntl.h>
36 #ifdef HAVE_GETOPT_LONG
37 #include <getopt.h>
38 #else
39 struct option {
40         const char *name;
41         int has_arg;
42         int *flag;
43         int val;
44 };
45 #define no_argument 0
46 #define required_argument 1
47 #endif
48 #ifdef HAVE_LANGINFO_H
49 #include <langinfo.h>
50 #endif
51 #include <locale.h>
52 #ifdef HAVE_PATHS_H
53 #include <paths.h>
54 #endif
55 #include <stdio.h>
56 #include <stdlib.h>
57 #include <string.h>
58 #include <time.h>
59 #include <unistd.h>
60 #if HAVE_ZLIB_H
61 #include <zlib.h>
62 #endif
63
64 #include "bsdtar.h"
65
66 #ifdef __linux
67 #define _PATH_DEFTAPE "/dev/st0"
68 #endif
69
70 #ifndef _PATH_DEFTAPE
71 #define _PATH_DEFTAPE "/dev/tape"
72 #endif
73
74 /* External function to parse a date/time string (from getdate.y) */
75 time_t get_date(const char *);
76
77 static int               bsdtar_getopt(struct bsdtar *, const char *optstring,
78     const struct option **poption);
79 static void              long_help(struct bsdtar *);
80 static void              only_mode(struct bsdtar *, const char *opt,
81                              const char *valid);
82 static char **           rewrite_argv(struct bsdtar *,
83                              int *argc, char ** src_argv,
84                              const char *optstring);
85 static void              set_mode(struct bsdtar *, char opt);
86 static void              version(void);
87
88 /*
89  * The leading '+' here forces the GNU version of getopt() (as well as
90  * both the GNU and BSD versions of getopt_long) to stop at the first
91  * non-option.  Otherwise, GNU getopt() permutes the arguments and
92  * screws up -C processing.
93  */
94 static const char *tar_opts = "+Bb:C:cF:f:HhI:jkLlmnOoPprtT:UuvW:wX:xyZz";
95
96 /*
97  * Most of these long options are deliberately not documented.  They
98  * are provided only to make life easier for people who also use GNU tar.
99  * The only long options documented in the manual page are the ones
100  * with no corresponding short option, such as --exclude, --nodump,
101  * and --fast-read.
102  *
103  * On systems that lack getopt_long, long options can be specified
104  * using -W longopt and -W longopt=value, e.g. "-W nodump" is the same
105  * as "--nodump" and "-W exclude=pattern" is the same as "--exclude
106  * pattern".  This does not rely the GNU getopt() "W;" extension, so
107  * should work correctly on any system with a POSIX-compliant getopt().
108  */
109
110 /* Fake short equivalents for long options that otherwise lack them. */
111 enum {
112         OPTION_CHECK_LINKS=1,
113         OPTION_EXCLUDE,
114         OPTION_FAST_READ,
115         OPTION_FORMAT,
116         OPTION_HELP,
117         OPTION_INCLUDE,
118         OPTION_NEWER_CTIME,
119         OPTION_NEWER_CTIME_THAN,
120         OPTION_NEWER_MTIME,
121         OPTION_NEWER_MTIME_THAN,
122         OPTION_NODUMP,
123         OPTION_NO_SAME_PERMISSIONS,
124         OPTION_NULL,
125         OPTION_ONE_FILE_SYSTEM,
126         OPTION_STRIP_COMPONENTS,
127         OPTION_TOTALS,
128         OPTION_VERSION
129 };
130
131 /*
132  * If you add anything, be very careful to keep this list properly
133  * sorted, as the -W logic relies on it.
134  */
135 static const struct option tar_longopts[] = {
136         { "absolute-paths",     no_argument,       NULL, 'P' },
137         { "append",             no_argument,       NULL, 'r' },
138         { "block-size",         required_argument, NULL, 'b' },
139         { "bunzip2",            no_argument,       NULL, 'j' },
140         { "bzip",               no_argument,       NULL, 'j' },
141         { "bzip2",              no_argument,       NULL, 'j' },
142         { "cd",                 required_argument, NULL, 'C' },
143         { "check-links",        no_argument,       NULL, OPTION_CHECK_LINKS },
144         { "confirmation",       no_argument,       NULL, 'w' },
145         { "create",             no_argument,       NULL, 'c' },
146         { "dereference",        no_argument,       NULL, 'L' },
147         { "directory",          required_argument, NULL, 'C' },
148         { "exclude",            required_argument, NULL, OPTION_EXCLUDE },
149         { "exclude-from",       required_argument, NULL, 'X' },
150         { "extract",            no_argument,       NULL, 'x' },
151         { "fast-read",          no_argument,       NULL, OPTION_FAST_READ },
152         { "file",               required_argument, NULL, 'f' },
153         { "files-from",         required_argument, NULL, 'T' },
154         { "format",             required_argument, NULL, OPTION_FORMAT },
155         { "gunzip",             no_argument,       NULL, 'z' },
156         { "gzip",               no_argument,       NULL, 'z' },
157         { "help",               no_argument,       NULL, OPTION_HELP },
158         { "include",            required_argument, NULL, OPTION_INCLUDE },
159         { "interactive",        no_argument,       NULL, 'w' },
160         { "keep-old-files",     no_argument,       NULL, 'k' },
161         { "list",               no_argument,       NULL, 't' },
162         { "modification-time",  no_argument,       NULL, 'm' },
163         { "newer",              required_argument, NULL, OPTION_NEWER_CTIME },
164         { "newer-ctime",        required_argument, NULL, OPTION_NEWER_CTIME },
165         { "newer-ctime-than",   required_argument, NULL, OPTION_NEWER_CTIME_THAN },
166         { "newer-mtime",        required_argument, NULL, OPTION_NEWER_MTIME },
167         { "newer-mtime-than",   required_argument, NULL, OPTION_NEWER_MTIME_THAN },
168         { "newer-than",         required_argument, NULL, OPTION_NEWER_CTIME_THAN },
169         { "nodump",             no_argument,       NULL, OPTION_NODUMP },
170         { "norecurse",          no_argument,       NULL, 'n' },
171         { "no-recursion",       no_argument,       NULL, 'n' },
172         { "no-same-owner",      no_argument,       NULL, 'o' },
173         { "no-same-permissions",no_argument,       NULL, OPTION_NO_SAME_PERMISSIONS },
174         { "null",               no_argument,       NULL, OPTION_NULL },
175         { "one-file-system",    no_argument,       NULL, OPTION_ONE_FILE_SYSTEM },
176         { "preserve-permissions", no_argument,     NULL, 'p' },
177         { "read-full-blocks",   no_argument,       NULL, 'B' },
178         { "same-permissions",   no_argument,       NULL, 'p' },
179         { "strip-components",   required_argument, NULL, OPTION_STRIP_COMPONENTS },
180         { "to-stdout",          no_argument,       NULL, 'O' },
181         { "totals",             no_argument,       NULL, OPTION_TOTALS },
182         { "unlink",             no_argument,       NULL, 'U' },
183         { "unlink-first",       no_argument,       NULL, 'U' },
184         { "update",             no_argument,       NULL, 'u' },
185         { "verbose",            no_argument,       NULL, 'v' },
186         { "version",            no_argument,       NULL, OPTION_VERSION },
187         { NULL, 0, NULL, 0 }
188 };
189
190 int
191 main(int argc, char **argv)
192 {
193         struct bsdtar           *bsdtar, bsdtar_storage;
194         const struct option     *option;
195         int                      opt, t;
196         char                     option_o;
197         char                     possible_help_request;
198         char                     buff[16];
199
200         /*
201          * Use a pointer for consistency, but stack-allocated storage
202          * for ease of cleanup.
203          */
204         bsdtar = &bsdtar_storage;
205         memset(bsdtar, 0, sizeof(*bsdtar));
206         bsdtar->fd = -1; /* Mark as "unused" */
207         option_o = 0;
208
209         if (setlocale(LC_ALL, "") == NULL)
210                 bsdtar_warnc(bsdtar, 0, "Failed to set default locale");
211 #if defined(HAVE_NL_LANGINFO) && defined(HAVE_D_MD_ORDER)
212         bsdtar->day_first = (*nl_langinfo(D_MD_ORDER) == 'd');
213 #endif
214         possible_help_request = 0;
215
216         /* Look up uid of current user for future reference */
217         bsdtar->user_uid = geteuid();
218
219         /* Default: open tape drive. */
220         bsdtar->filename = getenv("TAPE");
221         if (bsdtar->filename == NULL)
222                 bsdtar->filename = _PATH_DEFTAPE;
223
224         /* Default: preserve mod time on extract */
225         bsdtar->extract_flags = ARCHIVE_EXTRACT_TIME;
226
227         if (bsdtar->user_uid == 0)
228                 bsdtar->extract_flags |= ARCHIVE_EXTRACT_OWNER;
229
230         if (*argv == NULL)
231                 bsdtar->progname = "bsdtar";
232         else {
233                 bsdtar->progname = strrchr(*argv, '/');
234                 if (bsdtar->progname != NULL)
235                         bsdtar->progname++;
236                 else
237                         bsdtar->progname = *argv;
238         }
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_FFLAGS;
412                         break;
413                 case 'r': /* SUSv2 */
414                         set_mode(bsdtar, opt);
415                         break;
416                 case OPTION_STRIP_COMPONENTS: /* GNU tar 1.15 */
417                         bsdtar->strip_components = atoi(optarg);
418                         break;
419                 case 'T': /* GNU tar */
420                         bsdtar->names_from_file = optarg;
421                         break;
422                 case 't': /* SUSv2 */
423                         set_mode(bsdtar, opt);
424                         bsdtar->verbose++;
425                         break;
426                 case OPTION_TOTALS: /* GNU tar */
427                         bsdtar->option_totals++;
428                         break;
429                 case 'U': /* GNU tar */
430                         bsdtar->extract_flags |= ARCHIVE_EXTRACT_UNLINK;
431                         bsdtar->option_unlink_first = 1;
432                         break;
433                 case 'u': /* SUSv2 */
434                         set_mode(bsdtar, opt);
435                         break;
436                 case 'v': /* SUSv2 */
437                         bsdtar->verbose++;
438                         break;
439                 case OPTION_VERSION:
440                         version();
441                         break;
442                 case 'w': /* SUSv2 */
443                         bsdtar->option_interactive = 1;
444                         break;
445                 case 'X': /* GNU tar */
446                         if (exclude_from_file(bsdtar, optarg))
447                                 bsdtar_errc(bsdtar, 1, 0,
448                                     "failed to process exclusions from file %s",
449                                     optarg);
450                         break;
451                 case 'x': /* SUSv2 */
452                         set_mode(bsdtar, opt);
453                         break;
454                 case 'y': /* FreeBSD version of GNU tar */
455 #if HAVE_LIBBZ2
456                         if (bsdtar->create_compression != '\0')
457                                 bsdtar_errc(bsdtar, 1, 0,
458                                     "Can't specify both -%c and -%c", opt,
459                                     bsdtar->create_compression);
460                         bsdtar->create_compression = opt;
461 #else
462                         bsdtar_warnc(bsdtar, 0, "-y compression not supported by this version of bsdtar");
463                         usage(bsdtar);
464 #endif
465                         break;
466                 case 'Z': /* GNU tar */
467                         if (bsdtar->create_compression != '\0')
468                                 bsdtar_errc(bsdtar, 1, 0,
469                                     "Can't specify both -%c and -%c", opt,
470                                     bsdtar->create_compression);
471                         bsdtar->create_compression = opt;
472                         break;
473                 case 'z': /* GNU tar, star, many others */
474 #if HAVE_LIBZ
475                         if (bsdtar->create_compression != '\0')
476                                 bsdtar_errc(bsdtar, 1, 0,
477                                     "Can't specify both -%c and -%c", opt,
478                                     bsdtar->create_compression);
479                         bsdtar->create_compression = opt;
480 #else
481                         bsdtar_warnc(bsdtar, 0, "-z compression not supported by this version of bsdtar");
482                         usage(bsdtar);
483 #endif
484                         break;
485                 default:
486                         usage(bsdtar);
487                 }
488         }
489
490         /*
491          * Sanity-check options.
492          */
493         if ((bsdtar->mode == '\0') && possible_help_request) {
494                 long_help(bsdtar);
495                 exit(0);
496         }
497
498         if (bsdtar->mode == '\0')
499                 bsdtar_errc(bsdtar, 1, 0,
500                     "Must specify one of -c, -r, -t, -u, -x");
501
502         /* Check boolean options only permitted in certain modes. */
503         if (bsdtar->option_dont_traverse_mounts)
504                 only_mode(bsdtar, "-X", "cru");
505         if (bsdtar->option_fast_read)
506                 only_mode(bsdtar, "--fast-read", "xt");
507         if (bsdtar->option_honor_nodump)
508                 only_mode(bsdtar, "--nodump", "cru");
509         if (option_o > 0) {
510                 switch (bsdtar->mode) {
511                 case 'c':
512                         /*
513                          * In GNU tar, -o means "old format."  The
514                          * "ustar" format is the closest thing
515                          * supported by libarchive.
516                          */
517                         bsdtar->create_format = "ustar";
518                         /* TODO: bsdtar->create_format = "v7"; */
519                         break;
520                 case 'x':
521                         /* POSIX-compatible behavior. */
522                         bsdtar->option_no_owner = 1;
523                         bsdtar->extract_flags &= ~ARCHIVE_EXTRACT_OWNER;
524                         break;
525                 default:
526                         only_mode(bsdtar, "-o", "xc");
527                         break;
528                 }
529         }
530         if (bsdtar->option_no_subdirs)
531                 only_mode(bsdtar, "-n", "cru");
532         if (bsdtar->option_stdout)
533                 only_mode(bsdtar, "-O", "xt");
534         if (bsdtar->option_warn_links)
535                 only_mode(bsdtar, "--check-links", "cr");
536
537         /* Check other parameters only permitted in certain modes. */
538         if (bsdtar->create_compression == 'Z' && bsdtar->mode == 'c') {
539                 bsdtar_warnc(bsdtar, 0, ".Z compression not supported");
540                 usage(bsdtar);
541         }
542         if (bsdtar->create_compression != '\0') {
543                 strcpy(buff, "-?");
544                 buff[1] = bsdtar->create_compression;
545                 only_mode(bsdtar, buff, "cxt");
546         }
547         if (bsdtar->create_format != NULL)
548                 only_mode(bsdtar, "-F", "c");
549         if (bsdtar->symlink_mode != '\0') {
550                 strcpy(buff, "-?");
551                 buff[1] = bsdtar->symlink_mode;
552                 only_mode(bsdtar, buff, "cru");
553         }
554
555         bsdtar->argc -= optind;
556         bsdtar->argv += optind;
557
558         switch(bsdtar->mode) {
559         case 'c':
560                 tar_mode_c(bsdtar);
561                 break;
562         case 'r':
563                 tar_mode_r(bsdtar);
564                 break;
565         case 't':
566                 tar_mode_t(bsdtar);
567                 break;
568         case 'u':
569                 tar_mode_u(bsdtar);
570                 break;
571         case 'x':
572                 tar_mode_x(bsdtar);
573                 break;
574         }
575
576         cleanup_exclusions(bsdtar);
577         return (bsdtar->return_value);
578 }
579
580 static void
581 set_mode(struct bsdtar *bsdtar, char opt)
582 {
583         if (bsdtar->mode != '\0' && bsdtar->mode != opt)
584                 bsdtar_errc(bsdtar, 1, 0,
585                     "Can't specify both -%c and -%c", opt, bsdtar->mode);
586         bsdtar->mode = opt;
587 }
588
589 /*
590  * Verify that the mode is correct.
591  */
592 static void
593 only_mode(struct bsdtar *bsdtar, const char *opt, const char *valid_modes)
594 {
595         if (strchr(valid_modes, bsdtar->mode) == NULL)
596                 bsdtar_errc(bsdtar, 1, 0,
597                     "Option %s is not permitted in mode -%c",
598                     opt, bsdtar->mode);
599 }
600
601
602 /*-
603  * Convert traditional tar arguments into new-style.
604  * For example,
605  *     tar tvfb file.tar 32 --exclude FOO
606  * will be converted to
607  *     tar -t -v -f file.tar -b 32 --exclude FOO
608  *
609  * This requires building a new argv array.  The initial bundled word
610  * gets expanded into a new string that looks like "-t\0-v\0-f\0-b\0".
611  * The new argv array has pointers into this string intermingled with
612  * pointers to the existing arguments.  Arguments are moved to
613  * immediately follow their options.
614  *
615  * The optstring argument here is the same one passed to getopt(3).
616  * It is used to determine which option letters have trailing arguments.
617  */
618 char **
619 rewrite_argv(struct bsdtar *bsdtar, int *argc, char **src_argv,
620     const char *optstring)
621 {
622         char **new_argv, **dest_argv;
623         const char *p;
624         char *src, *dest;
625
626         if (src_argv[0] == NULL ||
627             src_argv[1] == NULL || src_argv[1][0] == '-')
628                 return (src_argv);
629
630         *argc += strlen(src_argv[1]) - 1;
631         new_argv = malloc((*argc + 1) * sizeof(new_argv[0]));
632         if (new_argv == NULL)
633                 bsdtar_errc(bsdtar, 1, errno, "No Memory");
634
635         dest_argv = new_argv;
636         *dest_argv++ = *src_argv++;
637
638         dest = malloc(strlen(*src_argv) * 3);
639         if (dest == NULL)
640                 bsdtar_errc(bsdtar, 1, errno, "No memory");
641         for (src = *src_argv++; *src != '\0'; src++) {
642                 *dest_argv++ = dest;
643                 *dest++ = '-';
644                 *dest++ = *src;
645                 *dest++ = '\0';
646                 /* If option takes an argument, insert that into the list. */
647                 for (p = optstring; p != NULL && *p != '\0'; p++) {
648                         if (*p != *src)
649                                 continue;
650                         if (p[1] != ':')        /* No arg required, done. */
651                                 break;
652                         if (*src_argv == NULL)  /* No arg available? Error. */
653                                 bsdtar_errc(bsdtar, 1, 0,
654                                     "Option %c requires an argument",
655                                     *src);
656                         *dest_argv++ = *src_argv++;
657                         break;
658                 }
659         }
660
661         /* Copy remaining arguments, including trailing NULL. */
662         while ((*dest_argv++ = *src_argv++) != NULL)
663                 ;
664
665         return (new_argv);
666 }
667
668 void
669 usage(struct bsdtar *bsdtar)
670 {
671         const char      *p;
672
673         p = bsdtar->progname;
674
675         fprintf(stderr, "Usage:\n");
676         fprintf(stderr, "  List:    %s -tf <archive-filename>\n", p);
677         fprintf(stderr, "  Extract: %s -xf <archive-filename>\n", p);
678         fprintf(stderr, "  Create:  %s -cf <archive-filename> [filenames...]\n", p);
679 #ifdef HAVE_GETOPT_LONG
680         fprintf(stderr, "  Help:    %s --help\n", p);
681 #else
682         fprintf(stderr, "  Help:    %s -h\n", p);
683 #endif
684         exit(1);
685 }
686
687 static void
688 version(void)
689 {
690         printf("bsdtar %s, ", PACKAGE_VERSION);
691         printf("%s\n", archive_version());
692         printf("Copyright (C) 2003-2005 Tim Kientzle\n");
693         exit(1);
694 }
695
696 static const char *long_help_msg =
697         "First option must be a mode specifier:\n"
698         "  -c Create  -r Add/Replace  -t List  -u Update  -x Extract\n"
699         "Common Options:\n"
700         "  -b #  Use # 512-byte records per I/O block\n"
701         "  -f <filename>  Location of archive (default " _PATH_DEFTAPE ")\n"
702         "  -v    Verbose\n"
703         "  -w    Interactive\n"
704         "Create: %p -c [options] [<file> | <dir> | @<archive> | -C <dir> ]\n"
705         "  <file>, <dir>  add these items to archive\n"
706         "  -z, -j  Compress archive with gzip/bzip2\n"
707         "  --format {ustar|pax|cpio|shar}  Select archive format\n"
708 #ifdef HAVE_GETOPT_LONG
709         "  --exclude <pattern>  Skip files that match pattern\n"
710 #else
711         "  -W exclude=<pattern>  Skip files that match pattern\n"
712 #endif
713         "  -C <dir>  Change to <dir> before processing remaining files\n"
714         "  @<archive>  Add entries from <archive> to output\n"
715         "List: %p -t [options] [<patterns>]\n"
716         "  <patterns>  If specified, list only entries that match\n"
717         "Extract: %p -x [options] [<patterns>]\n"
718         "  <patterns>  If specified, extract only entries that match\n"
719         "  -k    Keep (don't overwrite) existing files\n"
720         "  -m    Don't restore modification times\n"
721         "  -O    Write entries to stdout, don't restore to disk\n"
722         "  -p    Restore permissions (including ACLs, owner, file flags)\n";
723
724
725 /*
726  * Note that the word 'bsdtar' will always appear in the first line
727  * of output.
728  *
729  * In particular, /bin/sh scripts that need to test for the presence
730  * of bsdtar can use the following template:
731  *
732  * if (tar --help 2>&1 | grep bsdtar >/dev/null 2>&1 ) then \
733  *          echo bsdtar; else echo not bsdtar; fi
734  */
735 static void
736 long_help(struct bsdtar *bsdtar)
737 {
738         const char      *prog;
739         const char      *p;
740
741         prog = bsdtar->progname;
742
743         fflush(stderr);
744
745         p = (strcmp(prog,"bsdtar") != 0) ? "(bsdtar)" : "";
746         printf("%s%s: manipulate archive files\n", prog, p);
747
748         for (p = long_help_msg; *p != '\0'; p++) {
749                 if (*p == '%') {
750                         if (p[1] == 'p') {
751                                 fputs(prog, stdout);
752                                 p++;
753                         } else
754                                 putchar('%');
755                 } else
756                         putchar(*p);
757         }
758         fprintf(stdout, "\n%s %s\n", PACKAGE_NAME, PACKAGE_VERSION);
759         fprintf(stdout, "%s\n", archive_version());
760 }
761
762 static int
763 bsdtar_getopt(struct bsdtar *bsdtar, const char *optstring,
764     const struct option **poption)
765 {
766         char *p, *q;
767         const struct option *option;
768         int opt;
769         int option_index;
770         size_t option_length;
771
772         option_index = -1;
773         *poption = NULL;
774
775 #ifdef HAVE_GETOPT_LONG
776         opt = getopt_long(bsdtar->argc, bsdtar->argv, optstring,
777             tar_longopts, &option_index);
778         if (option_index > -1)
779                 *poption = tar_longopts + option_index;
780 #else
781         opt = getopt(bsdtar->argc, bsdtar->argv, optstring);
782 #endif
783
784         /* Support long options through -W longopt=value */
785         if (opt == 'W') {
786                 p = optarg;
787                 q = strchr(optarg, '=');
788                 if (q != NULL) {
789                         option_length = (size_t)(q - p);
790                         optarg = q + 1;
791                 } else {
792                         option_length = strlen(p);
793                         optarg = NULL;
794                 }
795                 option = tar_longopts;
796                 while (option->name != NULL &&
797                     (strlen(option->name) < option_length ||
798                     strncmp(p, option->name, option_length) != 0 )) {
799                         option++;
800                 }
801
802                 if (option->name != NULL) {
803                         *poption = option;
804                         opt = option->val;
805
806                         /* If the first match was exact, we're done. */
807                         if (strncmp(p, option->name, strlen(option->name)) == 0) {
808                                 while (option->name != NULL)
809                                         option++;
810                         } else {
811                                 /* Check if there's another match. */
812                                 option++;
813                                 while (option->name != NULL &&
814                                     (strlen(option->name) < option_length ||
815                                     strncmp(p, option->name, option_length) != 0)) {
816                                         option++;
817                                 }
818                         }
819                         if (option->name != NULL)
820                                 bsdtar_errc(bsdtar, 1, 0,
821                                     "Ambiguous option %s "
822                                     "(matches both %s and %s)",
823                                     p, (*poption)->name, option->name);
824
825                 } else {
826                         opt = '?';
827                         /* TODO: Set up a fake 'struct option' for
828                          * error reporting... ? ? ? */
829                 }
830         }
831
832         return (opt);
833 }