xref: /dragonfly/bin/sh/options.c (revision e293de53)
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.25 2006/04/09 12:20:42 stefanf Exp $
38  * $DragonFly: src/bin/sh/options.c,v 1.7 2007/01/14 04:41:32 pavalos Exp $
39  */
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 const char *shoptarg;		/* set by nextopt (like getopt) */
67 const 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 	/* turn on tabcomplete in an interactive shell by default */
101 	tabcomplete = iflag;
102 	for (i = 0; i < NOPTS; i++)
103 		if (optlist[i].val == 2)
104 			optlist[i].val = 0;
105 	arg0 = argv[0];
106 	if (sflag == 0 && minusc == NULL) {
107 		commandname = arg0 = *argptr++;
108 		setinputfile(commandname, 0);
109 	}
110 	/* POSIX 1003.2: first arg after -c cmd is $0, remainder $1... */
111 	if (argptr && minusc && *argptr)
112 		arg0 = *argptr++;
113 
114 	shellparam.p = argptr;
115 	shellparam.reset = 1;
116 	/* assert(shellparam.malloc == 0 && shellparam.nparam == 0); */
117 	while (*argptr) {
118 		shellparam.nparam++;
119 		argptr++;
120 	}
121 	optschanged();
122 }
123 
124 
125 void
126 optschanged(void)
127 {
128 	setinteractive(iflag);
129 #ifndef NO_HISTORY
130 	histedit();
131 #endif
132 	setjobctl(mflag);
133 }
134 
135 /*
136  * Process shell options.  The global variable argptr contains a pointer
137  * to the argument list; we advance it past the options.
138  */
139 
140 STATIC void
141 options(int cmdline)
142 {
143 	char *kp, *p;
144 	int val;
145 	int c;
146 
147 	if (cmdline)
148 		minusc = NULL;
149 	while ((p = *argptr) != NULL) {
150 		argptr++;
151 		if ((c = *p++) == '-') {
152 			val = 1;
153 			/* A "-" or  "--" terminates options */
154 			if (p[0] == '\0')
155 				goto end_options1;
156 			if (p[0] == '-' && p[1] == '\0')
157 				goto end_options2;
158 			/**
159 			 * For the benefit of `#!' lines in shell scripts,
160 			 * treat a string of '-- *#.*' the same as '--'.
161 			 * This is needed so that a script starting with:
162 			 *	#!/bin/sh -- # -*- perl -*-
163 			 * will continue to work after a change is made to
164 			 * kern/imgact_shell.c to NOT token-ize the options
165 			 * specified on a '#!' line.  A bit of a kludge,
166 			 * but that trick is recommended in documentation
167 			 * for some scripting languages, and we might as
168 			 * well continue to support it.
169 			 */
170 			if (p[0] == '-') {
171 				kp = p + 1;
172 				while (*kp == ' ' || *kp == '\t')
173 					kp++;
174 				if (*kp == '#' || *kp == '\0')
175 					goto end_options2;
176 			}
177 		} else if (c == '+') {
178 			val = 0;
179 		} else {
180 			argptr--;
181 			break;
182 		}
183 		while ((c = *p++) != '\0') {
184 			if (c == 'c' && cmdline) {
185 				char *q;
186 #ifdef NOHACK	/* removing this code allows sh -ce 'foo' for compat */
187 				if (*p == '\0')
188 #endif
189 					q = *argptr++;
190 				if (q == NULL || minusc != NULL)
191 					error("Bad -c option");
192 				minusc = q;
193 #ifdef NOHACK
194 				break;
195 #endif
196 			} else if (c == 'o') {
197 				minus_o(*argptr, val);
198 				if (*argptr)
199 					argptr++;
200 			} else {
201 				if (c == 'p' && !val && privileged) {
202 					setuid(getuid());
203 					setgid(getgid());
204 				}
205 				setoption(c, val);
206 			}
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 
254 	if (name == NULL) {
255 		if (val) {
256 			/* "Pretty" output. */
257 			out1str("Current option settings\n");
258 			for (i = 0; i < NOPTS; i++)
259 				out1fmt("%-16s%s\n", optlist[i].name,
260 					optlist[i].val ? "on" : "off");
261 		} else {
262 			/* Output suitable for re-input to shell. */
263 			for (i = 0; i < NOPTS; i++) {
264 				if (i % 6 == 0)
265 					out1str(i == 0 ? "set" : "\nset");
266 				out1fmt(" %co %s", optlist[i].val ? '-' : '+',
267 					optlist[i].name);
268 			}
269 			out1c('\n');
270 		}
271 	} else {
272 		for (i = 0; i < NOPTS; i++)
273 			if (equal(name, optlist[i].name)) {
274 				if (!val && privileged && equal(name, "privileged")) {
275 					setuid(getuid());
276 					setgid(getgid());
277 				}
278 				setoption(optlist[i].letter, val);
279 				return;
280 			}
281 		error("Illegal option -o %s", name);
282 	}
283 }
284 
285 
286 STATIC void
287 setoption(int flag, int val)
288 {
289 	int i;
290 
291 	for (i = 0; i < NOPTS; i++)
292 		if (optlist[i].letter == flag) {
293 			optlist[i].val = val;
294 			if (val) {
295 				/* #%$ hack for ksh semantics */
296 				if (flag == 'V')
297 					Eflag = 0;
298 				else if (flag == 'E')
299 					Vflag = 0;
300 			}
301 			return;
302 		}
303 	error("Illegal option -%c", flag);
304 }
305 
306 
307 
308 #ifdef mkinit
309 INCLUDE "options.h"
310 
311 SHELLPROC {
312 	int i;
313 
314 	for (i = 0; i < NOPTS; i++)
315 		optlist[i].val = 0;
316 	optschanged();
317 
318 }
319 #endif
320 
321 
322 /*
323  * Set the shell parameters.
324  */
325 
326 void
327 setparam(char **argv)
328 {
329 	char **newparam;
330 	char **ap;
331 	int nparam;
332 
333 	for (nparam = 0 ; argv[nparam] ; nparam++);
334 	ap = newparam = ckmalloc((nparam + 1) * sizeof *ap);
335 	while (*argv) {
336 		*ap++ = savestr(*argv++);
337 	}
338 	*ap = NULL;
339 	freeparam(&shellparam);
340 	shellparam.malloc = 1;
341 	shellparam.nparam = nparam;
342 	shellparam.p = newparam;
343 	shellparam.optnext = NULL;
344 }
345 
346 
347 /*
348  * Free the list of positional parameters.
349  */
350 
351 void
352 freeparam(volatile struct shparam *param)
353 {
354 	char **ap;
355 
356 	if (param->malloc) {
357 		for (ap = param->p ; *ap ; ap++)
358 			ckfree(*ap);
359 		ckfree(param->p);
360 	}
361 }
362 
363 
364 
365 /*
366  * The shift builtin command.
367  */
368 
369 int
370 shiftcmd(int argc, char **argv)
371 {
372 	int n;
373 	char **ap1, **ap2;
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 	for (ap1 = shellparam.p ; --n >= 0 ; ap1++) {
383 		if (shellparam.malloc)
384 			ckfree(*ap1);
385 	}
386 	ap2 = shellparam.p;
387 	while ((*ap2++ = *ap1++) != NULL);
388 	shellparam.optnext = NULL;
389 	INTON;
390 	return 0;
391 }
392 
393 
394 
395 /*
396  * The set command builtin.
397  */
398 
399 int
400 setcmd(int argc, char **argv)
401 {
402 	if (argc == 1)
403 		return showvarscmd(argc, argv);
404 	INTOFF;
405 	options(0);
406 	optschanged();
407 	if (*argptr != NULL) {
408 		setparam(argptr);
409 	}
410 	INTON;
411 	return 0;
412 }
413 
414 
415 void
416 getoptsreset(const char *value)
417 {
418 	if (number(value) == 1) {
419 		shellparam.optnext = NULL;
420 		shellparam.reset = 1;
421 	}
422 }
423 
424 /*
425  * The getopts builtin.  Shellparam.optnext points to the next argument
426  * to be processed.  Shellparam.optptr points to the next character to
427  * be processed in the current argument.  If shellparam.optnext is NULL,
428  * then it's the first time getopts has been called.
429  */
430 
431 int
432 getoptscmd(int argc, char **argv)
433 {
434 	char **optbase = NULL;
435 
436 	if (argc < 3)
437 		error("usage: getopts optstring var [arg]");
438 	else if (argc == 3)
439 		optbase = shellparam.p;
440 	else
441 		optbase = &argv[3];
442 
443 	if (shellparam.reset == 1) {
444 		shellparam.optnext = optbase;
445 		shellparam.optptr = NULL;
446 		shellparam.reset = 0;
447 	}
448 
449 	return getopts(argv[1], argv[2], optbase, &shellparam.optnext,
450 		       &shellparam.optptr);
451 }
452 
453 STATIC int
454 getopts(char *optstr, char *optvar, char **optfirst, char ***optnext,
455     char **optp)
456 {
457 	char *p, *q;
458 	char c = '?';
459 	int done = 0;
460 	int ind = 0;
461 	int err = 0;
462 	char s[10];
463 
464 	if ((p = *optp) == NULL || *p == '\0') {
465 		/* Current word is done, advance */
466 		if (*optnext == NULL)
467 			return 1;
468 		p = **optnext;
469 		if (p == NULL || *p != '-' || *++p == '\0') {
470 atend:
471 			ind = *optnext - optfirst + 1;
472 			*optnext = NULL;
473 			p = NULL;
474 			done = 1;
475 			goto out;
476 		}
477 		(*optnext)++;
478 		if (p[0] == '-' && p[1] == '\0')	/* check for "--" */
479 			goto atend;
480 	}
481 
482 	c = *p++;
483 	for (q = optstr; *q != c; ) {
484 		if (*q == '\0') {
485 			if (optstr[0] == ':') {
486 				s[0] = c;
487 				s[1] = '\0';
488 				err |= setvarsafe("OPTARG", s, 0);
489 			}
490 			else {
491 				out1fmt("Illegal option -%c\n", c);
492 				unsetvar("OPTARG");
493 			}
494 			c = '?';
495 			goto bad;
496 		}
497 		if (*++q == ':')
498 			q++;
499 	}
500 
501 	if (*++q == ':') {
502 		if (*p == '\0' && (p = **optnext) == NULL) {
503 			if (optstr[0] == ':') {
504 				s[0] = c;
505 				s[1] = '\0';
506 				err |= setvarsafe("OPTARG", s, 0);
507 				c = ':';
508 			}
509 			else {
510 				out1fmt("No arg for -%c option\n", c);
511 				unsetvar("OPTARG");
512 				c = '?';
513 			}
514 			goto bad;
515 		}
516 
517 		if (p == **optnext)
518 			(*optnext)++;
519 		setvarsafe("OPTARG", p, 0);
520 		p = NULL;
521 	}
522 	else
523 		setvarsafe("OPTARG", "", 0);
524 	ind = *optnext - optfirst + 1;
525 	goto out;
526 
527 bad:
528 	ind = 1;
529 	*optnext = NULL;
530 	p = NULL;
531 out:
532 	*optp = p;
533 	fmtstr(s, sizeof(s), "%d", ind);
534 	err |= setvarsafe("OPTIND", s, VNOFUNC);
535 	s[0] = c;
536 	s[1] = '\0';
537 	err |= setvarsafe(optvar, s, 0);
538 	if (err) {
539 		*optnext = NULL;
540 		*optp = NULL;
541 		flushall();
542 		exraise(EXERROR);
543 	}
544 	return done;
545 }
546 
547 /*
548  * XXX - should get rid of.  have all builtins use getopt(3).  the
549  * library getopt must have the BSD extension static variable "optreset"
550  * otherwise it can't be used within the shell safely.
551  *
552  * Standard option processing (a la getopt) for builtin routines.  The
553  * only argument that is passed to nextopt is the option string; the
554  * other arguments are unnecessary.  It return the character, or '\0' on
555  * end of input.
556  */
557 
558 int
559 nextopt(const char *optstring)
560 {
561 	const char *p, *q;
562 	char c;
563 
564 	if ((p = optptr) == NULL || *p == '\0') {
565 		p = *argptr;
566 		if (p == NULL || *p != '-' || *++p == '\0')
567 			return '\0';
568 		argptr++;
569 		if (p[0] == '-' && p[1] == '\0')	/* check for "--" */
570 			return '\0';
571 	}
572 	c = *p++;
573 	for (q = optstring ; *q != c ; ) {
574 		if (*q == '\0')
575 			error("Illegal option -%c", c);
576 		if (*++q == ':')
577 			q++;
578 	}
579 	if (*++q == ':') {
580 		if (*p == '\0' && (p = *argptr++) == NULL)
581 			error("No arg for -%c option", c);
582 		shoptarg = p;
583 		p = NULL;
584 	}
585 	optptr = p;
586 	return c;
587 }
588