start_stop_daemon.c 17 KB

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