start-stop-daemon: make --exec follow symlinks
[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, int uid)
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 == uid);
77 }
78
79 static int pid_is_cmd(pid_t pid, const char *name)
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, name);
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, user_id)) {
109                 return;
110         }
111         if (cmdname && !pid_is_cmd(pid, cmdname)) {
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 ((entry = readdir(procdir)) != NULL) {
149                 pid = bb_strtou(entry->d_name, NULL, 10);
150                 if (errno)
151                         continue;
152                 check(pid);
153         }
154         closedir(procdir);
155         if (!pid)
156                 bb_error_msg_and_die("nothing in /proc - not mounted?");
157 }
158
159 static int do_stop(void)
160 {
161         char *what;
162         struct pid_list *p;
163         int killed = 0;
164
165         do_procinit();
166
167         if (cmdname) {
168                 if (ENABLE_FEATURE_CLEAN_UP) what = xstrdup(cmdname);
169                 if (!ENABLE_FEATURE_CLEAN_UP) what = cmdname;
170         } else if (execname) {
171                 if (ENABLE_FEATURE_CLEAN_UP) what = xstrdup(execname);
172                 if (!ENABLE_FEATURE_CLEAN_UP) what = execname;
173         } else if (pidfile)
174                 what = xasprintf("process in pidfile '%s'", pidfile);
175         else if (userspec)
176                 what = xasprintf("process(es) owned by '%s'", userspec);
177         else
178                 bb_error_msg_and_die("internal error, please report");
179
180         if (!found) {
181                 if (!quiet)
182                         printf("no %s found; none killed\n", what);
183                 killed = -1;
184                 goto ret;
185         }
186         for (p = found; p; p = p->next) {
187                 if (kill(p->pid, signal_nr) == 0) {
188                         p->pid = - p->pid;
189                         killed++;
190                 } else {
191                         bb_perror_msg("warning: killing process %u", p->pid);
192                 }
193         }
194         if (!quiet && killed) {
195                 printf("stopped %s (pid", what);
196                 for (p = found; p; p = p->next)
197                         if (p->pid < 0)
198                                 printf(" %u", - p->pid);
199                 puts(")");
200         }
201  ret:
202         if (ENABLE_FEATURE_CLEAN_UP)
203                 free(what);
204         return killed;
205 }
206
207 #if ENABLE_FEATURE_START_STOP_DAEMON_LONG_OPTIONS
208 static const char start_stop_daemon_longopts[] ALIGN1 =
209         "stop\0"         No_argument       "K"
210         "start\0"        No_argument       "S"
211         "background\0"   No_argument       "b"
212         "quiet\0"        No_argument       "q"
213         "make-pidfile\0" No_argument       "m"
214 #if ENABLE_FEATURE_START_STOP_DAEMON_FANCY
215         "oknodo\0"       No_argument       "o"
216         "verbose\0"      No_argument       "v"
217         "nicelevel\0"    Required_argument "N"
218 #endif
219         "startas\0"      Required_argument "a"
220         "name\0"         Required_argument "n"
221         "signal\0"       Required_argument "s"
222         "user\0"         Required_argument "u"
223         "chuid\0"        Required_argument "c"
224         "exec\0"         Required_argument "x"
225         "pidfile\0"      Required_argument "p"
226 #if ENABLE_FEATURE_START_STOP_DAEMON_FANCY
227         "retry\0"        Required_argument "R"
228 #endif
229         ;
230 #endif
231
232 enum {
233         CTX_STOP       = 0x1,
234         CTX_START      = 0x2,
235         OPT_BACKGROUND = 0x4, // -b
236         OPT_QUIET      = 0x8, // -q
237         OPT_MAKEPID    = 0x10, // -m
238         OPT_a          = 0x20, // -a
239         OPT_n          = 0x40, // -n
240         OPT_s          = 0x80, // -s
241         OPT_u          = 0x100, // -u
242         OPT_c          = 0x200, // -c
243         OPT_x          = 0x400, // -x
244         OPT_p          = 0x800, // -p
245         OPT_OKNODO     = 0x1000 * ENABLE_FEATURE_START_STOP_DAEMON_FANCY, // -o
246         OPT_VERBOSE    = 0x2000 * ENABLE_FEATURE_START_STOP_DAEMON_FANCY, // -v
247         OPT_NICELEVEL  = 0x4000 * ENABLE_FEATURE_START_STOP_DAEMON_FANCY, // -N
248 };
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         /* Check required one context option was given */
270         opt_complementary = "K:S:K--S:S--K:m?p:K?xpun:S?xa";
271         opt = getopt32(argv, "KSbqma:n:s:u:c:x:p:"
272                 USE_FEATURE_START_STOP_DAEMON_FANCY("ovN:"),
273 //              USE_FEATURE_START_STOP_DAEMON_FANCY("ovN:R:"),
274                 &startas, &cmdname, &signame, &userspec, &chuid, &execname, &pidfile
275                 USE_FEATURE_START_STOP_DAEMON_FANCY(,&opt_N)
276 //              USE_FEATURE_START_STOP_DAEMON_FANCY(,&retry_arg)
277         );
278
279         quiet = (opt & OPT_QUIET) && !(opt & OPT_VERBOSE);
280
281         if (opt & OPT_s) {
282                 signal_nr = get_signum(signame);
283                 if (signal_nr < 0) bb_show_usage();
284         }
285
286         if (!(opt & OPT_a))
287                 startas = execname;
288
289 //      USE_FEATURE_START_STOP_DAEMON_FANCY(
290 //              if (retry_arg)
291 //                      retries = xatoi_u(retry_arg);
292 //      )
293         //argc -= optind;
294         argv += optind;
295
296         if (userspec) {
297                 user_id = bb_strtou(userspec, NULL, 10);
298                 if (errno)
299                         user_id = xuname2uid(userspec);
300         }
301         if (execname)
302                 xstat(execname, &execstat);
303
304         if (opt & CTX_STOP) {
305                 int i = do_stop();
306                 return (opt & OPT_OKNODO) ? 0 : (i <= 0);
307         }
308
309         do_procinit();
310
311         if (found) {
312                 if (!quiet)
313                         printf("%s already running\n%d\n", execname, found->pid);
314                 return !(opt & OPT_OKNODO);
315         }
316         *--argv = startas;
317         if (opt & OPT_BACKGROUND) {
318 #if BB_MMU
319                 bb_daemonize(0);
320 #else
321                 pid_t pid = vfork();
322                 if (pid < 0) /* error */
323                         bb_perror_msg_and_die("vfork");
324                 if (pid != 0) {
325                         /* parent */
326                         /* why _exit? the child may have changed the stack,
327                          * so "return 0" may do bad things */
328                         _exit(0);
329                 }
330                 /* child */
331                 setsid(); /* detach from controlling tty */
332                 /* Redirect stdio to /dev/null, close extra FDs.
333                  * We do not actually daemonize because of DAEMON_ONLY_SANITIZE */
334                 bb_daemonize_or_rexec(
335                         DAEMON_DEVNULL_STDIO
336                         + DAEMON_CLOSE_EXTRA_FDS
337                         + DAEMON_ONLY_SANITIZE,
338                         NULL /* argv, unused */ );
339 #endif
340         }
341         if (opt & OPT_MAKEPID) {
342                 /* user wants _us_ to make the pidfile */
343                 write_pidfile(pidfile);
344         }
345         if (opt & OPT_c) {
346                 struct bb_uidgid_t ugid;
347                 parse_chown_usergroup_or_die(&ugid, chuid);
348                 if (ugid.gid != (gid_t) -1) xsetgid(ugid.gid);
349                 if (ugid.uid != (uid_t) -1) xsetuid(ugid.uid);
350         }
351 #if ENABLE_FEATURE_START_STOP_DAEMON_FANCY
352         if (opt & OPT_NICELEVEL) {
353                 /* Set process priority */
354                 int prio = getpriority(PRIO_PROCESS, 0) + xatoi_range(opt_N, INT_MIN/2, INT_MAX/2);
355                 if (setpriority(PRIO_PROCESS, 0, prio) < 0) {
356                         bb_perror_msg_and_die("setpriority(%d)", prio);
357                 }
358         }
359 #endif
360         execv(startas, argv);
361         bb_perror_msg_and_die("cannot start %s", startas);
362 }