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