libbb: use _exit, not exit, in bb_daemonize_or_rexec()
[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                         /* reset some state and run without execing */
179
180                         /* msg_eol = "\n"; - no caller needs this reinited yet */
181                         logmode = LOGMODE_STDIO;
182                         /* die_func = NULL; - needed if the caller is a shell,
183                          * init, or a NOFORK applet. But none of those call us
184                          * as of yet (and that should probably always stay true).
185                          */
186                         /* xfunc_error_retval and applet_name are init by: */
187                         run_applet_no_and_exit(a, argv[0], argv);
188                 }
189 # endif
190         }
191 #endif /* FEATURE_PREFER_APPLETS */
192         rc = spawn(argv);
193         return wait4pid(rc);
194 }
195
196 #if !BB_MMU
197 void FAST_FUNC re_exec(char **argv)
198 {
199         /* high-order bit of first char in argv[0] is a hidden
200          * "we have (already) re-execed, don't do it again" flag */
201         argv[0][0] |= 0x80;
202         execv(bb_busybox_exec_path, argv);
203         bb_perror_msg_and_die("can't execute '%s'", bb_busybox_exec_path);
204 }
205
206 pid_t FAST_FUNC fork_or_rexec(char **argv)
207 {
208         pid_t pid;
209         /* Maybe we are already re-execed and come here again? */
210         if (re_execed)
211                 return 0;
212
213         /* fflush_all(); ? - so far all callers had no buffered output to flush */
214
215         pid = xvfork();
216         if (pid) /* parent */
217                 return pid;
218         /* child - re-exec ourself */
219         re_exec(argv);
220 }
221 #endif
222
223 /* Due to a #define in libbb.h on MMU systems we actually have 1 argument -
224  * char **argv "vanishes" */
225 void FAST_FUNC bb_daemonize_or_rexec(int flags, char **argv)
226 {
227         int fd;
228
229         if (flags & DAEMON_CHDIR_ROOT)
230                 xchdir("/");
231
232         if (flags & DAEMON_DEVNULL_STDIO) {
233                 close(0);
234                 close(1);
235                 close(2);
236         }
237
238         fd = open(bb_dev_null, O_RDWR);
239         if (fd < 0) {
240                 /* NB: we can be called as bb_sanitize_stdio() from init
241                  * or mdev, and there /dev/null may legitimately not (yet) exist!
242                  * Do not use xopen above, but obtain _ANY_ open descriptor,
243                  * even bogus one as below. */
244                 fd = xopen("/", O_RDONLY); /* don't believe this can fail */
245         }
246
247         while ((unsigned)fd < 2)
248                 fd = dup(fd); /* have 0,1,2 open at least to /dev/null */
249
250         if (!(flags & DAEMON_ONLY_SANITIZE)) {
251
252                 /* fflush_all(); - add it in fork_or_rexec() if necessary */
253
254                 if (fork_or_rexec(argv))
255                         _exit(EXIT_SUCCESS); /* parent */
256                 /* if daemonizing, detach from stdio & ctty */
257                 setsid();
258                 dup2(fd, 0);
259                 dup2(fd, 1);
260                 dup2(fd, 2);
261                 if (flags & DAEMON_DOUBLE_FORK) {
262                         /* On Linux, session leader can acquire ctty
263                          * unknowingly, by opening a tty.
264                          * Prevent this: stop being a session leader.
265                          */
266                         if (fork_or_rexec(argv))
267                                 _exit(EXIT_SUCCESS); /* parent */
268                 }
269         }
270         while (fd > 2) {
271                 close(fd--);
272                 if (!(flags & DAEMON_CLOSE_EXTRA_FDS))
273                         return;
274                 /* else close everything after fd#2 */
275         }
276 }
277
278 void FAST_FUNC bb_sanitize_stdio(void)
279 {
280         bb_daemonize_or_rexec(DAEMON_ONLY_SANITIZE, NULL);
281 }