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