start_stop_daemon.c 16 KB

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