1 /*        $NetBSD: options.c,v 1.62 2024/10/14 09:10:35 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.62 2024/10/14 09:10:35 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
procargs(int argc,char ** argv)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
optschanged(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
options(int cmdline)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 if (cmdline && c == 'r') {
248                                         out1fmt("NetBSD shell: %s\n",
249                                             lookupvar("NETBSD_SHELL"));
250                                         sh_exit(0);
251                               } else {
252                                         setoption(c, val);
253                               }
254                     }
255           }
256 }
257 
258 static void
set_opt_val(size_t i,int val)259 set_opt_val(size_t i, int val)
260 {
261           size_t j;
262           int flag;
263 
264           if (val && (flag = optlist[i].opt_set)) {
265                     /* some options (eg vi/emacs) are mutually exclusive */
266                     for (j = 0; j < NOPTS; j++)
267                         if (optlist[j].opt_set == flag)
268                               optlist[j].val = 0;
269           }
270 #ifndef SMALL
271           if (i == _SH_OPT_Xflag)
272                     xtracefdsetup(val);
273 #endif
274           optlist[i].val = val;
275 #ifdef DEBUG
276           if (&optlist[i].val == &debug)
277                     opentrace();        /* different "trace" than the -x one... */
278 #endif
279 }
280 
281 STATIC void
minus_o(char * name,int val)282 minus_o(char *name, int val)
283 {
284           size_t i;
285           const char *sep = ": ";
286 
287           if (name == NULL) {
288                     if (val) {
289                               out1str("Current option settings");
290                               for (i = 0; i < NOPTS; i++) {
291                                         if (optlist[i].name == NULL)  {
292                                                   out1fmt("%s%c%c", sep,
293                                                       "+-"[optlist[i].val],
294                                                       optlist[i].letter);
295                                                   sep = ", ";
296                                         }
297                               }
298                               out1c('\n');
299                               for (i = 0; i < NOPTS; i++) {
300                                         if (optlist[i].name)
301                                             out1fmt("%-19s %s\n", optlist[i].name,
302                                                   optlist[i].val ? "on" : "off");
303                               }
304                     } else {
305                               out1str("set -o default");
306                               for (i = 0; i < NOPTS; i++) {
307                                         if (optlist[i].val == optlist[i].dflt)
308                                                   continue;
309                                         if (optlist[i].name)
310                                             out1fmt(" %co %s",
311                                                   "+-"[optlist[i].val], optlist[i].name);
312                                         else
313                                             out1fmt(" %c%c", "+-"[optlist[i].val],
314                                                   optlist[i].letter);
315                               }
316                               out1c('\n');
317                     }
318           } else {
319                     if (val == 1 && equal(name, "default")) { /* special case */
320                               for (i = 0; i < NOPTS; i++)
321                                         set_opt_val(i, optlist[i].dflt);
322                               return;
323                     }
324                     if (val)
325                               val = 1;
326                     for (i = 0; i < NOPTS; i++)
327                               if (optlist[i].name && equal(name, optlist[i].name)) {
328                                         set_opt_val(i, val);
329 #ifndef SMALL
330                                         if (i == _SH_OPT_Xflag)
331                                                   set_opt_val(_SH_OPT_xflag, val);
332 #endif
333                                         return;
334                               }
335                     error("Unknown option %co %s", "+-"[val], name);
336           }
337 }
338 
339 
340 STATIC void
setoption(int flag,int val)341 setoption(int flag, int val)
342 {
343           size_t i;
344 
345           for (i = 0; i < NOPTS; i++)
346                     if (optlist[i].letter == flag) {
347                               set_opt_val(i, val);
348 #ifndef SMALL
349                               if (i == _SH_OPT_Xflag)
350                                         set_opt_val(_SH_OPT_xflag, val);
351 #endif
352                               return;
353                     }
354           error("Unknown option %c%c", "+-"[val], flag);
355           /* NOTREACHED */
356 }
357 
358 
359 
360 #ifdef mkinit
361 INCLUDE "options.h"
362 
363 SHELLPROC {
364           int i;
365 
366           for (i = 0; optlist[i].name; i++)
367                     optlist[i].val = 0;
368           optschanged();
369 
370 }
371 #endif
372 
373 
374 /*
375  * Set the shell parameters.
376  */
377 
378 void
setparam(char ** argv)379 setparam(char **argv)
380 {
381           char **newparam;
382           char **ap;
383           int nparam;
384 
385           for (nparam = 0 ; argv[nparam] ; nparam++)
386                     continue;
387           ap = newparam = ckmalloc((nparam + 1) * sizeof *ap);
388           while (*argv) {
389                     *ap++ = savestr(*argv++);
390           }
391           *ap = NULL;
392           freeparam(&shellparam);
393           shellparam.malloc = 1;
394           shellparam.nparam = nparam;
395           shellparam.p = newparam;
396           shellparam.optnext = NULL;
397 }
398 
399 
400 /*
401  * Free the list of positional parameters.
402  */
403 
404 void
freeparam(volatile struct shparam * param)405 freeparam(volatile struct shparam *param)
406 {
407           char **ap;
408 
409           if (param->malloc) {
410                     for (ap = param->p ; *ap ; ap++)
411                               ckfree(*ap);
412                     ckfree(param->p);
413           }
414 }
415 
416 
417 
418 /*
419  * The shift builtin command.
420  */
421 
422 #ifndef TINY
423 /* first the rotate variant */
424 static inline int
rotatecmd(int argc,char ** argv)425 rotatecmd(int argc, char **argv)
426 {
427           int n;
428           char **ap1, **ap2, **ss;
429 
430           (void) nextopt(NULL);         /* ignore '--' as leading option */
431 
432           /*
433            * half this is just in case it ever becomes
434            * a separate named command, while it remains
435            * puerly an inline inside shift, the compiler
436            * should optimise most of it to nothingness
437            */
438           if (argptr[0] && argptr[1])
439                     error("Usage: rotate [n]");
440           n = 1;
441           if (*argptr) {
442                     if (**argptr == '-')
443                               n = number(*argptr + 1);
444                     else                /* anti-clockwise n == clockwise $# - n */
445                               n = shellparam.nparam - number(*argptr);
446           }
447 
448           if (n == 0 || n == shellparam.nparam)             /* nothing to do */
449                     return 0;
450 
451           if (n < 0 || n > shellparam.nparam)
452                     error("can't rotate that many");
453 
454           ap2 = ss = (char **)stalloc(n * sizeof(char *));
455           INTOFF;
456           for (ap1 = shellparam.p + shellparam.nparam - n;
457                ap1 < shellparam.p + shellparam.nparam; )
458                     *ap2++ = *ap1++;
459           for (ap2 = shellparam.p + shellparam.nparam, ap1 = ap2 - n;
460                ap1 > shellparam.p; )
461                     *--ap2 = *--ap1;
462           for (ap1 = ss + n; ap1 > ss; )
463                     *--ap2 = *--ap1;
464           shellparam.optnext = NULL;
465           INTON;
466           stunalloc(ss);
467 
468           return 0;
469 }
470 #endif
471 
472 int
shiftcmd(int argc,char ** argv)473 shiftcmd(int argc, char **argv)
474 {
475           int n;
476           char **ap1, **ap2;
477 
478           (void) nextopt(NULL);         /* ignore '--' as leading option */
479 
480           if (argptr[0] && argptr[1])
481                     error("Usage: shift [n]");
482 
483 #ifndef TINY
484           if (*argptr && **argptr == '-') {
485                     argptr = argv + 1;  /* reinit nextopt() */
486                     optptr = NULL;
487                     return rotatecmd(argc, argv);
488           }
489 #endif
490 
491           n = 1;
492           if (*argptr)
493                     n = number(*argptr);
494           if (n > shellparam.nparam)
495                     error("can't shift that many");
496           INTOFF;
497           shellparam.nparam -= n;
498           for (ap1 = shellparam.p ; --n >= 0 ; ap1++) {
499                     if (shellparam.malloc)
500                               ckfree(*ap1);
501           }
502           ap2 = shellparam.p;
503           while ((*ap2++ = *ap1++) != NULL)
504                     continue;
505           shellparam.optnext = NULL;
506           INTON;
507           return 0;
508 }
509 
510 
511 
512 /*
513  * The set command builtin.
514  */
515 
516 int
setcmd(int argc,char ** argv)517 setcmd(int argc, char **argv)
518 {
519           if (argc == 1)
520                     return showvars(0, 0, 1, 0);
521           INTOFF;
522           options(0);
523           optschanged();
524           if (*argptr != NULL) {
525                     setparam(argptr);
526           }
527           INTON;
528           return 0;
529 }
530 
531 
532 void
getoptsreset(char * value,int flags __unused)533 getoptsreset(char *value, int flags __unused)
534 {
535           /*
536            * This is just to detect the case where OPTIND=1
537            * is executed.   Any other string assigned to OPTIND
538            * is OK, but is not a reset.   No errors, so cannot use number()
539            */
540           if (is_digit(*value) && strtol(value, NULL, 10) == 1) {
541                     shellparam.optnext = NULL;
542                     shellparam.reset = 1;
543           }
544 }
545 
546 /*
547  * The getopts builtin.  Shellparam.optnext points to the next argument
548  * to be processed.  Shellparam.optptr points to the next character to
549  * be processed in the current argument.  If shellparam.optnext is NULL,
550  * then it's the first time getopts has been called.
551  */
552 
553 int
getoptscmd(int argc,char ** argv)554 getoptscmd(int argc, char **argv)
555 {
556           char **optbase;
557 
558           if (argc < 3)
559                     error("usage: getopts optstring var [arg]");
560           else if (argc == 3)
561                     optbase = shellparam.p;
562           else
563                     optbase = &argv[3];
564 
565           if (shellparam.reset == 1) {
566                     shellparam.optnext = optbase;
567                     shellparam.optptr = NULL;
568                     shellparam.reset = 0;
569           }
570 
571           return getopts(argv[1], argv[2], optbase, &shellparam.optnext,
572                            &shellparam.optptr);
573 }
574 
575 STATIC int
getopts(char * optstr,char * optvar,char ** optfirst,char *** optnext,char ** optpptr)576 getopts(char *optstr, char *optvar, char **optfirst, char ***optnext, char **optpptr)
577 {
578           char *p, *q;
579           char c = '?';
580           int done = 0;
581           int ind = 0;
582           int err = 0;
583           char s[12];
584 
585           if ((p = *optpptr) == NULL || *p == '\0') {
586                     /* Current word is done, advance */
587                     if (*optnext == NULL)
588                               return 1;
589                     p = **optnext;
590                     if (p == NULL || *p != '-' || *++p == '\0') {
591 atend:
592                               ind = *optnext - optfirst + 1;
593                               *optnext = NULL;
594                               p = NULL;
595                               done = 1;
596                               goto out;
597                     }
598                     (*optnext)++;
599                     if (p[0] == '-' && p[1] == '\0')        /* check for "--" */
600                               goto atend;
601           }
602 
603           c = *p++;
604           for (q = optstr; *q != c; ) {
605                     if (*q == '\0') {
606                               if (optstr[0] == ':') {
607                                         s[0] = c;
608                                         s[1] = '\0';
609                                         err |= setvarsafe("OPTARG", s, 0);
610                               } else {
611                                         outfmt(&errout, "Unknown option -%c\n", c);
612                                         (void) unsetvar("OPTARG", 0);
613                               }
614                               c = '?';
615                               goto bad;
616                     }
617                     if (*++q == ':')
618                               q++;
619           }
620 
621           if (*++q == ':') {
622                     if (*p == '\0' && (p = **optnext) == NULL) {
623                               if (optstr[0] == ':') {
624                                         s[0] = c;
625                                         s[1] = '\0';
626                                         err |= setvarsafe("OPTARG", s, 0);
627                                         c = ':';
628                               } else {
629                                         outfmt(&errout, "No arg for -%c option\n", c);
630                                         (void) unsetvar("OPTARG", 0);
631                                         c = '?';
632                               }
633                               goto bad;
634                     }
635 
636                     if (p == **optnext)
637                               (*optnext)++;
638                     err |= setvarsafe("OPTARG", p, 0);
639                     p = NULL;
640           } else
641                     err |= setvarsafe("OPTARG", "", 0);
642           ind = *optnext - optfirst + 1;
643           goto out;
644 
645 bad:
646           ind = 1;
647           *optnext = NULL;
648           p = NULL;
649 out:
650           *optpptr = p;
651           fmtstr(s, sizeof(s), "%d", ind);
652           err |= setvarsafe("OPTIND", s, VNOFUNC);
653           s[0] = c;
654           s[1] = '\0';
655           err |= setvarsafe(optvar, s, 0);
656           if (err) {
657                     *optnext = NULL;
658                     *optpptr = NULL;
659                     flushall();
660                     exraise(EXERROR);
661           }
662           return done;
663 }
664 
665 /*
666  * XXX - should get rid of.  have all builtins use getopt(3).  the
667  * library getopt must have the BSD extension static variable "optreset"
668  * otherwise it can't be used within the shell safely.
669  *
670  * Standard option processing (a la getopt) for builtin routines.  The
671  * only argument that is passed to nextopt is the option string; the
672  * other arguments are unnecessary.  It return the character, or '\0' on
673  * end of input.  If optstring is NULL, then there are no options, and
674  * args are allowed to begin with '-', but a single leading "--" will be
675  * discarded.   This is for some POSIX special builtins that require
676  * -- processing, have no args, and we never did opt processing before
677  * and need to retain backwards compat.
678  */
679 
680 int
nextopt(const char * optstring)681 nextopt(const char *optstring)
682 {
683           char *p;
684           const char *q;
685           char c;
686 
687           if ((p = optptr) == NULL || *p == '\0') {
688                     p = *argptr;
689                     if (p == NULL || *p != '-' || *++p == '\0')
690                               return '\0';
691                     argptr++;
692                     if (p[0] == '-' && p[1] == '\0')        /* check for "--" */
693                               return '\0';
694                     if (optstring == NULL)        /* not processing the "option" */
695                               argptr--; /* so make it be an arg again */
696           }
697           if (optstring == NULL)
698                     return '\0';
699           c = *p++;
700           for (q = optstring ; *q != c ; ) {
701                     if (*q == '\0')
702                               error("Unknown option -%c", c);
703                     if (*++q == ':')
704                               q++;
705           }
706           if (*++q == ':') {
707                     if (*p == '\0' && (p = *argptr++) == NULL)
708                               error("No arg for -%c option", c);
709                     optionarg = p;
710                     p = NULL;
711           }
712           optptr = p;
713           return c;
714 }
715