free,stat: make NOEXEC
[oweals/busybox.git] / libbb / vfork_daemon_rexec.c
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
18 #include "busybox.h" /* uses applet tables */
19 #include "NUM_APPLETS.h"
20
21 /* This does a fork/exec in one call, using vfork().  Returns PID of new child,
22  * -1 for failure.  Runs argv[0], searching path if that has no / in it. */
23 pid_t FAST_FUNC spawn(char **argv)
24 {
25         /* Compiler should not optimize stores here */
26         volatile int failed;
27         pid_t pid;
28
29         fflush_all();
30
31         /* Be nice to nommu machines. */
32         failed = 0;
33         pid = vfork();
34         if (pid < 0) /* error */
35                 return pid;
36         if (!pid) { /* child */
37                 /* This macro is ok - it doesn't do NOEXEC/NOFORK tricks */
38                 BB_EXECVP(argv[0], argv);
39
40                 /* We are (maybe) sharing a stack with blocked parent,
41                  * let parent know we failed and then exit to unblock parent
42                  * (but don't run atexit() stuff, which would screw up parent.)
43                  */
44                 failed = errno;
45                 /* mount, for example, does not want the message */
46                 /*bb_perror_msg("can't execute '%s'", argv[0]);*/
47                 _exit(111);
48         }
49         /* parent */
50         /* Unfortunately, this is not reliable: according to standards
51          * vfork() can be equivalent to fork() and we won't see value
52          * of 'failed'.
53          * Interested party can wait on pid and learn exit code.
54          * If 111 - then it (most probably) failed to exec */
55         if (failed) {
56                 safe_waitpid(pid, NULL, 0); /* prevent zombie */
57                 errno = failed;
58                 return -1;
59         }
60         return pid;
61 }
62
63 /* Die with an error message if we can't spawn a child process. */
64 pid_t FAST_FUNC xspawn(char **argv)
65 {
66         pid_t pid = spawn(argv);
67         if (pid < 0)
68                 bb_simple_perror_msg_and_die(*argv);
69         return pid;
70 }
71
72 #if ENABLE_FEATURE_PREFER_APPLETS \
73  || ENABLE_FEATURE_SH_NOFORK
74 static jmp_buf die_jmp;
75 static void jump(void)
76 {
77         /* Special case. We arrive here if NOFORK applet
78          * calls xfunc, which then decides to die.
79          * We don't die, but jump instead back to caller.
80          * NOFORK applets still cannot carelessly call xfuncs:
81          * p = xmalloc(10);
82          * q = xmalloc(10); // BUG! if this dies, we leak p!
83          */
84         /* | 0x100 allows to pass zero exitcode (longjmp can't pass 0).
85          * This works because exitcodes are bytes,
86          * run_nofork_applet() ensures that by "& 0xff" */
87         longjmp(die_jmp, xfunc_error_retval | 0x100);
88 }
89
90 struct nofork_save_area {
91         jmp_buf die_jmp;
92         void (*die_func)(void);
93         const char *applet_name;
94         uint32_t option_mask32;
95         smallint logmode;
96         uint8_t xfunc_error_retval;
97 };
98 static void save_nofork_data(struct nofork_save_area *save)
99 {
100         memcpy(&save->die_jmp, &die_jmp, sizeof(die_jmp));
101         save->die_func = die_func;
102         save->applet_name = applet_name;
103         save->option_mask32 = option_mask32;
104         save->logmode = logmode;
105         save->xfunc_error_retval = xfunc_error_retval;
106 }
107 static void restore_nofork_data(struct nofork_save_area *save)
108 {
109         memcpy(&die_jmp, &save->die_jmp, sizeof(die_jmp));
110         die_func = save->die_func;
111         applet_name = save->applet_name;
112         option_mask32 = save->option_mask32;
113         logmode = save->logmode;
114         xfunc_error_retval = save->xfunc_error_retval;
115 }
116
117 int FAST_FUNC run_nofork_applet(int applet_no, char **argv)
118 {
119         int rc, argc;
120         struct nofork_save_area old;
121
122         save_nofork_data(&old);
123
124         logmode = LOGMODE_STDIO;
125         xfunc_error_retval = EXIT_FAILURE;
126         /* In case getopt() or getopt32() was already called:
127          * reset the libc getopt() function, which keeps internal state.
128          */
129         GETOPT_RESET();
130
131         argc = 1;
132         while (argv[argc])
133                 argc++;
134
135         /* If xfunc "dies" in NOFORK applet, die_func longjmp's here instead */
136         die_func = jump;
137         rc = setjmp(die_jmp);
138         if (!rc) {
139                 /* Some callers (xargs)
140                  * need argv untouched because they free argv[i]! */
141                 char *tmp_argv[argc+1];
142                 memcpy(tmp_argv, argv, (argc+1) * sizeof(tmp_argv[0]));
143                 applet_name = tmp_argv[0];
144                 /* Finally we can call NOFORK applet's main() */
145                 rc = applet_main[applet_no](argc, tmp_argv);
146                 /* Important for shells: `which CMD` was failing */
147                 fflush_all();
148         } else {
149                 /* xfunc died in NOFORK applet */
150         }
151
152         /* Restoring some globals */
153         restore_nofork_data(&old);
154         /* Other globals can be simply reset to defaults */
155         GETOPT_RESET();
156
157         return rc & 0xff; /* don't confuse people with "exitcodes" >255 */
158 }
159 #endif /* FEATURE_PREFER_APPLETS || FEATURE_SH_NOFORK */
160
161 int FAST_FUNC spawn_and_wait(char **argv)
162 {
163         int rc;
164 #if ENABLE_FEATURE_PREFER_APPLETS && (NUM_APPLETS > 1)
165         int a = find_applet_by_name(argv[0]);
166
167         if (a >= 0) {
168                 if (APPLET_IS_NOFORK(a))
169                         return run_nofork_applet(a, argv);
170 # if BB_MMU /* NOEXEC needs fork(), thus this is done only on MMU machines: */
171                 if (APPLET_IS_NOEXEC(a)) {
172                         fflush_all();
173                         rc = fork();
174                         if (rc) /* parent or error */
175                                 return wait4pid(rc);
176
177                         /* child */
178 //TODO: prctl(PR_SET_NAME, (long)argv[0], 0, 0, 0);? [think pidof, pgrep, pkill]
179 //Rewrite /proc/PID/cmdline? (need to save argv0 and length at init for this to work!)
180                         /* reset some state and run without execing */
181
182                         /* msg_eol = "\n"; - no caller needs this reinited yet */
183                         logmode = LOGMODE_STDIO;
184                         /* die_func = NULL; - needed if the caller is a shell,
185                          * init, or a NOFORK applet. But none of those call us
186                          * as of yet (and that should probably always stay true).
187                          */
188                         /* xfunc_error_retval and applet_name are init by: */
189                         run_applet_no_and_exit(a, argv[0], argv);
190                 }
191 # endif
192         }
193 #endif /* FEATURE_PREFER_APPLETS */
194         rc = spawn(argv);
195         return wait4pid(rc);
196 }
197
198 #if !BB_MMU
199 void FAST_FUNC re_exec(char **argv)
200 {
201         /* high-order bit of first char in argv[0] is a hidden
202          * "we have (already) re-execed, don't do it again" flag */
203         argv[0][0] |= 0x80;
204         execv(bb_busybox_exec_path, argv);
205         bb_perror_msg_and_die("can't execute '%s'", bb_busybox_exec_path);
206 }
207
208 pid_t FAST_FUNC fork_or_rexec(char **argv)
209 {
210         pid_t pid;
211         /* Maybe we are already re-execed and come here again? */
212         if (re_execed)
213                 return 0;
214
215         /* fflush_all(); ? - so far all callers had no buffered output to flush */
216
217         pid = xvfork();
218         if (pid) /* parent */
219                 return pid;
220         /* child - re-exec ourself */
221         re_exec(argv);
222 }
223 #endif
224
225 /* Due to a #define in libbb.h on MMU systems we actually have 1 argument -
226  * char **argv "vanishes" */
227 void FAST_FUNC bb_daemonize_or_rexec(int flags, char **argv)
228 {
229         int fd;
230
231         if (flags & DAEMON_CHDIR_ROOT)
232                 xchdir("/");
233
234         if (flags & DAEMON_DEVNULL_STDIO) {
235                 close(0);
236                 close(1);
237                 close(2);
238         }
239
240         fd = open(bb_dev_null, O_RDWR);
241         if (fd < 0) {
242                 /* NB: we can be called as bb_sanitize_stdio() from init
243                  * or mdev, and there /dev/null may legitimately not (yet) exist!
244                  * Do not use xopen above, but obtain _ANY_ open descriptor,
245                  * even bogus one as below. */
246                 fd = xopen("/", O_RDONLY); /* don't believe this can fail */
247         }
248
249         while ((unsigned)fd < 2)
250                 fd = dup(fd); /* have 0,1,2 open at least to /dev/null */
251
252         if (!(flags & DAEMON_ONLY_SANITIZE)) {
253
254                 /* fflush_all(); - add it in fork_or_rexec() if necessary */
255
256                 if (fork_or_rexec(argv))
257                         _exit(EXIT_SUCCESS); /* parent */
258                 /* if daemonizing, detach from stdio & ctty */
259                 setsid();
260                 dup2(fd, 0);
261                 dup2(fd, 1);
262                 dup2(fd, 2);
263                 if (flags & DAEMON_DOUBLE_FORK) {
264                         /* On Linux, session leader can acquire ctty
265                          * unknowingly, by opening a tty.
266                          * Prevent this: stop being a session leader.
267                          */
268                         if (fork_or_rexec(argv))
269                                 _exit(EXIT_SUCCESS); /* parent */
270                 }
271         }
272         while (fd > 2) {
273                 close(fd--);
274                 if (!(flags & DAEMON_CLOSE_EXTRA_FDS))
275                         return;
276                 /* else close everything after fd#2 */
277         }
278 }
279
280 void FAST_FUNC bb_sanitize_stdio(void)
281 {
282         bb_daemonize_or_rexec(DAEMON_ONLY_SANITIZE, NULL);
283 }