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