bb_daemonize_or_rexec(): add flag to double-fork; use it in start-stop-daemon
[oweals/busybox.git] / debianutils / start_stop_daemon.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * Mini start-stop-daemon implementation(s) for busybox
4  *
5  * Written by Marek Michalkiewicz <marekm@i17linuxb.ists.pwr.wroc.pl>,
6  * Adapted for busybox David Kimdon <dwhedon@gordian.com>
7  *
8  * Licensed under GPLv2 or later, see file LICENSE in this source tree.
9  */
10
11 /*
12 This is how it is supposed to work:
13
14 start-stop-daemon [OPTIONS] [--start|--stop] [[--] arguments...]
15
16 One (only) of these must be given:
17         -S,--start              Start
18         -K,--stop               Stop
19
20 Search for matching processes.
21 If --stop is given, stop all matching processes (by sending a signal).
22 If --start is given, start a new process unless a matching process was found.
23
24 Options controlling process matching
25 (if multiple conditions are specified, all must match):
26         -u,--user USERNAME|UID  Only consider this user's processes
27         -n,--name PROCESS_NAME  Look for processes by matching PROCESS_NAME
28                                 with comm field in /proc/$PID/stat.
29                                 Only basename is compared:
30                                 "ntpd" == "./ntpd" == "/path/to/ntpd".
31 [TODO: can PROCESS_NAME be a full pathname? Should we require full match then
32 with /proc/$PID/exe or argv[0] (comm can't be matched, it never contains path)]
33         -x,--exec EXECUTABLE    Look for processes that were started with this
34                                 command in /proc/$PID/cmdline.
35                                 Unlike -n, we match against the full path:
36                                 "ntpd" != "./ntpd" != "/path/to/ntpd"
37         -p,--pidfile PID_FILE   Look for processes with PID from this file
38
39 Options which are valid for --start only:
40         -x,--exec EXECUTABLE    Program to run (1st arg of execvp). Mandatory.
41         -a,--startas NAME       argv[0] (defaults to EXECUTABLE)
42         -b,--background         Put process into background
43         -N,--nicelevel N        Add N to process' nice level
44         -c,--chuid USER[:[GRP]] Change to specified user [and group]
45         -m,--make-pidfile       Write PID to the pidfile
46                                 (both -m and -p must be given!)
47
48 Options which are valid for --stop only:
49         -s,--signal SIG         Signal to send (default:TERM)
50         -t,--test               Exit with status 0 if process is found
51                                 (we don't actually start or stop daemons)
52
53 Misc options:
54         -o,--oknodo             Exit with status 0 if nothing is done
55         -q,--quiet              Quiet
56         -v,--verbose            Verbose
57 */
58
59 //usage:#define start_stop_daemon_trivial_usage
60 //usage:       "[OPTIONS] [-S|-K] ... [-- ARGS...]"
61 //usage:#define start_stop_daemon_full_usage "\n\n"
62 //usage:       "Search for matching processes, and then\n"
63 //usage:       "-K: stop all matching processes.\n"
64 //usage:       "-S: start a process unless a matching process is found.\n"
65 //usage:        IF_FEATURE_START_STOP_DAEMON_LONG_OPTIONS(
66 //usage:     "\nProcess matching:"
67 //usage:     "\n        -u,--user USERNAME|UID  Match only this user's processes"
68 //usage:     "\n        -n,--name NAME          Match processes with NAME"
69 //usage:     "\n                                in comm field in /proc/PID/stat"
70 //usage:     "\n        -x,--exec EXECUTABLE    Match processes with this command"
71 //usage:     "\n                                in /proc/PID/cmdline"
72 //usage:     "\n        -p,--pidfile FILE       Match a process with PID from the file"
73 //usage:     "\n        All specified conditions must match"
74 //usage:     "\n-S only:"
75 //usage:     "\n        -x,--exec EXECUTABLE    Program to run"
76 //usage:     "\n        -a,--startas NAME       Zeroth argument"
77 //usage:     "\n        -b,--background         Background"
78 //usage:        IF_FEATURE_START_STOP_DAEMON_FANCY(
79 //usage:     "\n        -N,--nicelevel N        Change nice level"
80 //usage:        )
81 //usage:     "\n        -c,--chuid USER[:[GRP]] Change to user/group"
82 //usage:     "\n        -m,--make-pidfile       Write PID to the pidfile specified by -p"
83 //usage:     "\n-K only:"
84 //usage:     "\n        -s,--signal SIG         Signal to send"
85 //usage:     "\n        -t,--test               Match only, exit with 0 if a process is found"
86 //usage:     "\nOther:"
87 //usage:        IF_FEATURE_START_STOP_DAEMON_FANCY(
88 //usage:     "\n        -o,--oknodo             Exit with status 0 if nothing is done"
89 //usage:     "\n        -v,--verbose            Verbose"
90 //usage:        )
91 //usage:     "\n        -q,--quiet              Quiet"
92 //usage:        )
93 //usage:        IF_NOT_FEATURE_START_STOP_DAEMON_LONG_OPTIONS(
94 //usage:     "\nProcess matching:"
95 //usage:     "\n        -u USERNAME|UID Match only this user's processes"
96 //usage:     "\n        -n NAME         Match processes with NAME"
97 //usage:     "\n                        in comm field in /proc/PID/stat"
98 //usage:     "\n        -x EXECUTABLE   Match processes with this command"
99 //usage:     "\n                        command in /proc/PID/cmdline"
100 //usage:     "\n        -p FILE         Match a process with PID from the file"
101 //usage:     "\n        All specified conditions must match"
102 //usage:     "\n-S only:"
103 //usage:     "\n        -x EXECUTABLE   Program to run"
104 //usage:     "\n        -a NAME         Zeroth argument"
105 //usage:     "\n        -b              Background"
106 //usage:        IF_FEATURE_START_STOP_DAEMON_FANCY(
107 //usage:     "\n        -N N            Change nice level"
108 //usage:        )
109 //usage:     "\n        -c USER[:[GRP]] Change to user/group"
110 //usage:     "\n        -m              Write PID to the pidfile specified by -p"
111 //usage:     "\n-K only:"
112 //usage:     "\n        -s SIG          Signal to send"
113 //usage:     "\n        -t              Match only, exit with 0 if a process is found"
114 //usage:     "\nOther:"
115 //usage:        IF_FEATURE_START_STOP_DAEMON_FANCY(
116 //usage:     "\n        -o              Exit with status 0 if nothing is done"
117 //usage:     "\n        -v              Verbose"
118 //usage:        )
119 //usage:     "\n        -q              Quiet"
120 //usage:        )
121
122 #include <sys/resource.h>
123
124 /* Override ENABLE_FEATURE_PIDFILE */
125 #define WANT_PIDFILE 1
126 #include "libbb.h"
127
128 struct pid_list {
129         struct pid_list *next;
130         pid_t pid;
131 };
132
133 enum {
134         CTX_STOP       = (1 <<  0),
135         CTX_START      = (1 <<  1),
136         OPT_BACKGROUND = (1 <<  2), // -b
137         OPT_QUIET      = (1 <<  3), // -q
138         OPT_TEST       = (1 <<  4), // -t
139         OPT_MAKEPID    = (1 <<  5), // -m
140         OPT_a          = (1 <<  6), // -a
141         OPT_n          = (1 <<  7), // -n
142         OPT_s          = (1 <<  8), // -s
143         OPT_u          = (1 <<  9), // -u
144         OPT_c          = (1 << 10), // -c
145         OPT_x          = (1 << 11), // -x
146         OPT_p          = (1 << 12), // -p
147         OPT_OKNODO     = (1 << 13) * ENABLE_FEATURE_START_STOP_DAEMON_FANCY, // -o
148         OPT_VERBOSE    = (1 << 14) * ENABLE_FEATURE_START_STOP_DAEMON_FANCY, // -v
149         OPT_NICELEVEL  = (1 << 15) * ENABLE_FEATURE_START_STOP_DAEMON_FANCY, // -N
150 };
151 #define QUIET (option_mask32 & OPT_QUIET)
152 #define TEST  (option_mask32 & OPT_TEST)
153
154 struct globals {
155         struct pid_list *found_procs;
156         char *userspec;
157         char *cmdname;
158         char *execname;
159         char *pidfile;
160         char *execname_cmpbuf;
161         unsigned execname_sizeof;
162         int user_id;
163         smallint signal_nr;
164 } FIX_ALIASING;
165 #define G (*(struct globals*)&bb_common_bufsiz1)
166 #define userspec          (G.userspec            )
167 #define cmdname           (G.cmdname             )
168 #define execname          (G.execname            )
169 #define pidfile           (G.pidfile             )
170 #define user_id           (G.user_id             )
171 #define signal_nr         (G.signal_nr           )
172 #define INIT_G() do { \
173         user_id = -1; \
174         signal_nr = 15; \
175 } while (0)
176
177 #ifdef OLDER_VERSION_OF_X
178 /* -x,--exec EXECUTABLE
179  * Look for processes with matching /proc/$PID/exe.
180  * Match is performed using device+inode.
181  */
182 static int pid_is_exec(pid_t pid)
183 {
184         struct stat st;
185         char buf[sizeof("/proc/%u/exe") + sizeof(int)*3];
186
187         sprintf(buf, "/proc/%u/exe", (unsigned)pid);
188         if (stat(buf, &st) < 0)
189                 return 0;
190         if (st.st_dev == execstat.st_dev
191          && st.st_ino == execstat.st_ino)
192                 return 1;
193         return 0;
194 }
195 #endif
196
197 static int pid_is_exec(pid_t pid)
198 {
199         ssize_t bytes;
200         char buf[sizeof("/proc/%u/cmdline") + sizeof(int)*3];
201
202         sprintf(buf, "/proc/%u/cmdline", (unsigned)pid);
203         bytes = open_read_close(buf, G.execname_cmpbuf, G.execname_sizeof);
204         if (bytes > 0) {
205                 G.execname_cmpbuf[bytes] = '\0';
206                 return strcmp(execname, G.execname_cmpbuf) == 0;
207         }
208         return 0;
209 }
210
211 static int pid_is_name(pid_t pid)
212 {
213         /* /proc/PID/stat is "PID (comm_15_bytes_max) ..." */
214         char buf[32]; /* should be enough */
215         char *p, *pe;
216
217         sprintf(buf, "/proc/%u/stat", (unsigned)pid);
218         if (open_read_close(buf, buf, sizeof(buf) - 1) < 0)
219                 return 0;
220         buf[sizeof(buf) - 1] = '\0'; /* paranoia */
221         p = strchr(buf, '(');
222         if (!p)
223                 return 0;
224         pe = strrchr(++p, ')');
225         if (!pe)
226                 return 0;
227         *pe = '\0';
228         /* we require comm to match and to not be truncated */
229         /* in Linux, if comm is 15 chars, it may be a truncated
230          * name, so we don't allow that to match */
231         if (strlen(p) >= COMM_LEN - 1) /* COMM_LEN is 16 */
232                 return 0;
233         return strcmp(p, cmdname) == 0;
234 }
235
236 static int pid_is_user(int pid)
237 {
238         struct stat sb;
239         char buf[sizeof("/proc/") + sizeof(int)*3];
240
241         sprintf(buf, "/proc/%u", (unsigned)pid);
242         if (stat(buf, &sb) != 0)
243                 return 0;
244         return (sb.st_uid == (uid_t)user_id);
245 }
246
247 static void check(int pid)
248 {
249         struct pid_list *p;
250
251         if (execname && !pid_is_exec(pid)) {
252                 return;
253         }
254         if (cmdname && !pid_is_name(pid)) {
255                 return;
256         }
257         if (userspec && !pid_is_user(pid)) {
258                 return;
259         }
260         p = xmalloc(sizeof(*p));
261         p->next = G.found_procs;
262         p->pid = pid;
263         G.found_procs = p;
264 }
265
266 static void do_pidfile(void)
267 {
268         FILE *f;
269         unsigned pid;
270
271         f = fopen_for_read(pidfile);
272         if (f) {
273                 if (fscanf(f, "%u", &pid) == 1)
274                         check(pid);
275                 fclose(f);
276         } else if (errno != ENOENT)
277                 bb_perror_msg_and_die("open pidfile %s", pidfile);
278 }
279
280 static void do_procinit(void)
281 {
282         DIR *procdir;
283         struct dirent *entry;
284         int pid;
285
286         if (pidfile) {
287                 do_pidfile();
288                 return;
289         }
290
291         procdir = xopendir("/proc");
292
293         pid = 0;
294         while (1) {
295                 errno = 0; /* clear any previous error */
296                 entry = readdir(procdir);
297 // TODO: this check is too generic, it's better
298 // to check for exact errno(s) which mean that we got stale entry
299                 if (errno) /* Stale entry, process has died after opendir */
300                         continue;
301                 if (!entry) /* EOF, no more entries */
302                         break;
303                 pid = bb_strtou(entry->d_name, NULL, 10);
304                 if (errno) /* NaN */
305                         continue;
306                 check(pid);
307         }
308         closedir(procdir);
309         if (!pid)
310                 bb_error_msg_and_die("nothing in /proc - not mounted?");
311 }
312
313 static int do_stop(void)
314 {
315         char *what;
316         struct pid_list *p;
317         int killed = 0;
318
319         if (cmdname) {
320                 if (ENABLE_FEATURE_CLEAN_UP) what = xstrdup(cmdname);
321                 if (!ENABLE_FEATURE_CLEAN_UP) what = cmdname;
322         } else if (execname) {
323                 if (ENABLE_FEATURE_CLEAN_UP) what = xstrdup(execname);
324                 if (!ENABLE_FEATURE_CLEAN_UP) what = execname;
325         } else if (pidfile) {
326                 what = xasprintf("process in pidfile '%s'", pidfile);
327         } else if (userspec) {
328                 what = xasprintf("process(es) owned by '%s'", userspec);
329         } else {
330                 bb_error_msg_and_die("internal error, please report");
331         }
332
333         if (!G.found_procs) {
334                 if (!QUIET)
335                         printf("no %s found; none killed\n", what);
336                 killed = -1;
337                 goto ret;
338         }
339         for (p = G.found_procs; p; p = p->next) {
340                 if (kill(p->pid, TEST ? 0 : signal_nr) == 0) {
341                         killed++;
342                 } else {
343                         bb_perror_msg("warning: killing process %u", (unsigned)p->pid);
344                         p->pid = 0;
345                         if (TEST) {
346                                 /* Example: -K --test --pidfile PIDFILE detected
347                                  * that PIDFILE's pid doesn't exist */
348                                 killed = -1;
349                                 goto ret;
350                         }
351                 }
352         }
353         if (!QUIET && killed) {
354                 printf("stopped %s (pid", what);
355                 for (p = G.found_procs; p; p = p->next)
356                         if (p->pid)
357                                 printf(" %u", (unsigned)p->pid);
358                 puts(")");
359         }
360  ret:
361         if (ENABLE_FEATURE_CLEAN_UP)
362                 free(what);
363         return killed;
364 }
365
366 #if ENABLE_FEATURE_START_STOP_DAEMON_LONG_OPTIONS
367 static const char start_stop_daemon_longopts[] ALIGN1 =
368         "stop\0"         No_argument       "K"
369         "start\0"        No_argument       "S"
370         "background\0"   No_argument       "b"
371         "quiet\0"        No_argument       "q"
372         "test\0"         No_argument       "t"
373         "make-pidfile\0" No_argument       "m"
374 #if ENABLE_FEATURE_START_STOP_DAEMON_FANCY
375         "oknodo\0"       No_argument       "o"
376         "verbose\0"      No_argument       "v"
377         "nicelevel\0"    Required_argument "N"
378 #endif
379         "startas\0"      Required_argument "a"
380         "name\0"         Required_argument "n"
381         "signal\0"       Required_argument "s"
382         "user\0"         Required_argument "u"
383         "chuid\0"        Required_argument "c"
384         "exec\0"         Required_argument "x"
385         "pidfile\0"      Required_argument "p"
386 #if ENABLE_FEATURE_START_STOP_DAEMON_FANCY
387         "retry\0"        Required_argument "R"
388 #endif
389         ;
390 #endif
391
392 int start_stop_daemon_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
393 int start_stop_daemon_main(int argc UNUSED_PARAM, char **argv)
394 {
395         unsigned opt;
396         char *signame;
397         char *startas;
398         char *chuid;
399 #ifdef OLDER_VERSION_OF_X
400         struct stat execstat;
401 #endif
402 #if ENABLE_FEATURE_START_STOP_DAEMON_FANCY
403 //      char *retry_arg = NULL;
404 //      int retries = -1;
405         char *opt_N;
406 #endif
407
408         INIT_G();
409
410 #if ENABLE_FEATURE_START_STOP_DAEMON_LONG_OPTIONS
411         applet_long_options = start_stop_daemon_longopts;
412 #endif
413
414         /* -K or -S is required; they are mutually exclusive */
415         /* -p is required if -m is given */
416         /* -xpun (at least one) is required if -K is given */
417         /* -xa (at least one) is required if -S is given */
418         /* -q turns off -v */
419         opt_complementary = "K:S:K--S:S--K:m?p:K?xpun:S?xa"
420                 IF_FEATURE_START_STOP_DAEMON_FANCY("q-v");
421         opt = getopt32(argv, "KSbqtma:n:s:u:c:x:p:"
422                 IF_FEATURE_START_STOP_DAEMON_FANCY("ovN:R:"),
423                 &startas, &cmdname, &signame, &userspec, &chuid, &execname, &pidfile
424                 IF_FEATURE_START_STOP_DAEMON_FANCY(,&opt_N)
425                 /* We accept and ignore -R <param> / --retry <param> */
426                 IF_FEATURE_START_STOP_DAEMON_FANCY(,NULL)
427         );
428
429         if (opt & OPT_s) {
430                 signal_nr = get_signum(signame);
431                 if (signal_nr < 0) bb_show_usage();
432         }
433
434         if (!(opt & OPT_a))
435                 startas = execname;
436         if (!execname) /* in case -a is given and -x is not */
437                 execname = startas;
438         if (execname) {
439                 G.execname_sizeof = strlen(execname) + 1;
440                 G.execname_cmpbuf = xmalloc(G.execname_sizeof + 1);
441         }
442
443 //      IF_FEATURE_START_STOP_DAEMON_FANCY(
444 //              if (retry_arg)
445 //                      retries = xatoi_positive(retry_arg);
446 //      )
447         //argc -= optind;
448         argv += optind;
449
450         if (userspec) {
451                 user_id = bb_strtou(userspec, NULL, 10);
452                 if (errno)
453                         user_id = xuname2uid(userspec);
454         }
455         /* Both start and stop need to know current processes */
456         do_procinit();
457
458         if (opt & CTX_STOP) {
459                 int i = do_stop();
460                 return (opt & OPT_OKNODO) ? 0 : (i <= 0);
461         }
462
463         if (G.found_procs) {
464                 if (!QUIET)
465                         printf("%s is already running\n%u\n", execname, (unsigned)G.found_procs->pid);
466                 return !(opt & OPT_OKNODO);
467         }
468
469 #ifdef OLDER_VERSION_OF_X
470         if (execname)
471                 xstat(execname, &execstat);
472 #endif
473
474         *--argv = startas;
475         if (opt & OPT_BACKGROUND) {
476 #if BB_MMU
477                 bb_daemonize(DAEMON_DEVNULL_STDIO + DAEMON_CLOSE_EXTRA_FDS + DAEMON_DOUBLE_FORK);
478                 /* DAEMON_DEVNULL_STDIO is superfluous -
479                  * it's always done by bb_daemonize() */
480 #else
481                 pid_t pid = xvfork();
482                 if (pid != 0) {
483                         /* parent */
484                         /* why _exit? the child may have changed the stack,
485                          * so "return 0" may do bad things */
486                         _exit(EXIT_SUCCESS);
487                 }
488                 /* Child */
489                 setsid(); /* detach from controlling tty */
490                 /* Redirect stdio to /dev/null, close extra FDs.
491                  * We do not actually daemonize because of DAEMON_ONLY_SANITIZE */
492                 bb_daemonize_or_rexec(DAEMON_DEVNULL_STDIO
493                         + DAEMON_CLOSE_EXTRA_FDS
494                         + DAEMON_ONLY_SANITIZE,
495                         NULL /* argv, unused */ );
496 #endif
497         }
498         if (opt & OPT_MAKEPID) {
499                 /* User wants _us_ to make the pidfile */
500                 write_pidfile(pidfile);
501         }
502         if (opt & OPT_c) {
503                 struct bb_uidgid_t ugid = { -1, -1 };
504                 parse_chown_usergroup_or_die(&ugid, chuid);
505                 if (ugid.uid != (uid_t) -1) {
506                         struct passwd *pw = xgetpwuid(ugid.uid);
507                         if (ugid.gid != (gid_t) -1)
508                                 pw->pw_gid = ugid.gid;
509                         /* initgroups, setgid, setuid: */
510                         change_identity(pw);
511                 } else if (ugid.gid != (gid_t) -1) {
512                         xsetgid(ugid.gid);
513                         setgroups(1, &ugid.gid);
514                 }
515         }
516 #if ENABLE_FEATURE_START_STOP_DAEMON_FANCY
517         if (opt & OPT_NICELEVEL) {
518                 /* Set process priority */
519                 int prio = getpriority(PRIO_PROCESS, 0) + xatoi_range(opt_N, INT_MIN/2, INT_MAX/2);
520                 if (setpriority(PRIO_PROCESS, 0, prio) < 0) {
521                         bb_perror_msg_and_die("setpriority(%d)", prio);
522                 }
523         }
524 #endif
525         execvp(startas, argv);
526         bb_perror_msg_and_die("can't execute '%s'", startas);
527 }