start_stop_daemon.c 17 KB

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