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