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