xref: /netbsd-src/bin/sh/main.c (revision 53b02e147d4ed531c0d2a5ca9b3e8026ba3e99b5)
1 /*	$NetBSD: main.c,v 1.88 2021/10/26 10:07:20 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.88 2021/10/26 10:07:20 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
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 
216 #if 0	/* This now happens (indirectly) in the procargs() just above */
217 	/*
218 	 * Limit bogus system(3) or popen(3) calls in setuid binaries,
219 	 * by requiring the -p flag
220 	 */
221 	if (!pflag && (uid != geteuid() || gid != getegid())) {
222 		setuid(uid);
223 		setgid(gid);
224 		/* PS1 might need to be changed accordingly. */
225 		choose_ps1();
226 	}
227 #else	/* except for this one little bit */
228 	if (waspriv && !privileged)
229 		choose_ps1();
230 #endif
231 
232 	if (argv[0] && argv[0][0] == '-') {
233 		state = 1;
234 		read_profile("/etc/profile");
235  state1:
236 		state = 2;
237 		if (!privileged) {
238 			char *profile;
239 			const char *home;
240 
241 			home = lookupvar("HOME");
242 			if (home == NULL)
243 				home = nullstr;
244 			profile = ststrcat(NULL, home, "/.profile", STSTRC_END);
245 			read_profile(profile);
246 			stunalloc(profile);
247 		}
248 #if 0	/* FreeBSD does (effectively) ...*/
249 		else
250 			read_profile("/etc/suid_profile");
251 #endif
252 	}
253  state2:
254 	state = 3;
255 	if ((iflag || !posix) && !privileged) {
256 		struct stackmark env_smark;
257 
258 		setstackmark(&env_smark);
259 		if ((shinit = lookupvar("ENV")) != NULL && *shinit != '\0') {
260 			state = 3;
261 			read_profile(expandenv(shinit));
262 		}
263 		popstackmark(&env_smark);
264 	}
265  state3:
266 	state = 4;
267 	line_number = 1;	/* undo anything from profile files */
268 
269 	if (sflag == 0 || minusc) {
270 		static int sigs[] =  {
271 		    SIGINT, SIGQUIT, SIGHUP,
272 #ifdef SIGTSTP
273 		    SIGTSTP,
274 #endif
275 		    SIGPIPE
276 		};
277 #define SIGSSIZE (sizeof(sigs)/sizeof(sigs[0]))
278 		size_t i;
279 
280 		for (i = 0; i < SIGSSIZE; i++)
281 		    setsignal(sigs[i], 0);
282 	}
283 
284 	rststackmark(&smark);	/* this one is never popped */
285 
286 	if (minusc)
287 		evalstring(minusc, sflag ? 0 : EV_EXIT);
288 
289 	if (sflag || minusc == NULL) {
290  state4:	/* XXX ??? - why isn't this before the "if" statement */
291 		cmdloop(1);
292 		if (iflag) {
293 			out2str("\n");
294 			flushout(&errout);
295 		}
296 	}
297 #if PROFILE
298 	monitor(0);
299 #endif
300 	line_number = plinno;
301 	exitshell(exitstatus);
302 	/* NOTREACHED */
303 }
304 
305 
306 /*
307  * Read and execute commands.  "Top" is nonzero for the top level command
308  * loop; it turns on prompting if the shell is interactive.
309  */
310 
311 void
312 cmdloop(int top)
313 {
314 	union node *n;
315 	struct stackmark smark;
316 	int inter;
317 	int numeof = 0;
318 	enum skipstate skip;
319 
320 	CTRACE(DBG_ALWAYS, ("cmdloop(%d) called\n", top));
321 	setstackmark(&smark);
322 	for (;;) {
323 		if (pendingsigs)
324 			dotrap();
325 		inter = 0;
326 		if (iflag == 1 && top) {
327 			inter = 1;
328 			showjobs(out2, SHOW_CHANGED);
329 			chkmail(0);
330 			flushout(&errout);
331 			nflag = 0;
332 		}
333 		n = parsecmd(inter);
334 		VXTRACE(DBG_PARSE|DBG_EVAL|DBG_CMDS,("cmdloop: "),showtree(n));
335 		if (n == NEOF) {
336 			if (!top || numeof >= 50)
337 				break;
338 			if (nflag)
339 				break;
340 			if (!stoppedjobs()) {
341 				if (!iflag || !Iflag)
342 					break;
343 				out2str("\nUse \"exit\" to leave shell.\n");
344 			}
345 			numeof++;
346 		} else if (n != NULL && nflag == 0) {
347 			job_warning = (job_warning == 2) ? 1 : 0;
348 			numeof = 0;
349 			evaltree(n, 0);
350 		}
351 		rststackmark(&smark);
352 
353 		/*
354 		 * Any SKIP* can occur here!  SKIP(FUNC|BREAK|CONT) occur when
355 		 * a dotcmd is in a loop or a function body and appropriate
356 		 * built-ins occurs in file scope in the sourced file.  Values
357 		 * other than SKIPFILE are reset by the appropriate eval*()
358 		 * that contained the dotcmd() call.
359 		 */
360 		skip = current_skipstate();
361 		if (skip != SKIPNONE) {
362 			if (skip == SKIPFILE)
363 				stop_skipping();
364 			break;
365 		}
366 	}
367 	popstackmark(&smark);
368 }
369 
370 
371 
372 /*
373  * Read /etc/profile or .profile.  Return on error.
374  */
375 
376 STATIC void
377 read_profile(const char *name)
378 {
379 	int fd;
380 	int xflag_set = 0;
381 	int vflag_set = 0;
382 
383 	if (*name == '\0')
384 		return;
385 
386 	INTOFF;
387 	if ((fd = open(name, O_RDONLY)) >= 0)
388 		setinputfd(fd, 1);
389 	INTON;
390 	if (fd < 0)
391 		return;
392 	/* -q turns off -x and -v just when executing init files */
393 	if (qflag)  {
394 	    if (xflag)
395 		    xflag = 0, xflag_set = 1;
396 	    if (vflag)
397 		    vflag = 0, vflag_set = 1;
398 	}
399 	(void)set_dot_funcnest(1);	/* allow profile to "return" */
400 	cmdloop(0);
401 	(void)set_dot_funcnest(0);
402 	if (qflag)  {
403 	    if (xflag_set)
404 		    xflag = 1;
405 	    if (vflag_set)
406 		    vflag = 1;
407 	}
408 	popfile();
409 }
410 
411 
412 
413 /*
414  * Read a file containing shell functions.
415  */
416 
417 void
418 readcmdfile(char *name)
419 {
420 	int fd;
421 
422 	INTOFF;
423 	if ((fd = open(name, O_RDONLY)) >= 0)
424 		setinputfd(fd, 1);
425 	else
426 		error("Can't open %s", name);
427 	INTON;
428 	cmdloop(0);
429 	popfile();
430 }
431 
432 
433 
434 int
435 exitcmd(int argc, char **argv)
436 {
437 	if (stoppedjobs())
438 		return 0;
439 	if (argc > 1)
440 		exitshell(number(argv[1]));
441 	else
442 		exitshell_savedstatus();
443 	/* NOTREACHED */
444 }
445