xref: /freebsd/bin/sh/options.c (revision 830940567b49bb0c08dfaed40418999e76616909)
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 *kp, *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 			/**
157 			 * For the benefit of `#!' lines in shell scripts,
158 			 * treat a string of '-- *#.*' the same as '--'.
159 			 * This is needed so that a script starting with:
160 			 *	#!/bin/sh -- # -*- perl -*-
161 			 * will continue to work after a change is made to
162 			 * kern/imgact_shell.c to NOT token-ize the options
163 			 * specified on a '#!' line.  A bit of a kludge,
164 			 * but that trick is recommended in documentation
165 			 * for some scripting languages, and we might as
166 			 * well continue to support it.
167 			 */
168 			if (p[0] == '-') {
169 				kp = p + 1;
170 				while (*kp == ' ' || *kp == '\t')
171 					kp++;
172 				if (*kp == '#' || *kp == '\0')
173 					goto end_options2;
174 			}
175 		} else if (c == '+') {
176 			val = 0;
177 		} else {
178 			argptr--;
179 			break;
180 		}
181 		while ((c = *p++) != '\0') {
182 			if (c == 'c' && cmdline) {
183 				char *q;
184 #ifdef NOHACK	/* removing this code allows sh -ce 'foo' for compat */
185 				if (*p == '\0')
186 #endif
187 					q = *argptr++;
188 				if (q == NULL || minusc != NULL)
189 					error("Bad -c option");
190 				minusc = q;
191 #ifdef NOHACK
192 				break;
193 #endif
194 			} else if (c == 'o') {
195 				minus_o(*argptr, val);
196 				if (*argptr)
197 					argptr++;
198 			} else {
199 				if (c == 'p' && !val && privileged) {
200 					(void) setuid(getuid());
201 					(void) setgid(getgid());
202 				}
203 				setoption(c, val);
204 			}
205 		}
206 	}
207 	return;
208 
209 	/* When processing `set', a single "-" means turn off -x and -v */
210 end_options1:
211 	if (!cmdline) {
212 		xflag = vflag = 0;
213 		return;
214 	}
215 
216 	/*
217 	 * When processing `set', a "--" means the remaining arguments
218 	 * replace the positional parameters in the active shell.  If
219 	 * there are no remaining options, then all the positional
220 	 * parameters are cleared (equivalent to doing ``shift $#'').
221 	 */
222 end_options2:
223 	if (!cmdline) {
224 		if (*argptr == NULL)
225 			setparam(argptr);
226 		return;
227 	}
228 
229 	/*
230 	 * At this point we are processing options given to 'sh' on a command
231 	 * line.  If an end-of-options marker ("-" or "--") is followed by an
232 	 * arg of "#", then skip over all remaining arguments.  Some scripting
233 	 * languages (e.g.: perl) document that /bin/sh will implement this
234 	 * behavior, and they recommend that users take advantage of it to
235 	 * solve certain issues that can come up when writing a perl script.
236 	 * Yes, this feature is in /bin/sh to help users write perl scripts.
237 	 */
238 	p = *argptr;
239 	if (p != NULL && p[0] == '#' && p[1] == '\0') {
240 		while (*argptr != NULL)
241 			argptr++;
242 		/* We need to keep the final argument */
243 		argptr--;
244 	}
245 }
246 
247 STATIC void
248 minus_o(char *name, int val)
249 {
250 	int i;
251 
252 	if (name == NULL) {
253 		if (val) {
254 			/* "Pretty" output. */
255 			out1str("Current option settings\n");
256 			for (i = 0; i < NOPTS; i++)
257 				out1fmt("%-16s%s\n", optlist[i].name,
258 					optlist[i].val ? "on" : "off");
259 		} else {
260 			/* Output suitable for re-input to shell. */
261 			for (i = 0; i < NOPTS; i++) {
262 				if (i % 6 == 0)
263 					out1str(i == 0 ? "set" : "\nset");
264 				out1fmt(" %co %s", optlist[i].val ? '-' : '+',
265 					optlist[i].name);
266 			}
267 			out1c('\n');
268 		}
269 	} else {
270 		for (i = 0; i < NOPTS; i++)
271 			if (equal(name, optlist[i].name)) {
272 				if (!val && privileged && equal(name, "privileged")) {
273 					(void) setuid(getuid());
274 					(void) setgid(getgid());
275 				}
276 				setoption(optlist[i].letter, val);
277 				return;
278 			}
279 		error("Illegal option -o %s", name);
280 	}
281 }
282 
283 
284 STATIC void
285 setoption(int flag, int val)
286 {
287 	int i;
288 
289 	for (i = 0; i < NOPTS; i++)
290 		if (optlist[i].letter == flag) {
291 			optlist[i].val = val;
292 			if (val) {
293 				/* #%$ hack for ksh semantics */
294 				if (flag == 'V')
295 					Eflag = 0;
296 				else if (flag == 'E')
297 					Vflag = 0;
298 			}
299 			return;
300 		}
301 	error("Illegal option -%c", flag);
302 }
303 
304 
305 
306 #ifdef mkinit
307 INCLUDE "options.h"
308 
309 SHELLPROC {
310 	int i;
311 
312 	for (i = 0; i < NOPTS; i++)
313 		optlist[i].val = 0;
314 	optschanged();
315 
316 }
317 #endif
318 
319 
320 /*
321  * Set the shell parameters.
322  */
323 
324 void
325 setparam(char **argv)
326 {
327 	char **newparam;
328 	char **ap;
329 	int nparam;
330 
331 	for (nparam = 0 ; argv[nparam] ; nparam++);
332 	ap = newparam = ckmalloc((nparam + 1) * sizeof *ap);
333 	while (*argv) {
334 		*ap++ = savestr(*argv++);
335 	}
336 	*ap = NULL;
337 	freeparam(&shellparam);
338 	shellparam.malloc = 1;
339 	shellparam.nparam = nparam;
340 	shellparam.p = newparam;
341 	shellparam.reset = 1;
342 	shellparam.optnext = NULL;
343 }
344 
345 
346 /*
347  * Free the list of positional parameters.
348  */
349 
350 void
351 freeparam(struct shparam *param)
352 {
353 	char **ap;
354 
355 	if (param->malloc) {
356 		for (ap = param->p ; *ap ; ap++)
357 			ckfree(*ap);
358 		ckfree(param->p);
359 	}
360 }
361 
362 
363 
364 /*
365  * The shift builtin command.
366  */
367 
368 int
369 shiftcmd(int argc, char **argv)
370 {
371 	int n;
372 	char **ap1, **ap2;
373 
374 	n = 1;
375 	if (argc > 1)
376 		n = number(argv[1]);
377 	if (n > shellparam.nparam)
378 		return 1;
379 	INTOFF;
380 	shellparam.nparam -= n;
381 	for (ap1 = shellparam.p ; --n >= 0 ; ap1++) {
382 		if (shellparam.malloc)
383 			ckfree(*ap1);
384 	}
385 	ap2 = shellparam.p;
386 	while ((*ap2++ = *ap1++) != NULL);
387 	shellparam.reset = 1;
388 	INTON;
389 	return 0;
390 }
391 
392 
393 
394 /*
395  * The set command builtin.
396  */
397 
398 int
399 setcmd(int argc, char **argv)
400 {
401 	if (argc == 1)
402 		return showvarscmd(argc, argv);
403 	INTOFF;
404 	options(0);
405 	optschanged();
406 	if (*argptr != NULL) {
407 		setparam(argptr);
408 	}
409 	INTON;
410 	return 0;
411 }
412 
413 
414 void
415 getoptsreset(const char *value)
416 {
417 	if (number(value) == 1) {
418 		shellparam.reset = 1;
419 	}
420 }
421 
422 /*
423  * The getopts builtin.  Shellparam.optnext points to the next argument
424  * to be processed.  Shellparam.optptr points to the next character to
425  * be processed in the current argument.  If shellparam.optnext is NULL,
426  * then it's the first time getopts has been called.
427  */
428 
429 int
430 getoptscmd(int argc, char **argv)
431 {
432 	char **optbase = NULL;
433 
434 	if (argc < 3)
435 		error("usage: getopts optstring var [arg]");
436 	else if (argc == 3)
437 		optbase = shellparam.p;
438 	else
439 		optbase = &argv[3];
440 
441 	if (shellparam.reset == 1) {
442 		shellparam.optnext = optbase;
443 		shellparam.optptr = NULL;
444 		shellparam.reset = 0;
445 	}
446 
447 	return getopts(argv[1], argv[2], optbase, &shellparam.optnext,
448 		       &shellparam.optptr);
449 }
450 
451 STATIC int
452 getopts(char *optstr, char *optvar, char **optfirst, char ***optnext,
453     char **optptr)
454 {
455 	char *p, *q;
456 	char c = '?';
457 	int done = 0;
458 	int ind = 0;
459 	int err = 0;
460 	char s[10];
461 
462 	if ((p = *optptr) == NULL || *p == '\0') {
463 		/* Current word is done, advance */
464 		if (*optnext == NULL)
465 			return 1;
466 		p = **optnext;
467 		if (p == NULL || *p != '-' || *++p == '\0') {
468 atend:
469 			ind = *optnext - optfirst + 1;
470 			*optnext = NULL;
471 			p = NULL;
472 			done = 1;
473 			goto out;
474 		}
475 		(*optnext)++;
476 		if (p[0] == '-' && p[1] == '\0')	/* check for "--" */
477 			goto atend;
478 	}
479 
480 	c = *p++;
481 	for (q = optstr; *q != c; ) {
482 		if (*q == '\0') {
483 			if (optstr[0] == ':') {
484 				s[0] = c;
485 				s[1] = '\0';
486 				err |= setvarsafe("OPTARG", s, 0);
487 			}
488 			else {
489 				out1fmt("Illegal option -%c\n", c);
490 				(void) unsetvar("OPTARG");
491 			}
492 			c = '?';
493 			goto bad;
494 		}
495 		if (*++q == ':')
496 			q++;
497 	}
498 
499 	if (*++q == ':') {
500 		if (*p == '\0' && (p = **optnext) == NULL) {
501 			if (optstr[0] == ':') {
502 				s[0] = c;
503 				s[1] = '\0';
504 				err |= setvarsafe("OPTARG", s, 0);
505 				c = ':';
506 			}
507 			else {
508 				out1fmt("No arg for -%c option\n", c);
509 				(void) unsetvar("OPTARG");
510 				c = '?';
511 			}
512 			goto bad;
513 		}
514 
515 		if (p == **optnext)
516 			(*optnext)++;
517 		setvarsafe("OPTARG", p, 0);
518 		p = NULL;
519 	}
520 	else
521 		setvarsafe("OPTARG", "", 0);
522 	ind = *optnext - optfirst + 1;
523 	goto out;
524 
525 bad:
526 	ind = 1;
527 	*optnext = NULL;
528 	p = NULL;
529 out:
530 	*optptr = p;
531 	fmtstr(s, sizeof(s), "%d", ind);
532 	err |= setvarsafe("OPTIND", s, VNOFUNC);
533 	s[0] = c;
534 	s[1] = '\0';
535 	err |= setvarsafe(optvar, s, 0);
536 	if (err) {
537 		*optnext = NULL;
538 		*optptr = NULL;
539 		flushall();
540 		exraise(EXERROR);
541 	}
542 	return done;
543 }
544 
545 /*
546  * XXX - should get rid of.  have all builtins use getopt(3).  the
547  * library getopt must have the BSD extension static variable "optreset"
548  * otherwise it can't be used within the shell safely.
549  *
550  * Standard option processing (a la getopt) for builtin routines.  The
551  * only argument that is passed to nextopt is the option string; the
552  * other arguments are unnecessary.  It return the character, or '\0' on
553  * end of input.
554  */
555 
556 int
557 nextopt(char *optstring)
558 {
559 	char *p, *q;
560 	char c;
561 
562 	if ((p = optptr) == NULL || *p == '\0') {
563 		p = *argptr;
564 		if (p == NULL || *p != '-' || *++p == '\0')
565 			return '\0';
566 		argptr++;
567 		if (p[0] == '-' && p[1] == '\0')	/* check for "--" */
568 			return '\0';
569 	}
570 	c = *p++;
571 	for (q = optstring ; *q != c ; ) {
572 		if (*q == '\0')
573 			error("Illegal option -%c", c);
574 		if (*++q == ':')
575 			q++;
576 	}
577 	if (*++q == ':') {
578 		if (*p == '\0' && (p = *argptr++) == NULL)
579 			error("No arg for -%c option", c);
580 		shoptarg = p;
581 		p = NULL;
582 	}
583 	optptr = p;
584 	return c;
585 }
586