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