xref: /dragonfly/bin/sh/options.c (revision 52f9f0d9)
1 /*-
2  * Copyright (c) 1991, 1993
3  *	The Regents of the University of California.  All rights reserved.
4  *
5  * This code is derived from software contributed to Berkeley by
6  * Kenneth Almquist.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. All advertising materials mentioning features or use of this software
17  *    must display the following acknowledgement:
18  *	This product includes software developed by the University of
19  *	California, Berkeley and its contributors.
20  * 4. Neither the name of the University nor the names of its contributors
21  *    may be used to endorse or promote products derived from this software
22  *    without specific prior written permission.
23  *
24  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34  * SUCH DAMAGE.
35  *
36  * @(#)options.c	8.2 (Berkeley) 5/4/95
37  * $FreeBSD: src/bin/sh/options.c,v 1.38 2011/11/20 21:48:50 jilles Exp $
38  */
39 
40 #include <signal.h>
41 #include <unistd.h>
42 #include <stdlib.h>
43 
44 #include "shell.h"
45 #define DEFINE_OPTIONS
46 #include "options.h"
47 #undef DEFINE_OPTIONS
48 #include "nodes.h"	/* for other header files */
49 #include "eval.h"
50 #include "jobs.h"
51 #include "input.h"
52 #include "output.h"
53 #include "trap.h"
54 #include "var.h"
55 #include "memalloc.h"
56 #include "error.h"
57 #include "mystring.h"
58 #include "builtins.h"
59 #ifndef NO_HISTORY
60 #include "myhistedit.h"
61 #endif
62 
63 char *arg0;			/* value of $0 */
64 struct shparam shellparam;	/* current positional parameters */
65 char **argptr;			/* argument list for builtin commands */
66 const char *shoptarg;		/* set by nextopt (like getopt) */
67 char *nextopt_optptr;		/* used by nextopt */
68 
69 char *minusc;			/* argument to -c option */
70 
71 
72 static void options(int);
73 static void minus_o(char *, int);
74 static void setoption(int, int);
75 static int getopts(char *, char *, char **, char ***, char **);
76 
77 
78 /*
79  * Process the shell command line arguments.
80  */
81 
82 void
83 procargs(int argc, char **argv)
84 {
85 	int i;
86 	char *scriptname;
87 
88 	argptr = argv;
89 	if (argc > 0)
90 		argptr++;
91 	for (i = 0; i < NOPTS; i++)
92 		optlist[i].val = 2;
93 	privileged = (getuid() != geteuid() || getgid() != getegid());
94 	options(1);
95 	if (*argptr == NULL && minusc == NULL)
96 		sflag = 1;
97 	if (iflag != 0 && sflag == 1 && isatty(0) && isatty(1)) {
98 		iflag = 1;
99 		if (Eflag == 2)
100 			Eflag = 1;
101 	}
102 	if (mflag == 2)
103 		mflag = iflag;
104 	/* turn on tabcomplete in an interactive shell by default */
105 	tabcomplete = iflag;
106 	for (i = 0; i < NOPTS; i++)
107 		if (optlist[i].val == 2)
108 			optlist[i].val = 0;
109 	arg0 = argv[0];
110 	if (sflag == 0 && minusc == NULL) {
111 		scriptname = *argptr++;
112 		setinputfile(scriptname, 0);
113 		commandname = arg0 = scriptname;
114 	}
115 	/* POSIX 1003.2: first arg after -c cmd is $0, remainder $1... */
116 	if (argptr && minusc && *argptr)
117 		arg0 = *argptr++;
118 
119 	shellparam.p = argptr;
120 	shellparam.reset = 1;
121 	/* assert(shellparam.malloc == 0 && shellparam.nparam == 0); */
122 	while (*argptr) {
123 		shellparam.nparam++;
124 		argptr++;
125 	}
126 	optschanged();
127 }
128 
129 
130 void
131 optschanged(void)
132 {
133 	setinteractive(iflag);
134 #ifndef NO_HISTORY
135 	histedit();
136 #endif
137 	setjobctl(mflag);
138 }
139 
140 /*
141  * Process shell options.  The global variable argptr contains a pointer
142  * to the argument list; we advance it past the options.
143  */
144 
145 static void
146 options(int cmdline)
147 {
148 	char *kp, *p;
149 	int val;
150 	int c;
151 
152 	if (cmdline)
153 		minusc = NULL;
154 	while ((p = *argptr) != NULL) {
155 		argptr++;
156 		if ((c = *p++) == '-') {
157 			val = 1;
158 			/* A "-" or  "--" terminates options */
159 			if (p[0] == '\0')
160 				goto end_options1;
161 			if (p[0] == '-' && p[1] == '\0')
162 				goto end_options2;
163 			/**
164 			 * For the benefit of `#!' lines in shell scripts,
165 			 * treat a string of '-- *#.*' the same as '--'.
166 			 * This is needed so that a script starting with:
167 			 *	#!/bin/sh -- # -*- perl -*-
168 			 * will continue to work after a change is made to
169 			 * kern/imgact_shell.c to NOT token-ize the options
170 			 * specified on a '#!' line.  A bit of a kludge,
171 			 * but that trick is recommended in documentation
172 			 * for some scripting languages, and we might as
173 			 * well continue to support it.
174 			 */
175 			if (p[0] == '-') {
176 				kp = p + 1;
177 				while (*kp == ' ' || *kp == '\t')
178 					kp++;
179 				if (*kp == '#' || *kp == '\0')
180 					goto end_options2;
181 			}
182 		} else if (c == '+') {
183 			val = 0;
184 		} else {
185 			argptr--;
186 			break;
187 		}
188 		while ((c = *p++) != '\0') {
189 			if (c == 'c' && cmdline) {
190 				char *q;
191 #ifdef NOHACK	/* removing this code allows sh -ce 'foo' for compat */
192 				if (*p == '\0')
193 #endif
194 					q = *argptr++;
195 				if (q == NULL || minusc != NULL)
196 					error("Bad -c option");
197 				minusc = q;
198 #ifdef NOHACK
199 				break;
200 #endif
201 			} else if (c == 'o') {
202 				minus_o(*argptr, val);
203 				if (*argptr)
204 					argptr++;
205 			} else
206 				setoption(c, val);
207 		}
208 	}
209 	return;
210 
211 	/* When processing `set', a single "-" means turn off -x and -v */
212 end_options1:
213 	if (!cmdline) {
214 		xflag = vflag = 0;
215 		return;
216 	}
217 
218 	/*
219 	 * When processing `set', a "--" means the remaining arguments
220 	 * replace the positional parameters in the active shell.  If
221 	 * there are no remaining options, then all the positional
222 	 * parameters are cleared (equivalent to doing ``shift $#'').
223 	 */
224 end_options2:
225 	if (!cmdline) {
226 		if (*argptr == NULL)
227 			setparam(argptr);
228 		return;
229 	}
230 
231 	/*
232 	 * At this point we are processing options given to 'sh' on a command
233 	 * line.  If an end-of-options marker ("-" or "--") is followed by an
234 	 * arg of "#", then skip over all remaining arguments.  Some scripting
235 	 * languages (e.g.: perl) document that /bin/sh will implement this
236 	 * behavior, and they recommend that users take advantage of it to
237 	 * solve certain issues that can come up when writing a perl script.
238 	 * Yes, this feature is in /bin/sh to help users write perl scripts.
239 	 */
240 	p = *argptr;
241 	if (p != NULL && p[0] == '#' && p[1] == '\0') {
242 		while (*argptr != NULL)
243 			argptr++;
244 		/* We need to keep the final argument */
245 		argptr--;
246 	}
247 }
248 
249 static void
250 minus_o(char *name, int val)
251 {
252 	int i;
253 
254 	if (name == NULL) {
255 		if (val) {
256 			/* "Pretty" output. */
257 			out1str("Current option settings\n");
258 			for (i = 0; i < NOPTS; i++)
259 				out1fmt("%-16s%s\n", optlist[i].name,
260 					optlist[i].val ? "on" : "off");
261 		} else {
262 			/* Output suitable for re-input to shell. */
263 			for (i = 0; i < NOPTS; i++)
264 				out1fmt("%s %co %s%s",
265 				    i % 6 == 0 ? "set" : "",
266 				    optlist[i].val ? '-' : '+',
267 				    optlist[i].name,
268 				    i % 6 == 5 || i == NOPTS - 1 ? "\n" : "");
269 		}
270 	} else {
271 		for (i = 0; i < NOPTS; i++)
272 			if (equal(name, optlist[i].name)) {
273 				setoption(optlist[i].letter, val);
274 				return;
275 			}
276 		error("Illegal option -o %s", name);
277 	}
278 }
279 
280 
281 static void
282 setoption(int flag, int val)
283 {
284 	int i;
285 
286 	if (flag == 'p' && !val && privileged) {
287 		if (setgid(getgid()) == -1)
288 			error("setgid");
289 		if (setuid(getuid()) == -1)
290 			error("setuid");
291 	}
292 	for (i = 0; i < NOPTS; i++)
293 		if (optlist[i].letter == flag) {
294 			optlist[i].val = val;
295 			if (val) {
296 				/* #%$ hack for ksh semantics */
297 				if (flag == 'V')
298 					Eflag = 0;
299 				else if (flag == 'E')
300 					Vflag = 0;
301 			}
302 			return;
303 		}
304 	error("Illegal option -%c", flag);
305 }
306 
307 
308 /*
309  * Set the shell parameters.
310  */
311 
312 void
313 setparam(char **argv)
314 {
315 	char **newparam;
316 	char **ap;
317 	int nparam;
318 
319 	for (nparam = 0 ; argv[nparam] ; nparam++);
320 	ap = newparam = ckmalloc((nparam + 1) * sizeof *ap);
321 	while (*argv) {
322 		*ap++ = savestr(*argv++);
323 	}
324 	*ap = NULL;
325 	freeparam(&shellparam);
326 	shellparam.malloc = 1;
327 	shellparam.nparam = nparam;
328 	shellparam.p = newparam;
329 	shellparam.reset = 1;
330 	shellparam.optnext = NULL;
331 }
332 
333 
334 /*
335  * Free the list of positional parameters.
336  */
337 
338 void
339 freeparam(volatile struct shparam *param)
340 {
341 	char **ap;
342 
343 	if (param->malloc) {
344 		for (ap = param->p ; *ap ; ap++)
345 			ckfree(*ap);
346 		ckfree(param->p);
347 	}
348 }
349 
350 
351 
352 /*
353  * The shift builtin command.
354  */
355 
356 int
357 shiftcmd(int argc, char **argv)
358 {
359 	int n;
360 	char **ap1, **ap2;
361 
362 	n = 1;
363 	if (argc > 1)
364 		n = number(argv[1]);
365 	if (n > shellparam.nparam)
366 		return 1;
367 	INTOFF;
368 	shellparam.nparam -= n;
369 	for (ap1 = shellparam.p ; --n >= 0 ; ap1++) {
370 		if (shellparam.malloc)
371 			ckfree(*ap1);
372 	}
373 	ap2 = shellparam.p;
374 	while ((*ap2++ = *ap1++) != NULL);
375 	shellparam.reset = 1;
376 	INTON;
377 	return 0;
378 }
379 
380 
381 
382 /*
383  * The set command builtin.
384  */
385 
386 int
387 setcmd(int argc, char **argv)
388 {
389 	if (argc == 1)
390 		return showvarscmd(argc, argv);
391 	INTOFF;
392 	options(0);
393 	optschanged();
394 	if (*argptr != NULL) {
395 		setparam(argptr);
396 	}
397 	INTON;
398 	return 0;
399 }
400 
401 
402 void
403 getoptsreset(const char *value)
404 {
405 	while (*value == '0')
406 		value++;
407 	if (strcmp(value, "1") == 0)
408 		shellparam.reset = 1;
409 }
410 
411 /*
412  * The getopts builtin.  Shellparam.optnext points to the next argument
413  * to be processed.  Shellparam.optptr points to the next character to
414  * be processed in the current argument.  If shellparam.optnext is NULL,
415  * then it's the first time getopts has been called.
416  */
417 
418 int
419 getoptscmd(int argc, char **argv)
420 {
421 	char **optbase = NULL;
422 
423 	if (argc < 3)
424 		error("usage: getopts optstring var [arg]");
425 	else if (argc == 3)
426 		optbase = shellparam.p;
427 	else
428 		optbase = &argv[3];
429 
430 	if (shellparam.reset == 1) {
431 		shellparam.optnext = optbase;
432 		shellparam.optptr = NULL;
433 		shellparam.reset = 0;
434 	}
435 
436 	return getopts(argv[1], argv[2], optbase, &shellparam.optnext,
437 		       &shellparam.optptr);
438 }
439 
440 static int
441 getopts(char *optstr, char *optvar, char **optfirst, char ***optnext,
442     char **optp)
443 {
444 	char *p, *q;
445 	char c = '?';
446 	int done = 0;
447 	int ind = 0;
448 	int err = 0;
449 	char s[10];
450 
451 	if ((p = *optp) == NULL || *p == '\0') {
452 		/* Current word is done, advance */
453 		if (*optnext == NULL)
454 			return 1;
455 		p = **optnext;
456 		if (p == NULL || *p != '-' || *++p == '\0') {
457 atend:
458 			ind = *optnext - optfirst + 1;
459 			*optnext = NULL;
460 			p = NULL;
461 			done = 1;
462 			goto out;
463 		}
464 		(*optnext)++;
465 		if (p[0] == '-' && p[1] == '\0')	/* check for "--" */
466 			goto atend;
467 	}
468 
469 	c = *p++;
470 	for (q = optstr; *q != c; ) {
471 		if (*q == '\0') {
472 			if (optstr[0] == ':') {
473 				s[0] = c;
474 				s[1] = '\0';
475 				err |= setvarsafe("OPTARG", s, 0);
476 			}
477 			else {
478 				out1fmt("Illegal option -%c\n", c);
479 				unsetvar("OPTARG");
480 			}
481 			c = '?';
482 			goto bad;
483 		}
484 		if (*++q == ':')
485 			q++;
486 	}
487 
488 	if (*++q == ':') {
489 		if (*p == '\0' && (p = **optnext) == NULL) {
490 			if (optstr[0] == ':') {
491 				s[0] = c;
492 				s[1] = '\0';
493 				err |= setvarsafe("OPTARG", s, 0);
494 				c = ':';
495 			}
496 			else {
497 				out1fmt("No arg for -%c option\n", c);
498 				unsetvar("OPTARG");
499 				c = '?';
500 			}
501 			goto bad;
502 		}
503 
504 		if (p == **optnext)
505 			(*optnext)++;
506 		setvarsafe("OPTARG", p, 0);
507 		p = NULL;
508 	}
509 	else
510 		setvarsafe("OPTARG", "", 0);
511 	ind = *optnext - optfirst + 1;
512 	goto out;
513 
514 bad:
515 	ind = 1;
516 	*optnext = NULL;
517 	p = NULL;
518 out:
519 	*optp = p;
520 	fmtstr(s, sizeof(s), "%d", ind);
521 	err |= setvarsafe("OPTIND", s, VNOFUNC);
522 	s[0] = c;
523 	s[1] = '\0';
524 	err |= setvarsafe(optvar, s, 0);
525 	if (err) {
526 		*optnext = NULL;
527 		*optp = NULL;
528 		flushall();
529 		exraise(EXERROR);
530 	}
531 	return done;
532 }
533 
534 /*
535  * XXX - should get rid of.  have all builtins use getopt(3).  the
536  * library getopt must have the BSD extension static variable "optreset"
537  * otherwise it can't be used within the shell safely.
538  *
539  * Standard option processing (a la getopt) for builtin routines.  The
540  * only argument that is passed to nextopt is the option string; the
541  * other arguments are unnecessary.  It return the character, or '\0' on
542  * end of input.
543  */
544 
545 int
546 nextopt(const char *optstring)
547 {
548 	char *p;
549 	const char *q;
550 	char c;
551 
552 	if ((p = nextopt_optptr) == NULL || *p == '\0') {
553 		p = *argptr;
554 		if (p == NULL || *p != '-' || *++p == '\0')
555 			return '\0';
556 		argptr++;
557 		if (p[0] == '-' && p[1] == '\0')	/* check for "--" */
558 			return '\0';
559 	}
560 	c = *p++;
561 	for (q = optstring ; *q != c ; ) {
562 		if (*q == '\0')
563 			error("Illegal option -%c", c);
564 		if (*++q == ':')
565 			q++;
566 	}
567 	if (*++q == ':') {
568 		if (*p == '\0' && (p = *argptr++) == NULL)
569 			error("No arg for -%c option", c);
570 		shoptarg = p;
571 		p = NULL;
572 	}
573 	nextopt_optptr = p;
574 	return c;
575 }
576