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