b9710dd4b75c08ff6f746e4b13c1853f8172ed86
[dragonfly.git] / bin / sh / options.c
1 /*-
2  * Copyright (c) 1991, 1993
3  *      The Regents of the University of California.  All rights reserved.
4  *
5  * This code is derived from software contributed to Berkeley by
6  * Kenneth Almquist.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. Neither the name of the University nor the names of its contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  *
32  * @(#)options.c        8.2 (Berkeley) 5/4/95
33  * $FreeBSD: head/bin/sh/options.c 240247 2012-09-08 19:24:03Z jilles $
34  */
35
36 #include <signal.h>
37 #include <unistd.h>
38 #include <stdlib.h>
39
40 #include "shell.h"
41 #define DEFINE_OPTIONS
42 #include "options.h"
43 #undef DEFINE_OPTIONS
44 #include "nodes.h"      /* for other header files */
45 #include "eval.h"
46 #include "jobs.h"
47 #include "input.h"
48 #include "output.h"
49 #include "trap.h"
50 #include "var.h"
51 #include "memalloc.h"
52 #include "error.h"
53 #include "mystring.h"
54 #include "builtins.h"
55 #ifndef NO_HISTORY
56 #include "myhistedit.h"
57 #endif
58
59 char *arg0;                     /* value of $0 */
60 struct shparam shellparam;      /* current positional parameters */
61 char **argptr;                  /* argument list for builtin commands */
62 const char *shoptarg;           /* set by nextopt (like getopt) */
63 char *nextopt_optptr;           /* used by nextopt */
64
65 char *minusc;                   /* argument to -c option */
66
67
68 static void options(int);
69 static void minus_o(char *, int);
70 static void setoption(int, int);
71 static int getopts(char *, char *, char **, char ***, char **);
72
73
74 /*
75  * Process the shell command line arguments.
76  */
77
78 void
79 procargs(int argc, char **argv)
80 {
81         int i;
82         char *scriptname;
83
84         argptr = argv;
85         if (argc > 0)
86                 argptr++;
87         for (i = 0; i < NOPTS; i++)
88                 optlist[i].val = 2;
89         privileged = (getuid() != geteuid() || getgid() != getegid());
90         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         /* turn on tabcomplete in an interactive shell by default */
101         tabcomplete = iflag;
102         for (i = 0; i < NOPTS; i++)
103                 if (optlist[i].val == 2)
104                         optlist[i].val = 0;
105         arg0 = argv[0];
106         if (sflag == 0 && minusc == NULL) {
107                 scriptname = *argptr++;
108                 setinputfile(scriptname, 0);
109                 commandname = arg0 = scriptname;
110         }
111         /* POSIX 1003.2: first arg after -c cmd is $0, remainder $1... */
112         if (argptr && minusc && *argptr)
113                 arg0 = *argptr++;
114
115         shellparam.p = argptr;
116         shellparam.reset = 1;
117         /* assert(shellparam.malloc == 0 && shellparam.nparam == 0); */
118         while (*argptr) {
119                 shellparam.nparam++;
120                 argptr++;
121         }
122         optschanged();
123 }
124
125
126 void
127 optschanged(void)
128 {
129         setinteractive(iflag);
130 #ifndef NO_HISTORY
131         histedit();
132 #endif
133         setjobctl(mflag);
134 }
135
136 /*
137  * Process shell options.  The global variable argptr contains a pointer
138  * to the argument list; we advance it past the options.
139  */
140
141 static void
142 options(int cmdline)
143 {
144         char *kp, *p;
145         int val;
146         int c;
147
148         if (cmdline)
149                 minusc = NULL;
150         while ((p = *argptr) != NULL) {
151                 argptr++;
152                 if ((c = *p++) == '-') {
153                         val = 1;
154                         /* A "-" or  "--" terminates options */
155                         if (p[0] == '\0')
156                                 goto end_options1;
157                         if (p[0] == '-' && p[1] == '\0')
158                                 goto end_options2;
159                         /**
160                          * For the benefit of `#!' lines in shell scripts,
161                          * treat a string of '-- *#.*' the same as '--'.
162                          * This is needed so that a script starting with:
163                          *      #!/bin/sh -- # -*- perl -*-
164                          * will continue to work after a change is made to
165                          * kern/imgact_shell.c to NOT token-ize the options
166                          * specified on a '#!' line.  A bit of a kludge,
167                          * but that trick is recommended in documentation
168                          * for some scripting languages, and we might as
169                          * well continue to support it.
170                          */
171                         if (p[0] == '-') {
172                                 kp = p + 1;
173                                 while (*kp == ' ' || *kp == '\t')
174                                         kp++;
175                                 if (*kp == '#' || *kp == '\0')
176                                         goto end_options2;
177                         }
178                 } else if (c == '+') {
179                         val = 0;
180                 } else {
181                         argptr--;
182                         break;
183                 }
184                 while ((c = *p++) != '\0') {
185                         if (c == 'c' && cmdline) {
186                                 char *q;
187 #ifdef NOHACK   /* removing this code allows sh -ce 'foo' for compat */
188                                 if (*p == '\0')
189 #endif
190                                         q = *argptr++;
191                                 if (q == NULL || minusc != NULL)
192                                         error("Bad -c option");
193                                 minusc = q;
194 #ifdef NOHACK
195                                 break;
196 #endif
197                         } else if (c == 'o') {
198                                 minus_o(*argptr, val);
199                                 if (*argptr)
200                                         argptr++;
201                         } else
202                                 setoption(c, val);
203                 }
204         }
205         return;
206
207         /* When processing `set', a single "-" means turn off -x and -v */
208 end_options1:
209         if (!cmdline) {
210                 xflag = vflag = 0;
211                 return;
212         }
213
214         /*
215          * When processing `set', a "--" means the remaining arguments
216          * replace the positional parameters in the active shell.  If
217          * there are no remaining options, then all the positional
218          * parameters are cleared (equivalent to doing ``shift $#'').
219          */
220 end_options2:
221         if (!cmdline) {
222                 if (*argptr == NULL)
223                         setparam(argptr);
224                 return;
225         }
226
227         /*
228          * At this point we are processing options given to 'sh' on a command
229          * line.  If an end-of-options marker ("-" or "--") is followed by an
230          * arg of "#", then skip over all remaining arguments.  Some scripting
231          * languages (e.g.: perl) document that /bin/sh will implement this
232          * behavior, and they recommend that users take advantage of it to
233          * solve certain issues that can come up when writing a perl script.
234          * Yes, this feature is in /bin/sh to help users write perl scripts.
235          */
236         p = *argptr;
237         if (p != NULL && p[0] == '#' && p[1] == '\0') {
238                 while (*argptr != NULL)
239                         argptr++;
240                 /* We need to keep the final argument */
241                 argptr--;
242         }
243 }
244
245 static void
246 minus_o(char *name, int val)
247 {
248         int i;
249
250         if (name == NULL) {
251                 if (val) {
252                         /* "Pretty" output. */
253                         out1str("Current option settings\n");
254                         for (i = 0; i < NOPTS; i++)
255                                 out1fmt("%-16s%s\n", optlist[i].name,
256                                         optlist[i].val ? "on" : "off");
257                 } else {
258                         /* Output suitable for re-input to shell. */
259                         for (i = 0; i < NOPTS; i++)
260                                 out1fmt("%s %co %s%s",
261                                     i % 6 == 0 ? "set" : "",
262                                     optlist[i].val ? '-' : '+',
263                                     optlist[i].name,
264                                     i % 6 == 5 || i == NOPTS - 1 ? "\n" : "");
265                 }
266         } else {
267                 for (i = 0; i < NOPTS; i++)
268                         if (equal(name, optlist[i].name)) {
269                                 setoption(optlist[i].letter, val);
270                                 return;
271                         }
272                 error("Illegal option -o %s", name);
273         }
274 }
275
276
277 static void
278 setoption(int flag, int val)
279 {
280         int i;
281
282         if (flag == 'p' && !val && privileged) {
283                 if (setgid(getgid()) == -1)
284                         error("setgid");
285                 if (setuid(getuid()) == -1)
286                         error("setuid");
287         }
288         for (i = 0; i < NOPTS; i++)
289                 if (optlist[i].letter == flag) {
290                         optlist[i].val = val;
291                         if (val) {
292                                 /* #%$ hack for ksh semantics */
293                                 if (flag == 'V')
294                                         Eflag = 0;
295                                 else if (flag == 'E')
296                                         Vflag = 0;
297                         }
298                         return;
299                 }
300         error("Illegal option -%c", flag);
301 }
302
303
304 /*
305  * Set the shell parameters.
306  */
307
308 void
309 setparam(char **argv)
310 {
311         char **newparam;
312         char **ap;
313         int nparam;
314
315         for (nparam = 0 ; argv[nparam] ; nparam++);
316         ap = newparam = ckmalloc((nparam + 1) * sizeof *ap);
317         while (*argv) {
318                 *ap++ = savestr(*argv++);
319         }
320         *ap = NULL;
321         freeparam(&shellparam);
322         shellparam.malloc = 1;
323         shellparam.nparam = nparam;
324         shellparam.p = newparam;
325         shellparam.reset = 1;
326         shellparam.optnext = NULL;
327 }
328
329
330 /*
331  * Free the list of positional parameters.
332  */
333
334 void
335 freeparam(volatile struct shparam *param)
336 {
337         char **ap;
338
339         if (param->malloc) {
340                 for (ap = param->p ; *ap ; ap++)
341                         ckfree(*ap);
342                 ckfree(param->p);
343         }
344 }
345
346
347
348 /*
349  * The shift builtin command.
350  */
351
352 int
353 shiftcmd(int argc, char **argv)
354 {
355         int n;
356         char **ap1, **ap2;
357
358         n = 1;
359         if (argc > 1)
360                 n = number(argv[1]);
361         if (n > shellparam.nparam)
362                 return 1;
363         INTOFF;
364         shellparam.nparam -= n;
365         for (ap1 = shellparam.p ; --n >= 0 ; ap1++) {
366                 if (shellparam.malloc)
367                         ckfree(*ap1);
368         }
369         ap2 = shellparam.p;
370         while ((*ap2++ = *ap1++) != NULL);
371         shellparam.reset = 1;
372         INTON;
373         return 0;
374 }
375
376
377
378 /*
379  * The set command builtin.
380  */
381
382 int
383 setcmd(int argc, char **argv)
384 {
385         if (argc == 1)
386                 return showvarscmd(argc, argv);
387         INTOFF;
388         options(0);
389         optschanged();
390         if (*argptr != NULL) {
391                 setparam(argptr);
392         }
393         INTON;
394         return 0;
395 }
396
397
398 void
399 getoptsreset(const char *value)
400 {
401         while (*value == '0')
402                 value++;
403         if (strcmp(value, "1") == 0)
404                 shellparam.reset = 1;
405 }
406
407 /*
408  * The getopts builtin.  Shellparam.optnext points to the next argument
409  * to be processed.  Shellparam.optptr points to the next character to
410  * be processed in the current argument.  If shellparam.optnext is NULL,
411  * then it's the first time getopts has been called.
412  */
413
414 int
415 getoptscmd(int argc, char **argv)
416 {
417         char **optbase = NULL;
418
419         if (argc < 3)
420                 error("usage: getopts optstring var [arg]");
421         else if (argc == 3)
422                 optbase = shellparam.p;
423         else
424                 optbase = &argv[3];
425
426         if (shellparam.reset == 1) {
427                 shellparam.optnext = optbase;
428                 shellparam.optptr = NULL;
429                 shellparam.reset = 0;
430         }
431
432         return getopts(argv[1], argv[2], optbase, &shellparam.optnext,
433                        &shellparam.optptr);
434 }
435
436 static int
437 getopts(char *optstr, char *optvar, char **optfirst, char ***optnext,
438     char **optp)
439 {
440         char *p, *q;
441         char c = '?';
442         int done = 0;
443         int ind = 0;
444         int err = 0;
445         char s[10];
446
447         if ((p = *optp) == NULL || *p == '\0') {
448                 /* Current word is done, advance */
449                 if (*optnext == NULL)
450                         return 1;
451                 p = **optnext;
452                 if (p == NULL || *p != '-' || *++p == '\0') {
453 atend:
454                         ind = *optnext - optfirst + 1;
455                         *optnext = NULL;
456                         p = NULL;
457                         done = 1;
458                         goto out;
459                 }
460                 (*optnext)++;
461                 if (p[0] == '-' && p[1] == '\0')        /* check for "--" */
462                         goto atend;
463         }
464
465         c = *p++;
466         for (q = optstr; *q != c; ) {
467                 if (*q == '\0') {
468                         if (optstr[0] == ':') {
469                                 s[0] = c;
470                                 s[1] = '\0';
471                                 err |= setvarsafe("OPTARG", s, 0);
472                         }
473                         else {
474                                 out1fmt("Illegal option -%c\n", c);
475                                 unsetvar("OPTARG");
476                         }
477                         c = '?';
478                         goto bad;
479                 }
480                 if (*++q == ':')
481                         q++;
482         }
483
484         if (*++q == ':') {
485                 if (*p == '\0' && (p = **optnext) == NULL) {
486                         if (optstr[0] == ':') {
487                                 s[0] = c;
488                                 s[1] = '\0';
489                                 err |= setvarsafe("OPTARG", s, 0);
490                                 c = ':';
491                         }
492                         else {
493                                 out1fmt("No arg for -%c option\n", c);
494                                 unsetvar("OPTARG");
495                                 c = '?';
496                         }
497                         goto bad;
498                 }
499
500                 if (p == **optnext)
501                         (*optnext)++;
502                 setvarsafe("OPTARG", p, 0);
503                 p = NULL;
504         }
505         else
506                 setvarsafe("OPTARG", "", 0);
507         ind = *optnext - optfirst + 1;
508         goto out;
509
510 bad:
511         ind = 1;
512         *optnext = NULL;
513         p = NULL;
514 out:
515         *optp = p;
516         fmtstr(s, sizeof(s), "%d", ind);
517         err |= setvarsafe("OPTIND", s, VNOFUNC);
518         s[0] = c;
519         s[1] = '\0';
520         err |= setvarsafe(optvar, s, 0);
521         if (err) {
522                 *optnext = NULL;
523                 *optp = NULL;
524                 flushall();
525                 exraise(EXERROR);
526         }
527         return done;
528 }
529
530 /*
531  * Standard option processing (a la getopt) for builtin routines.  The
532  * only argument that is passed to nextopt is the option string; the
533  * other arguments are unnecessary.  It return the character, or '\0' on
534  * end of input.
535  */
536
537 int
538 nextopt(const char *optstring)
539 {
540         char *p;
541         const char *q;
542         char c;
543
544         if ((p = nextopt_optptr) == NULL || *p == '\0') {
545                 p = *argptr;
546                 if (p == NULL || *p != '-' || *++p == '\0')
547                         return '\0';
548                 argptr++;
549                 if (p[0] == '-' && p[1] == '\0')        /* check for "--" */
550                         return '\0';
551         }
552         c = *p++;
553         for (q = optstring ; *q != c ; ) {
554                 if (*q == '\0')
555                         error("Illegal option -%c", c);
556                 if (*++q == ':')
557                         q++;
558         }
559         if (*++q == ':') {
560                 if (*p == '\0' && (p = *argptr++) == NULL)
561                         error("No arg for -%c option", c);
562                 shoptarg = p;
563                 p = NULL;
564         }
565         nextopt_optptr = p;
566         return c;
567 }