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