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