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