main: fix the case where user has "halt" as login shell. Closes 9986
[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         uint8_t xfunc_error_retval;
96 };
97 static void save_nofork_data(struct nofork_save_area *save)
98 {
99         memcpy(&save->die_jmp, &die_jmp, sizeof(die_jmp));
100         save->die_func = die_func;
101         save->applet_name = applet_name;
102         save->option_mask32 = option_mask32;
103         save->xfunc_error_retval = xfunc_error_retval;
104 }
105 static void restore_nofork_data(struct nofork_save_area *save)
106 {
107         memcpy(&die_jmp, &save->die_jmp, sizeof(die_jmp));
108         die_func = save->die_func;
109         applet_name = save->applet_name;
110         option_mask32 = save->option_mask32;
111         xfunc_error_retval = save->xfunc_error_retval;
112 }
113
114 int FAST_FUNC run_nofork_applet(int applet_no, char **argv)
115 {
116         int rc, argc;
117         struct nofork_save_area old;
118
119         save_nofork_data(&old);
120
121         xfunc_error_retval = EXIT_FAILURE;
122
123         /* In case getopt() or getopt32() was already called:
124          * reset the libc getopt() function, which keeps internal state.
125          */
126         GETOPT_RESET();
127
128         argc = 1;
129         while (argv[argc])
130                 argc++;
131
132         /* If xfunc "dies" in NOFORK applet, die_func longjmp's here instead */
133         die_func = jump;
134         rc = setjmp(die_jmp);
135         if (!rc) {
136                 /* Some callers (xargs)
137                  * need argv untouched because they free argv[i]! */
138                 char *tmp_argv[argc+1];
139                 memcpy(tmp_argv, argv, (argc+1) * sizeof(tmp_argv[0]));
140                 applet_name = tmp_argv[0];
141                 /* Finally we can call NOFORK applet's main() */
142                 rc = applet_main[applet_no](argc, tmp_argv);
143         } else {
144                 /* xfunc died in NOFORK applet */
145         }
146
147         /* Restoring some globals */
148         restore_nofork_data(&old);
149
150         /* Other globals can be simply reset to defaults */
151         GETOPT_RESET();
152
153         return rc & 0xff; /* don't confuse people with "exitcodes" >255 */
154 }
155 #endif /* FEATURE_PREFER_APPLETS || FEATURE_SH_NOFORK */
156
157 int FAST_FUNC spawn_and_wait(char **argv)
158 {
159         int rc;
160 #if ENABLE_FEATURE_PREFER_APPLETS && (NUM_APPLETS > 1)
161         int a = find_applet_by_name(argv[0]);
162
163         if (a >= 0) {
164                 if (APPLET_IS_NOFORK(a))
165                         return run_nofork_applet(a, argv);
166 # if BB_MMU /* NOEXEC needs fork(), thus this is done only on MMU machines: */
167                 if (APPLET_IS_NOEXEC(a)) {
168                         fflush_all();
169                         rc = fork();
170                         if (rc) /* parent or error */
171                                 return wait4pid(rc);
172
173                         /* child */
174                         /* reset some state and run without execing */
175
176                         /* msg_eol = "\n"; - no caller needs this reinited yet */
177                         logmode = LOGMODE_STDIO;
178                         /* die_func = NULL; - needed if the caller is a shell,
179                          * init, or a NOFORK applet. But none of those call us
180                          * as of yet (and that should probably always stay true).
181                          */
182                         /* xfunc_error_retval and applet_name are init by: */
183                         run_applet_no_and_exit(a, argv[0], argv);
184                 }
185 # endif
186         }
187 #endif /* FEATURE_PREFER_APPLETS */
188         rc = spawn(argv);
189         return wait4pid(rc);
190 }
191
192 #if !BB_MMU
193 void FAST_FUNC re_exec(char **argv)
194 {
195         /* high-order bit of first char in argv[0] is a hidden
196          * "we have (already) re-execed, don't do it again" flag */
197         argv[0][0] |= 0x80;
198         execv(bb_busybox_exec_path, argv);
199         bb_perror_msg_and_die("can't execute '%s'", bb_busybox_exec_path);
200 }
201
202 pid_t FAST_FUNC fork_or_rexec(char **argv)
203 {
204         pid_t pid;
205         /* Maybe we are already re-execed and come here again? */
206         if (re_execed)
207                 return 0;
208         pid = xvfork();
209         if (pid) /* parent */
210                 return pid;
211         /* child - re-exec ourself */
212         re_exec(argv);
213 }
214 #endif
215
216 /* Due to a #define in libbb.h on MMU systems we actually have 1 argument -
217  * char **argv "vanishes" */
218 void FAST_FUNC bb_daemonize_or_rexec(int flags, char **argv)
219 {
220         int fd;
221
222         if (flags & DAEMON_CHDIR_ROOT)
223                 xchdir("/");
224
225         if (flags & DAEMON_DEVNULL_STDIO) {
226                 close(0);
227                 close(1);
228                 close(2);
229         }
230
231         fd = open(bb_dev_null, O_RDWR);
232         if (fd < 0) {
233                 /* NB: we can be called as bb_sanitize_stdio() from init
234                  * or mdev, and there /dev/null may legitimately not (yet) exist!
235                  * Do not use xopen above, but obtain _ANY_ open descriptor,
236                  * even bogus one as below. */
237                 fd = xopen("/", O_RDONLY); /* don't believe this can fail */
238         }
239
240         while ((unsigned)fd < 2)
241                 fd = dup(fd); /* have 0,1,2 open at least to /dev/null */
242
243         if (!(flags & DAEMON_ONLY_SANITIZE)) {
244                 if (fork_or_rexec(argv))
245                         exit(EXIT_SUCCESS); /* parent */
246                 /* if daemonizing, detach from stdio & ctty */
247                 setsid();
248                 dup2(fd, 0);
249                 dup2(fd, 1);
250                 dup2(fd, 2);
251                 if (flags & DAEMON_DOUBLE_FORK) {
252                         /* On Linux, session leader can acquire ctty
253                          * unknowingly, by opening a tty.
254                          * Prevent this: stop being a session leader.
255                          */
256                         if (fork_or_rexec(argv))
257                                 exit(EXIT_SUCCESS); /* parent */
258                 }
259         }
260         while (fd > 2) {
261                 close(fd--);
262                 if (!(flags & DAEMON_CLOSE_EXTRA_FDS))
263                         return;
264                 /* else close everything after fd#2 */
265         }
266 }
267
268 void FAST_FUNC bb_sanitize_stdio(void)
269 {
270         bb_daemonize_or_rexec(DAEMON_ONLY_SANITIZE, NULL);
271 }