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