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