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