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