xref: /freebsd/bin/sh/main.c (revision e0c4386e7e71d93b0edc0c8fa156263fc4a8b0b6)
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 #include <stdio.h>
36 #include <signal.h>
37 #include <sys/stat.h>
38 #include <unistd.h>
39 #include <fcntl.h>
40 #include <locale.h>
41 #include <errno.h>
42 
43 #include "shell.h"
44 #include "main.h"
45 #include "mail.h"
46 #include "options.h"
47 #include "output.h"
48 #include "parser.h"
49 #include "nodes.h"
50 #include "expand.h"
51 #include "eval.h"
52 #include "jobs.h"
53 #include "input.h"
54 #include "trap.h"
55 #include "var.h"
56 #include "show.h"
57 #include "memalloc.h"
58 #include "error.h"
59 #include "mystring.h"
60 #include "exec.h"
61 #include "cd.h"
62 #include "redir.h"
63 #include "builtins.h"
64 #ifndef NO_HISTORY
65 #include "myhistedit.h"
66 #endif
67 
68 int rootpid;
69 int rootshell;
70 struct jmploc main_handler;
71 int localeisutf8, initial_localeisutf8;
72 
73 static void reset(void);
74 static void cmdloop(int);
75 static void read_profile(const char *);
76 static char *find_dot_file(char *);
77 
78 /*
79  * Main routine.  We initialize things, parse the arguments, execute
80  * profiles if we're a login shell, and then call cmdloop to execute
81  * commands.  The setjmp call sets up the location to jump to when an
82  * exception occurs.  When an exception occurs the variable "state"
83  * is used to figure out how far we had gotten.
84  */
85 
86 int
87 main(int argc, char *argv[])
88 {
89 	/*
90 	 * As smark is accessed after a longjmp, it cannot be a local in main().
91 	 * The C standard specifies that the values of non-volatile local
92 	 * variables are unspecified after a jump if modified between the
93 	 * setjmp and longjmp.
94 	 */
95 	static struct stackmark smark, smark2;
96 	volatile int state;
97 	char *shinit;
98 
99 	(void) setlocale(LC_ALL, "");
100 	initcharset();
101 	state = 0;
102 	if (setjmp(main_handler.loc)) {
103 		if (state == 0 || iflag == 0 || ! rootshell ||
104 		    exception == EXEXIT)
105 			exitshell(exitstatus);
106 		reset();
107 		if (exception == EXINT)
108 			out2fmt_flush("\n");
109 		popstackmark(&smark);
110 		FORCEINTON;				/* enable interrupts */
111 		if (state == 1)
112 			goto state1;
113 		else if (state == 2)
114 			goto state2;
115 		else if (state == 3)
116 			goto state3;
117 		else
118 			goto state4;
119 	}
120 	handler = &main_handler;
121 #ifdef DEBUG
122 	opentrace();
123 	trputs("Shell args:  ");  trargs(argv);
124 #endif
125 	rootpid = getpid();
126 	rootshell = 1;
127 	INTOFF;
128 	initvar();
129 	setstackmark(&smark);
130 	setstackmark(&smark2);
131 	procargs(argc, argv);
132 	trap_init();
133 	pwd_init(iflag);
134 	INTON;
135 	if (iflag)
136 		chkmail(1);
137 	if (argv[0] && argv[0][0] == '-') {
138 		state = 1;
139 		read_profile("/etc/profile");
140 state1:
141 		state = 2;
142 		if (privileged == 0)
143 			read_profile("${HOME-}/.profile");
144 		else
145 			read_profile("/etc/suid_profile");
146 	}
147 state2:
148 	state = 3;
149 	if (!privileged && iflag) {
150 		if ((shinit = lookupvar("ENV")) != NULL && *shinit != '\0') {
151 			state = 3;
152 			read_profile(shinit);
153 		}
154 	}
155 #ifndef NO_HISTORY
156 	if (iflag)
157 		histload();
158 #endif
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 	int oflags = O_RDONLY | O_CLOEXEC;
249 
250 	if (verifyflag)
251 		oflags |= O_VERIFY;
252 
253 	expandedname = expandstr(name);
254 	if (expandedname == NULL)
255 		return;
256 	INTOFF;
257 	if ((fd = open(expandedname, oflags)) >= 0)
258 		setinputfd(fd, 1);
259 	INTON;
260 	if (fd < 0)
261 		return;
262 	cmdloop(0);
263 	popfile();
264 }
265 
266 
267 
268 /*
269  * Read a file containing shell functions.
270  */
271 
272 void
273 readcmdfile(const char *name, int verify)
274 {
275 	setinputfile(name, 1, verify);
276 	cmdloop(0);
277 	popfile();
278 }
279 
280 
281 
282 /*
283  * Take commands from a file.  To be compatible we should do a path
284  * search for the file, which is necessary to find sub-commands.
285  */
286 
287 
288 static char *
289 find_dot_file(char *basename)
290 {
291 	char *fullname;
292 	const char *opt;
293 	const char *path = pathval();
294 	struct stat statb;
295 
296 	/* don't try this for absolute or relative paths */
297 	if( strchr(basename, '/'))
298 		return basename;
299 
300 	while ((fullname = padvance(&path, &opt, basename)) != NULL) {
301 		if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
302 			/*
303 			 * Don't bother freeing here, since it will
304 			 * be freed by the caller.
305 			 */
306 			return fullname;
307 		}
308 		stunalloc(fullname);
309 	}
310 	return basename;
311 }
312 
313 int
314 dotcmd(int argc, char **argv)
315 {
316 	char *filename, *fullname;
317 
318 	if (argc < 2)
319 		error("missing filename");
320 
321 	exitstatus = 0;
322 
323 	/*
324 	 * Because we have historically not supported any options,
325 	 * only treat "--" specially.
326 	 */
327 	filename = argc > 2 && strcmp(argv[1], "--") == 0 ? argv[2] : argv[1];
328 
329 	fullname = find_dot_file(filename);
330 	setinputfile(fullname, 1, -1 /* verify */);
331 	commandname = fullname;
332 	cmdloop(0);
333 	popfile();
334 	return exitstatus;
335 }
336 
337 
338 int
339 exitcmd(int argc, char **argv)
340 {
341 	if (stoppedjobs())
342 		return 0;
343 	if (argc > 1)
344 		exitshell(number(argv[1]));
345 	else
346 		exitshell_savedstatus();
347 }
348