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