xref: /dflybsd-src/bin/sh/options.c (revision f41d807a0c7c535d8f66f0593fb6e95fa20f82d4)
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. All advertising materials mentioning features or use of this software
17  *    must display the following acknowledgement:
18  *	This product includes software developed by the University of
19  *	California, Berkeley and its contributors.
20  * 4. Neither the name of the University nor the names of its contributors
21  *    may be used to endorse or promote products derived from this software
22  *    without specific prior written permission.
23  *
24  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34  * SUCH DAMAGE.
35  *
36  * @(#)options.c	8.2 (Berkeley) 5/4/95
37  * $FreeBSD: src/bin/sh/options.c,v 1.35 2011/04/25 10:14:29 jilles Exp $
38  */
39 
40 #include <signal.h>
41 #include <unistd.h>
42 #include <stdlib.h>
43 
44 #include "shell.h"
45 #define DEFINE_OPTIONS
46 #include "options.h"
47 #undef DEFINE_OPTIONS
48 #include "nodes.h"	/* for other header files */
49 #include "eval.h"
50 #include "jobs.h"
51 #include "input.h"
52 #include "output.h"
53 #include "trap.h"
54 #include "var.h"
55 #include "memalloc.h"
56 #include "error.h"
57 #include "mystring.h"
58 #ifndef NO_HISTORY
59 #include "myhistedit.h"
60 #endif
61 
62 char *arg0;			/* value of $0 */
63 struct shparam shellparam;	/* current positional parameters */
64 char **argptr;			/* argument list for builtin commands */
65 const char *shoptarg;		/* set by nextopt (like getopt) */
66 char *nextopt_optptr;		/* used by nextopt */
67 
68 char *minusc;			/* argument to -c option */
69 
70 
71 static void options(int);
72 static void minus_o(char *, int);
73 static void setoption(int, int);
74 static int getopts(char *, char *, char **, char ***, char **);
75 
76 
77 /*
78  * Process the shell command line arguments.
79  */
80 
81 void
82 procargs(int argc, char **argv)
83 {
84 	int i;
85 
86 	argptr = argv;
87 	if (argc > 0)
88 		argptr++;
89 	for (i = 0; i < NOPTS; i++)
90 		optlist[i].val = 2;
91 	privileged = (getuid() != geteuid() || getgid() != getegid());
92 	options(1);
93 	if (*argptr == NULL && minusc == NULL)
94 		sflag = 1;
95 	if (iflag != 0 && sflag == 1 && isatty(0) && isatty(1)) {
96 		iflag = 1;
97 		if (Eflag == 2)
98 			Eflag = 1;
99 	}
100 	if (mflag == 2)
101 		mflag = iflag;
102 	/* turn on tabcomplete in an interactive shell by default */
103 	tabcomplete = iflag;
104 	for (i = 0; i < NOPTS; i++)
105 		if (optlist[i].val == 2)
106 			optlist[i].val = 0;
107 	arg0 = argv[0];
108 	if (sflag == 0 && minusc == NULL) {
109 		commandname = arg0 = *argptr++;
110 		setinputfile(commandname, 0);
111 	}
112 	/* POSIX 1003.2: first arg after -c cmd is $0, remainder $1... */
113 	if (argptr && minusc && *argptr)
114 		arg0 = *argptr++;
115 
116 	shellparam.p = argptr;
117 	shellparam.reset = 1;
118 	/* assert(shellparam.malloc == 0 && shellparam.nparam == 0); */
119 	while (*argptr) {
120 		shellparam.nparam++;
121 		argptr++;
122 	}
123 	optschanged();
124 }
125 
126 
127 void
128 optschanged(void)
129 {
130 	setinteractive(iflag);
131 #ifndef NO_HISTORY
132 	histedit();
133 #endif
134 	setjobctl(mflag);
135 }
136 
137 /*
138  * Process shell options.  The global variable argptr contains a pointer
139  * to the argument list; we advance it past the options.
140  */
141 
142 static void
143 options(int cmdline)
144 {
145 	char *kp, *p;
146 	int val;
147 	int c;
148 
149 	if (cmdline)
150 		minusc = NULL;
151 	while ((p = *argptr) != NULL) {
152 		argptr++;
153 		if ((c = *p++) == '-') {
154 			val = 1;
155 			/* A "-" or  "--" terminates options */
156 			if (p[0] == '\0')
157 				goto end_options1;
158 			if (p[0] == '-' && p[1] == '\0')
159 				goto end_options2;
160 			/**
161 			 * For the benefit of `#!' lines in shell scripts,
162 			 * treat a string of '-- *#.*' the same as '--'.
163 			 * This is needed so that a script starting with:
164 			 *	#!/bin/sh -- # -*- perl -*-
165 			 * will continue to work after a change is made to
166 			 * kern/imgact_shell.c to NOT token-ize the options
167 			 * specified on a '#!' line.  A bit of a kludge,
168 			 * but that trick is recommended in documentation
169 			 * for some scripting languages, and we might as
170 			 * well continue to support it.
171 			 */
172 			if (p[0] == '-') {
173 				kp = p + 1;
174 				while (*kp == ' ' || *kp == '\t')
175 					kp++;
176 				if (*kp == '#' || *kp == '\0')
177 					goto end_options2;
178 			}
179 		} else if (c == '+') {
180 			val = 0;
181 		} else {
182 			argptr--;
183 			break;
184 		}
185 		while ((c = *p++) != '\0') {
186 			if (c == 'c' && cmdline) {
187 				char *q;
188 #ifdef NOHACK	/* removing this code allows sh -ce 'foo' for compat */
189 				if (*p == '\0')
190 #endif
191 					q = *argptr++;
192 				if (q == NULL || minusc != NULL)
193 					error("Bad -c option");
194 				minusc = q;
195 #ifdef NOHACK
196 				break;
197 #endif
198 			} else if (c == 'o') {
199 				minus_o(*argptr, val);
200 				if (*argptr)
201 					argptr++;
202 			} else
203 				setoption(c, val);
204 		}
205 	}
206 	return;
207 
208 	/* When processing `set', a single "-" means turn off -x and -v */
209 end_options1:
210 	if (!cmdline) {
211 		xflag = vflag = 0;
212 		return;
213 	}
214 
215 	/*
216 	 * When processing `set', a "--" means the remaining arguments
217 	 * replace the positional parameters in the active shell.  If
218 	 * there are no remaining options, then all the positional
219 	 * parameters are cleared (equivalent to doing ``shift $#'').
220 	 */
221 end_options2:
222 	if (!cmdline) {
223 		if (*argptr == NULL)
224 			setparam(argptr);
225 		return;
226 	}
227 
228 	/*
229 	 * At this point we are processing options given to 'sh' on a command
230 	 * line.  If an end-of-options marker ("-" or "--") is followed by an
231 	 * arg of "#", then skip over all remaining arguments.  Some scripting
232 	 * languages (e.g.: perl) document that /bin/sh will implement this
233 	 * behavior, and they recommend that users take advantage of it to
234 	 * solve certain issues that can come up when writing a perl script.
235 	 * Yes, this feature is in /bin/sh to help users write perl scripts.
236 	 */
237 	p = *argptr;
238 	if (p != NULL && p[0] == '#' && p[1] == '\0') {
239 		while (*argptr != NULL)
240 			argptr++;
241 		/* We need to keep the final argument */
242 		argptr--;
243 	}
244 }
245 
246 static void
247 minus_o(char *name, int val)
248 {
249 	int i;
250 
251 	if (name == NULL) {
252 		if (val) {
253 			/* "Pretty" output. */
254 			out1str("Current option settings\n");
255 			for (i = 0; i < NOPTS; i++)
256 				out1fmt("%-16s%s\n", optlist[i].name,
257 					optlist[i].val ? "on" : "off");
258 		} else {
259 			/* Output suitable for re-input to shell. */
260 			for (i = 0; i < NOPTS; i++)
261 				out1fmt("%s %co %s%s",
262 				    i % 6 == 0 ? "set" : "",
263 				    optlist[i].val ? '-' : '+',
264 				    optlist[i].name,
265 				    i % 6 == 5 || i == NOPTS - 1 ? "\n" : "");
266 		}
267 	} else {
268 		for (i = 0; i < NOPTS; i++)
269 			if (equal(name, optlist[i].name)) {
270 				setoption(optlist[i].letter, val);
271 				return;
272 			}
273 		error("Illegal option -o %s", name);
274 	}
275 }
276 
277 
278 static void
279 setoption(int flag, int val)
280 {
281 	int i;
282 
283 	if (flag == 'p' && !val && privileged) {
284 		if (setgid(getgid()) == -1)
285 			error("setgid");
286 		if (setuid(getuid()) == -1)
287 			error("setuid");
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  * Set the shell parameters.
307  */
308 
309 void
310 setparam(char **argv)
311 {
312 	char **newparam;
313 	char **ap;
314 	int nparam;
315 
316 	for (nparam = 0 ; argv[nparam] ; nparam++);
317 	ap = newparam = ckmalloc((nparam + 1) * sizeof *ap);
318 	while (*argv) {
319 		*ap++ = savestr(*argv++);
320 	}
321 	*ap = NULL;
322 	freeparam(&shellparam);
323 	shellparam.malloc = 1;
324 	shellparam.nparam = nparam;
325 	shellparam.p = newparam;
326 	shellparam.reset = 1;
327 	shellparam.optnext = NULL;
328 }
329 
330 
331 /*
332  * Free the list of positional parameters.
333  */
334 
335 void
336 freeparam(volatile struct shparam *param)
337 {
338 	char **ap;
339 
340 	if (param->malloc) {
341 		for (ap = param->p ; *ap ; ap++)
342 			ckfree(*ap);
343 		ckfree(param->p);
344 	}
345 }
346 
347 
348 
349 /*
350  * The shift builtin command.
351  */
352 
353 int
354 shiftcmd(int argc, char **argv)
355 {
356 	int n;
357 	char **ap1, **ap2;
358 
359 	n = 1;
360 	if (argc > 1)
361 		n = number(argv[1]);
362 	if (n > shellparam.nparam)
363 		return 1;
364 	INTOFF;
365 	shellparam.nparam -= n;
366 	for (ap1 = shellparam.p ; --n >= 0 ; ap1++) {
367 		if (shellparam.malloc)
368 			ckfree(*ap1);
369 	}
370 	ap2 = shellparam.p;
371 	while ((*ap2++ = *ap1++) != NULL);
372 	shellparam.reset = 1;
373 	INTON;
374 	return 0;
375 }
376 
377 
378 
379 /*
380  * The set command builtin.
381  */
382 
383 int
384 setcmd(int argc, char **argv)
385 {
386 	if (argc == 1)
387 		return showvarscmd(argc, argv);
388 	INTOFF;
389 	options(0);
390 	optschanged();
391 	if (*argptr != NULL) {
392 		setparam(argptr);
393 	}
394 	INTON;
395 	return 0;
396 }
397 
398 
399 void
400 getoptsreset(const char *value)
401 {
402 	if (number(value) == 1) {
403 		shellparam.reset = 1;
404 	}
405 }
406 
407 /*
408  * The getopts builtin.  Shellparam.optnext points to the next argument
409  * to be processed.  Shellparam.optptr points to the next character to
410  * be processed in the current argument.  If shellparam.optnext is NULL,
411  * then it's the first time getopts has been called.
412  */
413 
414 int
415 getoptscmd(int argc, char **argv)
416 {
417 	char **optbase = NULL;
418 
419 	if (argc < 3)
420 		error("usage: getopts optstring var [arg]");
421 	else if (argc == 3)
422 		optbase = shellparam.p;
423 	else
424 		optbase = &argv[3];
425 
426 	if (shellparam.reset == 1) {
427 		shellparam.optnext = optbase;
428 		shellparam.optptr = NULL;
429 		shellparam.reset = 0;
430 	}
431 
432 	return getopts(argv[1], argv[2], optbase, &shellparam.optnext,
433 		       &shellparam.optptr);
434 }
435 
436 static int
437 getopts(char *optstr, char *optvar, char **optfirst, char ***optnext,
438     char **optp)
439 {
440 	char *p, *q;
441 	char c = '?';
442 	int done = 0;
443 	int ind = 0;
444 	int err = 0;
445 	char s[10];
446 
447 	if ((p = *optp) == NULL || *p == '\0') {
448 		/* Current word is done, advance */
449 		if (*optnext == NULL)
450 			return 1;
451 		p = **optnext;
452 		if (p == NULL || *p != '-' || *++p == '\0') {
453 atend:
454 			ind = *optnext - optfirst + 1;
455 			*optnext = NULL;
456 			p = NULL;
457 			done = 1;
458 			goto out;
459 		}
460 		(*optnext)++;
461 		if (p[0] == '-' && p[1] == '\0')	/* check for "--" */
462 			goto atend;
463 	}
464 
465 	c = *p++;
466 	for (q = optstr; *q != c; ) {
467 		if (*q == '\0') {
468 			if (optstr[0] == ':') {
469 				s[0] = c;
470 				s[1] = '\0';
471 				err |= setvarsafe("OPTARG", s, 0);
472 			}
473 			else {
474 				out1fmt("Illegal option -%c\n", c);
475 				unsetvar("OPTARG");
476 			}
477 			c = '?';
478 			goto bad;
479 		}
480 		if (*++q == ':')
481 			q++;
482 	}
483 
484 	if (*++q == ':') {
485 		if (*p == '\0' && (p = **optnext) == NULL) {
486 			if (optstr[0] == ':') {
487 				s[0] = c;
488 				s[1] = '\0';
489 				err |= setvarsafe("OPTARG", s, 0);
490 				c = ':';
491 			}
492 			else {
493 				out1fmt("No arg for -%c option\n", c);
494 				unsetvar("OPTARG");
495 				c = '?';
496 			}
497 			goto bad;
498 		}
499 
500 		if (p == **optnext)
501 			(*optnext)++;
502 		setvarsafe("OPTARG", p, 0);
503 		p = NULL;
504 	}
505 	else
506 		setvarsafe("OPTARG", "", 0);
507 	ind = *optnext - optfirst + 1;
508 	goto out;
509 
510 bad:
511 	ind = 1;
512 	*optnext = NULL;
513 	p = NULL;
514 out:
515 	*optp = p;
516 	fmtstr(s, sizeof(s), "%d", ind);
517 	err |= setvarsafe("OPTIND", s, VNOFUNC);
518 	s[0] = c;
519 	s[1] = '\0';
520 	err |= setvarsafe(optvar, s, 0);
521 	if (err) {
522 		*optnext = NULL;
523 		*optp = NULL;
524 		flushall();
525 		exraise(EXERROR);
526 	}
527 	return done;
528 }
529 
530 /*
531  * XXX - should get rid of.  have all builtins use getopt(3).  the
532  * library getopt must have the BSD extension static variable "optreset"
533  * otherwise it can't be used within the shell safely.
534  *
535  * Standard option processing (a la getopt) for builtin routines.  The
536  * only argument that is passed to nextopt is the option string; the
537  * other arguments are unnecessary.  It return the character, or '\0' on
538  * end of input.
539  */
540 
541 int
542 nextopt(const char *optstring)
543 {
544 	char *p;
545 	const char *q;
546 	char c;
547 
548 	if ((p = nextopt_optptr) == NULL || *p == '\0') {
549 		p = *argptr;
550 		if (p == NULL || *p != '-' || *++p == '\0')
551 			return '\0';
552 		argptr++;
553 		if (p[0] == '-' && p[1] == '\0')	/* check for "--" */
554 			return '\0';
555 	}
556 	c = *p++;
557 	for (q = optstring ; *q != c ; ) {
558 		if (*q == '\0')
559 			error("Illegal option -%c", c);
560 		if (*++q == ':')
561 			q++;
562 	}
563 	if (*++q == ':') {
564 		if (*p == '\0' && (p = *argptr++) == NULL)
565 			error("No arg for -%c option", c);
566 		shoptarg = p;
567 		p = NULL;
568 	}
569 	nextopt_optptr = p;
570 	return c;
571 }
572