Home | History | Annotate | Line # | Download | only in sh
main.c revision 1.83
      1 /*	$NetBSD: main.c,v 1.83 2020/02/06 19:51:59 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 __COPYRIGHT("@(#) Copyright (c) 1991, 1993\
     38  The Regents of the University of California.  All rights reserved.");
     39 #endif /* not lint */
     40 
     41 #ifndef lint
     42 #if 0
     43 static char sccsid[] = "@(#)main.c	8.7 (Berkeley) 7/19/95";
     44 #else
     45 __RCSID("$NetBSD: main.c,v 1.83 2020/02/06 19:51:59 kre Exp $");
     46 #endif
     47 #endif /* not lint */
     48 
     49 #include <errno.h>
     50 #include <stdio.h>
     51 #include <signal.h>
     52 #include <sys/stat.h>
     53 #include <unistd.h>
     54 #include <stdlib.h>
     55 #include <locale.h>
     56 #include <fcntl.h>
     57 
     58 
     59 #include "shell.h"
     60 #include "main.h"
     61 #include "mail.h"
     62 #include "options.h"
     63 #include "builtins.h"
     64 #include "output.h"
     65 #include "parser.h"
     66 #include "nodes.h"
     67 #include "expand.h"
     68 #include "eval.h"
     69 #include "jobs.h"
     70 #include "input.h"
     71 #include "trap.h"
     72 #include "var.h"
     73 #include "show.h"
     74 #include "memalloc.h"
     75 #include "error.h"
     76 #include "init.h"
     77 #include "mystring.h"
     78 #include "exec.h"
     79 #include "cd.h"
     80 #include "redir.h"
     81 
     82 #define PROFILE 0
     83 
     84 int rootpid;
     85 int rootshell;
     86 struct jmploc main_handler;
     87 int max_user_fd;
     88 #if PROFILE
     89 short profile_buf[16384];
     90 extern int etext();
     91 #endif
     92 
     93 STATIC void read_profile(const char *);
     94 
     95 /*
     96  * Main routine.  We initialize things, parse the arguments, execute
     97  * profiles if we're a login shell, and then call cmdloop to execute
     98  * commands.  The setjmp call sets up the location to jump to when an
     99  * exception occurs.  When an exception occurs the variable "state"
    100  * is used to figure out how far we had gotten.
    101  */
    102 
    103 int
    104 main(int argc, char **argv)
    105 {
    106 	struct stackmark smark;
    107 	volatile int state;
    108 	char *shinit;
    109 	uid_t uid;
    110 	gid_t gid;
    111 
    112 	/*
    113 	 * If we happen to be invoked with SIGCHLD ignored, we cannot
    114 	 * successfully do almost anything.   Perhaps we should remember
    115 	 * its state and pass it on ignored to children if it was ignored
    116 	 * on entry, but that seems like just leaving the shit on the
    117 	 * footpath for someone else to fall into...
    118 	 */
    119 	(void)signal(SIGCHLD, SIG_DFL);
    120 
    121 	uid = getuid();
    122 	gid = getgid();
    123 
    124 	max_user_fd = fcntl(0, F_MAXFD);
    125 	if (max_user_fd < 2)
    126 		max_user_fd = 2;
    127 
    128 	setlocale(LC_ALL, "");
    129 
    130 	posix = getenv("POSIXLY_CORRECT") != NULL;
    131 #if PROFILE
    132 	monitor(4, etext, profile_buf, sizeof profile_buf, 50);
    133 #endif
    134 	state = 0;
    135 	if (setjmp(main_handler.loc)) {
    136 		/*
    137 		 * When a shell procedure is executed, we raise the
    138 		 * exception EXSHELLPROC to clean up before executing
    139 		 * the shell procedure.
    140 		 */
    141 		switch (exception) {
    142 		case EXSHELLPROC:
    143 			rootpid = getpid();
    144 			rootshell = 1;
    145 			minusc = NULL;
    146 			state = 3;
    147 			break;
    148 
    149 		case EXEXEC:
    150 			exitstatus = exerrno;
    151 			break;
    152 
    153 		case EXERROR:
    154 			exitstatus = 2;
    155 			break;
    156 
    157 		default:
    158 			break;
    159 		}
    160 
    161 		if (exception != EXSHELLPROC) {
    162 			if (state == 0 || iflag == 0 || ! rootshell ||
    163 			    exception == EXEXIT)
    164 				exitshell(exitstatus);
    165 		}
    166 		reset();
    167 		if (exception == EXINT) {
    168 			out2c('\n');
    169 			flushout(&errout);
    170 		}
    171 		popstackmark(&smark);
    172 		FORCEINTON;				/* enable interrupts */
    173 		if (state == 1)
    174 			goto state1;
    175 		else if (state == 2)
    176 			goto state2;
    177 		else if (state == 3)
    178 			goto state3;
    179 		else
    180 			goto state4;
    181 	}
    182 	handler = &main_handler;
    183 #ifdef DEBUG
    184 #if DEBUG >= 2
    185 	debug = 1;	/* this may be reset by procargs() later */
    186 #endif
    187 	opentrace();
    188 	trputs("Shell args:  ");  trargs(argv);
    189 #if DEBUG >= 3
    190 	set_debug(((DEBUG)==3 ? "_@" : "++"), 1);
    191 #endif
    192 #endif
    193 	rootpid = getpid();
    194 	rootshell = 1;
    195 	init();
    196 	initpwd();
    197 	setstackmark(&smark);
    198 	procargs(argc, argv);
    199 
    200 	/*
    201 	 * Limit bogus system(3) or popen(3) calls in setuid binaries,
    202 	 * by requiring the -p flag
    203 	 */
    204 	if (!pflag && (uid != geteuid() || gid != getegid())) {
    205 		setuid(uid);
    206 		setgid(gid);
    207 		/* PS1 might need to be changed accordingly. */
    208 		choose_ps1();
    209 	}
    210 
    211 	if (argv[0] && argv[0][0] == '-') {
    212 		state = 1;
    213 		read_profile("/etc/profile");
    214  state1:
    215 		state = 2;
    216 		read_profile(".profile");
    217 	}
    218  state2:
    219 	state = 3;
    220 	if ((iflag || !posix) &&
    221 	    getuid() == geteuid() && getgid() == getegid()) {
    222 		struct stackmark env_smark;
    223 
    224 		setstackmark(&env_smark);
    225 		if ((shinit = lookupvar("ENV")) != NULL && *shinit != '\0') {
    226 			state = 3;
    227 			read_profile(expandenv(shinit));
    228 		}
    229 		popstackmark(&env_smark);
    230 	}
    231  state3:
    232 	state = 4;
    233 	line_number = 1;	/* undo anything from profile files */
    234 
    235 	if (sflag == 0 || minusc) {
    236 		static int sigs[] =  {
    237 		    SIGINT, SIGQUIT, SIGHUP,
    238 #ifdef SIGTSTP
    239 		    SIGTSTP,
    240 #endif
    241 		    SIGPIPE
    242 		};
    243 #define SIGSSIZE (sizeof(sigs)/sizeof(sigs[0]))
    244 		size_t i;
    245 
    246 		for (i = 0; i < SIGSSIZE; i++)
    247 		    setsignal(sigs[i], 0);
    248 	}
    249 
    250 	if (minusc)
    251 		evalstring(minusc, sflag ? 0 : EV_EXIT);
    252 
    253 	if (sflag || minusc == NULL) {
    254  state4:	/* XXX ??? - why isn't this before the "if" statement */
    255 		cmdloop(1);
    256 		if (iflag) {
    257 			out2str("\n");
    258 			flushout(&errout);
    259 		}
    260 	}
    261 #if PROFILE
    262 	monitor(0);
    263 #endif
    264 	line_number = plinno;
    265 	exitshell(exitstatus);
    266 	/* NOTREACHED */
    267 }
    268 
    269 
    270 /*
    271  * Read and execute commands.  "Top" is nonzero for the top level command
    272  * loop; it turns on prompting if the shell is interactive.
    273  */
    274 
    275 void
    276 cmdloop(int top)
    277 {
    278 	union node *n;
    279 	struct stackmark smark;
    280 	int inter;
    281 	int numeof = 0;
    282 	enum skipstate skip;
    283 
    284 	CTRACE(DBG_ALWAYS, ("cmdloop(%d) called\n", top));
    285 	setstackmark(&smark);
    286 	for (;;) {
    287 		if (pendingsigs)
    288 			dotrap();
    289 		inter = 0;
    290 		if (iflag == 1 && top) {
    291 			inter = 1;
    292 			showjobs(out2, SHOW_CHANGED);
    293 			chkmail(0);
    294 			flushout(&errout);
    295 			nflag = 0;
    296 		}
    297 		n = parsecmd(inter);
    298 		VXTRACE(DBG_PARSE|DBG_EVAL|DBG_CMDS,("cmdloop: "),showtree(n));
    299 		if (n == NEOF) {
    300 			if (!top || numeof >= 50)
    301 				break;
    302 			if (nflag)
    303 				break;
    304 			if (!stoppedjobs()) {
    305 				if (!iflag || !Iflag)
    306 					break;
    307 				out2str("\nUse \"exit\" to leave shell.\n");
    308 			}
    309 			numeof++;
    310 		} else if (n != NULL && nflag == 0) {
    311 			job_warning = (job_warning == 2) ? 1 : 0;
    312 			numeof = 0;
    313 			evaltree(n, 0);
    314 		}
    315 		rststackmark(&smark);
    316 
    317 		/*
    318 		 * Any SKIP* can occur here!  SKIP(FUNC|BREAK|CONT) occur when
    319 		 * a dotcmd is in a loop or a function body and appropriate
    320 		 * built-ins occurs in file scope in the sourced file.  Values
    321 		 * other than SKIPFILE are reset by the appropriate eval*()
    322 		 * that contained the dotcmd() call.
    323 		 */
    324 		skip = current_skipstate();
    325 		if (skip != SKIPNONE) {
    326 			if (skip == SKIPFILE)
    327 				stop_skipping();
    328 			break;
    329 		}
    330 	}
    331 	popstackmark(&smark);
    332 }
    333 
    334 
    335 
    336 /*
    337  * Read /etc/profile or .profile.  Return on error.
    338  */
    339 
    340 STATIC void
    341 read_profile(const char *name)
    342 {
    343 	int fd;
    344 	int xflag_set = 0;
    345 	int vflag_set = 0;
    346 
    347 	if (*name == '\0')
    348 		return;
    349 
    350 	INTOFF;
    351 	if ((fd = open(name, O_RDONLY)) >= 0)
    352 		setinputfd(fd, 1);
    353 	INTON;
    354 	if (fd < 0)
    355 		return;
    356 	/* -q turns off -x and -v just when executing init files */
    357 	if (qflag)  {
    358 	    if (xflag)
    359 		    xflag = 0, xflag_set = 1;
    360 	    if (vflag)
    361 		    vflag = 0, vflag_set = 1;
    362 	}
    363 	(void)set_dot_funcnest(1);	/* allow profile to "return" */
    364 	cmdloop(0);
    365 	(void)set_dot_funcnest(0);
    366 	if (qflag)  {
    367 	    if (xflag_set)
    368 		    xflag = 1;
    369 	    if (vflag_set)
    370 		    vflag = 1;
    371 	}
    372 	popfile();
    373 }
    374 
    375 
    376 
    377 /*
    378  * Read a file containing shell functions.
    379  */
    380 
    381 void
    382 readcmdfile(char *name)
    383 {
    384 	int fd;
    385 
    386 	INTOFF;
    387 	if ((fd = open(name, O_RDONLY)) >= 0)
    388 		setinputfd(fd, 1);
    389 	else
    390 		error("Can't open %s", name);
    391 	INTON;
    392 	cmdloop(0);
    393 	popfile();
    394 }
    395 
    396 
    397 
    398 int
    399 exitcmd(int argc, char **argv)
    400 {
    401 	if (stoppedjobs())
    402 		return 0;
    403 	if (argc > 1)
    404 		exitshell(number(argv[1]));
    405 	else
    406 		exitshell_savedstatus();
    407 	/* NOTREACHED */
    408 }
    409