9150763cbd4ef19b59478314b7a6c6f5c47caf03
[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 tarball for details.
9  */
10
11 /* NB: we have a problem here with /proc/NN/exe usage, similar to
12  * one fixed in killall/pidof */
13
14 #include <sys/resource.h>
15
16 /* Override ENABLE_FEATURE_PIDFILE */
17 #define WANT_PIDFILE 1
18 #include "libbb.h"
19
20 struct pid_list {
21         struct pid_list *next;
22         pid_t pid;
23 };
24
25
26 struct globals {
27         struct pid_list *found;
28         char *userspec;
29         char *cmdname;
30         char *execname;
31         char *pidfile;
32         int user_id;
33         smallint quiet;
34         smallint signal_nr;
35 };
36 #define G (*(struct globals*)&bb_common_bufsiz1)
37 #define found             (G.found               )
38 #define userspec          (G.userspec            )
39 #define cmdname           (G.cmdname             )
40 #define execname          (G.execname            )
41 #define pidfile           (G.pidfile             )
42 #define user_id           (G.user_id             )
43 #define quiet             (G.quiet               )
44 #define signal_nr         (G.signal_nr           )
45 #define INIT_G() \
46         do { \
47                 user_id = -1; \
48                 signal_nr = 15; \
49         } while (0)
50
51
52 static int pid_is_exec(pid_t pid)
53 {
54         struct stat st, execstat;
55         char buf[sizeof("/proc//exe") + sizeof(int)*3];
56
57         sprintf(buf, "/proc/%u/exe", pid);
58         if (stat(buf, &st) < 0)
59                 return 0;
60         xstat(execname, &execstat);
61         if (st.st_dev == execstat.st_dev
62          && st.st_ino == execstat.st_ino)
63                 return 1;
64         return 0;
65 }
66
67 static int pid_is_user(int pid)
68 {
69         struct stat sb;
70         char buf[sizeof("/proc/") + sizeof(int)*3];
71
72         sprintf(buf, "/proc/%u", pid);
73         if (stat(buf, &sb) != 0)
74                 return 0;
75         return (sb.st_uid == user_id);
76 }
77
78 static int pid_is_cmd(pid_t pid)
79 {
80         char buf[256]; /* is it big enough? */
81         char *p, *pe;
82
83         sprintf(buf, "/proc/%u/stat", pid);
84         if (open_read_close(buf, buf, sizeof(buf) - 1) < 0)
85                 return 0;
86         buf[sizeof(buf) - 1] = '\0'; /* paranoia */
87         p = strchr(buf, '(');
88         if (!p)
89                 return 0;
90         pe = strrchr(++p, ')');
91         if (!pe)
92                 return 0;
93         *pe = '\0';
94         return !strcmp(p, cmdname);
95 }
96
97 static void check(int pid)
98 {
99         struct pid_list *p;
100
101         if (execname && !pid_is_exec(pid)) {
102                 return;
103         }
104         if (userspec && !pid_is_user(pid)) {
105                 return;
106         }
107         if (cmdname && !pid_is_cmd(pid)) {
108                 return;
109         }
110         p = xmalloc(sizeof(*p));
111         p->next = found;
112         p->pid = pid;
113         found = p;
114 }
115
116 static void do_pidfile(void)
117 {
118         FILE *f;
119         unsigned pid;
120
121         f = fopen(pidfile, "r");
122         if (f) {
123                 if (fscanf(f, "%u", &pid) == 1)
124                         check(pid);
125                 fclose(f);
126         } else if (errno != ENOENT)
127                 bb_perror_msg_and_die("open pidfile %s", pidfile);
128 }
129
130 static void do_procinit(void)
131 {
132         DIR *procdir;
133         struct dirent *entry;
134         int pid;
135
136         if (pidfile) {
137                 do_pidfile();
138                 return;
139         }
140
141         procdir = xopendir("/proc");
142
143         pid = 0;
144         while(1) {
145                 errno = 0; /* clear any previous error */
146                 entry = readdir(procdir);
147 // TODO: check for exact errno(s) which mean that we got stale entry
148                 if (errno) /* Stale entry, process has died after opendir */
149                         continue;
150                 if (!entry) /* EOF, no more entries */
151                         break;
152                 pid = bb_strtou(entry->d_name, NULL, 10);
153                 if (errno) /* NaN */
154                         continue;
155                 check(pid);
156         }
157         closedir(procdir);
158         if (!pid)
159                 bb_error_msg_and_die("nothing in /proc - not mounted?");
160 }
161
162 static int do_stop(void)
163 {
164         char *what;
165         struct pid_list *p;
166         int killed = 0;
167
168         if (cmdname) {
169                 if (ENABLE_FEATURE_CLEAN_UP) what = xstrdup(cmdname);
170                 if (!ENABLE_FEATURE_CLEAN_UP) what = cmdname;
171         } else if (execname) {
172                 if (ENABLE_FEATURE_CLEAN_UP) what = xstrdup(execname);
173                 if (!ENABLE_FEATURE_CLEAN_UP) what = execname;
174         } else if (pidfile)
175                 what = xasprintf("process in pidfile '%s'", pidfile);
176         else if (userspec)
177                 what = xasprintf("process(es) owned by '%s'", userspec);
178         else
179                 bb_error_msg_and_die("internal error, please report");
180
181         if (!found) {
182                 if (!quiet)
183                         printf("no %s found; none killed\n", what);
184                 killed = -1;
185                 goto ret;
186         }
187         for (p = found; p; p = p->next) {
188                 if (kill(p->pid, signal_nr) == 0) {
189                         p->pid = - p->pid;
190                         killed++;
191                 } else {
192                         bb_perror_msg("warning: killing process %u", p->pid);
193                 }
194         }
195         if (!quiet && killed) {
196                 printf("stopped %s (pid", what);
197                 for (p = found; p; p = p->next)
198                         if (p->pid < 0)
199                                 printf(" %u", - p->pid);
200                 puts(")");
201         }
202  ret:
203         if (ENABLE_FEATURE_CLEAN_UP)
204                 free(what);
205         return killed;
206 }
207
208 #if ENABLE_FEATURE_START_STOP_DAEMON_LONG_OPTIONS
209 static const char start_stop_daemon_longopts[] ALIGN1 =
210         "stop\0"         No_argument       "K"
211         "start\0"        No_argument       "S"
212         "background\0"   No_argument       "b"
213         "quiet\0"        No_argument       "q"
214         "make-pidfile\0" No_argument       "m"
215 #if ENABLE_FEATURE_START_STOP_DAEMON_FANCY
216         "oknodo\0"       No_argument       "o"
217         "verbose\0"      No_argument       "v"
218         "nicelevel\0"    Required_argument "N"
219 #endif
220         "startas\0"      Required_argument "a"
221         "name\0"         Required_argument "n"
222         "signal\0"       Required_argument "s"
223         "user\0"         Required_argument "u"
224         "chuid\0"        Required_argument "c"
225         "exec\0"         Required_argument "x"
226         "pidfile\0"      Required_argument "p"
227 #if ENABLE_FEATURE_START_STOP_DAEMON_FANCY
228         "retry\0"        Required_argument "R"
229 #endif
230         ;
231 #endif
232
233 enum {
234         CTX_STOP       = 0x1,
235         CTX_START      = 0x2,
236         OPT_BACKGROUND = 0x4, // -b
237         OPT_QUIET      = 0x8, // -q
238         OPT_MAKEPID    = 0x10, // -m
239         OPT_a          = 0x20, // -a
240         OPT_n          = 0x40, // -n
241         OPT_s          = 0x80, // -s
242         OPT_u          = 0x100, // -u
243         OPT_c          = 0x200, // -c
244         OPT_x          = 0x400, // -x
245         OPT_p          = 0x800, // -p
246         OPT_OKNODO     = 0x1000 * ENABLE_FEATURE_START_STOP_DAEMON_FANCY, // -o
247         OPT_VERBOSE    = 0x2000 * ENABLE_FEATURE_START_STOP_DAEMON_FANCY, // -v
248         OPT_NICELEVEL  = 0x4000 * ENABLE_FEATURE_START_STOP_DAEMON_FANCY, // -N
249 };
250
251 int start_stop_daemon_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
252 int start_stop_daemon_main(int argc ATTRIBUTE_UNUSED, char **argv)
253 {
254         unsigned opt;
255         char *signame;
256         char *startas;
257         char *chuid;
258 #if ENABLE_FEATURE_START_STOP_DAEMON_FANCY
259 //      char *retry_arg = NULL;
260 //      int retries = -1;
261         char *opt_N;
262 #endif
263
264         INIT_G();
265
266 #if ENABLE_FEATURE_START_STOP_DAEMON_LONG_OPTIONS
267         applet_long_options = start_stop_daemon_longopts;
268 #endif
269
270         /* Check required one context option was given */
271         opt_complementary = "K:S:K--S:S--K:m?p:K?xpun:S?xa";
272         opt = getopt32(argv, "KSbqma:n:s:u:c:x:p:"
273                 USE_FEATURE_START_STOP_DAEMON_FANCY("ovN:"),
274 //              USE_FEATURE_START_STOP_DAEMON_FANCY("ovN:R:"),
275                 &startas, &cmdname, &signame, &userspec, &chuid, &execname, &pidfile
276                 USE_FEATURE_START_STOP_DAEMON_FANCY(,&opt_N)
277 //              USE_FEATURE_START_STOP_DAEMON_FANCY(,&retry_arg)
278         );
279
280         quiet = (opt & OPT_QUIET) && !(opt & OPT_VERBOSE);
281
282         if (opt & OPT_s) {
283                 signal_nr = get_signum(signame);
284                 if (signal_nr < 0) bb_show_usage();
285         }
286
287         if (!(opt & OPT_a))
288                 startas = execname;
289
290 //      USE_FEATURE_START_STOP_DAEMON_FANCY(
291 //              if (retry_arg)
292 //                      retries = xatoi_u(retry_arg);
293 //      )
294         //argc -= optind;
295         argv += optind;
296
297         if (userspec) {
298                 user_id = bb_strtou(userspec, NULL, 10);
299                 if (errno)
300                         user_id = xuname2uid(userspec);
301         }
302
303         do_procinit(); /* Both start and stop needs to know current processes */
304
305         if (opt & CTX_STOP) {
306                 int i = do_stop();
307                 return (opt & OPT_OKNODO) ? 0 : (i <= 0);
308         }
309
310         if (found) {
311                 if (!quiet)
312                         printf("%s already running\n%d\n", execname, found->pid);
313                 return !(opt & OPT_OKNODO);
314         }
315         *--argv = startas;
316         if (opt & OPT_BACKGROUND) {
317 #if BB_MMU
318                 bb_daemonize(0);
319 #else
320                 pid_t pid = vfork();
321                 if (pid < 0) /* error */
322                         bb_perror_msg_and_die("vfork");
323                 if (pid != 0) {
324                         /* parent */
325                         /* why _exit? the child may have changed the stack,
326                          * so "return 0" may do bad things */
327                         _exit(0);
328                 }
329                 /* child */
330                 setsid(); /* detach from controlling tty */
331                 /* Redirect stdio to /dev/null, close extra FDs.
332                  * We do not actually daemonize because of DAEMON_ONLY_SANITIZE */
333                 bb_daemonize_or_rexec(
334                         DAEMON_DEVNULL_STDIO
335                         + DAEMON_CLOSE_EXTRA_FDS
336                         + DAEMON_ONLY_SANITIZE,
337                         NULL /* argv, unused */ );
338 #endif
339         }
340         if (opt & OPT_MAKEPID) {
341                 /* user wants _us_ to make the pidfile */
342                 write_pidfile(pidfile);
343         }
344         if (opt & OPT_c) {
345                 struct bb_uidgid_t ugid;
346                 parse_chown_usergroup_or_die(&ugid, chuid);
347                 if (ugid.gid != (gid_t) -1) xsetgid(ugid.gid);
348                 if (ugid.uid != (uid_t) -1) xsetuid(ugid.uid);
349         }
350 #if ENABLE_FEATURE_START_STOP_DAEMON_FANCY
351         if (opt & OPT_NICELEVEL) {
352                 /* Set process priority */
353                 int prio = getpriority(PRIO_PROCESS, 0) + xatoi_range(opt_N, INT_MIN/2, INT_MAX/2);
354                 if (setpriority(PRIO_PROCESS, 0, prio) < 0) {
355                         bb_perror_msg_and_die("setpriority(%d)", prio);
356                 }
357         }
358 #endif
359         execv(startas, argv);
360         bb_perror_msg_and_die("cannot start %s", startas);
361 }