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