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#include <signal.h>
36#include <stdlib.h>
37#include <unistd.h>
38
39#include "shell.h"
40#define DEFINE_OPTIONS
41#include "options.h"
42#undef DEFINE_OPTIONS
43#include "builtins.h"
44#include "error.h"
45#include "eval.h"
46#include "input.h"
47#include "jobs.h"
48#include "memalloc.h"
49#include "mystring.h"
50#include "nodes.h" /* for other header files */
51#include "output.h"
52#include "trap.h"
53#include "var.h"
54#ifndef NO_HISTORY
55#include "lineedit.h"
56#endif
57
58char *arg0; /* value of $0 */
59struct shparam shellparam; /* current positional parameters */
60char **argptr; /* argument list for builtin commands */
61char *shoptarg; /* set by nextopt (like getopt) */
62char *nextopt_optptr; /* used by nextopt */
63
64char *minusc; /* argument to -c option */
65
66static int options(int);
67static void minus_o(char *, int);
68static void setoption(int, int);
69static void setoptionbyindex(int, int);
70static void setparam(int, char **);
71static int getopts(char *, char *, char **, char ***, char **);
72
73/*
74 * Process the shell command line arguments.
75 */
76
77int
78procargs(int argc, char **argv)
79{
80 int i, login;
81 char *scriptname;
82
83 argptr = argv;
84 login = argptr[0] != NULL && argptr[0][0] == '-';
85 if (argc > 0)
86 argptr++;
87 for (i = 0; i < NOPTS; i++)
88 optval[i] = 2;
89 privileged = (getuid() != geteuid() || getgid() != getegid());
90 login |= options(1);
91 if (*argptr == NULL && minusc == NULL)
92 sflag = 1;
93 if (iflag != 0 && sflag == 1 && isatty(0) && isatty(1)) {
94 iflag = 1;
95 if (Eflag == 2)
96 Eflag = 1;
97 }
98 if (mflag == 2)
99 mflag = iflag;
100 for (i = 0; i < NOPTS; i++)
101 if (optval[i] == 2)
102 optval[i] = 0;
103 arg0 = argv[0];
104 if (sflag == 0 && minusc == NULL) {
105 scriptname = *argptr++;
106 setinputfile(scriptname, 0, -1 /* verify */);
107 commandname = arg0 = scriptname;
108 }
109 /* POSIX 1003.2: first arg after -c cmd is $0, remainder $1... */
110 if (argptr && minusc && *argptr)
111 arg0 = *argptr++;
112
113 shellparam.p = argptr;
114 shellparam.reset = 1;
115 /* assert(shellparam.malloc == 0 && shellparam.nparam == 0); */
116 while (*argptr) {
117 shellparam.nparam++;
118 argptr++;
119 }
120 optschanged();
121
122 return (login);
123}
124
125void
126optschanged(void)
127{
128 setinteractive();
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 * If cmdline is true, process the shell's argv; otherwise, process arguments
139 * to the set special builtin.
140 */
141
142static int
143options(int cmdline)
144{
145 char *kp, *p;
146 int val;
147 int c;
148 int login = 0;
149
150 if (cmdline)
151 minusc = NULL;
152 while ((p = *argptr) != NULL) {
153 argptr++;
154 if ((c = *p++) == '-') {
155 val = 1;
156 /* A "-" or "--" terminates options */
157 if (p[0] == '\0')
158 goto end_options1;
159 if (p[0] == '-' && p[1] == '\0')
160 goto end_options2;
161 /**
162 * For the benefit of `#!' lines in shell scripts,
163 * treat a string of '-- *#.*' the same as '--'.
164 * This is needed so that a script starting with:
165 * #!/bin/sh -- # -*- perl -*-
166 * will continue to work after a change is made to
167 * kern/imgact_shell.c to NOT token-ize the options
168 * specified on a '#!' line. A bit of a kludge,
169 * but that trick is recommended in documentation
170 * for some scripting languages, and we might as
171 * well continue to support it.
172 */
173 if (p[0] == '-') {
174 kp = p + 1;
175 while (*kp == ' ' || *kp == '\t')
176 kp++;
177 if (*kp == '#' || *kp == '\0')
178 goto end_options2;
179 }
180 } else if (c == '+') {
181 val = 0;
182 } else {
183 argptr--;
184 break;
185 }
186 while ((c = *p++) != '\0') {
187 if (c == 'c' && cmdline) {
188 char *q;
189
190 q = *argptr++;
191 if (q == NULL || minusc != NULL)
192 error("Bad -c option");
193 minusc = q;
194 } else if (c == 'l' && cmdline) {
195 login = 1;
196 } else if (c == 'o') {
197 minus_o(*argptr, val);
198 if (*argptr)
199 argptr++;
200 } else
201 setoption(c, val);
202 }
203 }
204 return (login);
205
206 /* When processing `set', a single "-" means turn off -x and -v */
207end_options1:
208 if (!cmdline) {
209 xflag = vflag = 0;
210 return (login);
211 }
212
213 /*
214 * When processing `set', a "--" means the remaining arguments
215 * replace the positional parameters in the active shell. If
216 * there are no remaining options, then all the positional
217 * parameters are cleared (equivalent to doing ``shift $#'').
218 */
219end_options2:
220 if (!cmdline) {
221 if (*argptr == NULL)
222 setparam(0, argptr);
223 return (login);
224 }
225
226 /*
227 * At this point we are processing options given to 'sh' on a command
228 * line. If an end-of-options marker ("-" or "--") is followed by an
229 * arg of "#", then skip over all remaining arguments. Some scripting
230 * languages (e.g.: perl) document that /bin/sh will implement this
231 * behavior, and they recommend that users take advantage of it to
232 * solve certain issues that can come up when writing a perl script.
233 * Yes, this feature is in /bin/sh to help users write perl scripts.
234 */
235 p = *argptr;
236 if (p != NULL && p[0] == '#' && p[1] == '\0') {
237 while (*argptr != NULL)
238 argptr++;
239 /* We need to keep the final argument */
240 argptr--;
241 }
242
243 return (login);
244}
245
246static void
247minus_o(char *name, int val)
248{
249 int i;
250 const unsigned char *on;
251 size_t len;
252
253 if (name == NULL) {
254 if (val) {
255 /* "Pretty" output. */
256 out1str("Current option settings\n");
257 for (i = 0, on = optname; i < NOPTS; i++, on += *on + 1)
258 out1fmt("%-16.*s%s\n", *on, on + 1, optval[i] ? "on" : "off");
259 } else {
260 /* Output suitable for re-input to shell. */
261 for (i = 0, on = optname; i < NOPTS; i++, on += *on + 1)
262 out1fmt(
263 "%s %co %.*s%s",
264 i % 6 == 0 ? "set" : "",
265 optval[i] ? '-' : '+',
266 *on,
267 on + 1,
268 i % 6 == 5 || i == NOPTS - 1 ? "\n" : ""
269 );
270 }
271 } else {
272 len = strlen(name);
273 for (i = 0, on = optname; i < NOPTS; i++, on += *on + 1)
274 if (*on == len && memcmp(on + 1, name, len) == 0) {
275 setoptionbyindex(i, val);
276 return;
277 }
278 error("Illegal option -o %s", name);
279 }
280}
281
282static void
283setoptionbyindex(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
301static void
302setoption(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 * Set the shell parameters.
316 */
317
318static void
319setparam(int argc, char **argv)
320{
321 char **newparam;
322 char **ap;
323
324 ap = newparam = ckmalloc((argc + 1) * sizeof *ap);
325 while (*argv) {
326 *ap++ = savestr(*argv++);
327 }
328 *ap = NULL;
329 freeparam(&shellparam);
330 shellparam.malloc = 1;
331 shellparam.nparam = argc;
332 shellparam.p = newparam;
333 shellparam.optp = NULL;
334 shellparam.reset = 1;
335 shellparam.optnext = NULL;
336}
337
338/*
339 * Free the list of positional parameters.
340 */
341
342void
343freeparam(struct shparam *param)
344{
345 char **ap;
346
347 if (param->malloc) {
348 for (ap = param->p; *ap; ap++)
349 ckfree(*ap);
350 ckfree(param->p);
351 }
352 if (param->optp) {
353 for (ap = param->optp; *ap; ap++)
354 ckfree(*ap);
355 ckfree(param->optp);
356 }
357}
358
359/*
360 * The shift builtin command.
361 */
362
363int
364shiftcmd(int argc, char **argv)
365{
366 int i, n;
367
368 n = 1;
369 if (argc > 1)
370 n = number(argv[1]);
371 if (n > shellparam.nparam)
372 return 1;
373 INTOFF;
374 shellparam.nparam -= n;
375 if (shellparam.malloc)
376 for (i = 0; i < n; i++)
377 ckfree(shellparam.p[i]);
378 memmove(shellparam.p, shellparam.p + n, (shellparam.nparam + 1) * sizeof(shellparam.p[0]));
379 shellparam.reset = 1;
380 INTON;
381 return 0;
382}
383
384/*
385 * The set builtin command.
386 */
387
388int
389setcmd(int argc, char **argv)
390{
391 if (argc == 1)
392 return showvarscmd(argc, argv);
393 INTOFF;
394 options(0);
395 optschanged();
396 if (*argptr != NULL) {
397 setparam(argc - (argptr - argv), argptr);
398 }
399 INTON;
400 return 0;
401}
402
403void
404getoptsreset(const char *value)
405{
406 while (*value == '0')
407 value++;
408 if (strcmp(value, "1") == 0)
409 shellparam.reset = 1;
410}
411
412/*
413 * The getopts builtin. Shellparam.optnext points to the next argument
414 * to be processed. Shellparam.optptr points to the next character to
415 * be processed in the current argument. If shellparam.optnext is NULL,
416 * then it's the first time getopts has been called.
417 */
418
419int
420getoptscmd(int argc, char **argv)
421{
422 char **optbase = NULL, **ap;
423 int i;
424
425 if (argc < 3)
426 error("usage: getopts optstring var [arg]");
427
428 if (shellparam.reset == 1) {
429 INTOFF;
430 if (shellparam.optp) {
431 for (ap = shellparam.optp; *ap; ap++)
432 ckfree(*ap);
433 ckfree(shellparam.optp);
434 shellparam.optp = NULL;
435 }
436 if (argc > 3) {
437 shellparam.optp = ckmalloc((argc - 2) * sizeof *ap);
438 memset(shellparam.optp, '\0', (argc - 2) * sizeof *ap);
439 for (i = 0; i < argc - 3; i++)
440 shellparam.optp[i] = savestr(argv[i + 3]);
441 }
442 INTON;
443 optbase = argc == 3 ? shellparam.p : shellparam.optp;
444 shellparam.optnext = optbase;
445 shellparam.optptr = NULL;
446 shellparam.reset = 0;
447 } else
448 optbase = shellparam.optp ? shellparam.optp : shellparam.p;
449
450 return getopts(argv[1], argv[2], optbase, &shellparam.optnext, &shellparam.optptr);
451}
452
453static int
454getopts(char *optstr, char *optvar, char **optfirst, char ***optnext, char **optptr)
455{
456 char *p, *q;
457 char c = '?';
458 int done = 0;
459 int ind = 0;
460 int err = 0;
461 char s[10];
462 const char *newoptarg = NULL;
463
464 if ((p = *optptr) == 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 newoptarg = s;
489 } else
490 out2fmt_flush("Illegal option -%c\n", c);
491 c = '?';
492 goto out;
493 }
494 if (*++q == ':')
495 q++;
496 }
497
498 if (*++q == ':') {
499 if (*p == '\0' && (p = **optnext) == NULL) {
500 if (optstr[0] == ':') {
501 s[0] = c;
502 s[1] = '\0';
503 newoptarg = s;
504 c = ':';
505 } else {
506 out2fmt_flush("No arg for -%c option\n", c);
507 c = '?';
508 }
509 goto out;
510 }
511
512 if (p == **optnext)
513 (*optnext)++;
514 newoptarg = p;
515 p = NULL;
516 }
517
518out:
519 if (*optnext != NULL)
520 ind = *optnext - optfirst + 1;
521 *optptr = p;
522 if (newoptarg != NULL)
523 err |= setvarsafe("OPTARG", newoptarg, 0);
524 else {
525 INTOFF;
526 err |= unsetvar("OPTARG");
527 INTON;
528 }
529 fmtstr(s, sizeof(s), "%d", ind);
530 err |= setvarsafe("OPTIND", s, VNOFUNC);
531 s[0] = c;
532 s[1] = '\0';
533 err |= setvarsafe(optvar, s, 0);
534 if (err) {
535 *optnext = NULL;
536 *optptr = NULL;
537 flushall();
538 exraise(EXERROR);
539 }
540 return done;
541}
542
543/*
544 * Standard option processing (a la getopt) for builtin routines. The
545 * only argument that is passed to nextopt is the option string; the
546 * other arguments are unnecessary. It returns the option, or '\0' on
547 * end of input.
548 */
549
550int
551nextopt(const char *optstring)
552{
553 char *p;
554 const char *q;
555 char c;
556
557 if ((p = nextopt_optptr) == NULL || *p == '\0') {
558 p = *argptr;
559 if (p == NULL || *p != '-' || *++p == '\0')
560 return '\0';
561 argptr++;
562 if (p[0] == '-' && p[1] == '\0') /* check for "--" */
563 return '\0';
564 }
565 c = *p++;
566 for (q = optstring; *q != c;) {
567 if (*q == '\0')
568 error("Illegal option -%c", c);
569 if (*++q == ':')
570 q++;
571 }
572 if (*++q == ':') {
573 if (*p == '\0' && (p = *argptr++) == NULL)
574 error("No arg for -%c option", c);
575 shoptarg = p;
576 p = NULL;
577 }
578 if (p != NULL && *p != '\0')
579 nextopt_optptr = p;
580 else
581 nextopt_optptr = NULL;
582 return c;
583}