stty: fix bb_common_bufsiz1 use in NOEXEC
[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 source tree.
9  */
10
11 /*
12 This is how it is supposed to work:
13
14 start-stop-daemon [OPTIONS] [--start|--stop] [[--] arguments...]
15
16 One (only) of these must be given:
17         -S,--start              Start
18         -K,--stop               Stop
19
20 Search for matching processes.
21 If --stop is given, stop all matching processes (by sending a signal).
22 If --start is given, start a new process unless a matching process was found.
23
24 Options controlling process matching
25 (if multiple conditions are specified, all must match):
26         -u,--user USERNAME|UID  Only consider this user's processes
27         -n,--name PROCESS_NAME  Look for processes by matching PROCESS_NAME
28                                 with comm field in /proc/$PID/stat.
29                                 Only basename is compared:
30                                 "ntpd" == "./ntpd" == "/path/to/ntpd".
31 [TODO: can PROCESS_NAME be a full pathname? Should we require full match then
32 with /proc/$PID/exe or argv[0] (comm can't be matched, it never contains path)]
33         -x,--exec EXECUTABLE    Look for processes that were started with this
34                                 command in /proc/$PID/exe and /proc/$PID/cmdline
35                                 (/proc/$PID/cmdline is a bbox extension)
36                                 Unlike -n, we match against the full path:
37                                 "ntpd" != "./ntpd" != "/path/to/ntpd"
38         -p,--pidfile PID_FILE   Look for processes with PID from this file
39
40 Options which are valid for --start only:
41         -x,--exec EXECUTABLE    Program to run (1st arg of execvp). Mandatory.
42         -a,--startas NAME       argv[0] (defaults to EXECUTABLE)
43         -b,--background         Put process into background
44         -N,--nicelevel N        Add N to process' nice level
45         -c,--chuid USER[:[GRP]] Change to specified user [and group]
46         -m,--make-pidfile       Write PID to the pidfile
47                                 (both -m and -p must be given!)
48
49 Options which are valid for --stop only:
50         -s,--signal SIG         Signal to send (default:TERM)
51         -t,--test               Exit with status 0 if process is found
52                                 (we don't actually start or stop daemons)
53
54 Misc options:
55         -o,--oknodo             Exit with status 0 if nothing is done
56         -q,--quiet              Quiet
57         -v,--verbose            Verbose
58 */
59 //config:config START_STOP_DAEMON
60 //config:       bool "start-stop-daemon (12 kb)"
61 //config:       default y
62 //config:       help
63 //config:       start-stop-daemon is used to control the creation and
64 //config:       termination of system-level processes, usually the ones
65 //config:       started during the startup of the system.
66 //config:
67 //config:config FEATURE_START_STOP_DAEMON_LONG_OPTIONS
68 //config:       bool "Enable long options"
69 //config:       default y
70 //config:       depends on START_STOP_DAEMON && LONG_OPTS
71 //config:
72 //config:config FEATURE_START_STOP_DAEMON_FANCY
73 //config:       bool "Support additional arguments"
74 //config:       default y
75 //config:       depends on START_STOP_DAEMON
76 //config:       help
77 //config:       -o|--oknodo ignored since we exit with 0 anyway
78 //config:       -v|--verbose
79 //config:       -N|--nicelevel N
80
81 //applet:IF_START_STOP_DAEMON(APPLET_ODDNAME(start-stop-daemon, start_stop_daemon, BB_DIR_SBIN, BB_SUID_DROP, start_stop_daemon))
82 /* not NOEXEC: uses bb_common_bufsiz1 */
83
84 //kbuild:lib-$(CONFIG_START_STOP_DAEMON) += start_stop_daemon.o
85
86 //usage:#define start_stop_daemon_trivial_usage
87 //usage:       "[OPTIONS] [-S|-K] ... [-- ARGS...]"
88 //usage:#define start_stop_daemon_full_usage "\n\n"
89 //usage:       "Search for matching processes, and then\n"
90 //usage:       "-K: stop all matching processes.\n"
91 //usage:       "-S: start a process unless a matching process is found.\n"
92 //usage:        IF_FEATURE_START_STOP_DAEMON_LONG_OPTIONS(
93 //usage:     "\nProcess matching:"
94 //usage:     "\n        -u,--user USERNAME|UID  Match only this user's processes"
95 //usage:     "\n        -n,--name NAME          Match processes with NAME"
96 //usage:     "\n                                in comm field in /proc/PID/stat"
97 //usage:     "\n        -x,--exec EXECUTABLE    Match processes with this command"
98 //usage:     "\n                                in /proc/PID/{exe,cmdline}"
99 //usage:     "\n        -p,--pidfile FILE       Match a process with PID from the file"
100 //usage:     "\n        All specified conditions must match"
101 //usage:     "\n-S only:"
102 //usage:     "\n        -x,--exec EXECUTABLE    Program to run"
103 //usage:     "\n        -a,--startas NAME       Zeroth argument"
104 //usage:     "\n        -b,--background         Background"
105 //usage:        IF_FEATURE_START_STOP_DAEMON_FANCY(
106 //usage:     "\n        -N,--nicelevel N        Change nice level"
107 //usage:        )
108 //usage:     "\n        -c,--chuid USER[:[GRP]] Change to user/group"
109 //usage:     "\n        -m,--make-pidfile       Write PID to the pidfile specified by -p"
110 //usage:     "\n-K only:"
111 //usage:     "\n        -s,--signal SIG         Signal to send"
112 //usage:     "\n        -t,--test               Match only, exit with 0 if a process is found"
113 //usage:     "\nOther:"
114 //usage:        IF_FEATURE_START_STOP_DAEMON_FANCY(
115 //usage:     "\n        -o,--oknodo             Exit with status 0 if nothing is done"
116 //usage:     "\n        -v,--verbose            Verbose"
117 //usage:        )
118 //usage:     "\n        -q,--quiet              Quiet"
119 //usage:        )
120 //usage:        IF_NOT_FEATURE_START_STOP_DAEMON_LONG_OPTIONS(
121 //usage:     "\nProcess matching:"
122 //usage:     "\n        -u USERNAME|UID Match only this user's processes"
123 //usage:     "\n        -n NAME         Match processes with NAME"
124 //usage:     "\n                        in comm field in /proc/PID/stat"
125 //usage:     "\n        -x EXECUTABLE   Match processes with this command"
126 //usage:     "\n                        command in /proc/PID/cmdline"
127 //usage:     "\n        -p FILE         Match a process with PID from the file"
128 //usage:     "\n        All specified conditions must match"
129 //usage:     "\n-S only:"
130 //usage:     "\n        -x EXECUTABLE   Program to run"
131 //usage:     "\n        -a NAME         Zeroth argument"
132 //usage:     "\n        -b              Background"
133 //usage:        IF_FEATURE_START_STOP_DAEMON_FANCY(
134 //usage:     "\n        -N N            Change nice level"
135 //usage:        )
136 //usage:     "\n        -c USER[:[GRP]] Change to user/group"
137 //usage:     "\n        -m              Write PID to the pidfile specified by -p"
138 //usage:     "\n-K only:"
139 //usage:     "\n        -s SIG          Signal to send"
140 //usage:     "\n        -t              Match only, exit with 0 if a process is found"
141 //usage:     "\nOther:"
142 //usage:        IF_FEATURE_START_STOP_DAEMON_FANCY(
143 //usage:     "\n        -o              Exit with status 0 if nothing is done"
144 //usage:     "\n        -v              Verbose"
145 //usage:        )
146 //usage:     "\n        -q              Quiet"
147 //usage:        )
148
149 #include <sys/resource.h>
150
151 /* Override ENABLE_FEATURE_PIDFILE */
152 #define WANT_PIDFILE 1
153 #include "libbb.h"
154 #include "common_bufsiz.h"
155
156 struct pid_list {
157         struct pid_list *next;
158         pid_t pid;
159 };
160
161 enum {
162         CTX_STOP       = (1 <<  0),
163         CTX_START      = (1 <<  1),
164         OPT_BACKGROUND = (1 <<  2), // -b
165         OPT_QUIET      = (1 <<  3), // -q
166         OPT_TEST       = (1 <<  4), // -t
167         OPT_MAKEPID    = (1 <<  5), // -m
168         OPT_a          = (1 <<  6), // -a
169         OPT_n          = (1 <<  7), // -n
170         OPT_s          = (1 <<  8), // -s
171         OPT_u          = (1 <<  9), // -u
172         OPT_c          = (1 << 10), // -c
173         OPT_x          = (1 << 11), // -x
174         OPT_p          = (1 << 12), // -p
175         OPT_OKNODO     = (1 << 13) * ENABLE_FEATURE_START_STOP_DAEMON_FANCY, // -o
176         OPT_VERBOSE    = (1 << 14) * ENABLE_FEATURE_START_STOP_DAEMON_FANCY, // -v
177         OPT_NICELEVEL  = (1 << 15) * ENABLE_FEATURE_START_STOP_DAEMON_FANCY, // -N
178 };
179 #define QUIET (option_mask32 & OPT_QUIET)
180 #define TEST  (option_mask32 & OPT_TEST)
181
182 struct globals {
183         struct pid_list *found_procs;
184         char *userspec;
185         char *cmdname;
186         char *execname;
187         char *pidfile;
188         char *execname_cmpbuf;
189         unsigned execname_sizeof;
190         int user_id;
191         smallint signal_nr;
192 } FIX_ALIASING;
193 #define G (*(struct globals*)bb_common_bufsiz1)
194 #define userspec          (G.userspec            )
195 #define cmdname           (G.cmdname             )
196 #define execname          (G.execname            )
197 #define pidfile           (G.pidfile             )
198 #define user_id           (G.user_id             )
199 #define signal_nr         (G.signal_nr           )
200 #define INIT_G() do { \
201         setup_common_bufsiz(); \
202         user_id = -1; \
203         signal_nr = 15; \
204 } while (0)
205
206 #ifdef OLDER_VERSION_OF_X
207 /* -x,--exec EXECUTABLE
208  * Look for processes with matching /proc/$PID/exe.
209  * Match is performed using device+inode.
210  */
211 static int pid_is_exec(pid_t pid)
212 {
213         struct stat st;
214         char buf[sizeof("/proc/%u/exe") + sizeof(int)*3];
215
216         sprintf(buf, "/proc/%u/exe", (unsigned)pid);
217         if (stat(buf, &st) < 0)
218                 return 0;
219         if (st.st_dev == execstat.st_dev
220          && st.st_ino == execstat.st_ino)
221                 return 1;
222         return 0;
223 }
224 #endif
225
226 static int pid_is_exec(pid_t pid)
227 {
228         ssize_t bytes;
229         char buf[sizeof("/proc/%u/cmdline") + sizeof(int)*3];
230         char *procname, *exelink;
231         int match;
232
233         procname = buf + sprintf(buf, "/proc/%u/exe", (unsigned)pid) - 3;
234
235         exelink = xmalloc_readlink(buf);
236         match = (exelink && strcmp(execname, exelink) == 0);
237         free(exelink);
238         if (match)
239                 return match;
240
241         strcpy(procname, "cmdline");
242         bytes = open_read_close(buf, G.execname_cmpbuf, G.execname_sizeof);
243         if (bytes > 0) {
244                 G.execname_cmpbuf[bytes] = '\0';
245                 return strcmp(execname, G.execname_cmpbuf) == 0;
246         }
247         return 0;
248 }
249
250 static int pid_is_name(pid_t pid)
251 {
252         /* /proc/PID/stat is "PID (comm_15_bytes_max) ..." */
253         char buf[32]; /* should be enough */
254         char *p, *pe;
255
256         sprintf(buf, "/proc/%u/stat", (unsigned)pid);
257         if (open_read_close(buf, buf, sizeof(buf) - 1) < 0)
258                 return 0;
259         buf[sizeof(buf) - 1] = '\0'; /* paranoia */
260         p = strchr(buf, '(');
261         if (!p)
262                 return 0;
263         pe = strrchr(++p, ')');
264         if (!pe)
265                 return 0;
266         *pe = '\0';
267         /* we require comm to match and to not be truncated */
268         /* in Linux, if comm is 15 chars, it may be a truncated
269          * name, so we don't allow that to match */
270         if (strlen(p) >= COMM_LEN - 1) /* COMM_LEN is 16 */
271                 return 0;
272         return strcmp(p, cmdname) == 0;
273 }
274
275 static int pid_is_user(int pid)
276 {
277         struct stat sb;
278         char buf[sizeof("/proc/") + sizeof(int)*3];
279
280         sprintf(buf, "/proc/%u", (unsigned)pid);
281         if (stat(buf, &sb) != 0)
282                 return 0;
283         return (sb.st_uid == (uid_t)user_id);
284 }
285
286 static void check(int pid)
287 {
288         struct pid_list *p;
289
290         if (execname && !pid_is_exec(pid)) {
291                 return;
292         }
293         if (cmdname && !pid_is_name(pid)) {
294                 return;
295         }
296         if (userspec && !pid_is_user(pid)) {
297                 return;
298         }
299         p = xmalloc(sizeof(*p));
300         p->next = G.found_procs;
301         p->pid = pid;
302         G.found_procs = p;
303 }
304
305 static void do_pidfile(void)
306 {
307         FILE *f;
308         unsigned pid;
309
310         f = fopen_for_read(pidfile);
311         if (f) {
312                 if (fscanf(f, "%u", &pid) == 1)
313                         check(pid);
314                 fclose(f);
315         } else if (errno != ENOENT)
316                 bb_perror_msg_and_die("open pidfile %s", pidfile);
317 }
318
319 static void do_procinit(void)
320 {
321         DIR *procdir;
322         struct dirent *entry;
323         int pid;
324
325         if (pidfile) {
326                 do_pidfile();
327                 return;
328         }
329
330         procdir = xopendir("/proc");
331
332         pid = 0;
333         while (1) {
334                 errno = 0; /* clear any previous error */
335                 entry = readdir(procdir);
336 // TODO: this check is too generic, it's better
337 // to check for exact errno(s) which mean that we got stale entry
338                 if (errno) /* Stale entry, process has died after opendir */
339                         continue;
340                 if (!entry) /* EOF, no more entries */
341                         break;
342                 pid = bb_strtou(entry->d_name, NULL, 10);
343                 if (errno) /* NaN */
344                         continue;
345                 check(pid);
346         }
347         closedir(procdir);
348         if (!pid)
349                 bb_error_msg_and_die("nothing in /proc - not mounted?");
350 }
351
352 static int do_stop(void)
353 {
354         char *what;
355         struct pid_list *p;
356         int killed = 0;
357
358         if (cmdname) {
359                 if (ENABLE_FEATURE_CLEAN_UP) what = xstrdup(cmdname);
360                 if (!ENABLE_FEATURE_CLEAN_UP) what = cmdname;
361         } else if (execname) {
362                 if (ENABLE_FEATURE_CLEAN_UP) what = xstrdup(execname);
363                 if (!ENABLE_FEATURE_CLEAN_UP) what = execname;
364         } else if (pidfile) {
365                 what = xasprintf("process in pidfile '%s'", pidfile);
366         } else if (userspec) {
367                 what = xasprintf("process(es) owned by '%s'", userspec);
368         } else {
369                 bb_error_msg_and_die("internal error, please report");
370         }
371
372         if (!G.found_procs) {
373                 if (!QUIET)
374                         printf("no %s found; none killed\n", what);
375                 killed = -1;
376                 goto ret;
377         }
378         for (p = G.found_procs; p; p = p->next) {
379                 if (kill(p->pid, TEST ? 0 : signal_nr) == 0) {
380                         killed++;
381                 } else {
382                         bb_perror_msg("warning: killing process %u", (unsigned)p->pid);
383                         p->pid = 0;
384                         if (TEST) {
385                                 /* Example: -K --test --pidfile PIDFILE detected
386                                  * that PIDFILE's pid doesn't exist */
387                                 killed = -1;
388                                 goto ret;
389                         }
390                 }
391         }
392         if (!QUIET && killed) {
393                 printf("stopped %s (pid", what);
394                 for (p = G.found_procs; p; p = p->next)
395                         if (p->pid)
396                                 printf(" %u", (unsigned)p->pid);
397                 puts(")");
398         }
399  ret:
400         if (ENABLE_FEATURE_CLEAN_UP)
401                 free(what);
402         return killed;
403 }
404
405 #if ENABLE_FEATURE_START_STOP_DAEMON_LONG_OPTIONS
406 static const char start_stop_daemon_longopts[] ALIGN1 =
407         "stop\0"         No_argument       "K"
408         "start\0"        No_argument       "S"
409         "background\0"   No_argument       "b"
410         "quiet\0"        No_argument       "q"
411         "test\0"         No_argument       "t"
412         "make-pidfile\0" No_argument       "m"
413 # if ENABLE_FEATURE_START_STOP_DAEMON_FANCY
414         "oknodo\0"       No_argument       "o"
415         "verbose\0"      No_argument       "v"
416         "nicelevel\0"    Required_argument "N"
417 # endif
418         "startas\0"      Required_argument "a"
419         "name\0"         Required_argument "n"
420         "signal\0"       Required_argument "s"
421         "user\0"         Required_argument "u"
422         "chuid\0"        Required_argument "c"
423         "exec\0"         Required_argument "x"
424         "pidfile\0"      Required_argument "p"
425 # if ENABLE_FEATURE_START_STOP_DAEMON_FANCY
426         "retry\0"        Required_argument "R"
427 # endif
428         ;
429 #endif
430
431 int start_stop_daemon_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
432 int start_stop_daemon_main(int argc UNUSED_PARAM, char **argv)
433 {
434         unsigned opt;
435         char *signame;
436         char *startas;
437         char *chuid;
438 #ifdef OLDER_VERSION_OF_X
439         struct stat execstat;
440 #endif
441 #if ENABLE_FEATURE_START_STOP_DAEMON_FANCY
442 //      char *retry_arg = NULL;
443 //      int retries = -1;
444         char *opt_N;
445 #endif
446
447         INIT_G();
448
449 #if ENABLE_FEATURE_START_STOP_DAEMON_LONG_OPTIONS
450         applet_long_options = start_stop_daemon_longopts;
451 #endif
452
453         /* -K or -S is required; they are mutually exclusive */
454         /* -p is required if -m is given */
455         /* -xpun (at least one) is required if -K is given */
456         /* -xa (at least one) is required if -S is given */
457         /* -q turns off -v */
458         opt_complementary = "K:S:K--S:S--K:m?p:K?xpun:S?xa"
459                 IF_FEATURE_START_STOP_DAEMON_FANCY("q-v");
460         opt = getopt32(argv, "KSbqtma:n:s:u:c:x:p:"
461                 IF_FEATURE_START_STOP_DAEMON_FANCY("ovN:R:"),
462                 &startas, &cmdname, &signame, &userspec, &chuid, &execname, &pidfile
463                 IF_FEATURE_START_STOP_DAEMON_FANCY(,&opt_N)
464                 /* We accept and ignore -R <param> / --retry <param> */
465                 IF_FEATURE_START_STOP_DAEMON_FANCY(,NULL)
466         );
467
468         if (opt & OPT_s) {
469                 signal_nr = get_signum(signame);
470                 if (signal_nr < 0) bb_show_usage();
471         }
472
473         if (!(opt & OPT_a))
474                 startas = execname;
475         if (!execname) /* in case -a is given and -x is not */
476                 execname = startas;
477         if (execname) {
478                 G.execname_sizeof = strlen(execname) + 1;
479                 G.execname_cmpbuf = xmalloc(G.execname_sizeof + 1);
480         }
481
482 //      IF_FEATURE_START_STOP_DAEMON_FANCY(
483 //              if (retry_arg)
484 //                      retries = xatoi_positive(retry_arg);
485 //      )
486         //argc -= optind;
487         argv += optind;
488
489         if (userspec) {
490                 user_id = bb_strtou(userspec, NULL, 10);
491                 if (errno)
492                         user_id = xuname2uid(userspec);
493         }
494         /* Both start and stop need to know current processes */
495         do_procinit();
496
497         if (opt & CTX_STOP) {
498                 int i = do_stop();
499                 return (opt & OPT_OKNODO) ? 0 : (i <= 0);
500         }
501
502         if (G.found_procs) {
503                 if (!QUIET)
504                         printf("%s is already running\n%u\n", execname, (unsigned)G.found_procs->pid);
505                 return !(opt & OPT_OKNODO);
506         }
507
508 #ifdef OLDER_VERSION_OF_X
509         if (execname)
510                 xstat(execname, &execstat);
511 #endif
512
513         *--argv = startas;
514         if (opt & OPT_BACKGROUND) {
515 #if BB_MMU
516                 bb_daemonize(DAEMON_DEVNULL_STDIO + DAEMON_CLOSE_EXTRA_FDS + DAEMON_DOUBLE_FORK);
517                 /* DAEMON_DEVNULL_STDIO is superfluous -
518                  * it's always done by bb_daemonize() */
519 #else
520                 /* Daemons usually call bb_daemonize_or_rexec(), but SSD can do
521                  * without: SSD is not itself a daemon, it _execs_ a daemon.
522                  * The usual NOMMU problem of "child can't run indefinitely,
523                  * it must exec" does not bite us: we exec anyway.
524                  */
525                 pid_t pid = xvfork();
526                 if (pid != 0) {
527                         /* parent */
528                         /* why _exit? the child may have changed the stack,
529                          * so "return 0" may do bad things */
530                         _exit(EXIT_SUCCESS);
531                 }
532                 /* Child */
533                 setsid(); /* detach from controlling tty */
534                 /* Redirect stdio to /dev/null, close extra FDs */
535                 bb_daemon_helper(DAEMON_DEVNULL_STDIO + DAEMON_CLOSE_EXTRA_FDS);
536 #endif
537         }
538         if (opt & OPT_MAKEPID) {
539                 /* User wants _us_ to make the pidfile */
540                 write_pidfile(pidfile);
541         }
542         if (opt & OPT_c) {
543                 struct bb_uidgid_t ugid;
544                 parse_chown_usergroup_or_die(&ugid, chuid);
545                 if (ugid.uid != (uid_t) -1L) {
546                         struct passwd *pw = xgetpwuid(ugid.uid);
547                         if (ugid.gid != (gid_t) -1L)
548                                 pw->pw_gid = ugid.gid;
549                         /* initgroups, setgid, setuid: */
550                         change_identity(pw);
551                 } else if (ugid.gid != (gid_t) -1L) {
552                         xsetgid(ugid.gid);
553                         setgroups(1, &ugid.gid);
554                 }
555         }
556 #if ENABLE_FEATURE_START_STOP_DAEMON_FANCY
557         if (opt & OPT_NICELEVEL) {
558                 /* Set process priority */
559                 int prio = getpriority(PRIO_PROCESS, 0) + xatoi_range(opt_N, INT_MIN/2, INT_MAX/2);
560                 if (setpriority(PRIO_PROCESS, 0, prio) < 0) {
561                         bb_perror_msg_and_die("setpriority(%d)", prio);
562                 }
563         }
564 #endif
565         execvp(startas, argv);
566         bb_perror_msg_and_die("can't execute '%s'", startas);
567 }