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