source: MondoRescue/branches/3.2/mindi-busybox/debianutils/start_stop_daemon.c@ 3232

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