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