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