xref: /freebsd/bin/sh/options.c (revision 99429157e8615dc3b7f11afbe3ed92de7476a5db)
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. 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 #include "builtins.h"
60 #ifndef NO_HISTORY
61 #include "myhistedit.h"
62 #endif
63 
64 char *arg0;			/* value of $0 */
65 struct shparam shellparam;	/* current positional parameters */
66 char **argptr;			/* argument list for builtin commands */
67 char *shoptarg;			/* set by nextopt (like getopt) */
68 char *nextopt_optptr;		/* used by nextopt */
69 
70 char *minusc;			/* argument to -c option */
71 
72 
73 static void options(int);
74 static void minus_o(char *, int);
75 static void setoption(int, int);
76 static void setoptionbyindex(int, int);
77 static void setparam(int, char **);
78 static int getopts(char *, char *, char **, char ***, char **);
79 
80 
81 /*
82  * Process the shell command line arguments.
83  */
84 
85 void
86 procargs(int argc, char **argv)
87 {
88 	int i;
89 	char *scriptname;
90 
91 	argptr = argv;
92 	if (argc > 0)
93 		argptr++;
94 	for (i = 0; i < NOPTS; i++)
95 		optval[i] = 2;
96 	privileged = (getuid() != geteuid() || getgid() != getegid());
97 	options(1);
98 	if (*argptr == NULL && minusc == NULL)
99 		sflag = 1;
100 	if (iflag != 0 && sflag == 1 && isatty(0) && isatty(1)) {
101 		iflag = 1;
102 		if (Eflag == 2)
103 			Eflag = 1;
104 	}
105 	if (mflag == 2)
106 		mflag = iflag;
107 	for (i = 0; i < NOPTS; i++)
108 		if (optval[i] == 2)
109 			optval[i] = 0;
110 	arg0 = argv[0];
111 	if (sflag == 0 && minusc == NULL) {
112 		scriptname = *argptr++;
113 		setinputfile(scriptname, 0);
114 		commandname = arg0 = scriptname;
115 	}
116 	/* POSIX 1003.2: first arg after -c cmd is $0, remainder $1... */
117 	if (argptr && minusc && *argptr)
118 		arg0 = *argptr++;
119 
120 	shellparam.p = argptr;
121 	shellparam.reset = 1;
122 	/* assert(shellparam.malloc == 0 && shellparam.nparam == 0); */
123 	while (*argptr) {
124 		shellparam.nparam++;
125 		argptr++;
126 	}
127 	optschanged();
128 }
129 
130 
131 void
132 optschanged(void)
133 {
134 	setinteractive();
135 #ifndef NO_HISTORY
136 	histedit();
137 #endif
138 	setjobctl(mflag);
139 }
140 
141 /*
142  * Process shell options.  The global variable argptr contains a pointer
143  * to the argument list; we advance it past the options.
144  * If cmdline is true, process the shell's argv; otherwise, process arguments
145  * to the set special builtin.
146  */
147 
148 static void
149 options(int cmdline)
150 {
151 	char *kp, *p;
152 	int val;
153 	int c;
154 
155 	if (cmdline)
156 		minusc = NULL;
157 	while ((p = *argptr) != NULL) {
158 		argptr++;
159 		if ((c = *p++) == '-') {
160 			val = 1;
161 			/* A "-" or  "--" terminates options */
162 			if (p[0] == '\0')
163 				goto end_options1;
164 			if (p[0] == '-' && p[1] == '\0')
165 				goto end_options2;
166 			/**
167 			 * For the benefit of `#!' lines in shell scripts,
168 			 * treat a string of '-- *#.*' the same as '--'.
169 			 * This is needed so that a script starting with:
170 			 *	#!/bin/sh -- # -*- perl -*-
171 			 * will continue to work after a change is made to
172 			 * kern/imgact_shell.c to NOT token-ize the options
173 			 * specified on a '#!' line.  A bit of a kludge,
174 			 * but that trick is recommended in documentation
175 			 * for some scripting languages, and we might as
176 			 * well continue to support it.
177 			 */
178 			if (p[0] == '-') {
179 				kp = p + 1;
180 				while (*kp == ' ' || *kp == '\t')
181 					kp++;
182 				if (*kp == '#' || *kp == '\0')
183 					goto end_options2;
184 			}
185 		} else if (c == '+') {
186 			val = 0;
187 		} else {
188 			argptr--;
189 			break;
190 		}
191 		while ((c = *p++) != '\0') {
192 			if (c == 'c' && cmdline) {
193 				char *q;
194 #ifdef NOHACK	/* removing this code allows sh -ce 'foo' for compat */
195 				if (*p == '\0')
196 #endif
197 					q = *argptr++;
198 				if (q == NULL || minusc != NULL)
199 					error("Bad -c option");
200 				minusc = q;
201 #ifdef NOHACK
202 				break;
203 #endif
204 			} else if (c == 'o') {
205 				minus_o(*argptr, val);
206 				if (*argptr)
207 					argptr++;
208 			} else
209 				setoption(c, val);
210 		}
211 	}
212 	return;
213 
214 	/* When processing `set', a single "-" means turn off -x and -v */
215 end_options1:
216 	if (!cmdline) {
217 		xflag = vflag = 0;
218 		return;
219 	}
220 
221 	/*
222 	 * When processing `set', a "--" means the remaining arguments
223 	 * replace the positional parameters in the active shell.  If
224 	 * there are no remaining options, then all the positional
225 	 * parameters are cleared (equivalent to doing ``shift $#'').
226 	 */
227 end_options2:
228 	if (!cmdline) {
229 		if (*argptr == NULL)
230 			setparam(0, argptr);
231 		return;
232 	}
233 
234 	/*
235 	 * At this point we are processing options given to 'sh' on a command
236 	 * line.  If an end-of-options marker ("-" or "--") is followed by an
237 	 * arg of "#", then skip over all remaining arguments.  Some scripting
238 	 * languages (e.g.: perl) document that /bin/sh will implement this
239 	 * behavior, and they recommend that users take advantage of it to
240 	 * solve certain issues that can come up when writing a perl script.
241 	 * Yes, this feature is in /bin/sh to help users write perl scripts.
242 	 */
243 	p = *argptr;
244 	if (p != NULL && p[0] == '#' && p[1] == '\0') {
245 		while (*argptr != NULL)
246 			argptr++;
247 		/* We need to keep the final argument */
248 		argptr--;
249 	}
250 }
251 
252 static void
253 minus_o(char *name, int val)
254 {
255 	int i;
256 	const unsigned char *on;
257 	size_t len;
258 
259 	if (name == NULL) {
260 		if (val) {
261 			/* "Pretty" output. */
262 			out1str("Current option settings\n");
263 			for (i = 0, on = optname; i < NOPTS; i++, on += *on + 1)
264 				out1fmt("%-16.*s%s\n", *on, on + 1,
265 					optval[i] ? "on" : "off");
266 		} else {
267 			/* Output suitable for re-input to shell. */
268 			for (i = 0, on = optname; i < NOPTS; i++, on += *on + 1)
269 				out1fmt("%s %co %.*s%s",
270 				    i % 6 == 0 ? "set" : "",
271 				    optval[i] ? '-' : '+',
272 				    *on, on + 1,
273 				    i % 6 == 5 || i == NOPTS - 1 ? "\n" : "");
274 		}
275 	} else {
276 		len = strlen(name);
277 		for (i = 0, on = optname; i < NOPTS; i++, on += *on + 1)
278 			if (*on == len && memcmp(on + 1, name, len) == 0) {
279 				setoptionbyindex(i, val);
280 				return;
281 			}
282 		error("Illegal option -o %s", name);
283 	}
284 }
285 
286 
287 static void
288 setoptionbyindex(int idx, int val)
289 {
290 	if (&optval[idx] == &privileged && !val && privileged) {
291 		if (setgid(getgid()) == -1)
292 			error("setgid");
293 		if (setuid(getuid()) == -1)
294 			error("setuid");
295 	}
296 	optval[idx] = val;
297 	if (val) {
298 		/* #%$ hack for ksh semantics */
299 		if (&optval[idx] == &Vflag)
300 			Eflag = 0;
301 		else if (&optval[idx] == &Eflag)
302 			Vflag = 0;
303 	}
304 }
305 
306 static void
307 setoption(int flag, int val)
308 {
309 	int i;
310 
311 	for (i = 0; i < NSHORTOPTS; i++)
312 		if (optletter[i] == flag) {
313 			setoptionbyindex(i, val);
314 			return;
315 		}
316 	error("Illegal option -%c", flag);
317 }
318 
319 
320 /*
321  * Set the shell parameters.
322  */
323 
324 static void
325 setparam(int argc, char **argv)
326 {
327 	char **newparam;
328 	char **ap;
329 
330 	ap = newparam = ckmalloc((argc + 1) * sizeof *ap);
331 	while (*argv) {
332 		*ap++ = savestr(*argv++);
333 	}
334 	*ap = NULL;
335 	freeparam(&shellparam);
336 	shellparam.malloc = 1;
337 	shellparam.nparam = argc;
338 	shellparam.p = newparam;
339 	shellparam.optp = NULL;
340 	shellparam.reset = 1;
341 	shellparam.optnext = NULL;
342 }
343 
344 
345 /*
346  * Free the list of positional parameters.
347  */
348 
349 void
350 freeparam(struct shparam *param)
351 {
352 	char **ap;
353 
354 	if (param->malloc) {
355 		for (ap = param->p ; *ap ; ap++)
356 			ckfree(*ap);
357 		ckfree(param->p);
358 	}
359 	if (param->optp) {
360 		for (ap = param->optp ; *ap ; ap++)
361 			ckfree(*ap);
362 		ckfree(param->optp);
363 	}
364 }
365 
366 
367 
368 /*
369  * The shift builtin command.
370  */
371 
372 int
373 shiftcmd(int argc, char **argv)
374 {
375 	int i, n;
376 
377 	n = 1;
378 	if (argc > 1)
379 		n = number(argv[1]);
380 	if (n > shellparam.nparam)
381 		return 1;
382 	INTOFF;
383 	shellparam.nparam -= n;
384 	if (shellparam.malloc)
385 		for (i = 0; i < n; i++)
386 			ckfree(shellparam.p[i]);
387 	memmove(shellparam.p, shellparam.p + n,
388 	    (shellparam.nparam + 1) * sizeof(shellparam.p[0]));
389 	shellparam.reset = 1;
390 	INTON;
391 	return 0;
392 }
393 
394 
395 
396 /*
397  * The set builtin command.
398  */
399 
400 int
401 setcmd(int argc, char **argv)
402 {
403 	if (argc == 1)
404 		return showvarscmd(argc, argv);
405 	INTOFF;
406 	options(0);
407 	optschanged();
408 	if (*argptr != NULL) {
409 		setparam(argc - (argptr - argv), argptr);
410 	}
411 	INTON;
412 	return 0;
413 }
414 
415 
416 void
417 getoptsreset(const char *value)
418 {
419 	while (*value == '0')
420 		value++;
421 	if (strcmp(value, "1") == 0)
422 		shellparam.reset = 1;
423 }
424 
425 /*
426  * The getopts builtin.  Shellparam.optnext points to the next argument
427  * to be processed.  Shellparam.optptr points to the next character to
428  * be processed in the current argument.  If shellparam.optnext is NULL,
429  * then it's the first time getopts has been called.
430  */
431 
432 int
433 getoptscmd(int argc, char **argv)
434 {
435 	char **optbase = NULL, **ap;
436 	int i;
437 
438 	if (argc < 3)
439 		error("usage: getopts optstring var [arg]");
440 
441 	if (shellparam.reset == 1) {
442 		INTOFF;
443 		if (shellparam.optp) {
444 			for (ap = shellparam.optp ; *ap ; ap++)
445 				ckfree(*ap);
446 			ckfree(shellparam.optp);
447 			shellparam.optp = NULL;
448 		}
449 		if (argc > 3) {
450 			shellparam.optp = ckmalloc((argc - 2) * sizeof *ap);
451 			memset(shellparam.optp, '\0', (argc - 2) * sizeof *ap);
452 			for (i = 0; i < argc - 3; i++)
453 				shellparam.optp[i] = savestr(argv[i + 3]);
454 		}
455 		INTON;
456 		optbase = argc == 3 ? shellparam.p : shellparam.optp;
457 		shellparam.optnext = optbase;
458 		shellparam.optptr = NULL;
459 		shellparam.reset = 0;
460 	} else
461 		optbase = shellparam.optp ? shellparam.optp : shellparam.p;
462 
463 	return getopts(argv[1], argv[2], optbase, &shellparam.optnext,
464 		       &shellparam.optptr);
465 }
466 
467 static int
468 getopts(char *optstr, char *optvar, char **optfirst, char ***optnext,
469     char **optptr)
470 {
471 	char *p, *q;
472 	char c = '?';
473 	int done = 0;
474 	int ind = 0;
475 	int err = 0;
476 	char s[10];
477 	const char *newoptarg = NULL;
478 
479 	if ((p = *optptr) == NULL || *p == '\0') {
480 		/* Current word is done, advance */
481 		if (*optnext == NULL)
482 			return 1;
483 		p = **optnext;
484 		if (p == NULL || *p != '-' || *++p == '\0') {
485 atend:
486 			ind = *optnext - optfirst + 1;
487 			*optnext = NULL;
488 			p = NULL;
489 			done = 1;
490 			goto out;
491 		}
492 		(*optnext)++;
493 		if (p[0] == '-' && p[1] == '\0')	/* check for "--" */
494 			goto atend;
495 	}
496 
497 	c = *p++;
498 	for (q = optstr; *q != c; ) {
499 		if (*q == '\0') {
500 			if (optstr[0] == ':') {
501 				s[0] = c;
502 				s[1] = '\0';
503 				newoptarg = s;
504 			}
505 			else
506 				out2fmt_flush("Illegal option -%c\n", c);
507 			c = '?';
508 			goto out;
509 		}
510 		if (*++q == ':')
511 			q++;
512 	}
513 
514 	if (*++q == ':') {
515 		if (*p == '\0' && (p = **optnext) == NULL) {
516 			if (optstr[0] == ':') {
517 				s[0] = c;
518 				s[1] = '\0';
519 				newoptarg = s;
520 				c = ':';
521 			}
522 			else {
523 				out2fmt_flush("No arg for -%c option\n", c);
524 				c = '?';
525 			}
526 			goto out;
527 		}
528 
529 		if (p == **optnext)
530 			(*optnext)++;
531 		newoptarg = p;
532 		p = NULL;
533 	}
534 
535 out:
536 	if (*optnext != NULL)
537 		ind = *optnext - optfirst + 1;
538 	*optptr = p;
539 	if (newoptarg != NULL)
540 		err |= setvarsafe("OPTARG", newoptarg, 0);
541 	else {
542 		INTOFF;
543 		err |= unsetvar("OPTARG");
544 		INTON;
545 	}
546 	fmtstr(s, sizeof(s), "%d", ind);
547 	err |= setvarsafe("OPTIND", s, VNOFUNC);
548 	s[0] = c;
549 	s[1] = '\0';
550 	err |= setvarsafe(optvar, s, 0);
551 	if (err) {
552 		*optnext = NULL;
553 		*optptr = NULL;
554 		flushall();
555 		exraise(EXERROR);
556 	}
557 	return done;
558 }
559 
560 /*
561  * Standard option processing (a la getopt) for builtin routines.  The
562  * only argument that is passed to nextopt is the option string; the
563  * other arguments are unnecessary.  It returns the option, or '\0' on
564  * end of input.
565  */
566 
567 int
568 nextopt(const char *optstring)
569 {
570 	char *p;
571 	const char *q;
572 	char c;
573 
574 	if ((p = nextopt_optptr) == NULL || *p == '\0') {
575 		p = *argptr;
576 		if (p == NULL || *p != '-' || *++p == '\0')
577 			return '\0';
578 		argptr++;
579 		if (p[0] == '-' && p[1] == '\0')	/* check for "--" */
580 			return '\0';
581 	}
582 	c = *p++;
583 	for (q = optstring ; *q != c ; ) {
584 		if (*q == '\0')
585 			error("Illegal option -%c", c);
586 		if (*++q == ':')
587 			q++;
588 	}
589 	if (*++q == ':') {
590 		if (*p == '\0' && (p = *argptr++) == NULL)
591 			error("No arg for -%c option", c);
592 		shoptarg = p;
593 		p = NULL;
594 	}
595 	nextopt_optptr = p;
596 	return c;
597 }
598