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