start_stop_daemon.c 17 KB

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