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