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