xref: /freebsd/bin/sh/options.c (revision 2008043f386721d58158e37e0d7e50df8095942d)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 1991, 1993
5  *	The Regents of the University of California.  All rights reserved.
6  *
7  * This code is derived from software contributed to Berkeley by
8  * Kenneth Almquist.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 3. Neither the name of the University nor the names of its contributors
19  *    may be used to endorse or promote products derived from this software
20  *    without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  */
34 
35 #ifndef lint
36 #if 0
37 static char sccsid[] = "@(#)options.c	8.2 (Berkeley) 5/4/95";
38 #endif
39 #endif /* not lint */
40 #include <sys/cdefs.h>
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, -1 /* verify */);
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();
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  * If cmdline is true, process the shell's argv; otherwise, process arguments
145  * to the set special builtin.
146  */
147 
148 static void
149 options(int cmdline)
150 {
151 	char *kp, *p;
152 	int val;
153 	int c;
154 
155 	if (cmdline)
156 		minusc = NULL;
157 	while ((p = *argptr) != NULL) {
158 		argptr++;
159 		if ((c = *p++) == '-') {
160 			val = 1;
161 			/* A "-" or  "--" terminates options */
162 			if (p[0] == '\0')
163 				goto end_options1;
164 			if (p[0] == '-' && p[1] == '\0')
165 				goto end_options2;
166 			/**
167 			 * For the benefit of `#!' lines in shell scripts,
168 			 * treat a string of '-- *#.*' the same as '--'.
169 			 * This is needed so that a script starting with:
170 			 *	#!/bin/sh -- # -*- perl -*-
171 			 * will continue to work after a change is made to
172 			 * kern/imgact_shell.c to NOT token-ize the options
173 			 * specified on a '#!' line.  A bit of a kludge,
174 			 * but that trick is recommended in documentation
175 			 * for some scripting languages, and we might as
176 			 * well continue to support it.
177 			 */
178 			if (p[0] == '-') {
179 				kp = p + 1;
180 				while (*kp == ' ' || *kp == '\t')
181 					kp++;
182 				if (*kp == '#' || *kp == '\0')
183 					goto end_options2;
184 			}
185 		} else if (c == '+') {
186 			val = 0;
187 		} else {
188 			argptr--;
189 			break;
190 		}
191 		while ((c = *p++) != '\0') {
192 			if (c == 'c' && cmdline) {
193 				char *q;
194 
195 				q = *argptr++;
196 				if (q == NULL || minusc != NULL)
197 					error("Bad -c option");
198 				minusc = q;
199 			} else if (c == 'o') {
200 				minus_o(*argptr, val);
201 				if (*argptr)
202 					argptr++;
203 			} else
204 				setoption(c, val);
205 		}
206 	}
207 	return;
208 
209 	/* When processing `set', a single "-" means turn off -x and -v */
210 end_options1:
211 	if (!cmdline) {
212 		xflag = vflag = 0;
213 		return;
214 	}
215 
216 	/*
217 	 * When processing `set', a "--" means the remaining arguments
218 	 * replace the positional parameters in the active shell.  If
219 	 * there are no remaining options, then all the positional
220 	 * parameters are cleared (equivalent to doing ``shift $#'').
221 	 */
222 end_options2:
223 	if (!cmdline) {
224 		if (*argptr == NULL)
225 			setparam(0, argptr);
226 		return;
227 	}
228 
229 	/*
230 	 * At this point we are processing options given to 'sh' on a command
231 	 * line.  If an end-of-options marker ("-" or "--") is followed by an
232 	 * arg of "#", then skip over all remaining arguments.  Some scripting
233 	 * languages (e.g.: perl) document that /bin/sh will implement this
234 	 * behavior, and they recommend that users take advantage of it to
235 	 * solve certain issues that can come up when writing a perl script.
236 	 * Yes, this feature is in /bin/sh to help users write perl scripts.
237 	 */
238 	p = *argptr;
239 	if (p != NULL && p[0] == '#' && p[1] == '\0') {
240 		while (*argptr != NULL)
241 			argptr++;
242 		/* We need to keep the final argument */
243 		argptr--;
244 	}
245 }
246 
247 static void
248 minus_o(char *name, int val)
249 {
250 	int i;
251 	const unsigned char *on;
252 	size_t len;
253 
254 	if (name == NULL) {
255 		if (val) {
256 			/* "Pretty" output. */
257 			out1str("Current option settings\n");
258 			for (i = 0, on = optname; i < NOPTS; i++, on += *on + 1)
259 				out1fmt("%-16.*s%s\n", *on, on + 1,
260 					optval[i] ? "on" : "off");
261 		} else {
262 			/* Output suitable for re-input to shell. */
263 			for (i = 0, on = optname; i < NOPTS; i++, on += *on + 1)
264 				out1fmt("%s %co %.*s%s",
265 				    i % 6 == 0 ? "set" : "",
266 				    optval[i] ? '-' : '+',
267 				    *on, on + 1,
268 				    i % 6 == 5 || i == NOPTS - 1 ? "\n" : "");
269 		}
270 	} else {
271 		len = strlen(name);
272 		for (i = 0, on = optname; i < NOPTS; i++, on += *on + 1)
273 			if (*on == len && memcmp(on + 1, name, len) == 0) {
274 				setoptionbyindex(i, val);
275 				return;
276 			}
277 		error("Illegal option -o %s", name);
278 	}
279 }
280 
281 
282 static void
283 setoptionbyindex(int idx, int val)
284 {
285 	if (&optval[idx] == &privileged && !val && privileged) {
286 		if (setgid(getgid()) == -1)
287 			error("setgid");
288 		if (setuid(getuid()) == -1)
289 			error("setuid");
290 	}
291 	optval[idx] = val;
292 	if (val) {
293 		/* #%$ hack for ksh semantics */
294 		if (&optval[idx] == &Vflag)
295 			Eflag = 0;
296 		else if (&optval[idx] == &Eflag)
297 			Vflag = 0;
298 	}
299 }
300 
301 static void
302 setoption(int flag, int val)
303 {
304 	int i;
305 
306 	for (i = 0; i < NSHORTOPTS; i++)
307 		if (optletter[i] == flag) {
308 			setoptionbyindex(i, val);
309 			return;
310 		}
311 	error("Illegal option -%c", flag);
312 }
313 
314 
315 /*
316  * Set the shell parameters.
317  */
318 
319 static void
320 setparam(int argc, char **argv)
321 {
322 	char **newparam;
323 	char **ap;
324 
325 	ap = newparam = ckmalloc((argc + 1) * sizeof *ap);
326 	while (*argv) {
327 		*ap++ = savestr(*argv++);
328 	}
329 	*ap = NULL;
330 	freeparam(&shellparam);
331 	shellparam.malloc = 1;
332 	shellparam.nparam = argc;
333 	shellparam.p = newparam;
334 	shellparam.optp = NULL;
335 	shellparam.reset = 1;
336 	shellparam.optnext = NULL;
337 }
338 
339 
340 /*
341  * Free the list of positional parameters.
342  */
343 
344 void
345 freeparam(struct shparam *param)
346 {
347 	char **ap;
348 
349 	if (param->malloc) {
350 		for (ap = param->p ; *ap ; ap++)
351 			ckfree(*ap);
352 		ckfree(param->p);
353 	}
354 	if (param->optp) {
355 		for (ap = param->optp ; *ap ; ap++)
356 			ckfree(*ap);
357 		ckfree(param->optp);
358 	}
359 }
360 
361 
362 
363 /*
364  * The shift builtin command.
365  */
366 
367 int
368 shiftcmd(int argc, char **argv)
369 {
370 	int i, n;
371 
372 	n = 1;
373 	if (argc > 1)
374 		n = number(argv[1]);
375 	if (n > shellparam.nparam)
376 		return 1;
377 	INTOFF;
378 	shellparam.nparam -= n;
379 	if (shellparam.malloc)
380 		for (i = 0; i < n; i++)
381 			ckfree(shellparam.p[i]);
382 	memmove(shellparam.p, shellparam.p + n,
383 	    (shellparam.nparam + 1) * sizeof(shellparam.p[0]));
384 	shellparam.reset = 1;
385 	INTON;
386 	return 0;
387 }
388 
389 
390 
391 /*
392  * The set builtin command.
393  */
394 
395 int
396 setcmd(int argc, char **argv)
397 {
398 	if (argc == 1)
399 		return showvarscmd(argc, argv);
400 	INTOFF;
401 	options(0);
402 	optschanged();
403 	if (*argptr != NULL) {
404 		setparam(argc - (argptr - argv), argptr);
405 	}
406 	INTON;
407 	return 0;
408 }
409 
410 
411 void
412 getoptsreset(const char *value)
413 {
414 	while (*value == '0')
415 		value++;
416 	if (strcmp(value, "1") == 0)
417 		shellparam.reset = 1;
418 }
419 
420 /*
421  * The getopts builtin.  Shellparam.optnext points to the next argument
422  * to be processed.  Shellparam.optptr points to the next character to
423  * be processed in the current argument.  If shellparam.optnext is NULL,
424  * then it's the first time getopts has been called.
425  */
426 
427 int
428 getoptscmd(int argc, char **argv)
429 {
430 	char **optbase = NULL, **ap;
431 	int i;
432 
433 	if (argc < 3)
434 		error("usage: getopts optstring var [arg]");
435 
436 	if (shellparam.reset == 1) {
437 		INTOFF;
438 		if (shellparam.optp) {
439 			for (ap = shellparam.optp ; *ap ; ap++)
440 				ckfree(*ap);
441 			ckfree(shellparam.optp);
442 			shellparam.optp = NULL;
443 		}
444 		if (argc > 3) {
445 			shellparam.optp = ckmalloc((argc - 2) * sizeof *ap);
446 			memset(shellparam.optp, '\0', (argc - 2) * sizeof *ap);
447 			for (i = 0; i < argc - 3; i++)
448 				shellparam.optp[i] = savestr(argv[i + 3]);
449 		}
450 		INTON;
451 		optbase = argc == 3 ? shellparam.p : shellparam.optp;
452 		shellparam.optnext = optbase;
453 		shellparam.optptr = NULL;
454 		shellparam.reset = 0;
455 	} else
456 		optbase = shellparam.optp ? shellparam.optp : shellparam.p;
457 
458 	return getopts(argv[1], argv[2], optbase, &shellparam.optnext,
459 		       &shellparam.optptr);
460 }
461 
462 static int
463 getopts(char *optstr, char *optvar, char **optfirst, char ***optnext,
464     char **optptr)
465 {
466 	char *p, *q;
467 	char c = '?';
468 	int done = 0;
469 	int ind = 0;
470 	int err = 0;
471 	char s[10];
472 	const char *newoptarg = NULL;
473 
474 	if ((p = *optptr) == NULL || *p == '\0') {
475 		/* Current word is done, advance */
476 		if (*optnext == NULL)
477 			return 1;
478 		p = **optnext;
479 		if (p == NULL || *p != '-' || *++p == '\0') {
480 atend:
481 			ind = *optnext - optfirst + 1;
482 			*optnext = NULL;
483 			p = NULL;
484 			done = 1;
485 			goto out;
486 		}
487 		(*optnext)++;
488 		if (p[0] == '-' && p[1] == '\0')	/* check for "--" */
489 			goto atend;
490 	}
491 
492 	c = *p++;
493 	for (q = optstr; *q != c; ) {
494 		if (*q == '\0') {
495 			if (optstr[0] == ':') {
496 				s[0] = c;
497 				s[1] = '\0';
498 				newoptarg = s;
499 			}
500 			else
501 				out2fmt_flush("Illegal option -%c\n", c);
502 			c = '?';
503 			goto out;
504 		}
505 		if (*++q == ':')
506 			q++;
507 	}
508 
509 	if (*++q == ':') {
510 		if (*p == '\0' && (p = **optnext) == NULL) {
511 			if (optstr[0] == ':') {
512 				s[0] = c;
513 				s[1] = '\0';
514 				newoptarg = s;
515 				c = ':';
516 			}
517 			else {
518 				out2fmt_flush("No arg for -%c option\n", c);
519 				c = '?';
520 			}
521 			goto out;
522 		}
523 
524 		if (p == **optnext)
525 			(*optnext)++;
526 		newoptarg = p;
527 		p = NULL;
528 	}
529 
530 out:
531 	if (*optnext != NULL)
532 		ind = *optnext - optfirst + 1;
533 	*optptr = p;
534 	if (newoptarg != NULL)
535 		err |= setvarsafe("OPTARG", newoptarg, 0);
536 	else {
537 		INTOFF;
538 		err |= unsetvar("OPTARG");
539 		INTON;
540 	}
541 	fmtstr(s, sizeof(s), "%d", ind);
542 	err |= setvarsafe("OPTIND", s, VNOFUNC);
543 	s[0] = c;
544 	s[1] = '\0';
545 	err |= setvarsafe(optvar, s, 0);
546 	if (err) {
547 		*optnext = NULL;
548 		*optptr = NULL;
549 		flushall();
550 		exraise(EXERROR);
551 	}
552 	return done;
553 }
554 
555 /*
556  * Standard option processing (a la getopt) for builtin routines.  The
557  * only argument that is passed to nextopt is the option string; the
558  * other arguments are unnecessary.  It returns the option, or '\0' on
559  * end of input.
560  */
561 
562 int
563 nextopt(const char *optstring)
564 {
565 	char *p;
566 	const char *q;
567 	char c;
568 
569 	if ((p = nextopt_optptr) == NULL || *p == '\0') {
570 		p = *argptr;
571 		if (p == NULL || *p != '-' || *++p == '\0')
572 			return '\0';
573 		argptr++;
574 		if (p[0] == '-' && p[1] == '\0')	/* check for "--" */
575 			return '\0';
576 	}
577 	c = *p++;
578 	for (q = optstring ; *q != c ; ) {
579 		if (*q == '\0')
580 			error("Illegal option -%c", c);
581 		if (*++q == ':')
582 			q++;
583 	}
584 	if (*++q == ':') {
585 		if (*p == '\0' && (p = *argptr++) == NULL)
586 			error("No arg for -%c option", c);
587 		shoptarg = p;
588 		p = NULL;
589 	}
590 	if (p != NULL && *p != '\0')
591 		nextopt_optptr = p;
592 	else
593 		nextopt_optptr = NULL;
594 	return c;
595 }
596