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