xref: /freebsd/bin/sh/main.c (revision 9119bafbaf52e5d86e5879e54b38c5aba3efa2e9)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
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 #ifndef lint
36 static char const copyright[] =
37 "@(#) Copyright (c) 1991, 1993\n\
38 	The Regents of the University of California.  All rights reserved.\n";
39 #endif /* not lint */
40 
41 #ifndef lint
42 #if 0
43 static char sccsid[] = "@(#)main.c	8.6 (Berkeley) 5/28/95";
44 #endif
45 #endif /* not lint */
46 #include <sys/cdefs.h>
47 __FBSDID("$FreeBSD$");
48 
49 #include <stdio.h>
50 #include <signal.h>
51 #include <sys/stat.h>
52 #include <unistd.h>
53 #include <fcntl.h>
54 #include <locale.h>
55 #include <errno.h>
56 
57 #include "shell.h"
58 #include "main.h"
59 #include "mail.h"
60 #include "options.h"
61 #include "output.h"
62 #include "parser.h"
63 #include "nodes.h"
64 #include "expand.h"
65 #include "eval.h"
66 #include "jobs.h"
67 #include "input.h"
68 #include "trap.h"
69 #include "var.h"
70 #include "show.h"
71 #include "memalloc.h"
72 #include "error.h"
73 #include "mystring.h"
74 #include "exec.h"
75 #include "cd.h"
76 #include "redir.h"
77 #include "builtins.h"
78 
79 int rootpid;
80 int rootshell;
81 struct jmploc main_handler;
82 int localeisutf8, initial_localeisutf8;
83 
84 static void reset(void);
85 static void cmdloop(int);
86 static void read_profile(const char *);
87 static char *find_dot_file(char *);
88 
89 /*
90  * Main routine.  We initialize things, parse the arguments, execute
91  * profiles if we're a login shell, and then call cmdloop to execute
92  * commands.  The setjmp call sets up the location to jump to when an
93  * exception occurs.  When an exception occurs the variable "state"
94  * is used to figure out how far we had gotten.
95  */
96 
97 int
98 main(int argc, char *argv[])
99 {
100 	struct stackmark smark, smark2;
101 	volatile int state;
102 	char *shinit;
103 
104 	(void) setlocale(LC_ALL, "");
105 	initcharset();
106 	state = 0;
107 	if (setjmp(main_handler.loc)) {
108 		if (state == 0 || iflag == 0 || ! rootshell ||
109 		    exception == EXEXIT)
110 			exitshell(exitstatus);
111 		reset();
112 		if (exception == EXINT)
113 			out2fmt_flush("\n");
114 		popstackmark(&smark);
115 		FORCEINTON;				/* enable interrupts */
116 		if (state == 1)
117 			goto state1;
118 		else if (state == 2)
119 			goto state2;
120 		else if (state == 3)
121 			goto state3;
122 		else
123 			goto state4;
124 	}
125 	handler = &main_handler;
126 #ifdef DEBUG
127 	opentrace();
128 	trputs("Shell args:  ");  trargs(argv);
129 #endif
130 	rootpid = getpid();
131 	rootshell = 1;
132 	INTOFF;
133 	initvar();
134 	setstackmark(&smark);
135 	setstackmark(&smark2);
136 	procargs(argc, argv);
137 	pwd_init(iflag);
138 	INTON;
139 	if (iflag)
140 		chkmail(1);
141 	if (argv[0] && argv[0][0] == '-') {
142 		state = 1;
143 		read_profile("/etc/profile");
144 state1:
145 		state = 2;
146 		if (privileged == 0)
147 			read_profile("${HOME-}/.profile");
148 		else
149 			read_profile("/etc/suid_profile");
150 	}
151 state2:
152 	state = 3;
153 	if (!privileged && iflag) {
154 		if ((shinit = lookupvar("ENV")) != NULL && *shinit != '\0') {
155 			state = 3;
156 			read_profile(shinit);
157 		}
158 	}
159 state3:
160 	state = 4;
161 	popstackmark(&smark2);
162 	if (minusc) {
163 		evalstring(minusc, sflag ? 0 : EV_EXIT);
164 	}
165 state4:
166 	if (sflag || minusc == NULL) {
167 		cmdloop(1);
168 	}
169 	exitshell(exitstatus);
170 	/*NOTREACHED*/
171 	return 0;
172 }
173 
174 static void
175 reset(void)
176 {
177 	reseteval();
178 	resetinput();
179 }
180 
181 /*
182  * Read and execute commands.  "Top" is nonzero for the top level command
183  * loop; it turns on prompting if the shell is interactive.
184  */
185 
186 static void
187 cmdloop(int top)
188 {
189 	union node *n;
190 	struct stackmark smark;
191 	int inter;
192 	int numeof = 0;
193 
194 	TRACE(("cmdloop(%d) called\n", top));
195 	setstackmark(&smark);
196 	for (;;) {
197 		if (pendingsig)
198 			dotrap();
199 		inter = 0;
200 		if (iflag && top) {
201 			inter++;
202 			showjobs(1, SHOWJOBS_DEFAULT);
203 			chkmail(0);
204 			flushout(&output);
205 		}
206 		n = parsecmd(inter);
207 		/* showtree(n); DEBUG */
208 		if (n == NEOF) {
209 			if (!top || numeof >= 50)
210 				break;
211 			if (!stoppedjobs()) {
212 				if (!Iflag)
213 					break;
214 				out2fmt_flush("\nUse \"exit\" to leave shell.\n");
215 			}
216 			numeof++;
217 		} else if (n != NULL && nflag == 0) {
218 			job_warning = (job_warning == 2) ? 1 : 0;
219 			numeof = 0;
220 			evaltree(n, 0);
221 		}
222 		popstackmark(&smark);
223 		setstackmark(&smark);
224 		if (evalskip != 0) {
225 			if (evalskip == SKIPRETURN)
226 				evalskip = 0;
227 			break;
228 		}
229 	}
230 	popstackmark(&smark);
231 	if (top && iflag) {
232 		out2c('\n');
233 		flushout(out2);
234 	}
235 }
236 
237 
238 
239 /*
240  * Read /etc/profile or .profile.  Return on error.
241  */
242 
243 static void
244 read_profile(const char *name)
245 {
246 	int fd;
247 	const char *expandedname;
248 
249 	expandedname = expandstr(name);
250 	if (expandedname == NULL)
251 		return;
252 	INTOFF;
253 	if ((fd = open(expandedname, O_RDONLY | O_CLOEXEC)) >= 0)
254 		setinputfd(fd, 1);
255 	INTON;
256 	if (fd < 0)
257 		return;
258 	cmdloop(0);
259 	popfile();
260 }
261 
262 
263 
264 /*
265  * Read a file containing shell functions.
266  */
267 
268 void
269 readcmdfile(const char *name)
270 {
271 	setinputfile(name, 1);
272 	cmdloop(0);
273 	popfile();
274 }
275 
276 
277 
278 /*
279  * Take commands from a file.  To be compatible we should do a path
280  * search for the file, which is necessary to find sub-commands.
281  */
282 
283 
284 static char *
285 find_dot_file(char *basename)
286 {
287 	char *fullname;
288 	const char *opt;
289 	const char *path = pathval();
290 	struct stat statb;
291 
292 	/* don't try this for absolute or relative paths */
293 	if( strchr(basename, '/'))
294 		return basename;
295 
296 	while ((fullname = padvance(&path, &opt, basename)) != NULL) {
297 		if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
298 			/*
299 			 * Don't bother freeing here, since it will
300 			 * be freed by the caller.
301 			 */
302 			return fullname;
303 		}
304 		stunalloc(fullname);
305 	}
306 	return basename;
307 }
308 
309 int
310 dotcmd(int argc, char **argv)
311 {
312 	char *filename, *fullname;
313 
314 	if (argc < 2)
315 		error("missing filename");
316 
317 	exitstatus = 0;
318 
319 	/*
320 	 * Because we have historically not supported any options,
321 	 * only treat "--" specially.
322 	 */
323 	filename = argc > 2 && strcmp(argv[1], "--") == 0 ? argv[2] : argv[1];
324 
325 	fullname = find_dot_file(filename);
326 	setinputfile(fullname, 1);
327 	commandname = fullname;
328 	cmdloop(0);
329 	popfile();
330 	return exitstatus;
331 }
332 
333 
334 int
335 exitcmd(int argc, char **argv)
336 {
337 	if (stoppedjobs())
338 		return 0;
339 	if (argc > 1)
340 		exitshell(number(argv[1]));
341 	else
342 		exitshell_savedstatus();
343 }
344