start_stop_daemon.c 16 KB

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