]> CyberLeo.Net >> Repos - FreeBSD/stable/10.git/blob - contrib/libarchive/tar/cmdline.c
MFC r299529,r299540,r299576,r299896:
[FreeBSD/stable/10.git] / contrib / libarchive / tar / cmdline.c
1 /*-
2  * Copyright (c) 2003-2008 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 /*
27  * Command line parser for tar.
28  */
29
30 #include "bsdtar_platform.h"
31 __FBSDID("$FreeBSD$");
32
33 #ifdef HAVE_ERRNO_H
34 #include <errno.h>
35 #endif
36 #ifdef HAVE_STDLIB_H
37 #include <stdlib.h>
38 #endif
39 #ifdef HAVE_STRING_H
40 #include <string.h>
41 #endif
42
43 #include "bsdtar.h"
44 #include "err.h"
45
46 /*
47  * Short options for tar.  Please keep this sorted.
48  */
49 static const char *short_options
50         = "aBb:C:cf:HhI:JjkLlmnOoPpqrSs:T:tUuvW:wX:xyZz";
51
52 /*
53  * Long options for tar.  Please keep this list sorted.
54  *
55  * The symbolic names for options that lack a short equivalent are
56  * defined in bsdtar.h.  Also note that so far I've found no need
57  * to support optional arguments to long options.  That would be
58  * a small change to the code below.
59  */
60
61 static const struct bsdtar_option {
62         const char *name;
63         int required;      /* 1 if this option requires an argument. */
64         int equivalent;    /* Equivalent short option. */
65 } tar_longopts[] = {
66         { "absolute-paths",       0, 'P' },
67         { "append",               0, 'r' },
68         { "auto-compress",        0, 'a' },
69         { "b64encode",            0, OPTION_B64ENCODE },
70         { "block-size",           1, 'b' },
71         { "bunzip2",              0, 'j' },
72         { "bzip",                 0, 'j' },
73         { "bzip2",                0, 'j' },
74         { "cd",                   1, 'C' },
75         { "check-links",          0, OPTION_CHECK_LINKS },
76         { "chroot",               0, OPTION_CHROOT },
77         { "clear-nochange-fflags", 0, OPTION_CLEAR_NOCHANGE_FFLAGS },
78         { "compress",             0, 'Z' },
79         { "confirmation",         0, 'w' },
80         { "create",               0, 'c' },
81         { "dereference",          0, 'L' },
82         { "directory",            1, 'C' },
83         { "disable-copyfile",     0, OPTION_DISABLE_COPYFILE },
84         { "exclude",              1, OPTION_EXCLUDE },
85         { "exclude-from",         1, 'X' },
86         { "extract",              0, 'x' },
87         { "fast-read",            0, 'q' },
88         { "file",                 1, 'f' },
89         { "files-from",           1, 'T' },
90         { "format",               1, OPTION_FORMAT },
91         { "gid",                  1, OPTION_GID },
92         { "gname",                1, OPTION_GNAME },
93         { "grzip",                0, OPTION_GRZIP },
94         { "gunzip",               0, 'z' },
95         { "gzip",                 0, 'z' },
96         { "help",                 0, OPTION_HELP },
97         { "hfsCompression",       0, OPTION_HFS_COMPRESSION },
98         { "ignore-zeros",         0, OPTION_IGNORE_ZEROS },
99         { "include",              1, OPTION_INCLUDE },
100         { "insecure",             0, 'P' },
101         { "interactive",          0, 'w' },
102         { "keep-newer-files",     0, OPTION_KEEP_NEWER_FILES },
103         { "keep-old-files",       0, 'k' },
104         { "list",                 0, 't' },
105         { "lrzip",                0, OPTION_LRZIP },
106         { "lz4",                  0, OPTION_LZ4 },
107         { "lzip",                 0, OPTION_LZIP },
108         { "lzma",                 0, OPTION_LZMA },
109         { "lzop",                 0, OPTION_LZOP },
110         { "modification-time",    0, 'm' },
111         { "newer",                1, OPTION_NEWER_CTIME },
112         { "newer-ctime",          1, OPTION_NEWER_CTIME },
113         { "newer-ctime-than",     1, OPTION_NEWER_CTIME_THAN },
114         { "newer-mtime",          1, OPTION_NEWER_MTIME },
115         { "newer-mtime-than",     1, OPTION_NEWER_MTIME_THAN },
116         { "newer-than",           1, OPTION_NEWER_CTIME_THAN },
117         { "no-recursion",         0, 'n' },
118         { "no-same-owner",        0, OPTION_NO_SAME_OWNER },
119         { "no-same-permissions",  0, OPTION_NO_SAME_PERMISSIONS },
120         { "no-xattr",             0, OPTION_NO_XATTR },
121         { "nodump",               0, OPTION_NODUMP },
122         { "nopreserveHFSCompression",0, OPTION_NOPRESERVE_HFS_COMPRESSION },
123         { "norecurse",            0, 'n' },
124         { "null",                 0, OPTION_NULL },
125         { "numeric-owner",        0, OPTION_NUMERIC_OWNER },
126         { "older",                1, OPTION_OLDER_CTIME },
127         { "older-ctime",          1, OPTION_OLDER_CTIME },
128         { "older-ctime-than",     1, OPTION_OLDER_CTIME_THAN },
129         { "older-mtime",          1, OPTION_OLDER_MTIME },
130         { "older-mtime-than",     1, OPTION_OLDER_MTIME_THAN },
131         { "older-than",           1, OPTION_OLDER_CTIME_THAN },
132         { "one-file-system",      0, OPTION_ONE_FILE_SYSTEM },
133         { "options",              1, OPTION_OPTIONS },
134         { "passphrase",           1, OPTION_PASSPHRASE },
135         { "posix",                0, OPTION_POSIX },
136         { "preserve-permissions", 0, 'p' },
137         { "read-full-blocks",     0, 'B' },
138         { "same-owner",           0, OPTION_SAME_OWNER },
139         { "same-permissions",     0, 'p' },
140         { "strip-components",     1, OPTION_STRIP_COMPONENTS },
141         { "to-stdout",            0, 'O' },
142         { "totals",               0, OPTION_TOTALS },
143         { "uid",                  1, OPTION_UID },
144         { "uname",                1, OPTION_UNAME },
145         { "uncompress",           0, 'Z' },
146         { "unlink",               0, 'U' },
147         { "unlink-first",         0, 'U' },
148         { "update",               0, 'u' },
149         { "use-compress-program", 1, OPTION_USE_COMPRESS_PROGRAM },
150         { "uuencode",             0, OPTION_UUENCODE },
151         { "verbose",              0, 'v' },
152         { "version",              0, OPTION_VERSION },
153         { "xz",                   0, 'J' },
154         { NULL, 0, 0 }
155 };
156
157 /*
158  * This getopt implementation has two key features that common
159  * getopt_long() implementations lack.  Apart from those, it's a
160  * straightforward option parser, considerably simplified by not
161  * needing to support the wealth of exotic getopt_long() features.  It
162  * has, of course, been shamelessly tailored for bsdtar.  (If you're
163  * looking for a generic getopt_long() implementation for your
164  * project, I recommend Gregory Pietsch's public domain getopt_long()
165  * implementation.)  The two additional features are:
166  *
167  * Old-style tar arguments: The original tar implementation treated
168  * the first argument word as a list of single-character option
169  * letters.  All arguments follow as separate words.  For example,
170  *    tar xbf 32 /dev/tape
171  * Here, the "xbf" is three option letters, "32" is the argument for
172  * "b" and "/dev/tape" is the argument for "f".  We support this usage
173  * if the first command-line argument does not begin with '-'.  We
174  * also allow regular short and long options to follow, e.g.,
175  *    tar xbf 32 /dev/tape -P --format=pax
176  *
177  * -W long options: There's an obscure GNU convention (only rarely
178  * supported even there) that allows "-W option=argument" as an
179  * alternative way to support long options.  This was supported in
180  * early bsdtar as a way to access long options on platforms that did
181  * not support getopt_long() and is preserved here for backwards
182  * compatibility.  (Of course, if I'd started with a custom
183  * command-line parser from the beginning, I would have had normal
184  * long option support on every platform so that hack wouldn't have
185  * been necessary.  Oh, well.  Some mistakes you just have to live
186  * with.)
187  *
188  * TODO: We should be able to use this to pull files and intermingled
189  * options (such as -C) from the command line in write mode.  That
190  * will require a little rethinking of the argument handling in
191  * bsdtar.c.
192  *
193  * TODO: If we want to support arbitrary command-line options from -T
194  * input (as GNU tar does), we may need to extend this to handle option
195  * words from sources other than argv/argc.  I'm not really sure if I
196  * like that feature of GNU tar, so it's certainly not a priority.
197  */
198
199 int
200 bsdtar_getopt(struct bsdtar *bsdtar)
201 {
202         enum { state_start = 0, state_old_tar, state_next_word,
203                state_short, state_long };
204
205         const struct bsdtar_option *popt, *match = NULL, *match2 = NULL;
206         const char *p, *long_prefix = "--";
207         size_t optlength;
208         int opt = '?';
209         int required = 0;
210
211         bsdtar->argument = NULL;
212
213         /* First time through, initialize everything. */
214         if (bsdtar->getopt_state == state_start) {
215                 /* Skip program name. */
216                 ++bsdtar->argv;
217                 --bsdtar->argc;
218                 if (*bsdtar->argv == NULL)
219                         return (-1);
220                 /* Decide between "new style" and "old style" arguments. */
221                 if (bsdtar->argv[0][0] == '-') {
222                         bsdtar->getopt_state = state_next_word;
223                 } else {
224                         bsdtar->getopt_state = state_old_tar;
225                         bsdtar->getopt_word = *bsdtar->argv++;
226                         --bsdtar->argc;
227                 }
228         }
229
230         /*
231          * We're parsing old-style tar arguments
232          */
233         if (bsdtar->getopt_state == state_old_tar) {
234                 /* Get the next option character. */
235                 opt = *bsdtar->getopt_word++;
236                 if (opt == '\0') {
237                         /* New-style args can follow old-style. */
238                         bsdtar->getopt_state = state_next_word;
239                 } else {
240                         /* See if it takes an argument. */
241                         p = strchr(short_options, opt);
242                         if (p == NULL)
243                                 return ('?');
244                         if (p[1] == ':') {
245                                 bsdtar->argument = *bsdtar->argv;
246                                 if (bsdtar->argument == NULL) {
247                                         lafe_warnc(0,
248                                             "Option %c requires an argument",
249                                             opt);
250                                         return ('?');
251                                 }
252                                 ++bsdtar->argv;
253                                 --bsdtar->argc;
254                         }
255                 }
256         }
257
258         /*
259          * We're ready to look at the next word in argv.
260          */
261         if (bsdtar->getopt_state == state_next_word) {
262                 /* No more arguments, so no more options. */
263                 if (bsdtar->argv[0] == NULL)
264                         return (-1);
265                 /* Doesn't start with '-', so no more options. */
266                 if (bsdtar->argv[0][0] != '-')
267                         return (-1);
268                 /* "--" marks end of options; consume it and return. */
269                 if (strcmp(bsdtar->argv[0], "--") == 0) {
270                         ++bsdtar->argv;
271                         --bsdtar->argc;
272                         return (-1);
273                 }
274                 /* Get next word for parsing. */
275                 bsdtar->getopt_word = *bsdtar->argv++;
276                 --bsdtar->argc;
277                 if (bsdtar->getopt_word[1] == '-') {
278                         /* Set up long option parser. */
279                         bsdtar->getopt_state = state_long;
280                         bsdtar->getopt_word += 2; /* Skip leading '--' */
281                 } else {
282                         /* Set up short option parser. */
283                         bsdtar->getopt_state = state_short;
284                         ++bsdtar->getopt_word;  /* Skip leading '-' */
285                 }
286         }
287
288         /*
289          * We're parsing a group of POSIX-style single-character options.
290          */
291         if (bsdtar->getopt_state == state_short) {
292                 /* Peel next option off of a group of short options. */
293                 opt = *bsdtar->getopt_word++;
294                 if (opt == '\0') {
295                         /* End of this group; recurse to get next option. */
296                         bsdtar->getopt_state = state_next_word;
297                         return bsdtar_getopt(bsdtar);
298                 }
299
300                 /* Does this option take an argument? */
301                 p = strchr(short_options, opt);
302                 if (p == NULL)
303                         return ('?');
304                 if (p[1] == ':')
305                         required = 1;
306
307                 /* If it takes an argument, parse that. */
308                 if (required) {
309                         /* If arg is run-in, bsdtar->getopt_word already points to it. */
310                         if (bsdtar->getopt_word[0] == '\0') {
311                                 /* Otherwise, pick up the next word. */
312                                 bsdtar->getopt_word = *bsdtar->argv;
313                                 if (bsdtar->getopt_word == NULL) {
314                                         lafe_warnc(0,
315                                             "Option -%c requires an argument",
316                                             opt);
317                                         return ('?');
318                                 }
319                                 ++bsdtar->argv;
320                                 --bsdtar->argc;
321                         }
322                         if (opt == 'W') {
323                                 bsdtar->getopt_state = state_long;
324                                 long_prefix = "-W "; /* For clearer errors. */
325                         } else {
326                                 bsdtar->getopt_state = state_next_word;
327                                 bsdtar->argument = bsdtar->getopt_word;
328                         }
329                 }
330         }
331
332         /* We're reading a long option, including -W long=arg convention. */
333         if (bsdtar->getopt_state == state_long) {
334                 /* After this long option, we'll be starting a new word. */
335                 bsdtar->getopt_state = state_next_word;
336
337                 /* Option name ends at '=' if there is one. */
338                 p = strchr(bsdtar->getopt_word, '=');
339                 if (p != NULL) {
340                         optlength = (size_t)(p - bsdtar->getopt_word);
341                         bsdtar->argument = (char *)(uintptr_t)(p + 1);
342                 } else {
343                         optlength = strlen(bsdtar->getopt_word);
344                 }
345
346                 /* Search the table for an unambiguous match. */
347                 for (popt = tar_longopts; popt->name != NULL; popt++) {
348                         /* Short-circuit if first chars don't match. */
349                         if (popt->name[0] != bsdtar->getopt_word[0])
350                                 continue;
351                         /* If option is a prefix of name in table, record it.*/
352                         if (strncmp(bsdtar->getopt_word, popt->name, optlength) == 0) {
353                                 match2 = match; /* Record up to two matches. */
354                                 match = popt;
355                                 /* If it's an exact match, we're done. */
356                                 if (strlen(popt->name) == optlength) {
357                                         match2 = NULL; /* Forget the others. */
358                                         break;
359                                 }
360                         }
361                 }
362
363                 /* Fail if there wasn't a unique match. */
364                 if (match == NULL) {
365                         lafe_warnc(0,
366                             "Option %s%s is not supported",
367                             long_prefix, bsdtar->getopt_word);
368                         return ('?');
369                 }
370                 if (match2 != NULL) {
371                         lafe_warnc(0,
372                             "Ambiguous option %s%s (matches --%s and --%s)",
373                             long_prefix, bsdtar->getopt_word, match->name, match2->name);
374                         return ('?');
375                 }
376
377                 /* We've found a unique match; does it need an argument? */
378                 if (match->required) {
379                         /* Argument required: get next word if necessary. */
380                         if (bsdtar->argument == NULL) {
381                                 bsdtar->argument = *bsdtar->argv;
382                                 if (bsdtar->argument == NULL) {
383                                         lafe_warnc(0,
384                                             "Option %s%s requires an argument",
385                                             long_prefix, match->name);
386                                         return ('?');
387                                 }
388                                 ++bsdtar->argv;
389                                 --bsdtar->argc;
390                         }
391                 } else {
392                         /* Argument forbidden: fail if there is one. */
393                         if (bsdtar->argument != NULL) {
394                                 lafe_warnc(0,
395                                     "Option %s%s does not allow an argument",
396                                     long_prefix, match->name);
397                                 return ('?');
398                         }
399                 }
400                 return (match->equivalent);
401         }
402
403         return (opt);
404 }