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