start_stop_daemon.c 15 KB

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