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