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