tentatively fix getopt state corruption for NOFORK applets
[platform/upstream/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 tarball for details.
16  */
17
18 #include <paths.h>
19 #include "busybox.h" /* uses applet tables */
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 spawn(char **argv)
24 {
25         /* Compiler should not optimize stores here */
26         volatile int failed;
27         pid_t pid;
28
29 // Ain't it a good place to fflush(NULL)?
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                 _exit(111);
46         }
47         /* parent */
48         /* Unfortunately, this is not reliable: according to standards
49          * vfork() can be equivalent to fork() and we won't see value
50          * of 'failed'.
51          * Interested party can wait on pid and learn exit code.
52          * If 111 - then it (most probably) failed to exec */
53         if (failed) {
54                 errno = failed;
55                 return -1;
56         }
57         return pid;
58 }
59
60 /* Die with an error message if we can't spawn a child process. */
61 pid_t xspawn(char **argv)
62 {
63         pid_t pid = spawn(argv);
64         if (pid < 0)
65                 bb_simple_perror_msg_and_die(*argv);
66         return pid;
67 }
68
69 int safe_waitpid(int pid, int *wstat, int options)
70 {
71         int r;
72
73         do
74                 r = waitpid(pid, wstat, options);
75         while ((r == -1) && (errno == EINTR));
76         return r;
77 }
78
79 int wait_any_nohang(int *wstat)
80 {
81         return safe_waitpid(-1, wstat, WNOHANG);
82 }
83
84 // Wait for the specified child PID to exit, returning child's error return.
85 int wait4pid(int pid)
86 {
87         int status;
88
89         if (pid <= 0) {
90                 /*errno = ECHILD; -- wrong. */
91                 /* we expect errno to be already set from failed [v]fork/exec */
92                 return -1;
93         }
94         if (safe_waitpid(pid, &status, 0) == -1)
95                 return -1;
96         if (WIFEXITED(status))
97                 return WEXITSTATUS(status);
98         if (WIFSIGNALED(status))
99                 return WTERMSIG(status) + 1000;
100         return 0;
101         if (WIFEXITED(status))
102                 return WEXITSTATUS(status);
103         if (WIFSIGNALED(status))
104                 return WTERMSIG(status) + 1000;
105         return 0;
106 }
107
108 #if ENABLE_FEATURE_PREFER_APPLETS
109 void save_nofork_data(struct nofork_save_area *save)
110 {
111         memcpy(&save->die_jmp, &die_jmp, sizeof(die_jmp));
112         save->applet_name = applet_name;
113         save->xfunc_error_retval = xfunc_error_retval;
114         save->option_mask32 = option_mask32;
115         save->die_sleep = die_sleep;
116         save->saved = 1;
117 }
118
119 void restore_nofork_data(struct nofork_save_area *save)
120 {
121         memcpy(&die_jmp, &save->die_jmp, sizeof(die_jmp));
122         applet_name = save->applet_name;
123         xfunc_error_retval = save->xfunc_error_retval;
124         option_mask32 = save->option_mask32;
125         die_sleep = save->die_sleep;
126 }
127
128 int run_nofork_applet_prime(struct nofork_save_area *old, int applet_no, char **argv)
129 {
130         int rc, argc;
131
132         applet_name = APPLET_NAME(applet_no);
133         xfunc_error_retval = EXIT_FAILURE;
134
135         /* Special flag for xfunc_die(). If xfunc will "die"
136          * in NOFORK applet, xfunc_die() sees negative
137          * die_sleep and longjmp here instead. */
138         die_sleep = -1;
139
140         /* Reset the libc getopt() function, which keeps internal state.
141          *
142          * BSD-derived getopt() functions require that optind be reset to 1 in
143          * order to reset getopt() state.  This used to be generally accepted
144          * way of resetting getopt().  However, glibc's getopt()
145          * has additional getopt() state beyond optind, and requires that
146          * optind be set zero to reset its state.  So the unfortunate state of
147          * affairs is that BSD-derived versions of getopt() misbehave if
148          * optind is set to 0 in order to reset getopt(), and glibc's getopt()
149          * will core ump if optind is set 1 in order to reset getopt().
150          * 
151          * More modern versions of BSD require that optreset be set to 1 in
152          * order to reset getopt().   Sigh.  Standards, anyone?
153          */
154 #ifdef __GLIBC__
155         optind = 0;
156 #else /* BSD style */
157         optind = 1;
158         /* optreset = 1; */
159 #endif
160         /* option_mask32 = 0; - not needed */
161
162         argc = 1;
163         while (argv[argc])
164                 argc++;
165
166         rc = setjmp(die_jmp);
167         if (!rc) {
168                 /* Some callers (xargs)
169                  * need argv untouched because they free argv[i]! */
170                 char *tmp_argv[argc+1];
171                 memcpy(tmp_argv, argv, (argc+1) * sizeof(tmp_argv[0]));
172                 /* Finally we can call NOFORK applet's main() */
173                 rc = applet_main[applet_no](argc, tmp_argv);
174         } else { /* xfunc died in NOFORK applet */
175                 /* in case they meant to return 0... */
176                 if (rc == -2222)
177                         rc = 0;
178         }
179
180         /* Restoring globals */
181         restore_nofork_data(old);
182         return rc;
183 }
184
185 int run_nofork_applet(int applet_no, char **argv)
186 {
187         struct nofork_save_area old;
188
189         /* Saving globals */
190         save_nofork_data(&old);
191         return run_nofork_applet_prime(&old, applet_no, argv);
192 }
193 #endif /* FEATURE_PREFER_APPLETS */
194
195 int spawn_and_wait(char **argv)
196 {
197         int rc;
198 #if ENABLE_FEATURE_PREFER_APPLETS
199         int a = find_applet_by_name(argv[0]);
200
201         if (a >= 0 && (APPLET_IS_NOFORK(a)
202 #if BB_MMU
203                         || APPLET_IS_NOEXEC(a) /* NOEXEC trick needs fork() */
204 #endif
205         )) {
206 #if BB_MMU
207                 if (APPLET_IS_NOFORK(a))
208 #endif
209                 {
210                         return run_nofork_applet(a, argv);
211                 }
212 #if BB_MMU
213                 /* MMU only */
214                 /* a->noexec is true */
215                 rc = fork();
216                 if (rc) /* parent or error */
217                         return wait4pid(rc);
218                 /* child */
219                 xfunc_error_retval = EXIT_FAILURE;
220                 run_applet_no_and_exit(a, argv);
221 #endif
222         }
223 #endif /* FEATURE_PREFER_APPLETS */
224         rc = spawn(argv);
225         return wait4pid(rc);
226 }
227
228 #if !BB_MMU
229 void re_exec(char **argv)
230 {
231         /* high-order bit of first char in argv[0] is a hidden
232          * "we have (already) re-execed, don't do it again" flag */
233         argv[0][0] |= 0x80;
234         execv(bb_busybox_exec_path, argv);
235         bb_perror_msg_and_die("exec %s", bb_busybox_exec_path);
236 }
237
238 void forkexit_or_rexec(char **argv)
239 {
240         pid_t pid;
241         /* Maybe we are already re-execed and come here again? */
242         if (re_execed)
243                 return;
244
245         pid = vfork();
246         if (pid < 0) /* wtf? */
247                 bb_perror_msg_and_die("vfork");
248         if (pid) /* parent */
249                 exit(0);
250         /* child - re-exec ourself */
251         re_exec(argv);
252 }
253 #else
254 /* Dance around (void)...*/
255 #undef forkexit_or_rexec
256 void forkexit_or_rexec(void)
257 {
258         pid_t pid;
259         pid = fork();
260         if (pid < 0) /* wtf? */
261                 bb_perror_msg_and_die("fork");
262         if (pid) /* parent */
263                 exit(0);
264         /* child */
265 }
266 #define forkexit_or_rexec(argv) forkexit_or_rexec()
267 #endif
268
269 /* Due to a #define in libbb.h on MMU systems we actually have 1 argument -
270  * char **argv "vanishes" */
271 void bb_daemonize_or_rexec(int flags, char **argv)
272 {
273         int fd;
274
275         if (flags & DAEMON_CHDIR_ROOT)
276                 xchdir("/");
277
278         if (flags & DAEMON_DEVNULL_STDIO) {
279                 close(0);
280                 close(1);
281                 close(2);
282         }
283
284         fd = xopen(bb_dev_null, O_RDWR);
285
286         while ((unsigned)fd < 2)
287                 fd = dup(fd); /* have 0,1,2 open at least to /dev/null */
288
289         if (!(flags & DAEMON_ONLY_SANITIZE)) {
290                 forkexit_or_rexec(argv);
291                 /* if daemonizing, make sure we detach from stdio & ctty */
292                 setsid();
293                 dup2(fd, 0);
294                 dup2(fd, 1);
295                 dup2(fd, 2);
296         }
297         while (fd > 2) {
298                 close(fd--);
299                 if (!(flags & DAEMON_CLOSE_EXTRA_FDS))
300                         return;
301                 /* else close everything after fd#2 */
302         }
303 }
304
305 void bb_sanitize_stdio(void)
306 {
307         bb_daemonize_or_rexec(DAEMON_ONLY_SANITIZE, NULL);
308 }