cmdline.c revision 370535
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 *    in this position and unchanged.
11 * 2. Redistributions in binary form must reproduce the above copyright
12 *    notice, this list of conditions and the following disclaimer in the
13 *    documentation and/or other materials provided with the distribution.
14 *
15 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS OR
16 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
17 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
18 * IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY DIRECT, INDIRECT,
19 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
20 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
21 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
22 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
24 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25 */
26
27
28#include "cpio_platform.h"
29__FBSDID("$FreeBSD: stable/11/contrib/libarchive/cpio/cmdline.c 370535 2021-09-10 08:34:36Z git2svn $");
30
31#ifdef HAVE_ERRNO_H
32#include <errno.h>
33#endif
34#ifdef HAVE_GRP_H
35#include <grp.h>
36#endif
37#ifdef HAVE_PWD_H
38#include <pwd.h>
39#endif
40#include <stdio.h>
41#ifdef HAVE_STDLIB_H
42#include <stdlib.h>
43#endif
44#ifdef HAVE_STRING_H
45#include <string.h>
46#endif
47
48#include "cpio.h"
49#include "err.h"
50
51/*
52 * Short options for cpio.  Please keep this sorted.
53 */
54static const char *short_options = "067AaBC:cdE:F:f:H:hI:iJjLlmnO:opR:rtuVvW:yZz";
55
56/*
57 * Long options for cpio.  Please keep this sorted.
58 */
59static const struct option {
60	const char *name;
61	int required;	/* 1 if this option requires an argument */
62	int equivalent;	/* Equivalent short option. */
63} cpio_longopts[] = {
64	{ "b64encode",			0, OPTION_B64ENCODE },
65	{ "binary",			0, '7' },
66	{ "create",			0, 'o' },
67	{ "dereference",		0, 'L' },
68	{ "dot",			0, 'V' },
69	{ "extract",			0, 'i' },
70	{ "file",			1, 'F' },
71	{ "format",             	1, 'H' },
72	{ "grzip",			0, OPTION_GRZIP },
73	{ "help",			0, 'h' },
74	{ "insecure",			0, OPTION_INSECURE },
75	{ "link",			0, 'l' },
76	{ "list",			0, 't' },
77	{ "lrzip",			0, OPTION_LRZIP },
78	{ "lz4",			0, OPTION_LZ4 },
79	{ "lzma",			0, OPTION_LZMA },
80	{ "lzop",			0, OPTION_LZOP },
81	{ "make-directories",		0, 'd' },
82	{ "no-preserve-owner",		0, OPTION_NO_PRESERVE_OWNER },
83	{ "null",			0, '0' },
84	{ "numeric-uid-gid",		0, 'n' },
85	{ "owner",			1, 'R' },
86	{ "passphrase",			1, OPTION_PASSPHRASE },
87	{ "pass-through",		0, 'p' },
88	{ "preserve-modification-time", 0, 'm' },
89	{ "preserve-owner",		0, OPTION_PRESERVE_OWNER },
90	{ "pwb",			0, '6' },
91	{ "quiet",			0, OPTION_QUIET },
92	{ "unconditional",		0, 'u' },
93	{ "uuencode",			0, OPTION_UUENCODE },
94	{ "verbose",			0, 'v' },
95	{ "version",			0, OPTION_VERSION },
96	{ "xz",				0, 'J' },
97	{ "zstd",			0, OPTION_ZSTD },
98	{ NULL, 0, 0 }
99};
100
101/*
102 * I used to try to select platform-provided getopt() or
103 * getopt_long(), but that caused a lot of headaches.  In particular,
104 * I couldn't consistently use long options in the test harness
105 * because not all platforms have getopt_long().  That in turn led to
106 * overuse of the -W hack in the test harness, which made it rough to
107 * run the test harness against GNU cpio.  (I periodically run the
108 * test harness here against GNU cpio as a sanity-check.  Yes,
109 * I've found a couple of bugs in GNU cpio that way.)
110 */
111int
112cpio_getopt(struct cpio *cpio)
113{
114	enum { state_start = 0, state_next_word, state_short, state_long };
115	static int state = state_start;
116	static char *opt_word;
117
118	const struct option *popt, *match = NULL, *match2 = NULL;
119	const char *p, *long_prefix = "--";
120	size_t optlength;
121	int opt = '?';
122	int required = 0;
123
124	cpio->argument = NULL;
125
126	/* First time through, initialize everything. */
127	if (state == state_start) {
128		/* Skip program name. */
129		++cpio->argv;
130		--cpio->argc;
131		state = state_next_word;
132	}
133
134	/*
135	 * We're ready to look at the next word in argv.
136	 */
137	if (state == state_next_word) {
138		/* No more arguments, so no more options. */
139		if (cpio->argv[0] == NULL)
140			return (-1);
141		/* Doesn't start with '-', so no more options. */
142		if (cpio->argv[0][0] != '-')
143			return (-1);
144		/* "--" marks end of options; consume it and return. */
145		if (strcmp(cpio->argv[0], "--") == 0) {
146			++cpio->argv;
147			--cpio->argc;
148			return (-1);
149		}
150		/* Get next word for parsing. */
151		opt_word = *cpio->argv++;
152		--cpio->argc;
153		if (opt_word[1] == '-') {
154			/* Set up long option parser. */
155			state = state_long;
156			opt_word += 2; /* Skip leading '--' */
157		} else {
158			/* Set up short option parser. */
159			state = state_short;
160			++opt_word;  /* Skip leading '-' */
161		}
162	}
163
164	/*
165	 * We're parsing a group of POSIX-style single-character options.
166	 */
167	if (state == state_short) {
168		/* Peel next option off of a group of short options. */
169		opt = *opt_word++;
170		if (opt == '\0') {
171			/* End of this group; recurse to get next option. */
172			state = state_next_word;
173			return cpio_getopt(cpio);
174		}
175
176		/* Does this option take an argument? */
177		p = strchr(short_options, opt);
178		if (p == NULL)
179			return ('?');
180		if (p[1] == ':')
181			required = 1;
182
183		/* If it takes an argument, parse that. */
184		if (required) {
185			/* If arg is run-in, opt_word already points to it. */
186			if (opt_word[0] == '\0') {
187				/* Otherwise, pick up the next word. */
188				opt_word = *cpio->argv;
189				if (opt_word == NULL) {
190					lafe_warnc(0,
191					    "Option -%c requires an argument",
192					    opt);
193					return ('?');
194				}
195				++cpio->argv;
196				--cpio->argc;
197			}
198			if (opt == 'W') {
199				state = state_long;
200				long_prefix = "-W "; /* For clearer errors. */
201			} else {
202				state = state_next_word;
203				cpio->argument = opt_word;
204			}
205		}
206	}
207
208	/* We're reading a long option, including -W long=arg convention. */
209	if (state == state_long) {
210		/* After this long option, we'll be starting a new word. */
211		state = state_next_word;
212
213		/* Option name ends at '=' if there is one. */
214		p = strchr(opt_word, '=');
215		if (p != NULL) {
216			optlength = (size_t)(p - opt_word);
217			cpio->argument = (char *)(uintptr_t)(p + 1);
218		} else {
219			optlength = strlen(opt_word);
220		}
221
222		/* Search the table for an unambiguous match. */
223		for (popt = cpio_longopts; popt->name != NULL; popt++) {
224			/* Short-circuit if first chars don't match. */
225			if (popt->name[0] != opt_word[0])
226				continue;
227			/* If option is a prefix of name in table, record it.*/
228			if (strncmp(opt_word, popt->name, optlength) == 0) {
229				match2 = match; /* Record up to two matches. */
230				match = popt;
231				/* If it's an exact match, we're done. */
232				if (strlen(popt->name) == optlength) {
233					match2 = NULL; /* Forget the others. */
234					break;
235				}
236			}
237		}
238
239		/* Fail if there wasn't a unique match. */
240		if (match == NULL) {
241			lafe_warnc(0,
242			    "Option %s%s is not supported",
243			    long_prefix, opt_word);
244			return ('?');
245		}
246		if (match2 != NULL) {
247			lafe_warnc(0,
248			    "Ambiguous option %s%s (matches --%s and --%s)",
249			    long_prefix, opt_word, match->name, match2->name);
250			return ('?');
251		}
252
253		/* We've found a unique match; does it need an argument? */
254		if (match->required) {
255			/* Argument required: get next word if necessary. */
256			if (cpio->argument == NULL) {
257				cpio->argument = *cpio->argv;
258				if (cpio->argument == NULL) {
259					lafe_warnc(0,
260					    "Option %s%s requires an argument",
261					    long_prefix, match->name);
262					return ('?');
263				}
264				++cpio->argv;
265				--cpio->argc;
266			}
267		} else {
268			/* Argument forbidden: fail if there is one. */
269			if (cpio->argument != NULL) {
270				lafe_warnc(0,
271				    "Option %s%s does not allow an argument",
272				    long_prefix, match->name);
273				return ('?');
274			}
275		}
276		return (match->equivalent);
277	}
278
279	return (opt);
280}
281
282
283/*
284 * Parse the argument to the -R or --owner flag.
285 *
286 * The format is one of the following:
287 *   <username|uid>    - Override user but not group
288 *   <username>:   - Override both, group is user's default group
289 *   <uid>:    - Override user but not group
290 *   <username|uid>:<groupname|gid> - Override both
291 *   :<groupname|gid>  - Override group but not user
292 *
293 * Where uid/gid are decimal representations and groupname/username
294 * are names to be looked up in system database.  Note that we try
295 * to look up an argument as a name first, then try numeric parsing.
296 *
297 * A period can be used instead of the colon.
298 *
299 * Sets uid/gid return as appropriate, -1 indicates uid/gid not specified.
300 * TODO: If the spec uses uname/gname, then return those to the caller
301 * as well.  If the spec provides uid/gid, just return names as NULL.
302 *
303 * Returns NULL if no error, otherwise returns error string for display.
304 *
305 */
306const char *
307owner_parse(const char *spec, int *uid, int *gid)
308{
309	static char errbuff[128];
310	const char *u, *ue, *g;
311
312	*uid = -1;
313	*gid = -1;
314
315	if (spec[0] == '\0')
316		return ("Invalid empty user/group spec");
317
318	/*
319	 * Split spec into [user][:.][group]
320	 *  u -> first char of username, NULL if no username
321	 *  ue -> first char after username (colon, period, or \0)
322	 *  g -> first char of group name
323	 */
324	if (*spec == ':' || *spec == '.') {
325		/* If spec starts with ':' or '.', then just group. */
326		ue = u = NULL;
327		g = spec + 1;
328	} else {
329		/* Otherwise, [user] or [user][:] or [user][:][group] */
330		ue = u = spec;
331		while (*ue != ':' && *ue != '.' && *ue != '\0')
332			++ue;
333		g = ue;
334		if (*g != '\0') /* Skip : or . to find first char of group. */
335			++g;
336	}
337
338	if (u != NULL) {
339		/* Look up user: ue is first char after end of user. */
340		char *user;
341		struct passwd *pwent;
342
343		user = (char *)malloc(ue - u + 1);
344		if (user == NULL)
345			return ("Couldn't allocate memory");
346		memcpy(user, u, ue - u);
347		user[ue - u] = '\0';
348		if ((pwent = getpwnam(user)) != NULL) {
349			*uid = pwent->pw_uid;
350			if (*ue != '\0')
351				*gid = pwent->pw_gid;
352		} else {
353			char *end;
354			errno = 0;
355			*uid = (int)strtoul(user, &end, 10);
356			if (errno || *end != '\0') {
357				snprintf(errbuff, sizeof(errbuff),
358				    "Couldn't lookup user ``%s''", user);
359				errbuff[sizeof(errbuff) - 1] = '\0';
360				free(user);
361				return (errbuff);
362			}
363		}
364		free(user);
365	}
366
367	if (*g != '\0') {
368		struct group *grp;
369		if ((grp = getgrnam(g)) != NULL) {
370			*gid = grp->gr_gid;
371		} else {
372			char *end;
373			errno = 0;
374			*gid = (int)strtoul(g, &end, 10);
375			if (errno || *end != '\0') {
376				snprintf(errbuff, sizeof(errbuff),
377				    "Couldn't lookup group ``%s''", g);
378				errbuff[sizeof(errbuff) - 1] = '\0';
379				return (errbuff);
380			}
381		}
382	}
383	return (NULL);
384}
385