xref: /netbsd-src/bin/sh/main.c (revision bdc22b2e01993381dcefeff2bc9b56ca75a4235c)
1 /*	$NetBSD: main.c,v 1.73 2018/01/23 22:12:52 sevan 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.73 2018/01/23 22:12:52 sevan 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 int max_user_fd;
87 #if PROFILE
88 short profile_buf[16384];
89 extern int etext();
90 #endif
91 
92 STATIC void read_profile(const char *);
93 
94 /*
95  * Main routine.  We initialize things, parse the arguments, execute
96  * profiles if we're a login shell, and then call cmdloop to execute
97  * commands.  The setjmp call sets up the location to jump to when an
98  * exception occurs.  When an exception occurs the variable "state"
99  * is used to figure out how far we had gotten.
100  */
101 
102 int
103 main(int argc, char **argv)
104 {
105 	struct jmploc jmploc;
106 	struct stackmark smark;
107 	volatile int state;
108 	char *shinit;
109 	uid_t uid;
110 	gid_t gid;
111 
112 	uid = getuid();
113 	gid = getgid();
114 
115 	max_user_fd = fcntl(0, F_MAXFD);
116 	if (max_user_fd < 2)
117 		max_user_fd = 2;
118 
119 	setlocale(LC_ALL, "");
120 
121 	posix = getenv("POSIXLY_CORRECT") != NULL;
122 #if PROFILE
123 	monitor(4, etext, profile_buf, sizeof profile_buf, 50);
124 #endif
125 	state = 0;
126 	if (setjmp(jmploc.loc)) {
127 		/*
128 		 * When a shell procedure is executed, we raise the
129 		 * exception EXSHELLPROC to clean up before executing
130 		 * the shell procedure.
131 		 */
132 		switch (exception) {
133 		case EXSHELLPROC:
134 			rootpid = getpid();
135 			rootshell = 1;
136 			minusc = NULL;
137 			state = 3;
138 			break;
139 
140 		case EXEXEC:
141 			exitstatus = exerrno;
142 			break;
143 
144 		case EXERROR:
145 			exitstatus = 2;
146 			break;
147 
148 		default:
149 			break;
150 		}
151 
152 		if (exception != EXSHELLPROC) {
153 			if (state == 0 || iflag == 0 || ! rootshell)
154 				exitshell(exitstatus);
155 		}
156 		reset();
157 		if (exception == EXINT) {
158 			out2c('\n');
159 			flushout(&errout);
160 		}
161 		popstackmark(&smark);
162 		FORCEINTON;				/* enable interrupts */
163 		if (state == 1)
164 			goto state1;
165 		else if (state == 2)
166 			goto state2;
167 		else if (state == 3)
168 			goto state3;
169 		else
170 			goto state4;
171 	}
172 	handler = &jmploc;
173 #ifdef DEBUG
174 #if DEBUG >= 2
175 	debug = 1;	/* this may be reset by procargs() later */
176 #endif
177 	opentrace();
178 	trputs("Shell args:  ");  trargs(argv);
179 #if DEBUG >= 3
180 	set_debug(((DEBUG)==3 ? "_@" : "++"), 1);
181 #endif
182 #endif
183 	rootpid = getpid();
184 	rootshell = 1;
185 	init();
186 	initpwd();
187 	setstackmark(&smark);
188 	procargs(argc, argv);
189 
190 	/*
191 	 * Limit bogus system(3) or popen(3) calls in setuid binaries,
192 	 * by requiring the -p flag
193 	 */
194 	if (!pflag && (uid != geteuid() || gid != getegid())) {
195 		setuid(uid);
196 		setgid(gid);
197 		/* PS1 might need to be changed accordingly. */
198 		choose_ps1();
199 	}
200 
201 	if (argv[0] && argv[0][0] == '-') {
202 		state = 1;
203 		read_profile("/etc/profile");
204 state1:
205 		state = 2;
206 		read_profile(".profile");
207 	}
208 state2:
209 	state = 3;
210 	if ((iflag || !posix) &&
211 	    getuid() == geteuid() && getgid() == getegid()) {
212 		if ((shinit = lookupvar("ENV")) != NULL && *shinit != '\0') {
213 			state = 3;
214 			read_profile(shinit);
215 		}
216 	}
217 state3:
218 	state = 4;
219 	line_number = 1;	/* undo anything from profile files */
220 
221 	if (sflag == 0 || minusc) {
222 		static int sigs[] =  {
223 		    SIGINT, SIGQUIT, SIGHUP,
224 #ifdef SIGTSTP
225 		    SIGTSTP,
226 #endif
227 		    SIGPIPE
228 		};
229 #define SIGSSIZE (sizeof(sigs)/sizeof(sigs[0]))
230 		size_t i;
231 
232 		for (i = 0; i < SIGSSIZE; i++)
233 		    setsignal(sigs[i], 0);
234 	}
235 
236 	if (minusc)
237 		evalstring(minusc, 0);
238 
239 	if (sflag || minusc == NULL) {
240 state4:	/* XXX ??? - why isn't this before the "if" statement */
241 		cmdloop(1);
242 	}
243 #if PROFILE
244 	monitor(0);
245 #endif
246 	exitshell(exitstatus);
247 	/* NOTREACHED */
248 }
249 
250 
251 /*
252  * Read and execute commands.  "Top" is nonzero for the top level command
253  * loop; it turns on prompting if the shell is interactive.
254  */
255 
256 void
257 cmdloop(int top)
258 {
259 	union node *n;
260 	struct stackmark smark;
261 	int inter;
262 	int numeof = 0;
263 	enum skipstate skip;
264 
265 	CTRACE(DBG_ALWAYS, ("cmdloop(%d) called\n", top));
266 	setstackmark(&smark);
267 	for (;;) {
268 		if (pendingsigs)
269 			dotrap();
270 		inter = 0;
271 		if (iflag == 1 && top) {
272 			inter = 1;
273 			showjobs(out2, SHOW_CHANGED);
274 			chkmail(0);
275 			flushout(&errout);
276 			nflag = 0;
277 		}
278 		n = parsecmd(inter);
279 		VXTRACE(DBG_PARSE|DBG_EVAL|DBG_CMDS,("cmdloop: "),showtree(n));
280 		if (n == NEOF) {
281 			if (!top || numeof >= 50)
282 				break;
283 			if (nflag)
284 				break;
285 			if (!stoppedjobs()) {
286 				if (!iflag || !Iflag)
287 					break;
288 				out2str("\nUse \"exit\" to leave shell.\n");
289 			}
290 			numeof++;
291 		} else if (n != NULL && nflag == 0) {
292 			job_warning = (job_warning == 2) ? 1 : 0;
293 			numeof = 0;
294 			evaltree(n, EV_MORE);
295 		}
296 		popstackmark(&smark);
297 		setstackmark(&smark);
298 
299 		/*
300 		 * Any SKIP* can occur here!  SKIP(FUNC|BREAK|CONT) occur when
301 		 * a dotcmd is in a loop or a function body and appropriate
302 		 * built-ins occurs in file scope in the sourced file.  Values
303 		 * other than SKIPFILE are reset by the appropriate eval*()
304 		 * that contained the dotcmd() call.
305 		 */
306 		skip = current_skipstate();
307 		if (skip != SKIPNONE) {
308 			if (skip == SKIPFILE)
309 				stop_skipping();
310 			break;
311 		}
312 	}
313 	popstackmark(&smark);
314 }
315 
316 
317 
318 /*
319  * Read /etc/profile or .profile.  Return on error.
320  */
321 
322 STATIC void
323 read_profile(const char *name)
324 {
325 	int fd;
326 	int xflag_set = 0;
327 	int vflag_set = 0;
328 
329 	INTOFF;
330 	if ((fd = open(name, O_RDONLY)) >= 0)
331 		setinputfd(fd, 1);
332 	INTON;
333 	if (fd < 0)
334 		return;
335 	/* -q turns off -x and -v just when executing init files */
336 	if (qflag)  {
337 	    if (xflag)
338 		    xflag = 0, xflag_set = 1;
339 	    if (vflag)
340 		    vflag = 0, vflag_set = 1;
341 	}
342 	cmdloop(0);
343 	if (qflag)  {
344 	    if (xflag_set)
345 		    xflag = 1;
346 	    if (vflag_set)
347 		    vflag = 1;
348 	}
349 	popfile();
350 }
351 
352 
353 
354 /*
355  * Read a file containing shell functions.
356  */
357 
358 void
359 readcmdfile(char *name)
360 {
361 	int fd;
362 
363 	INTOFF;
364 	if ((fd = open(name, O_RDONLY)) >= 0)
365 		setinputfd(fd, 1);
366 	else
367 		error("Can't open %s", name);
368 	INTON;
369 	cmdloop(0);
370 	popfile();
371 }
372 
373 
374 
375 int
376 exitcmd(int argc, char **argv)
377 {
378 	if (stoppedjobs())
379 		return 0;
380 	if (argc > 1)
381 		exitstatus = number(argv[1]);
382 	exitshell(exitstatus);
383 	/* NOTREACHED */
384 }
385