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