start_stop_daemon: try to clarify intended meaning of the options
[platform/upstream/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 tarball for details.
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 if given, start a new process unless a matching process was found.
23
24 Options controlling process matching:
25         -u,--user USERNAME|UID  Only consider this user's processes
26         -n,--name PROCESS_NAME  Look for processes with matching argv[0]
27                                 or /proc/$PID/exe or /proc/$PID/stat (comm field).
28                                 Only basename is compared:
29                                 "ntpd" == "./ntpd" == "/path/to/ntpd".
30 [TODO: can PROCESS_NAME be a full pathname? Should we require full match then
31 with /proc/$PID/exe or argv[0] (comm can't be matched, it never contains path)]
32         -x,--exec EXECUTABLE    Look for processes with matching /proc/$PID/exe.
33                                 Match is performed using device+inode.
34         -p,--pidfile PID_FILE   Look for processes with PID from this file
35
36 Options which are valid for --start only:
37         -x,--exec EXECUTABLE    Program to run (1st arg of execvp). Mandatory.
38         -a,--startas NAME       argv[0] (defaults to EXECUTABLE)
39         -b,--background         Put process into background
40         -N,--nicelevel N        Add N to process' nice level
41         -c,--chuid USER[:[GRP]] Change to specified user [and group]
42         -m,--make-pidfile       Write PID to the pidfile
43                                 (both -m and -p must be given!)
44 Misc options:
45         -s,--signal SIG         Signal to send (default:TERM)
46         -o,--oknodo             Exit with status 0 if nothing is done
47         -q,--quiet              Quiet
48         -v,--verbose            Verbose
49 */
50
51 #include <sys/resource.h>
52
53 /* Override ENABLE_FEATURE_PIDFILE */
54 #define WANT_PIDFILE 1
55 #include "libbb.h"
56
57 struct pid_list {
58         struct pid_list *next;
59         pid_t pid;
60 };
61
62 enum {
63         CTX_STOP       = (1 <<  0),
64         CTX_START      = (1 <<  1),
65         OPT_BACKGROUND = (1 <<  2), // -b
66         OPT_QUIET      = (1 <<  3), // -q
67         OPT_MAKEPID    = (1 <<  4), // -m
68         OPT_a          = (1 <<  5), // -a
69         OPT_n          = (1 <<  6), // -n
70         OPT_s          = (1 <<  7), // -s
71         OPT_u          = (1 <<  8), // -u
72         OPT_c          = (1 <<  9), // -c
73         OPT_x          = (1 << 10), // -x
74         OPT_p          = (1 << 11), // -p
75         OPT_OKNODO     = (1 << 12) * ENABLE_FEATURE_START_STOP_DAEMON_FANCY, // -o
76         OPT_VERBOSE    = (1 << 13) * ENABLE_FEATURE_START_STOP_DAEMON_FANCY, // -v
77         OPT_NICELEVEL  = (1 << 14) * ENABLE_FEATURE_START_STOP_DAEMON_FANCY, // -N
78 };
79 #define QUIET (option_mask32 & OPT_QUIET)
80
81 struct globals {
82         struct pid_list *found;
83         char *userspec;
84         char *cmdname;
85         char *execname;
86         char *pidfile;
87         int user_id;
88         smallint signal_nr;
89         struct stat execstat;
90 };
91 #define G (*(struct globals*)&bb_common_bufsiz1)
92 #define found             (G.found               )
93 #define userspec          (G.userspec            )
94 #define cmdname           (G.cmdname             )
95 #define execname          (G.execname            )
96 #define pidfile           (G.pidfile             )
97 #define user_id           (G.user_id             )
98 #define signal_nr         (G.signal_nr           )
99 #define execstat          (G.execstat            )
100 #define INIT_G() \
101         do { \
102                 user_id = -1; \
103                 signal_nr = 15; \
104         } while (0)
105
106
107 static int pid_is_exec(pid_t pid)
108 {
109         struct stat st;
110         char buf[sizeof("/proc//exe") + sizeof(int)*3];
111
112         sprintf(buf, "/proc/%u/exe", pid);
113         if (stat(buf, &st) < 0)
114                 return 0;
115         if (st.st_dev == execstat.st_dev
116          && st.st_ino == execstat.st_ino)
117                 return 1;
118         return 0;
119 }
120
121 static int pid_is_user(int pid)
122 {
123         struct stat sb;
124         char buf[sizeof("/proc/") + sizeof(int)*3];
125
126         sprintf(buf, "/proc/%u", pid);
127         if (stat(buf, &sb) != 0)
128                 return 0;
129         return (sb.st_uid == user_id);
130 }
131
132 static int pid_is_cmd(pid_t pid)
133 {
134         char buf[256]; /* is it big enough? */
135         char *p, *pe;
136
137         sprintf(buf, "/proc/%u/stat", pid);
138         if (open_read_close(buf, buf, sizeof(buf) - 1) < 0)
139                 return 0;
140         buf[sizeof(buf) - 1] = '\0'; /* paranoia */
141         p = strchr(buf, '(');
142         if (!p)
143                 return 0;
144         pe = strrchr(++p, ')');
145         if (!pe)
146                 return 0;
147         *pe = '\0';
148         return !strcmp(p, cmdname);
149 }
150
151 static void check(int pid)
152 {
153         struct pid_list *p;
154
155         if (execname && !pid_is_exec(pid)) {
156                 return;
157         }
158         if (userspec && !pid_is_user(pid)) {
159                 return;
160         }
161         if (cmdname && !pid_is_cmd(pid)) {
162                 return;
163         }
164         p = xmalloc(sizeof(*p));
165         p->next = found;
166         p->pid = pid;
167         found = p;
168 }
169
170 static void do_pidfile(void)
171 {
172         FILE *f;
173         unsigned pid;
174
175         f = fopen(pidfile, "r");
176         if (f) {
177                 if (fscanf(f, "%u", &pid) == 1)
178                         check(pid);
179                 fclose(f);
180         } else if (errno != ENOENT)
181                 bb_perror_msg_and_die("open pidfile %s", pidfile);
182 }
183
184 static void do_procinit(void)
185 {
186         DIR *procdir;
187         struct dirent *entry;
188         int pid;
189
190         if (pidfile) {
191                 do_pidfile();
192                 return;
193         }
194
195         procdir = xopendir("/proc");
196
197         pid = 0;
198         while(1) {
199                 errno = 0; /* clear any previous error */
200                 entry = readdir(procdir);
201 // TODO: check for exact errno(s) which mean that we got stale entry
202                 if (errno) /* Stale entry, process has died after opendir */
203                         continue;
204                 if (!entry) /* EOF, no more entries */
205                         break;
206                 pid = bb_strtou(entry->d_name, NULL, 10);
207                 if (errno) /* NaN */
208                         continue;
209                 check(pid);
210         }
211         closedir(procdir);
212         if (!pid)
213                 bb_error_msg_and_die("nothing in /proc - not mounted?");
214 }
215
216 static int do_stop(void)
217 {
218         char *what;
219         struct pid_list *p;
220         int killed = 0;
221
222         if (cmdname) {
223                 if (ENABLE_FEATURE_CLEAN_UP) what = xstrdup(cmdname);
224                 if (!ENABLE_FEATURE_CLEAN_UP) what = cmdname;
225         } else if (execname) {
226                 if (ENABLE_FEATURE_CLEAN_UP) what = xstrdup(execname);
227                 if (!ENABLE_FEATURE_CLEAN_UP) what = execname;
228         } else if (pidfile)
229                 what = xasprintf("process in pidfile '%s'", pidfile);
230         else if (userspec)
231                 what = xasprintf("process(es) owned by '%s'", userspec);
232         else
233                 bb_error_msg_and_die("internal error, please report");
234
235         if (!found) {
236                 if (!QUIET)
237                         printf("no %s found; none killed\n", what);
238                 killed = -1;
239                 goto ret;
240         }
241         for (p = found; p; p = p->next) {
242                 if (kill(p->pid, signal_nr) == 0) {
243                         p->pid = - p->pid;
244                         killed++;
245                 } else {
246                         bb_perror_msg("warning: killing process %u", p->pid);
247                 }
248         }
249         if (!QUIET && killed) {
250                 printf("stopped %s (pid", what);
251                 for (p = found; p; p = p->next)
252                         if (p->pid < 0)
253                                 printf(" %u", - p->pid);
254                 puts(")");
255         }
256  ret:
257         if (ENABLE_FEATURE_CLEAN_UP)
258                 free(what);
259         return killed;
260 }
261
262 #if ENABLE_FEATURE_START_STOP_DAEMON_LONG_OPTIONS
263 static const char start_stop_daemon_longopts[] ALIGN1 =
264         "stop\0"         No_argument       "K"
265         "start\0"        No_argument       "S"
266         "background\0"   No_argument       "b"
267         "quiet\0"        No_argument       "q"
268         "make-pidfile\0" No_argument       "m"
269 #if ENABLE_FEATURE_START_STOP_DAEMON_FANCY
270         "oknodo\0"       No_argument       "o"
271         "verbose\0"      No_argument       "v"
272         "nicelevel\0"    Required_argument "N"
273 #endif
274         "startas\0"      Required_argument "a"
275         "name\0"         Required_argument "n"
276         "signal\0"       Required_argument "s"
277         "user\0"         Required_argument "u"
278         "chuid\0"        Required_argument "c"
279         "exec\0"         Required_argument "x"
280         "pidfile\0"      Required_argument "p"
281 #if ENABLE_FEATURE_START_STOP_DAEMON_FANCY
282         "retry\0"        Required_argument "R"
283 #endif
284         ;
285 #endif
286
287 int start_stop_daemon_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
288 int start_stop_daemon_main(int argc ATTRIBUTE_UNUSED, char **argv)
289 {
290         unsigned opt;
291         char *signame;
292         char *startas;
293         char *chuid;
294 #if ENABLE_FEATURE_START_STOP_DAEMON_FANCY
295 //      char *retry_arg = NULL;
296 //      int retries = -1;
297         char *opt_N;
298 #endif
299
300         INIT_G();
301
302 #if ENABLE_FEATURE_START_STOP_DAEMON_LONG_OPTIONS
303         applet_long_options = start_stop_daemon_longopts;
304 #endif
305
306         /* -K or -S is required; they are mutually exclusive */
307         /* -p is required if -m is given */
308         /* -xpun (at least one) is required if -K is given */
309         /* -xa (at least one) is required if -S is given */
310         /* -q turns off -v */
311         opt_complementary = "K:S:K--S:S--K:m?p:K?xpun:S?xa"
312                 USE_FEATURE_START_STOP_DAEMON_FANCY("q-v");
313         opt = getopt32(argv, "KSbqma:n:s:u:c:x:p:"
314                 USE_FEATURE_START_STOP_DAEMON_FANCY("ovN:"),
315 //              USE_FEATURE_START_STOP_DAEMON_FANCY("ovN:R:"),
316                 &startas, &cmdname, &signame, &userspec, &chuid, &execname, &pidfile
317                 USE_FEATURE_START_STOP_DAEMON_FANCY(,&opt_N)
318 //              USE_FEATURE_START_STOP_DAEMON_FANCY(,&retry_arg)
319         );
320
321         if (opt & OPT_s) {
322                 signal_nr = get_signum(signame);
323                 if (signal_nr < 0) bb_show_usage();
324         }
325
326         if (!(opt & OPT_a))
327                 startas = execname;
328
329 //      USE_FEATURE_START_STOP_DAEMON_FANCY(
330 //              if (retry_arg)
331 //                      retries = xatoi_u(retry_arg);
332 //      )
333         //argc -= optind;
334         argv += optind;
335
336         if (userspec) {
337                 user_id = bb_strtou(userspec, NULL, 10);
338                 if (errno)
339                         user_id = xuname2uid(userspec);
340         }
341         if (execname)
342                 xstat(execname, &execstat);
343
344         do_procinit(); /* Both start and stop needs to know current processes */
345
346         if (opt & CTX_STOP) {
347                 int i = do_stop();
348                 return (opt & OPT_OKNODO) ? 0 : (i <= 0);
349         }
350
351         if (found) {
352                 if (!QUIET)
353                         printf("%s already running\n%d\n", execname, found->pid);
354                 return !(opt & OPT_OKNODO);
355         }
356         *--argv = startas;
357         if (opt & OPT_BACKGROUND) {
358 #if BB_MMU
359                 bb_daemonize(0);
360 #else
361                 pid_t pid = vfork();
362                 if (pid < 0) /* error */
363                         bb_perror_msg_and_die("vfork");
364                 if (pid != 0) {
365                         /* parent */
366                         /* why _exit? the child may have changed the stack,
367                          * so "return 0" may do bad things */
368                         _exit(0);
369                 }
370                 /* child */
371                 setsid(); /* detach from controlling tty */
372                 /* Redirect stdio to /dev/null, close extra FDs.
373                  * We do not actually daemonize because of DAEMON_ONLY_SANITIZE */
374                 bb_daemonize_or_rexec(
375                         DAEMON_DEVNULL_STDIO
376                         + DAEMON_CLOSE_EXTRA_FDS
377                         + DAEMON_ONLY_SANITIZE,
378                         NULL /* argv, unused */ );
379 #endif
380         }
381         if (opt & OPT_MAKEPID) {
382                 /* user wants _us_ to make the pidfile */
383                 write_pidfile(pidfile);
384         }
385         if (opt & OPT_c) {
386                 struct bb_uidgid_t ugid;
387                 parse_chown_usergroup_or_die(&ugid, chuid);
388                 if (ugid.gid != (gid_t) -1) xsetgid(ugid.gid);
389                 if (ugid.uid != (uid_t) -1) xsetuid(ugid.uid);
390         }
391 #if ENABLE_FEATURE_START_STOP_DAEMON_FANCY
392         if (opt & OPT_NICELEVEL) {
393                 /* Set process priority */
394                 int prio = getpriority(PRIO_PROCESS, 0) + xatoi_range(opt_N, INT_MIN/2, INT_MAX/2);
395                 if (setpriority(PRIO_PROCESS, 0, prio) < 0) {
396                         bb_perror_msg_and_die("setpriority(%d)", prio);
397                 }
398         }
399 #endif
400         execv(startas, argv);
401         bb_perror_msg_and_die("cannot start %s", startas);
402 }