1 /* vi: set sw=4 ts=4: */
2 /*
3  * Rexec program for system have fork() as vfork() with foreground option
4  *
5  * Copyright (C) Vladimir N. Oleynik <dzo@simtreas.ru>
6  * Copyright (C) 2003 Russ Dill <Russ.Dill@asu.edu>
7  *
8  * daemon() portion taken from uClibc:
9  *
10  * Copyright (c) 1991, 1993
11  *      The Regents of the University of California.  All rights reserved.
12  *
13  * Modified for uClibc by Erik Andersen <andersee@debian.org>
14  *
15  * Licensed under GPLv2 or later, see file LICENSE in this source tree.
16  */
17 #include "busybox.h" /* uses applet tables */
18 #include "NUM_APPLETS.h"
19 
20 #define NOFORK_SUPPORT ((NUM_APPLETS > 1) && (ENABLE_FEATURE_PREFER_APPLETS || ENABLE_FEATURE_SH_NOFORK))
21 #define NOEXEC_SUPPORT ((NUM_APPLETS > 1) && (ENABLE_FEATURE_PREFER_APPLETS || ENABLE_FEATURE_SH_STANDALONE))
22 
23 #if defined(__linux__) && (NUM_APPLETS > 1)
24 # include <sys/prctl.h>
25 # ifndef PR_SET_NAME
26 # define PR_SET_NAME 15
27 # endif
28 # ifndef PR_GET_NAME
29 # define PR_GET_NAME 16
30 # endif
31 # if ENABLE_FEATURE_SH_STANDALONE || ENABLE_FEATURE_PREFER_APPLETS || !BB_MMU
re_execed_comm(void)32 int FAST_FUNC re_execed_comm(void)
33 {
34 	const char *e, *expected_comm;
35 	char comm[16];
36 
37 	BUILD_BUG_ON(CONFIG_BUSYBOX_EXEC_PATH[0] != '/');
38 	e = CONFIG_BUSYBOX_EXEC_PATH;
39 	/* Hopefully (strrchr(e) - e) evaluates to constant at compile time: */
40 	expected_comm = bb_busybox_exec_path + (strrchr(e, '/') - e) + 1;
41 
42 	prctl(PR_GET_NAME, (long)comm, 0, 0, 0);
43 	//bb_error_msg("comm:'%.*s' expected:'%s'", 16, comm, expected_comm);
44 	return strcmp(comm, expected_comm) == 0;
45 }
46 # endif
set_task_comm(const char * comm)47 void FAST_FUNC set_task_comm(const char *comm)
48 {
49 	/* okay if too long (truncates) */
50 	prctl(PR_SET_NAME, (long)comm, 0, 0, 0);
51 }
52 #endif
53 
54 /*
55  * NOFORK/NOEXEC support
56  */
57 #if NOFORK_SUPPORT
58 static jmp_buf die_jmp;
jump(void)59 static void jump(void)
60 {
61 	/* Special case. We arrive here if NOFORK applet
62 	 * calls xfunc, which then decides to die.
63 	 * We don't die, but instead jump back to caller.
64 	 * NOFORK applets still cannot carelessly call xfuncs:
65 	 * p = xmalloc(10);
66 	 * q = xmalloc(10); // BUG! if this dies, we leak p!
67 	 */
68 	/* | 0x100 allows to pass zero exitcode (longjmp can't pass 0).
69 	 * This works because exitcodes are bytes,
70 	 * run_nofork_applet() ensures that by "& 0xff"
71 	 */
72 	longjmp(die_jmp, xfunc_error_retval | 0x100);
73 }
74 
75 struct nofork_save_area {
76 	jmp_buf die_jmp;
77 	void (*die_func)(void);
78 	const char *applet_name;
79 	uint32_t option_mask32;
80 	smallint logmode;
81 	uint8_t xfunc_error_retval;
82 };
save_nofork_data(struct nofork_save_area * save)83 static void save_nofork_data(struct nofork_save_area *save)
84 {
85 	memcpy(&save->die_jmp, &die_jmp, sizeof(die_jmp));
86 	save->die_func = die_func;
87 	save->applet_name = applet_name;
88 	save->option_mask32 = option_mask32;
89 	save->logmode = logmode;
90 	save->xfunc_error_retval = xfunc_error_retval;
91 }
restore_nofork_data(struct nofork_save_area * save)92 static void restore_nofork_data(struct nofork_save_area *save)
93 {
94 	memcpy(&die_jmp, &save->die_jmp, sizeof(die_jmp));
95 	die_func = save->die_func;
96 	applet_name = save->applet_name;
97 	option_mask32 = save->option_mask32;
98 	logmode = save->logmode;
99 	xfunc_error_retval = save->xfunc_error_retval;
100 }
101 
run_nofork_applet(int applet_no,char ** argv)102 int FAST_FUNC run_nofork_applet(int applet_no, char **argv)
103 {
104 	int rc, argc;
105 	struct nofork_save_area old;
106 
107 	save_nofork_data(&old);
108 
109 	logmode = LOGMODE_STDIO;
110 	xfunc_error_retval = EXIT_FAILURE;
111 	/* In case getopt() was already called:
112 	 * reset the libc getopt() function, which keeps internal state.
113 	 * (getopt32() does it itself, but getopt() doesn't (and can't))
114 	 */
115 	GETOPT_RESET();
116 
117 	argc = string_array_len(argv);
118 
119 	/* If xfunc "dies" in NOFORK applet, die_func longjmp's here instead */
120 	die_func = jump;
121 	rc = setjmp(die_jmp);
122 	if (!rc) {
123 		/* Some callers (xargs)
124 		 * need argv untouched because they free argv[i]! */
125 		char *tmp_argv[argc+1];
126 		memcpy(tmp_argv, argv, (argc+1) * sizeof(tmp_argv[0]));
127 		applet_name = tmp_argv[0];
128 
129 		/* longjmp's (instead of returning) if --help is seen */
130 		show_usage_if_dash_dash_help(applet_no, argv);
131 
132 		/* Finally we can call NOFORK applet's main() */
133 		rc = applet_main[applet_no](argc, tmp_argv);
134 
135 		/* Important for shells: `which CMD` was failing */
136 		fflush_all();
137 	} else {
138 		/* xfunc died in NOFORK applet */
139 	}
140 
141 	/* Restoring some globals */
142 	restore_nofork_data(&old);
143 	/* Other globals can be simply reset to defaults */
144 	GETOPT_RESET();
145 
146 	return rc & 0xff; /* don't confuse people with "exitcodes" >255 */
147 }
148 #endif
149 
150 #if NOEXEC_SUPPORT
run_noexec_applet_and_exit(int a,const char * name,char ** argv)151 void FAST_FUNC run_noexec_applet_and_exit(int a, const char *name, char **argv)
152 {
153 	/* reset some state and run without execing */
154 	/* msg_eol = "\n"; - no caller needs this reinited yet */
155 	logmode = LOGMODE_STDIO;
156 	xfunc_error_retval = EXIT_FAILURE;
157 	die_func = NULL;
158 	GETOPT_RESET();
159 
160 //TODO: think pidof, pgrep, pkill!
161 //set_task_comm() makes our pidof find NOEXECs (e.g. "yes >/dev/null"),
162 //but one from procps-ng-3.3.10 needs more!
163 //Rewrite /proc/PID/cmdline? (need to save argv0 and length at init for this to work!)
164 	set_task_comm(name);
165 	/* applet_name is set by this function: */
166 	run_applet_no_and_exit(a, name, argv);
167 }
168 #endif
169 
170 /*
171  * Higher-level code, hiding optional NOFORK/NOEXEC trickery.
172  */
173 
174 /* This does a fork/exec in one call, using vfork().  Returns PID of new child,
175  * -1 for failure.  Runs argv[0], searching path if that has no / in it. */
spawn(char ** argv)176 pid_t FAST_FUNC spawn(char **argv)
177 {
178 	/* Compiler should not optimize stores here */
179 	volatile int failed;
180 	pid_t pid;
181 
182 	fflush_all();
183 
184 	/* Be nice to nommu machines. */
185 	failed = 0;
186 	pid = vfork();
187 	if (pid < 0) /* error */
188 		return pid;
189 	if (!pid) { /* child */
190 		/* This macro is ok - it doesn't do NOEXEC/NOFORK tricks */
191 		BB_EXECVP(argv[0], argv);
192 
193 		/* We are (maybe) sharing a stack with blocked parent,
194 		 * let parent know we failed and then exit to unblock parent
195 		 * (but don't run atexit() stuff, which would screw up parent.)
196 		 */
197 		failed = errno;
198 		/* mount, for example, does not want the message */
199 		/*bb_perror_msg("can't execute '%s'", argv[0]);*/
200 		_exit(111);
201 	}
202 	/* parent */
203 	/* Unfortunately, this is not reliable: according to standards
204 	 * vfork() can be equivalent to fork() and we won't see value
205 	 * of 'failed'.
206 	 * Interested party can wait on pid and learn exit code.
207 	 * If 111 - then it (most probably) failed to exec */
208 	if (failed) {
209 		safe_waitpid(pid, NULL, 0); /* prevent zombie */
210 		errno = failed;
211 		return -1;
212 	}
213 	return pid;
214 }
215 
216 /* Die with an error message if we can't spawn a child process. */
xspawn(char ** argv)217 pid_t FAST_FUNC xspawn(char **argv)
218 {
219 	pid_t pid = spawn(argv);
220 	if (pid < 0)
221 		bb_simple_perror_msg_and_die(*argv);
222 	return pid;
223 }
224 
spawn_and_wait(char ** argv)225 int FAST_FUNC spawn_and_wait(char **argv)
226 {
227 	int rc;
228 #if ENABLE_FEATURE_PREFER_APPLETS && (NUM_APPLETS > 1)
229 	int a = find_applet_by_name(argv[0]);
230 
231 	if (a >= 0) {
232 		if (APPLET_IS_NOFORK(a))
233 			return run_nofork_applet(a, argv);
234 # if BB_MMU /* NOEXEC needs fork(), thus this is done only on MMU machines: */
235 		if (APPLET_IS_NOEXEC(a)) {
236 			fflush_all();
237 			rc = fork();
238 			if (rc) /* parent or error */
239 				return wait4pid(rc);
240 
241 			/* child */
242 			run_noexec_applet_and_exit(a, argv[0], argv);
243 		}
244 # endif
245 	}
246 #endif
247 	rc = spawn(argv);
248 	return wait4pid(rc);
249 }
250 
251 #if !BB_MMU
re_exec(char ** argv)252 void FAST_FUNC re_exec(char **argv)
253 {
254 	/* high-order bit of first char in argv[0] is a hidden
255 	 * "we have (already) re-execed, don't do it again" flag */
256 	argv[0][0] |= 0x80;
257 	execv(bb_busybox_exec_path, argv);
258 	bb_perror_msg_and_die("can't execute '%s'", bb_busybox_exec_path);
259 }
260 
fork_or_rexec(char ** argv)261 pid_t FAST_FUNC fork_or_rexec(char **argv)
262 {
263 	pid_t pid;
264 	/* Maybe we are already re-execed and come here again? */
265 	if (re_execed)
266 		return 0;
267 
268 	/* fflush_all(); ? - so far all callers had no buffered output to flush */
269 
270 	pid = xvfork();
271 	if (pid) /* parent */
272 		return pid;
273 	/* child - re-exec ourself */
274 	re_exec(argv);
275 }
276 #endif
277 
278 /* Due to a #define in libbb.h on MMU systems we actually have 1 argument -
279  * char **argv "vanishes" */
bb_daemonize_or_rexec(int flags,char ** argv)280 void FAST_FUNC bb_daemonize_or_rexec(int flags, char **argv)
281 {
282 	int fd;
283 
284 	if (flags & DAEMON_CHDIR_ROOT)
285 		xchdir("/");
286 
287 	fd = open(bb_dev_null, O_RDWR);
288 	if (fd < 0) {
289 		/* NB: we can be called as bb_sanitize_stdio() from init
290 		 * or mdev, and there /dev/null may legitimately not (yet) exist!
291 		 * Do not use xopen above, but obtain _ANY_ open descriptor,
292 		 * even bogus one as below. */
293 		fd = xopen("/", O_RDONLY); /* don't believe this can fail */
294 	}
295 
296 	if (flags & DAEMON_DEVNULL_STDIO) {
297 		xdup2(fd, 0);
298 		xdup2(fd, 1);
299 		xdup2(fd, 2);
300 	} else {
301 		/* have 0,1,2 open at least to /dev/null */
302 		while ((unsigned)fd < 2)
303 			fd = dup(fd);
304 	}
305 
306 	if (!(flags & DAEMON_ONLY_SANITIZE)) {
307 
308 		/* fflush_all(); - add it in fork_or_rexec() if necessary */
309 
310 		if (fork_or_rexec(argv))
311 			_exit(EXIT_SUCCESS); /* parent */
312 		/* if daemonizing, detach from stdio & ctty */
313 		setsid();
314 		dup2(fd, 0);
315 		dup2(fd, 1);
316 		dup2(fd, 2);
317 //		if (flags & DAEMON_DOUBLE_FORK) {
318 //			/* On Linux, session leader can acquire ctty
319 //			 * unknowingly, by opening a tty.
320 //			 * Prevent this: stop being a session leader.
321 //			 */
322 //			if (fork_or_rexec(argv))
323 //				_exit(EXIT_SUCCESS); /* parent */
324 //		}
325 	}
326 	while (fd > 2) {
327 		close(fd--);
328 		if (!(flags & DAEMON_CLOSE_EXTRA_FDS))
329 			return;
330 		/* else close everything after fd#2 */
331 	}
332 }
333 
bb_sanitize_stdio(void)334 void FAST_FUNC bb_sanitize_stdio(void)
335 {
336 	bb_daemonize_or_rexec(DAEMON_ONLY_SANITIZE, NULL);
337 }
338