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