new NOFORKs: pwdx,kill[all5],ttysize,realpath,readlink NOEXECs: date,resize
[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         } else {
147                 /* xfunc died in NOFORK applet */
148         }
149
150         /* Restoring some globals */
151         restore_nofork_data(&old);
152         /* Other globals can be simply reset to defaults */
153         GETOPT_RESET();
154
155         return rc & 0xff; /* don't confuse people with "exitcodes" >255 */
156 }
157 #endif /* FEATURE_PREFER_APPLETS || FEATURE_SH_NOFORK */
158
159 int FAST_FUNC spawn_and_wait(char **argv)
160 {
161         int rc;
162 #if ENABLE_FEATURE_PREFER_APPLETS && (NUM_APPLETS > 1)
163         int a = find_applet_by_name(argv[0]);
164
165         if (a >= 0) {
166                 if (APPLET_IS_NOFORK(a))
167                         return run_nofork_applet(a, argv);
168 # if BB_MMU /* NOEXEC needs fork(), thus this is done only on MMU machines: */
169                 if (APPLET_IS_NOEXEC(a)) {
170                         fflush_all();
171                         rc = fork();
172                         if (rc) /* parent or error */
173                                 return wait4pid(rc);
174
175                         /* child */
176                         /* reset some state and run without execing */
177
178                         /* msg_eol = "\n"; - no caller needs this reinited yet */
179                         logmode = LOGMODE_STDIO;
180                         /* die_func = NULL; - needed if the caller is a shell,
181                          * init, or a NOFORK applet. But none of those call us
182                          * as of yet (and that should probably always stay true).
183                          */
184                         /* xfunc_error_retval and applet_name are init by: */
185                         run_applet_no_and_exit(a, argv[0], argv);
186                 }
187 # endif
188         }
189 #endif /* FEATURE_PREFER_APPLETS */
190         rc = spawn(argv);
191         return wait4pid(rc);
192 }
193
194 #if !BB_MMU
195 void FAST_FUNC re_exec(char **argv)
196 {
197         /* high-order bit of first char in argv[0] is a hidden
198          * "we have (already) re-execed, don't do it again" flag */
199         argv[0][0] |= 0x80;
200         execv(bb_busybox_exec_path, argv);
201         bb_perror_msg_and_die("can't execute '%s'", bb_busybox_exec_path);
202 }
203
204 pid_t FAST_FUNC fork_or_rexec(char **argv)
205 {
206         pid_t pid;
207         /* Maybe we are already re-execed and come here again? */
208         if (re_execed)
209                 return 0;
210         pid = xvfork();
211         if (pid) /* parent */
212                 return pid;
213         /* child - re-exec ourself */
214         re_exec(argv);
215 }
216 #endif
217
218 /* Due to a #define in libbb.h on MMU systems we actually have 1 argument -
219  * char **argv "vanishes" */
220 void FAST_FUNC bb_daemonize_or_rexec(int flags, char **argv)
221 {
222         int fd;
223
224         if (flags & DAEMON_CHDIR_ROOT)
225                 xchdir("/");
226
227         if (flags & DAEMON_DEVNULL_STDIO) {
228                 close(0);
229                 close(1);
230                 close(2);
231         }
232
233         fd = open(bb_dev_null, O_RDWR);
234         if (fd < 0) {
235                 /* NB: we can be called as bb_sanitize_stdio() from init
236                  * or mdev, and there /dev/null may legitimately not (yet) exist!
237                  * Do not use xopen above, but obtain _ANY_ open descriptor,
238                  * even bogus one as below. */
239                 fd = xopen("/", O_RDONLY); /* don't believe this can fail */
240         }
241
242         while ((unsigned)fd < 2)
243                 fd = dup(fd); /* have 0,1,2 open at least to /dev/null */
244
245         if (!(flags & DAEMON_ONLY_SANITIZE)) {
246                 if (fork_or_rexec(argv))
247                         exit(EXIT_SUCCESS); /* parent */
248                 /* if daemonizing, detach from stdio & ctty */
249                 setsid();
250                 dup2(fd, 0);
251                 dup2(fd, 1);
252                 dup2(fd, 2);
253                 if (flags & DAEMON_DOUBLE_FORK) {
254                         /* On Linux, session leader can acquire ctty
255                          * unknowingly, by opening a tty.
256                          * Prevent this: stop being a session leader.
257                          */
258                         if (fork_or_rexec(argv))
259                                 exit(EXIT_SUCCESS); /* parent */
260                 }
261         }
262         while (fd > 2) {
263                 close(fd--);
264                 if (!(flags & DAEMON_CLOSE_EXTRA_FDS))
265                         return;
266                 /* else close everything after fd#2 */
267         }
268 }
269
270 void FAST_FUNC bb_sanitize_stdio(void)
271 {
272         bb_daemonize_or_rexec(DAEMON_ONLY_SANITIZE, NULL);
273 }