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