Home | History | Annotate | Line # | Download | only in sh
options.c revision 1.57
      1 /*	$NetBSD: options.c,v 1.57 2022/04/16 14:20:45 kre Exp $	*/
      2 
      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 #include <sys/cdefs.h>
     36 #ifndef lint
     37 #if 0
     38 static char sccsid[] = "@(#)options.c	8.2 (Berkeley) 5/4/95";
     39 #else
     40 __RCSID("$NetBSD: options.c,v 1.57 2022/04/16 14:20:45 kre Exp $");
     41 #endif
     42 #endif /* not lint */
     43 
     44 #include <signal.h>
     45 #include <unistd.h>
     46 #include <stdlib.h>
     47 
     48 #include "shell.h"
     49 #define DEFINE_OPTIONS
     50 #include "options.h"
     51 #undef DEFINE_OPTIONS
     52 #include "builtins.h"
     53 #include "nodes.h"	/* for other header files */
     54 #include "eval.h"
     55 #include "jobs.h"
     56 #include "input.h"
     57 #include "output.h"
     58 #include "trap.h"
     59 #include "var.h"
     60 #include "memalloc.h"
     61 #include "error.h"
     62 #include "mystring.h"
     63 #include "syntax.h"
     64 #ifndef SMALL
     65 #include "myhistedit.h"
     66 #endif
     67 #include "show.h"
     68 
     69 char *arg0;			/* value of $0 */
     70 struct shparam shellparam;	/* current positional parameters */
     71 char **argptr;			/* argument list for builtin commands */
     72 char *optionarg;		/* set by nextopt (like getopt) */
     73 char *optptr;			/* used by nextopt */
     74 
     75 char *minusc;			/* argument to -c option */
     76 
     77 
     78 STATIC void options(int);
     79 STATIC void minus_o(char *, int);
     80 STATIC void setoption(int, int);
     81 STATIC int getopts(char *, char *, char **, char ***, char **);
     82 
     83 
     84 /*
     85  * Process the shell command line arguments.
     86  */
     87 
     88 void
     89 procargs(int argc, char **argv)
     90 {
     91 	size_t i;
     92 	int psx;
     93 
     94 	argptr = argv;
     95 	if (argc > 0)
     96 		argptr++;
     97 
     98 	psx = posix;		/* save what we set it to earlier */
     99 	/*
    100 	 * option values are mostly boolean 0:off 1:on
    101 	 * we use 2 (just in this routine) to mean "unknown yet"
    102 	 */
    103 	for (i = 0; i < NOPTS; i++)
    104 		optlist[i].val = 2;
    105 	posix = psx;		/* restore before processing -o ... */
    106 
    107 	options(1);
    108 
    109 	if (*argptr == NULL && minusc == NULL)
    110 		sflag = 1;
    111 	if (iflag == 2 && sflag == 1 && isatty(0) && isatty(2))
    112 		iflag = 1;
    113 	if (iflag == 1 && sflag == 2)
    114 		iflag = 2;
    115 	if (mflag == 2)
    116 		mflag = iflag;
    117 #ifndef DO_SHAREDVFORK
    118 	if (usefork == 2)
    119 		usefork = 1;
    120 #endif
    121 #if DEBUG >= 2
    122 	if (debug == 2)
    123 		debug = 1;
    124 #endif
    125 	/*
    126 	 * Any options not dealt with as special cases just above,
    127 	 * and which were not set on the command line, are set to
    128 	 * their expected default values (mostly "off")
    129 	 *
    130 	 * then as each option is initialised, save its setting now
    131 	 * as its "default" value for future use ("set -o default").
    132 	 */
    133 	for (i = 0; i < NOPTS; i++) {
    134 		if (optlist[i].val == 2)
    135 			optlist[i].val = optlist[i].dflt;
    136 		optlist[i].dflt = optlist[i].val;
    137 	}
    138 
    139 	arg0 = argv[0];
    140 	if (sflag == 0 && minusc == NULL) {
    141 		commandname = argv[0];
    142 		arg0 = *argptr++;
    143 		setinputfile(arg0, 0);
    144 		commandname = arg0;
    145 	}
    146 	/* POSIX 1003.2: first arg after -c cmd is $0, remainder $1... */
    147 	if (minusc != NULL) {
    148 		if (argptr == NULL || *argptr == NULL)
    149 			error("Bad -c option");
    150 		minusc = *argptr++;
    151 		if (*argptr != 0)
    152 			arg0 = *argptr++;
    153 	}
    154 
    155 	shellparam.p = argptr;
    156 	shellparam.reset = 1;
    157 	/* assert(shellparam.malloc == 0 && shellparam.nparam == 0); */
    158 	while (*argptr) {
    159 		shellparam.nparam++;
    160 		argptr++;
    161 	}
    162 	optschanged();
    163 }
    164 
    165 
    166 void
    167 optschanged(void)
    168 {
    169 	setinteractive(iflag);
    170 #ifndef SMALL
    171 	histedit();
    172 #endif
    173 	setjobctl(mflag);
    174 
    175 	if (privileged && !pflag) {
    176 		setuid(getuid());
    177 		setgid(getgid());
    178 		privileged = 0;
    179 		setvarsafe("PSc", (getuid() == 0 ? "#" : "$"), 0);
    180 	}
    181 }
    182 
    183 /*
    184  * Process shell options.  The global variable argptr contains a pointer
    185  * to the argument list; we advance it past the options.
    186  */
    187 
    188 STATIC void
    189 options(int cmdline)
    190 {
    191 	static char empty[] = "";
    192 	char *p;
    193 	int val;
    194 	int c;
    195 
    196 	if (cmdline)
    197 		minusc = NULL;
    198 	while ((p = *argptr) != NULL) {
    199 		argptr++;
    200 		if ((c = *p++) == '-') {
    201 			val = 1;
    202                         if (p[0] == '\0' || (p[0] == '-' && p[1] == '\0')) {
    203                                 if (!cmdline) {
    204                                         /* "-" means turn off -x and -v */
    205                                         if (p[0] == '\0')
    206                                                 xflag = vflag = 0;
    207                                         /* "--" means reset params */
    208                                         else if (*argptr == NULL)
    209 						setparam(argptr);
    210                                 }
    211 				break;	  /* "-" or  "--" terminates options */
    212 			}
    213 		} else if (c == '+') {
    214 			val = 0;
    215 		} else {
    216 			argptr--;
    217 			break;
    218 		}
    219 		while ((c = *p++) != '\0') {
    220 			if (val == 1 && c == 'c' && cmdline) {
    221 				/* command is after shell args*/
    222 				minusc = empty;
    223 			} else if (c == 'o') {
    224 				if (*p != '\0')
    225 					minus_o(p, val + (cmdline ? val : 0));
    226 				else if (*argptr)
    227 					minus_o(*argptr++,
    228 					    val + (cmdline ? val : 0));
    229 				else if (!cmdline)
    230 					minus_o(NULL, val);
    231 				else
    232 					error("arg for %co missing", "+-"[val]);
    233 				break;
    234 #ifdef DEBUG
    235 			} else if (c == 'D') {
    236 				if (*p) {
    237 					set_debug(p, val);
    238 					break;
    239 				} else if (*argptr)
    240 					set_debug(*argptr++, val);
    241 				else
    242 					set_debug("*$", val);
    243 #endif
    244 			} else {
    245 				setoption(c, val);
    246 			}
    247 		}
    248 	}
    249 }
    250 
    251 static void
    252 set_opt_val(size_t i, int val)
    253 {
    254 	size_t j;
    255 	int flag;
    256 
    257 	if (val && (flag = optlist[i].opt_set)) {
    258 		/* some options (eg vi/emacs) are mutually exclusive */
    259 		for (j = 0; j < NOPTS; j++)
    260 		    if (optlist[j].opt_set == flag)
    261 			optlist[j].val = 0;
    262 	}
    263 #ifndef SMALL
    264 	if (i == _SH_OPT_Xflag)
    265 		xtracefdsetup(val);
    266 #endif
    267 	optlist[i].val = val;
    268 #ifdef DEBUG
    269 	if (&optlist[i].val == &debug)
    270 		opentrace();	/* different "trace" than the -x one... */
    271 #endif
    272 }
    273 
    274 STATIC void
    275 minus_o(char *name, int val)
    276 {
    277 	size_t i;
    278 	const char *sep = ": ";
    279 
    280 	if (name == NULL) {
    281 		if (val) {
    282 			out1str("Current option settings");
    283 			for (i = 0; i < NOPTS; i++) {
    284 				if (optlist[i].name == NULL)  {
    285 					out1fmt("%s%c%c", sep,
    286 					    "+-"[optlist[i].val],
    287 					    optlist[i].letter);
    288 					sep = ", ";
    289 				}
    290 			}
    291 			out1c('\n');
    292 			for (i = 0; i < NOPTS; i++) {
    293 				if (optlist[i].name)
    294 				    out1fmt("%-19s %s\n", optlist[i].name,
    295 					optlist[i].val ? "on" : "off");
    296 			}
    297 		} else {
    298 			out1str("set -o default");
    299 			for (i = 0; i < NOPTS; i++) {
    300 				if (optlist[i].val == optlist[i].dflt)
    301 					continue;
    302 				if (optlist[i].name)
    303 				    out1fmt(" %co %s",
    304 					"+-"[optlist[i].val], optlist[i].name);
    305 				else
    306 				    out1fmt(" %c%c", "+-"[optlist[i].val],
    307 					optlist[i].letter);
    308 			}
    309 			out1c('\n');
    310 		}
    311 	} else {
    312 		if (val == 1 && equal(name, "default")) { /* special case */
    313 			for (i = 0; i < NOPTS; i++)
    314 				set_opt_val(i, optlist[i].dflt);
    315 			return;
    316 		}
    317 		if (val)
    318 			val = 1;
    319 		for (i = 0; i < NOPTS; i++)
    320 			if (optlist[i].name && equal(name, optlist[i].name)) {
    321 				set_opt_val(i, val);
    322 #ifndef SMALL
    323 				if (i == _SH_OPT_Xflag)
    324 					set_opt_val(_SH_OPT_xflag, val);
    325 #endif
    326 				return;
    327 			}
    328 		error("Unknown option %co %s", "+-"[val], name);
    329 	}
    330 }
    331 
    332 
    333 STATIC void
    334 setoption(int flag, int val)
    335 {
    336 	size_t i;
    337 
    338 	for (i = 0; i < NOPTS; i++)
    339 		if (optlist[i].letter == flag) {
    340 			set_opt_val(i, val);
    341 #ifndef SMALL
    342 			if (i == _SH_OPT_Xflag)
    343 				set_opt_val(_SH_OPT_xflag, val);
    344 #endif
    345 			return;
    346 		}
    347 	error("Unknown option %c%c", "+-"[val], flag);
    348 	/* NOTREACHED */
    349 }
    350 
    351 
    352 
    353 #ifdef mkinit
    354 INCLUDE "options.h"
    355 
    356 SHELLPROC {
    357 	int i;
    358 
    359 	for (i = 0; optlist[i].name; i++)
    360 		optlist[i].val = 0;
    361 	optschanged();
    362 
    363 }
    364 #endif
    365 
    366 
    367 /*
    368  * Set the shell parameters.
    369  */
    370 
    371 void
    372 setparam(char **argv)
    373 {
    374 	char **newparam;
    375 	char **ap;
    376 	int nparam;
    377 
    378 	for (nparam = 0 ; argv[nparam] ; nparam++)
    379 		continue;
    380 	ap = newparam = ckmalloc((nparam + 1) * sizeof *ap);
    381 	while (*argv) {
    382 		*ap++ = savestr(*argv++);
    383 	}
    384 	*ap = NULL;
    385 	freeparam(&shellparam);
    386 	shellparam.malloc = 1;
    387 	shellparam.nparam = nparam;
    388 	shellparam.p = newparam;
    389 	shellparam.optnext = NULL;
    390 }
    391 
    392 
    393 /*
    394  * Free the list of positional parameters.
    395  */
    396 
    397 void
    398 freeparam(volatile struct shparam *param)
    399 {
    400 	char **ap;
    401 
    402 	if (param->malloc) {
    403 		for (ap = param->p ; *ap ; ap++)
    404 			ckfree(*ap);
    405 		ckfree(param->p);
    406 	}
    407 }
    408 
    409 
    410 
    411 /*
    412  * The shift builtin command.
    413  */
    414 
    415 int
    416 shiftcmd(int argc, char **argv)
    417 {
    418 	int n;
    419 	char **ap1, **ap2;
    420 
    421 	if (argc > 2)
    422 		error("Usage: shift [n]");
    423 	n = 1;
    424 	if (argc > 1)
    425 		n = number(argv[1]);
    426 	if (n > shellparam.nparam)
    427 		error("can't shift that many");
    428 	INTOFF;
    429 	shellparam.nparam -= n;
    430 	for (ap1 = shellparam.p ; --n >= 0 ; ap1++) {
    431 		if (shellparam.malloc)
    432 			ckfree(*ap1);
    433 	}
    434 	ap2 = shellparam.p;
    435 	while ((*ap2++ = *ap1++) != NULL)
    436 		continue;
    437 	shellparam.optnext = NULL;
    438 	INTON;
    439 	return 0;
    440 }
    441 
    442 
    443 
    444 /*
    445  * The set command builtin.
    446  */
    447 
    448 int
    449 setcmd(int argc, char **argv)
    450 {
    451 	if (argc == 1)
    452 		return showvars(0, 0, 1, 0);
    453 	INTOFF;
    454 	options(0);
    455 	optschanged();
    456 	if (*argptr != NULL) {
    457 		setparam(argptr);
    458 	}
    459 	INTON;
    460 	return 0;
    461 }
    462 
    463 
    464 void
    465 getoptsreset(const char *value)
    466 {
    467 	/*
    468 	 * This is just to detect the case where OPTIND=1
    469 	 * is executed.   Any other string assigned to OPTIND
    470 	 * is OK, but is not a reset.   No errors, so cannot use number()
    471 	 */
    472 	if (is_digit(*value) && strtol(value, NULL, 10) == 1) {
    473 		shellparam.optnext = NULL;
    474 		shellparam.reset = 1;
    475 	}
    476 }
    477 
    478 /*
    479  * The getopts builtin.  Shellparam.optnext points to the next argument
    480  * to be processed.  Shellparam.optptr points to the next character to
    481  * be processed in the current argument.  If shellparam.optnext is NULL,
    482  * then it's the first time getopts has been called.
    483  */
    484 
    485 int
    486 getoptscmd(int argc, char **argv)
    487 {
    488 	char **optbase;
    489 
    490 	if (argc < 3)
    491 		error("usage: getopts optstring var [arg]");
    492 	else if (argc == 3)
    493 		optbase = shellparam.p;
    494 	else
    495 		optbase = &argv[3];
    496 
    497 	if (shellparam.reset == 1) {
    498 		shellparam.optnext = optbase;
    499 		shellparam.optptr = NULL;
    500 		shellparam.reset = 0;
    501 	}
    502 
    503 	return getopts(argv[1], argv[2], optbase, &shellparam.optnext,
    504 		       &shellparam.optptr);
    505 }
    506 
    507 STATIC int
    508 getopts(char *optstr, char *optvar, char **optfirst, char ***optnext, char **optpptr)
    509 {
    510 	char *p, *q;
    511 	char c = '?';
    512 	int done = 0;
    513 	int ind = 0;
    514 	int err = 0;
    515 	char s[12];
    516 
    517 	if ((p = *optpptr) == NULL || *p == '\0') {
    518 		/* Current word is done, advance */
    519 		if (*optnext == NULL)
    520 			return 1;
    521 		p = **optnext;
    522 		if (p == NULL || *p != '-' || *++p == '\0') {
    523 atend:
    524 			ind = *optnext - optfirst + 1;
    525 			*optnext = NULL;
    526 			p = NULL;
    527 			done = 1;
    528 			goto out;
    529 		}
    530 		(*optnext)++;
    531 		if (p[0] == '-' && p[1] == '\0')	/* check for "--" */
    532 			goto atend;
    533 	}
    534 
    535 	c = *p++;
    536 	for (q = optstr; *q != c; ) {
    537 		if (*q == '\0') {
    538 			if (optstr[0] == ':') {
    539 				s[0] = c;
    540 				s[1] = '\0';
    541 				err |= setvarsafe("OPTARG", s, 0);
    542 			} else {
    543 				outfmt(&errout, "Unknown option -%c\n", c);
    544 				(void) unsetvar("OPTARG", 0);
    545 			}
    546 			c = '?';
    547 			goto bad;
    548 		}
    549 		if (*++q == ':')
    550 			q++;
    551 	}
    552 
    553 	if (*++q == ':') {
    554 		if (*p == '\0' && (p = **optnext) == NULL) {
    555 			if (optstr[0] == ':') {
    556 				s[0] = c;
    557 				s[1] = '\0';
    558 				err |= setvarsafe("OPTARG", s, 0);
    559 				c = ':';
    560 			} else {
    561 				outfmt(&errout, "No arg for -%c option\n", c);
    562 				(void) unsetvar("OPTARG", 0);
    563 				c = '?';
    564 			}
    565 			goto bad;
    566 		}
    567 
    568 		if (p == **optnext)
    569 			(*optnext)++;
    570 		err |= setvarsafe("OPTARG", p, 0);
    571 		p = NULL;
    572 	} else
    573 		err |= setvarsafe("OPTARG", "", 0);
    574 	ind = *optnext - optfirst + 1;
    575 	goto out;
    576 
    577 bad:
    578 	ind = 1;
    579 	*optnext = NULL;
    580 	p = NULL;
    581 out:
    582 	*optpptr = p;
    583 	fmtstr(s, sizeof(s), "%d", ind);
    584 	err |= setvarsafe("OPTIND", s, VNOFUNC);
    585 	s[0] = c;
    586 	s[1] = '\0';
    587 	err |= setvarsafe(optvar, s, 0);
    588 	if (err) {
    589 		*optnext = NULL;
    590 		*optpptr = NULL;
    591 		flushall();
    592 		exraise(EXERROR);
    593 	}
    594 	return done;
    595 }
    596 
    597 /*
    598  * XXX - should get rid of.  have all builtins use getopt(3).  the
    599  * library getopt must have the BSD extension static variable "optreset"
    600  * otherwise it can't be used within the shell safely.
    601  *
    602  * Standard option processing (a la getopt) for builtin routines.  The
    603  * only argument that is passed to nextopt is the option string; the
    604  * other arguments are unnecessary.  It return the character, or '\0' on
    605  * end of input.  If optstring is NULL, then there are no options, and
    606  * args are allowed to begin with '-', but a single leading "--" will be
    607  * discarded.   This is for some POSIX special builtins that require
    608  * -- processing, have no args, and we never did opt processing before
    609  * and need to retain backwards compat.
    610  */
    611 
    612 int
    613 nextopt(const char *optstring)
    614 {
    615 	char *p;
    616 	const char *q;
    617 	char c;
    618 
    619 	if ((p = optptr) == NULL || *p == '\0') {
    620 		p = *argptr;
    621 		if (p == NULL || *p != '-' || *++p == '\0')
    622 			return '\0';
    623 		argptr++;
    624 		if (p[0] == '-' && p[1] == '\0')	/* check for "--" */
    625 			return '\0';
    626 		if (optstring == NULL)	/* not processing the "option" */
    627 			argptr--;	/* so make it be an arg again */
    628 	}
    629 	if (optstring == NULL)
    630 		return '\0';
    631 	c = *p++;
    632 	for (q = optstring ; *q != c ; ) {
    633 		if (*q == '\0')
    634 			error("Unknown option -%c", c);
    635 		if (*++q == ':')
    636 			q++;
    637 	}
    638 	if (*++q == ':') {
    639 		if (*p == '\0' && (p = *argptr++) == NULL)
    640 			error("No arg for -%c option", c);
    641 		optionarg = p;
    642 		p = NULL;
    643 	}
    644 	optptr = p;
    645 	return c;
    646 }
    647