xref: /freebsd/bin/sh/options.c (revision ca9ac06c99bfd0150b85d4d83c396ce6237c0e05)
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 *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 == 2 && sflag == 1 && isatty(0) && isatty(1))
97 		iflag = 1;
98 	if (mflag == 2)
99 		mflag = iflag;
100 	for (i = 0; i < NOPTS; i++)
101 		if (optlist[i].val == 2)
102 			optlist[i].val = 0;
103 	arg0 = argv[0];
104 	if (sflag == 0 && minusc == NULL) {
105 		commandname = arg0 = *argptr++;
106 		setinputfile(commandname, 0);
107 	}
108 	/* POSIX 1003.2: first arg after -c cmd is $0, remainder $1... */
109 	if (argptr && minusc && *argptr)
110 		arg0 = *argptr++;
111 
112 	shellparam.p = argptr;
113 	shellparam.reset = 1;
114 	/* assert(shellparam.malloc == 0 && shellparam.nparam == 0); */
115 	while (*argptr) {
116 		shellparam.nparam++;
117 		argptr++;
118 	}
119 	optschanged();
120 }
121 
122 
123 void
124 optschanged(void)
125 {
126 	setinteractive(iflag);
127 #ifndef NO_HISTORY
128 	histedit();
129 #endif
130 	setjobctl(mflag);
131 }
132 
133 /*
134  * Process shell options.  The global variable argptr contains a pointer
135  * to the argument list; we advance it past the options.
136  */
137 
138 STATIC void
139 options(int cmdline)
140 {
141 	char *p;
142 	int val;
143 	int c;
144 
145 	if (cmdline)
146 		minusc = NULL;
147 	while ((p = *argptr) != NULL) {
148 		argptr++;
149 		if ((c = *p++) == '-') {
150 			val = 1;
151 			/* A "-" or  "--" terminates options */
152 			if (p[0] == '\0')
153 				goto end_options1;
154 			if (p[0] == '-' && p[1] == '\0')
155 				goto end_options2;
156 		} else if (c == '+') {
157 			val = 0;
158 		} else {
159 			argptr--;
160 			break;
161 		}
162 		while ((c = *p++) != '\0') {
163 			if (c == 'c' && cmdline) {
164 				char *q;
165 #ifdef NOHACK	/* removing this code allows sh -ce 'foo' for compat */
166 				if (*p == '\0')
167 #endif
168 					q = *argptr++;
169 				if (q == NULL || minusc != NULL)
170 					error("Bad -c option");
171 				minusc = q;
172 #ifdef NOHACK
173 				break;
174 #endif
175 			} else if (c == 'o') {
176 				minus_o(*argptr, val);
177 				if (*argptr)
178 					argptr++;
179 			} else {
180 				if (c == 'p' && !val && privileged) {
181 					(void) setuid(getuid());
182 					(void) setgid(getgid());
183 				}
184 				setoption(c, val);
185 			}
186 		}
187 	}
188 	return;
189 
190 	/* When processing `set', a single "-" means turn off -x and -v */
191 end_options1:
192 	if (!cmdline) {
193 		xflag = vflag = 0;
194 		return;
195 	}
196 
197 	/*
198 	 * When processing `set', a "--" means the remaining arguments
199 	 * replace the positional parameters in the active shell.  If
200 	 * there are no remaining options, then all the positional
201 	 * parameters are cleared (equivalent to doing ``shift $#'').
202 	 */
203 end_options2:
204 	if (!cmdline) {
205 		if (*argptr == NULL)
206 			setparam(argptr);
207 		return;
208 	}
209 
210 	/*
211 	 * At this point we are processing options given to 'sh' on a command
212 	 * line.  If an end-of-options marker ("-" or "--") is followed by an
213 	 * arg of "#", then skip over all remaining arguments.  Some scripting
214 	 * languages (e.g.: perl) document that /bin/sh will implement this
215 	 * behavior, and they recommend that users take advantage of it to
216 	 * solve certain issues that can come up when writing a perl script.
217 	 * Yes, this feature is in /bin/sh to help users write perl scripts.
218 	 */
219 	p = *argptr;
220 	if (p != NULL && p[0] == '#' && p[1] == '\0') {
221 		while (*argptr != NULL)
222 			argptr++;
223 		/* We need to keep the final argument */
224 		argptr--;
225 	}
226 }
227 
228 STATIC void
229 minus_o(char *name, int val)
230 {
231 	int doneset, i;
232 
233 	if (name == NULL) {
234 		if (val) {
235 			/* "Pretty" output. */
236 			out1str("Current option settings\n");
237 			for (i = 0; i < NOPTS; i++)
238 				out1fmt("%-16s%s\n", optlist[i].name,
239 					optlist[i].val ? "on" : "off");
240 		} else {
241 			/* Output suitable for re-input to shell. */
242 			for (doneset = i = 0; i < NOPTS; i++)
243 				if (optlist[i].val) {
244 					if (!doneset) {
245 						out1str("set");
246 						doneset = 1;
247 					}
248 					out1fmt(" -o %s", optlist[i].name);
249 				}
250 			if (doneset)
251 				out1c('\n');
252 		}
253 	} else {
254 		for (i = 0; i < NOPTS; i++)
255 			if (equal(name, optlist[i].name)) {
256 				if (!val && privileged && equal(name, "privileged")) {
257 					(void) setuid(getuid());
258 					(void) setgid(getgid());
259 				}
260 				setoption(optlist[i].letter, val);
261 				return;
262 			}
263 		error("Illegal option -o %s", name);
264 	}
265 }
266 
267 
268 STATIC void
269 setoption(int flag, int val)
270 {
271 	int i;
272 
273 	for (i = 0; i < NOPTS; i++)
274 		if (optlist[i].letter == flag) {
275 			optlist[i].val = val;
276 			if (val) {
277 				/* #%$ hack for ksh semantics */
278 				if (flag == 'V')
279 					Eflag = 0;
280 				else if (flag == 'E')
281 					Vflag = 0;
282 			}
283 			return;
284 		}
285 	error("Illegal option -%c", flag);
286 }
287 
288 
289 
290 #ifdef mkinit
291 INCLUDE "options.h"
292 
293 SHELLPROC {
294 	int i;
295 
296 	for (i = 0; i < NOPTS; i++)
297 		optlist[i].val = 0;
298 	optschanged();
299 
300 }
301 #endif
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.optnext = NULL;
326 }
327 
328 
329 /*
330  * Free the list of positional parameters.
331  */
332 
333 void
334 freeparam(struct shparam *param)
335 {
336 	char **ap;
337 
338 	if (param->malloc) {
339 		for (ap = param->p ; *ap ; ap++)
340 			ckfree(*ap);
341 		ckfree(param->p);
342 	}
343 }
344 
345 
346 
347 /*
348  * The shift builtin command.
349  */
350 
351 int
352 shiftcmd(int argc, char **argv)
353 {
354 	int n;
355 	char **ap1, **ap2;
356 
357 	n = 1;
358 	if (argc > 1)
359 		n = number(argv[1]);
360 	if (n > shellparam.nparam)
361 		error("can't shift that many");
362 	INTOFF;
363 	shellparam.nparam -= n;
364 	for (ap1 = shellparam.p ; --n >= 0 ; ap1++) {
365 		if (shellparam.malloc)
366 			ckfree(*ap1);
367 	}
368 	ap2 = shellparam.p;
369 	while ((*ap2++ = *ap1++) != NULL);
370 	shellparam.optnext = NULL;
371 	INTON;
372 	return 0;
373 }
374 
375 
376 
377 /*
378  * The set command builtin.
379  */
380 
381 int
382 setcmd(int argc, char **argv)
383 {
384 	if (argc == 1)
385 		return showvarscmd(argc, argv);
386 	INTOFF;
387 	options(0);
388 	optschanged();
389 	if (*argptr != NULL) {
390 		setparam(argptr);
391 	}
392 	INTON;
393 	return 0;
394 }
395 
396 
397 void
398 getoptsreset(const char *value)
399 {
400 	if (number(value) == 1) {
401 		shellparam.optnext = NULL;
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(char *optstring)
542 {
543 	char *p, *q;
544 	char c;
545 
546 	if ((p = optptr) == NULL || *p == '\0') {
547 		p = *argptr;
548 		if (p == NULL || *p != '-' || *++p == '\0')
549 			return '\0';
550 		argptr++;
551 		if (p[0] == '-' && p[1] == '\0')	/* check for "--" */
552 			return '\0';
553 	}
554 	c = *p++;
555 	for (q = optstring ; *q != c ; ) {
556 		if (*q == '\0')
557 			error("Illegal option -%c", c);
558 		if (*++q == ':')
559 			q++;
560 	}
561 	if (*++q == ':') {
562 		if (*p == '\0' && (p = *argptr++) == NULL)
563 			error("No arg for -%c option", c);
564 		shoptarg = p;
565 		p = NULL;
566 	}
567 	optptr = p;
568 	return c;
569 }
570