start_stop_daemon.c 12 KB

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