]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - usr.bin/tar/bsdtar.c
This commit was generated by cvs2svn to compensate for changes in r172771,
[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 /*
82  * Per POSIX.1-1988, tar defaults to reading/writing archives to/from
83  * the default tape device for the system.  Pick something reasonable here.
84  */
85 #ifdef __linux
86 #define _PATH_DEFTAPE "/dev/st0"
87 #endif
88
89 #ifndef _PATH_DEFTAPE
90 #define _PATH_DEFTAPE "/dev/tape"
91 #endif
92
93 /* External function to parse a date/time string (from getdate.y) */
94 time_t get_date(const char *);
95
96 static int               bsdtar_getopt(struct bsdtar *, const char *optstring,
97     const struct option **poption);
98 static void              long_help(struct bsdtar *);
99 static void              only_mode(struct bsdtar *, const char *opt,
100                              const char *valid);
101 static char **           rewrite_argv(struct bsdtar *,
102                              int *argc, char ** src_argv,
103                              const char *optstring);
104 static void              set_mode(struct bsdtar *, char opt);
105 static void              version(void);
106
107 /*
108  * The leading '+' here forces the GNU version of getopt() (as well as
109  * both the GNU and BSD versions of getopt_long) to stop at the first
110  * non-option.  Otherwise, GNU getopt() permutes the arguments and
111  * screws up -C processing.
112  */
113 static const char *tar_opts = "+Bb:C:cf:HhI:jkLlmnOoPprtT:UuvW:wX:xyZz";
114
115 /*
116  * Most of these long options are deliberately not documented.  They
117  * are provided only to make life easier for people who also use GNU tar.
118  * The only long options documented in the manual page are the ones
119  * with no corresponding short option, such as --exclude, --nodump,
120  * and --fast-read.
121  *
122  * On systems that lack getopt_long, long options can be specified
123  * using -W longopt and -W longopt=value, e.g. "-W nodump" is the same
124  * as "--nodump" and "-W exclude=pattern" is the same as "--exclude
125  * pattern".  This does not rely the GNU getopt() "W;" extension, so
126  * should work correctly on any system with a POSIX-compliant getopt().
127  */
128
129 /* Fake short equivalents for long options that otherwise lack them. */
130 enum {
131         OPTION_CHECK_LINKS=1,
132         OPTION_EXCLUDE,
133         OPTION_FAST_READ,
134         OPTION_FORMAT,
135         OPTION_HELP,
136         OPTION_INCLUDE,
137         OPTION_NEWER_CTIME,
138         OPTION_NEWER_CTIME_THAN,
139         OPTION_NEWER_MTIME,
140         OPTION_NEWER_MTIME_THAN,
141         OPTION_NODUMP,
142         OPTION_NO_SAME_OWNER,
143         OPTION_NO_SAME_PERMISSIONS,
144         OPTION_NULL,
145         OPTION_ONE_FILE_SYSTEM,
146         OPTION_POSIX,
147         OPTION_STRIP_COMPONENTS,
148         OPTION_TOTALS,
149         OPTION_USE_COMPRESS_PROGRAM,
150         OPTION_VERSION
151 };
152
153 /*
154  * If you add anything, be very careful to keep this list properly
155  * sorted, as the -W logic relies on it.
156  */
157 static const struct option tar_longopts[] = {
158         { "absolute-paths",     no_argument,       NULL, 'P' },
159         { "append",             no_argument,       NULL, 'r' },
160         { "block-size",         required_argument, NULL, 'b' },
161         { "bunzip2",            no_argument,       NULL, 'j' },
162         { "bzip",               no_argument,       NULL, 'j' },
163         { "bzip2",              no_argument,       NULL, 'j' },
164         { "cd",                 required_argument, NULL, 'C' },
165         { "check-links",        no_argument,       NULL, OPTION_CHECK_LINKS },
166         { "confirmation",       no_argument,       NULL, 'w' },
167         { "create",             no_argument,       NULL, 'c' },
168         { "dereference",        no_argument,       NULL, 'L' },
169         { "directory",          required_argument, NULL, 'C' },
170         { "exclude",            required_argument, NULL, OPTION_EXCLUDE },
171         { "exclude-from",       required_argument, NULL, 'X' },
172         { "extract",            no_argument,       NULL, 'x' },
173         { "fast-read",          no_argument,       NULL, OPTION_FAST_READ },
174         { "file",               required_argument, NULL, 'f' },
175         { "files-from",         required_argument, NULL, 'T' },
176         { "format",             required_argument, NULL, OPTION_FORMAT },
177         { "gunzip",             no_argument,       NULL, 'z' },
178         { "gzip",               no_argument,       NULL, 'z' },
179         { "help",               no_argument,       NULL, OPTION_HELP },
180         { "include",            required_argument, NULL, OPTION_INCLUDE },
181         { "interactive",        no_argument,       NULL, 'w' },
182         { "keep-old-files",     no_argument,       NULL, 'k' },
183         { "list",               no_argument,       NULL, 't' },
184         { "modification-time",  no_argument,       NULL, 'm' },
185         { "newer",              required_argument, NULL, OPTION_NEWER_CTIME },
186         { "newer-ctime",        required_argument, NULL, OPTION_NEWER_CTIME },
187         { "newer-ctime-than",   required_argument, NULL, OPTION_NEWER_CTIME_THAN },
188         { "newer-mtime",        required_argument, NULL, OPTION_NEWER_MTIME },
189         { "newer-mtime-than",   required_argument, NULL, OPTION_NEWER_MTIME_THAN },
190         { "newer-than",         required_argument, NULL, OPTION_NEWER_CTIME_THAN },
191         { "nodump",             no_argument,       NULL, OPTION_NODUMP },
192         { "norecurse",          no_argument,       NULL, 'n' },
193         { "no-recursion",       no_argument,       NULL, 'n' },
194         { "no-same-owner",      no_argument,       NULL, OPTION_NO_SAME_OWNER },
195         { "no-same-permissions",no_argument,       NULL, OPTION_NO_SAME_PERMISSIONS },
196         { "null",               no_argument,       NULL, OPTION_NULL },
197         { "one-file-system",    no_argument,       NULL, OPTION_ONE_FILE_SYSTEM },
198         { "posix",              no_argument,       NULL, OPTION_POSIX },
199         { "preserve-permissions", no_argument,     NULL, 'p' },
200         { "read-full-blocks",   no_argument,       NULL, 'B' },
201         { "same-permissions",   no_argument,       NULL, 'p' },
202         { "strip-components",   required_argument, NULL, OPTION_STRIP_COMPONENTS },
203         { "to-stdout",          no_argument,       NULL, 'O' },
204         { "totals",             no_argument,       NULL, OPTION_TOTALS },
205         { "unlink",             no_argument,       NULL, 'U' },
206         { "unlink-first",       no_argument,       NULL, 'U' },
207         { "update",             no_argument,       NULL, 'u' },
208         { "use-compress-program",
209                                 required_argument, NULL, OPTION_USE_COMPRESS_PROGRAM },
210         { "verbose",            no_argument,       NULL, 'v' },
211         { "version",            no_argument,       NULL, OPTION_VERSION },
212         { NULL, 0, NULL, 0 }
213 };
214
215 /* A basic set of security flags to request from libarchive. */
216 #define SECURITY                                        \
217         (ARCHIVE_EXTRACT_SECURE_SYMLINKS                \
218          | ARCHIVE_EXTRACT_SECURE_NODOTDOT)
219
220 int
221 main(int argc, char **argv)
222 {
223         struct bsdtar           *bsdtar, bsdtar_storage;
224         const struct option     *option;
225         int                      opt, t;
226         char                     option_o;
227         char                     possible_help_request;
228         char                     buff[16];
229
230         /*
231          * Use a pointer for consistency, but stack-allocated storage
232          * for ease of cleanup.
233          */
234         bsdtar = &bsdtar_storage;
235         memset(bsdtar, 0, sizeof(*bsdtar));
236         bsdtar->fd = -1; /* Mark as "unused" */
237         option_o = 0;
238
239         /* Need bsdtar->progname before calling bsdtar_warnc. */
240         if (*argv == NULL)
241                 bsdtar->progname = "bsdtar";
242         else {
243                 bsdtar->progname = strrchr(*argv, '/');
244                 if (bsdtar->progname != NULL)
245                         bsdtar->progname++;
246                 else
247                         bsdtar->progname = *argv;
248         }
249
250         if (setlocale(LC_ALL, "") == NULL)
251                 bsdtar_warnc(bsdtar, 0, "Failed to set default locale");
252 #if defined(HAVE_NL_LANGINFO) && defined(HAVE_D_MD_ORDER)
253         bsdtar->day_first = (*nl_langinfo(D_MD_ORDER) == 'd');
254 #endif
255         possible_help_request = 0;
256
257         /* Look up uid of current user for future reference */
258         bsdtar->user_uid = geteuid();
259
260         /* Default: open tape drive. */
261         bsdtar->filename = getenv("TAPE");
262         if (bsdtar->filename == NULL)
263                 bsdtar->filename = _PATH_DEFTAPE;
264
265         /* Default: preserve mod time on extract */
266         bsdtar->extract_flags = ARCHIVE_EXTRACT_TIME;
267
268         /* Default: Perform basic security checks. */
269         bsdtar->extract_flags |= SECURITY;
270
271         /* Defaults for root user: */
272         if (bsdtar->user_uid == 0) {
273                 /* --same-owner */
274                 bsdtar->extract_flags |= ARCHIVE_EXTRACT_OWNER;
275                 /* -p */
276                 bsdtar->extract_flags |= ARCHIVE_EXTRACT_PERM;
277                 bsdtar->extract_flags |= ARCHIVE_EXTRACT_ACL;
278                 bsdtar->extract_flags |= ARCHIVE_EXTRACT_XATTR;
279                 bsdtar->extract_flags |= ARCHIVE_EXTRACT_FFLAGS;
280         }
281
282         /* Rewrite traditional-style tar arguments, if used. */
283         argv = rewrite_argv(bsdtar, &argc, argv, tar_opts);
284
285         bsdtar->argv = argv;
286         bsdtar->argc = argc;
287
288         /* Process all remaining arguments now. */
289         /*
290          * Comments following each option indicate where that option
291          * originated:  SUSv2, POSIX, GNU tar, star, etc.  If there's
292          * no such comment, then I don't know of anyone else who
293          * implements that option.
294          */
295         while ((opt = bsdtar_getopt(bsdtar, tar_opts, &option)) != -1) {
296                 switch (opt) {
297                 case 'B': /* GNU tar */
298                         /* libarchive doesn't need this; just ignore it. */
299                         break;
300                 case 'b': /* SUSv2 */
301                         t = atoi(optarg);
302                         if (t <= 0 || t > 1024)
303                                 bsdtar_errc(bsdtar, 1, 0,
304                                     "Argument to -b is out of range (1..1024)");
305                         bsdtar->bytes_per_block = 512 * t;
306                         break;
307                 case 'C': /* GNU tar */
308                         set_chdir(bsdtar, optarg);
309                         break;
310                 case 'c': /* SUSv2 */
311                         set_mode(bsdtar, opt);
312                         break;
313                 case OPTION_CHECK_LINKS: /* GNU tar */
314                         bsdtar->option_warn_links = 1;
315                         break;
316                 case OPTION_EXCLUDE: /* GNU tar */
317                         if (exclude(bsdtar, optarg))
318                                 bsdtar_errc(bsdtar, 1, 0,
319                                     "Couldn't exclude %s\n", optarg);
320                         break;
321                 case OPTION_FORMAT: /* GNU tar, others */
322                         bsdtar->create_format = optarg;
323                         break;
324                 case 'f': /* SUSv2 */
325                         bsdtar->filename = optarg;
326                         if (strcmp(bsdtar->filename, "-") == 0)
327                                 bsdtar->filename = NULL;
328                         break;
329                 case OPTION_FAST_READ: /* GNU tar */
330                         bsdtar->option_fast_read = 1;
331                         break;
332                 case 'H': /* BSD convention */
333                         bsdtar->symlink_mode = 'H';
334                         break;
335                 case 'h': /* Linux Standards Base, gtar; synonym for -L */
336                         bsdtar->symlink_mode = 'L';
337                         /* Hack: -h by itself is the "help" command. */
338                         possible_help_request = 1;
339                         break;
340                 case OPTION_HELP: /* GNU tar, others */
341                         long_help(bsdtar);
342                         exit(0);
343                         break;
344                 case 'I': /* GNU tar */
345                         /*
346                          * TODO: Allow 'names' to come from an archive,
347                          * not just a text file.  Design a good UI for
348                          * allowing names and mode/owner to be read
349                          * from an archive, with contents coming from
350                          * disk.  This can be used to "refresh" an
351                          * archive or to design archives with special
352                          * permissions without having to create those
353                          * permissions on disk.
354                          */
355                         bsdtar->names_from_file = optarg;
356                         break;
357                 case OPTION_INCLUDE:
358                         /*
359                          * Noone else has the @archive extension, so
360                          * noone else needs this to filter entries
361                          * when transforming archives.
362                          */
363                         if (include(bsdtar, optarg))
364                                 bsdtar_errc(bsdtar, 1, 0,
365                                     "Failed to add %s to inclusion list",
366                                     optarg);
367                         break;
368                 case 'j': /* GNU tar */
369 #if HAVE_LIBBZ2
370                         if (bsdtar->create_compression != '\0')
371                                 bsdtar_errc(bsdtar, 1, 0,
372                                     "Can't specify both -%c and -%c", opt,
373                                     bsdtar->create_compression);
374                         bsdtar->create_compression = opt;
375 #else
376                         bsdtar_warnc(bsdtar, 0, "-j compression not supported by this version of bsdtar");
377                         usage(bsdtar);
378 #endif
379                         break;
380                 case 'k': /* GNU tar */
381                         bsdtar->extract_flags |= ARCHIVE_EXTRACT_NO_OVERWRITE;
382                         break;
383                 case 'L': /* BSD convention */
384                         bsdtar->symlink_mode = 'L';
385                         break;
386                 case 'l': /* SUSv2 and GNU conflict badly here */
387                         if (getenv("POSIXLY_CORRECT") != NULL) {
388                                 /* User has asked for POSIX/SUS behavior. */
389                                 bsdtar->option_warn_links = 1;
390                         } else {
391                                 fprintf(stderr,
392 "Error: -l has different behaviors in different tar programs.\n");
393                                 fprintf(stderr,
394 "  For the GNU behavior, use --one-file-system instead.\n");
395                                 fprintf(stderr,
396 "  For the POSIX behavior, use --check-links instead.\n");
397                                 usage(bsdtar);
398                         }
399                         break;
400                 case 'm': /* SUSv2 */
401                         bsdtar->extract_flags &= ~ARCHIVE_EXTRACT_TIME;
402                         break;
403                 case 'n': /* GNU tar */
404                         bsdtar->option_no_subdirs = 1;
405                         break;
406                 /*
407                  * Selecting files by time:
408                  *    --newer-?time='date' Only files newer than 'date'
409                  *    --newer-?time-than='file' Only files newer than time
410                  *         on specified file (useful for incremental backups)
411                  * TODO: Add corresponding "older" options to reverse these.
412                  */
413                 case OPTION_NEWER_CTIME: /* GNU tar */
414                         bsdtar->newer_ctime_sec = get_date(optarg);
415                         break;
416                 case OPTION_NEWER_CTIME_THAN:
417                         {
418                                 struct stat st;
419                                 if (stat(optarg, &st) != 0)
420                                         bsdtar_errc(bsdtar, 1, 0,
421                                             "Can't open file %s", optarg);
422                                 bsdtar->newer_ctime_sec = st.st_ctime;
423                                 bsdtar->newer_ctime_nsec =
424                                     ARCHIVE_STAT_CTIME_NANOS(&st);
425                         }
426                         break;
427                 case OPTION_NEWER_MTIME: /* GNU tar */
428                         bsdtar->newer_mtime_sec = get_date(optarg);
429                         break;
430                 case OPTION_NEWER_MTIME_THAN:
431                         {
432                                 struct stat st;
433                                 if (stat(optarg, &st) != 0)
434                                         bsdtar_errc(bsdtar, 1, 0,
435                                             "Can't open file %s", optarg);
436                                 bsdtar->newer_mtime_sec = st.st_mtime;
437                                 bsdtar->newer_mtime_nsec =
438                                     ARCHIVE_STAT_MTIME_NANOS(&st);
439                         }
440                         break;
441                 case OPTION_NODUMP: /* star */
442                         bsdtar->option_honor_nodump = 1;
443                         break;
444                 case OPTION_NO_SAME_OWNER: /* GNU tar */
445                         bsdtar->extract_flags &= ~ARCHIVE_EXTRACT_OWNER;
446                         break;
447                 case OPTION_NO_SAME_PERMISSIONS: /* GNU tar */
448                         bsdtar->extract_flags &= ~ARCHIVE_EXTRACT_PERM;
449                         bsdtar->extract_flags &= ~ARCHIVE_EXTRACT_ACL;
450                         bsdtar->extract_flags &= ~ARCHIVE_EXTRACT_XATTR;
451                         bsdtar->extract_flags &= ~ARCHIVE_EXTRACT_FFLAGS;
452                         break;
453                 case OPTION_NULL: /* GNU tar */
454                         bsdtar->option_null++;
455                         break;
456                 case 'O': /* GNU tar */
457                         bsdtar->option_stdout = 1;
458                         break;
459                 case 'o': /* SUSv2 and GNU conflict here, but not fatally */
460                         option_o = 1; /* Record it and resolve it later. */
461                         break;
462                 case OPTION_ONE_FILE_SYSTEM: /* GNU tar */
463                         bsdtar->option_dont_traverse_mounts = 1;
464                         break;
465 #if 0
466                 /*
467                  * The common BSD -P option is not necessary, since
468                  * our default is to archive symlinks, not follow
469                  * them.  This is convenient, as -P conflicts with GNU
470                  * tar anyway.
471                  */
472                 case 'P': /* BSD convention */
473                         /* Default behavior, no option necessary. */
474                         break;
475 #endif
476                 case 'P': /* GNU tar */
477                         bsdtar->extract_flags &= ~SECURITY;
478                         bsdtar->option_absolute_paths = 1;
479                         break;
480                 case 'p': /* GNU tar, star */
481                         bsdtar->extract_flags |= ARCHIVE_EXTRACT_PERM;
482                         bsdtar->extract_flags |= ARCHIVE_EXTRACT_ACL;
483                         bsdtar->extract_flags |= ARCHIVE_EXTRACT_XATTR;
484                         bsdtar->extract_flags |= ARCHIVE_EXTRACT_FFLAGS;
485                         break;
486                 case OPTION_POSIX: /* GNU tar */
487                         bsdtar->create_format = "pax";
488                         break;
489                 case 'r': /* SUSv2 */
490                         set_mode(bsdtar, opt);
491                         break;
492                 case OPTION_STRIP_COMPONENTS: /* GNU tar 1.15 */
493                         bsdtar->strip_components = atoi(optarg);
494                         break;
495                 case 'T': /* GNU tar */
496                         bsdtar->names_from_file = optarg;
497                         break;
498                 case 't': /* SUSv2 */
499                         set_mode(bsdtar, opt);
500                         bsdtar->verbose++;
501                         break;
502                 case OPTION_TOTALS: /* GNU tar */
503                         bsdtar->option_totals++;
504                         break;
505                 case 'U': /* GNU tar */
506                         bsdtar->extract_flags |= ARCHIVE_EXTRACT_UNLINK;
507                         bsdtar->option_unlink_first = 1;
508                         break;
509                 case 'u': /* SUSv2 */
510                         set_mode(bsdtar, opt);
511                         break;
512                 case 'v': /* SUSv2 */
513                         bsdtar->verbose++;
514                         break;
515                 case OPTION_VERSION: /* GNU convention */
516                         version();
517                         break;
518 #if 0
519                 /*
520                  * The -W longopt feature is handled inside of
521                  * bsdtar_getop(), so -W is not available here.
522                  */
523                 case 'W': /* Obscure, but useful GNU convention. */
524                         break;
525 #endif
526                 case 'w': /* SUSv2 */
527                         bsdtar->option_interactive = 1;
528                         break;
529                 case 'X': /* GNU tar */
530                         if (exclude_from_file(bsdtar, optarg))
531                                 bsdtar_errc(bsdtar, 1, 0,
532                                     "failed to process exclusions from file %s",
533                                     optarg);
534                         break;
535                 case 'x': /* SUSv2 */
536                         set_mode(bsdtar, opt);
537                         break;
538                 case 'y': /* FreeBSD version of GNU tar */
539 #if HAVE_LIBBZ2
540                         if (bsdtar->create_compression != '\0')
541                                 bsdtar_errc(bsdtar, 1, 0,
542                                     "Can't specify both -%c and -%c", opt,
543                                     bsdtar->create_compression);
544                         bsdtar->create_compression = opt;
545 #else
546                         bsdtar_warnc(bsdtar, 0, "-y compression not supported by this version of bsdtar");
547                         usage(bsdtar);
548 #endif
549                         break;
550                 case 'Z': /* GNU tar */
551                         if (bsdtar->create_compression != '\0')
552                                 bsdtar_errc(bsdtar, 1, 0,
553                                     "Can't specify both -%c and -%c", opt,
554                                     bsdtar->create_compression);
555                         bsdtar->create_compression = opt;
556                         break;
557                 case 'z': /* GNU tar, star, many others */
558 #if HAVE_LIBZ
559                         if (bsdtar->create_compression != '\0')
560                                 bsdtar_errc(bsdtar, 1, 0,
561                                     "Can't specify both -%c and -%c", opt,
562                                     bsdtar->create_compression);
563                         bsdtar->create_compression = opt;
564 #else
565                         bsdtar_warnc(bsdtar, 0, "-z compression not supported by this version of bsdtar");
566                         usage(bsdtar);
567 #endif
568                         break;
569                 case OPTION_USE_COMPRESS_PROGRAM:
570                         bsdtar->compress_program = optarg;
571                         break;
572                 default:
573                         usage(bsdtar);
574                 }
575         }
576
577         /*
578          * Sanity-check options.
579          */
580
581         /* If no "real" mode was specified, treat -h as --help. */
582         if ((bsdtar->mode == '\0') && possible_help_request) {
583                 long_help(bsdtar);
584                 exit(0);
585         }
586
587         /* Otherwise, a mode is required. */
588         if (bsdtar->mode == '\0')
589                 bsdtar_errc(bsdtar, 1, 0,
590                     "Must specify one of -c, -r, -t, -u, -x");
591
592         /* Check boolean options only permitted in certain modes. */
593         if (bsdtar->option_dont_traverse_mounts)
594                 only_mode(bsdtar, "--one-file-system", "cru");
595         if (bsdtar->option_fast_read)
596                 only_mode(bsdtar, "--fast-read", "xt");
597         if (bsdtar->option_honor_nodump)
598                 only_mode(bsdtar, "--nodump", "cru");
599         if (option_o > 0) {
600                 switch (bsdtar->mode) {
601                 case 'c':
602                         /*
603                          * In GNU tar, -o means "old format."  The
604                          * "ustar" format is the closest thing
605                          * supported by libarchive.
606                          */
607                         bsdtar->create_format = "ustar";
608                         /* TODO: bsdtar->create_format = "v7"; */
609                         break;
610                 case 'x':
611                         /* POSIX-compatible behavior. */
612                         bsdtar->option_no_owner = 1;
613                         bsdtar->extract_flags &= ~ARCHIVE_EXTRACT_OWNER;
614                         break;
615                 default:
616                         only_mode(bsdtar, "-o", "xc");
617                         break;
618                 }
619         }
620         if (bsdtar->option_no_subdirs)
621                 only_mode(bsdtar, "-n", "cru");
622         if (bsdtar->option_stdout)
623                 only_mode(bsdtar, "-O", "xt");
624         if (bsdtar->option_unlink_first)
625                 only_mode(bsdtar, "-U", "x");
626         if (bsdtar->option_warn_links)
627                 only_mode(bsdtar, "--check-links", "cr");
628
629         /* Check other parameters only permitted in certain modes. */
630         if (bsdtar->create_compression == 'Z' && bsdtar->mode == 'c') {
631                 bsdtar_warnc(bsdtar, 0, ".Z compression not supported");
632                 usage(bsdtar);
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", PACKAGE_VERSION, archive_version());
788         exit(1);
789 }
790
791 static const char *long_help_msg =
792         "First option must be a mode specifier:\n"
793         "  -c Create  -r Add/Replace  -t List  -u Update  -x Extract\n"
794         "Common Options:\n"
795         "  -b #  Use # 512-byte records per I/O block\n"
796         "  -f <filename>  Location of archive (default " _PATH_DEFTAPE ")\n"
797         "  -v    Verbose\n"
798         "  -w    Interactive\n"
799         "Create: %p -c [options] [<file> | <dir> | @<archive> | -C <dir> ]\n"
800         "  <file>, <dir>  add these items to archive\n"
801         "  -z, -j  Compress archive with gzip/bzip2\n"
802         "  --format {ustar|pax|cpio|shar}  Select archive format\n"
803 #ifdef HAVE_GETOPT_LONG
804         "  --exclude <pattern>  Skip files that match pattern\n"
805 #else
806         "  -W exclude=<pattern>  Skip files that match pattern\n"
807 #endif
808         "  -C <dir>  Change to <dir> before processing remaining files\n"
809         "  @<archive>  Add entries from <archive> to output\n"
810         "List: %p -t [options] [<patterns>]\n"
811         "  <patterns>  If specified, list only entries that match\n"
812         "Extract: %p -x [options] [<patterns>]\n"
813         "  <patterns>  If specified, extract only entries that match\n"
814         "  -k    Keep (don't overwrite) existing files\n"
815         "  -m    Don't restore modification times\n"
816         "  -O    Write entries to stdout, don't restore to disk\n"
817         "  -p    Restore permissions (including ACLs, owner, file flags)\n";
818
819
820 /*
821  * Note that the word 'bsdtar' will always appear in the first line
822  * of output.
823  *
824  * In particular, /bin/sh scripts that need to test for the presence
825  * of bsdtar can use the following template:
826  *
827  * if (tar --help 2>&1 | grep bsdtar >/dev/null 2>&1 ) then \
828  *          echo bsdtar; else echo not bsdtar; fi
829  */
830 static void
831 long_help(struct bsdtar *bsdtar)
832 {
833         const char      *prog;
834         const char      *p;
835
836         prog = bsdtar->progname;
837
838         fflush(stderr);
839
840         p = (strcmp(prog,"bsdtar") != 0) ? "(bsdtar)" : "";
841         printf("%s%s: manipulate archive files\n", prog, p);
842
843         for (p = long_help_msg; *p != '\0'; p++) {
844                 if (*p == '%') {
845                         if (p[1] == 'p') {
846                                 fputs(prog, stdout);
847                                 p++;
848                         } else
849                                 putchar('%');
850                 } else
851                         putchar(*p);
852         }
853         version();
854 }
855
856 static int
857 bsdtar_getopt(struct bsdtar *bsdtar, const char *optstring,
858     const struct option **poption)
859 {
860         char *p, *q;
861         const struct option *option;
862         int opt;
863         int option_index;
864         size_t option_length;
865
866         option_index = -1;
867         *poption = NULL;
868
869 #ifdef HAVE_GETOPT_LONG
870         opt = getopt_long(bsdtar->argc, bsdtar->argv, optstring,
871             tar_longopts, &option_index);
872         if (option_index > -1)
873                 *poption = tar_longopts + option_index;
874 #else
875         opt = getopt(bsdtar->argc, bsdtar->argv, optstring);
876 #endif
877
878         /* Support long options through -W longopt=value */
879         if (opt == 'W') {
880                 p = optarg;
881                 q = strchr(optarg, '=');
882                 if (q != NULL) {
883                         option_length = (size_t)(q - p);
884                         optarg = q + 1;
885                 } else {
886                         option_length = strlen(p);
887                         optarg = NULL;
888                 }
889                 option = tar_longopts;
890                 while (option->name != NULL &&
891                     (strlen(option->name) < option_length ||
892                     strncmp(p, option->name, option_length) != 0 )) {
893                         option++;
894                 }
895
896                 if (option->name != NULL) {
897                         *poption = option;
898                         opt = option->val;
899
900                         /* If the first match was exact, we're done. */
901                         if (strncmp(p, option->name, strlen(option->name)) == 0) {
902                                 while (option->name != NULL)
903                                         option++;
904                         } else {
905                                 /* Check if there's another match. */
906                                 option++;
907                                 while (option->name != NULL &&
908                                     (strlen(option->name) < option_length ||
909                                     strncmp(p, option->name, option_length) != 0)) {
910                                         option++;
911                                 }
912                         }
913                         if (option->name != NULL)
914                                 bsdtar_errc(bsdtar, 1, 0,
915                                     "Ambiguous option %s "
916                                     "(matches both %s and %s)",
917                                     p, (*poption)->name, option->name);
918
919                         if ((*poption)->has_arg == required_argument
920                             && optarg == NULL)
921                                 bsdtar_errc(bsdtar, 1, 0,
922                                     "Option \"%s\" requires argument", p);
923                 } else {
924                         opt = '?';
925                         /* TODO: Set up a fake 'struct option' for
926                          * error reporting... ? ? ? */
927                 }
928         }
929
930         return (opt);
931 }