start-stop-daemon.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720
  1. /*
  2. * A rewrite of the original Debian's start-stop-daemon Perl script
  3. * in C (faster - it is executed many times during system startup).
  4. *
  5. * Written by Marek Michalkiewicz <marekm@i17linuxb.ists.pwr.wroc.pl>,
  6. * public domain. Based conceptually on start-stop-daemon.pl, by Ian
  7. * Jackson <ijackson@gnu.ai.mit.edu>. May be used and distributed
  8. * freely for any purpose. Changes by Christian Schwarz
  9. * <schwarz@monet.m.isar.de>, to make output conform to the Debian
  10. * Console Message Standard, also placed in public domain. Minor
  11. * changes by Klee Dienes <klee@debian.org>, also placed in the Public
  12. * Domain.
  13. *
  14. * Changes by Ben Collins <bcollins@debian.org>, added --chuid, --background
  15. * and --make-pidfile options, placed in public domain aswell.
  16. */
  17. #include "config.h"
  18. #if defined(linux)
  19. #define OSLinux
  20. #elif defined(__GNU__)
  21. #define OSHURD
  22. #elif defined(__sparc__)
  23. #define OSsunos
  24. #else
  25. #error Unknown architecture - cannot build start-stop-daemon
  26. #endif
  27. #ifdef HAVE_HURH_H
  28. #include <hurd.h>
  29. #endif
  30. #ifdef HAVE_PS_H
  31. #include <ps.h>
  32. #endif
  33. #include <errno.h>
  34. #include <stdio.h>
  35. #include <stdlib.h>
  36. #include <string.h>
  37. #include <stdarg.h>
  38. #include <signal.h>
  39. #include <sys/stat.h>
  40. #include <dirent.h>
  41. #include <unistd.h>
  42. #include <getopt.h>
  43. #include <pwd.h>
  44. #include <grp.h>
  45. #include <sys/ioctl.h>
  46. #include <sys/types.h>
  47. #include <sys/termios.h>
  48. #include <fcntl.h>
  49. #ifdef HAVE_ERROR_H
  50. #include <error.h>
  51. #endif
  52. #ifdef HURD_IHASH_H
  53. #include <hurd/ihash.h>
  54. #endif
  55. static int testmode = 0;
  56. static int quietmode = 0;
  57. static int exitnodo = 1;
  58. static int start = 0;
  59. static int stop = 0;
  60. static int background = 0;
  61. static int mpidfile = 0;
  62. static int signal_nr = 15;
  63. static const char *signal_str = NULL;
  64. static int user_id = -1;
  65. static int runas_uid = -1;
  66. static int runas_gid = -1;
  67. static const char *userspec = NULL;
  68. static char *changeuser = NULL;
  69. static char *changegroup = NULL;
  70. static char *changeroot = NULL;
  71. static const char *cmdname = NULL;
  72. static char *execname = NULL;
  73. static char *startas = NULL;
  74. static const char *pidfile = NULL;
  75. static const char *progname = "";
  76. static struct stat exec_stat;
  77. #if defined(OSHURD)
  78. static struct ps_context *context;
  79. static struct proc_stat_list *procset;
  80. #endif
  81. struct pid_list {
  82. struct pid_list *next;
  83. int pid;
  84. };
  85. static struct pid_list *found = NULL;
  86. static struct pid_list *killed = NULL;
  87. static void *xmalloc(int size);
  88. static void push(struct pid_list **list, int pid);
  89. static void do_help(void);
  90. static void parse_options(int argc, char * const *argv);
  91. static int pid_is_user(int pid, int uid);
  92. static int pid_is_cmd(int pid, const char *name);
  93. static void check(int pid);
  94. static void do_pidfile(const char *name);
  95. static int do_stop(void);
  96. #if defined(OSLinux)
  97. static int pid_is_exec(int pid, const struct stat *esb);
  98. #endif
  99. static void do_psinit(void);
  100. #ifdef __GNUC__
  101. static void fatal(const char *format, ...)
  102. __attribute__((noreturn, format(printf, 1, 2)));
  103. static void badusage(const char *msg)
  104. __attribute__((noreturn));
  105. #else
  106. static void fatal(const char *format, ...);
  107. static void badusage(const char *msg);
  108. #endif
  109. static void
  110. fatal(const char *format, ...)
  111. {
  112. va_list arglist;
  113. fprintf(stderr, "%s: ", progname);
  114. va_start(arglist, format);
  115. vfprintf(stderr, format, arglist);
  116. va_end(arglist);
  117. putc('\n', stderr);
  118. exit(2);
  119. }
  120. static void *
  121. xmalloc(int size)
  122. {
  123. void *ptr;
  124. ptr = malloc(size);
  125. if (ptr)
  126. return ptr;
  127. fatal("malloc(%d) failed", size);
  128. }
  129. static void
  130. push(struct pid_list **list, int pid)
  131. {
  132. struct pid_list *p;
  133. p = xmalloc(sizeof(*p));
  134. p->next = *list;
  135. p->pid = pid;
  136. *list = p;
  137. }
  138. static void
  139. do_help(void)
  140. {
  141. printf("\
  142. start-stop-daemon for Debian GNU/Linux - small and fast C version written by\n\
  143. Marek Michalkiewicz <marekm@i17linuxb.ists.pwr.wroc.pl>, public domain.\n"
  144. VERSION "\n\
  145. \n\
  146. Usage:
  147. start-stop-daemon -S|--start options ... -- arguments ...\n\
  148. start-stop-daemon -K|--stop options ...\n\
  149. start-stop-daemon -H|--help\n\
  150. start-stop-daemon -V|--version\n\
  151. \n\
  152. Options (at least one of --exec|--pidfile|--user is required):
  153. -x|--exec <executable> program to start/check if it is running\n\
  154. -p|--pidfile <pid-file> pid file to check\n\
  155. -c|--chuid <name|uid[:group|gid]>
  156. change to this user/group before starting process\n\
  157. -u|--user <username>|<uid> stop processes owned by this user\n\
  158. -n|--name <process-name> stop processes with this name\n\
  159. -s|--signal <signal> signal to send (default TERM)\n\
  160. -a|--startas <pathname> program to start (default is <executable>)\n\
  161. -b|--background force the process to detach\n\
  162. -m|--make-pidfile create the pidfile before starting\n\
  163. -t|--test test mode, don't do anything\n\
  164. -o|--oknodo exit status 0 (not 1) if nothing done\n\
  165. -q|--quiet be more quiet\n\
  166. -v|--verbose be more verbose\n\
  167. \n\
  168. Exit status: 0 = done 1 = nothing done (=> 0 if --oknodo) 2 = trouble\n");
  169. }
  170. static void
  171. badusage(const char *msg)
  172. {
  173. if (msg)
  174. fprintf(stderr, "%s: %s\n", progname, msg);
  175. fprintf(stderr, "Try `%s --help' for more information.\n", progname);
  176. exit(2);
  177. }
  178. struct sigpair {
  179. const char *name;
  180. int signal;
  181. };
  182. const struct sigpair siglist[] = {
  183. { "ABRT", SIGABRT },
  184. { "ALRM", SIGALRM },
  185. { "FPE", SIGFPE },
  186. { "HUP", SIGHUP },
  187. { "ILL", SIGILL },
  188. { "INT", SIGINT },
  189. { "KILL", SIGKILL },
  190. { "PIPE", SIGPIPE },
  191. { "QUIT", SIGQUIT },
  192. { "SEGV", SIGSEGV },
  193. { "TERM", SIGTERM },
  194. { "USR1", SIGUSR1 },
  195. { "USR2", SIGUSR2 },
  196. { "CHLD", SIGCHLD },
  197. { "CONT", SIGCONT },
  198. { "STOP", SIGSTOP },
  199. { "TSTP", SIGTSTP },
  200. { "TTIN", SIGTTIN },
  201. { "TTOU", SIGTTOU }
  202. };
  203. static int parse_signal (const char *signal_str, int *signal_nr)
  204. {
  205. int i;
  206. for (i = 0; i < sizeof (siglist) / sizeof (siglist[0]); i++) {
  207. if (strcmp (signal_str, siglist[i].name) == 0) {
  208. *signal_nr = siglist[i].signal;
  209. return 0;
  210. }
  211. }
  212. return -1;
  213. }
  214. static void
  215. parse_options(int argc, char * const *argv)
  216. {
  217. static struct option longopts[] = {
  218. { "help", 0, NULL, 'H'},
  219. { "stop", 0, NULL, 'K'},
  220. { "start", 0, NULL, 'S'},
  221. { "version", 0, NULL, 'V'},
  222. { "startas", 1, NULL, 'a'},
  223. { "name", 1, NULL, 'n'},
  224. { "oknodo", 0, NULL, 'o'},
  225. { "pidfile", 1, NULL, 'p'},
  226. { "quiet", 0, NULL, 'q'},
  227. { "signal", 1, NULL, 's'},
  228. { "test", 0, NULL, 't'},
  229. { "user", 1, NULL, 'u'},
  230. { "chroot", 1, NULL, 'r'},
  231. { "verbose", 0, NULL, 'v'},
  232. { "exec", 1, NULL, 'x'},
  233. { "chuid", 1, NULL, 'c'},
  234. { "background", 0, NULL, 'b'},
  235. { "make-pidfile", 0, NULL, 'm'},
  236. { NULL, 0, NULL, 0}
  237. };
  238. int c;
  239. for (;;) {
  240. c = getopt_long(argc, argv, "HKSVa:n:op:qr:s:tu:vx:c:bm",
  241. longopts, (int *) 0);
  242. if (c == -1)
  243. break;
  244. switch (c) {
  245. case 'H': /* --help */
  246. do_help();
  247. exit(0);
  248. case 'K': /* --stop */
  249. stop = 1;
  250. break;
  251. case 'S': /* --start */
  252. start = 1;
  253. break;
  254. case 'V': /* --version */
  255. printf("start-stop-daemon " VERSION "\n");
  256. exit(0);
  257. case 'a': /* --startas <pathname> */
  258. startas = optarg;
  259. break;
  260. case 'n': /* --name <process-name> */
  261. cmdname = optarg;
  262. break;
  263. case 'o': /* --oknodo */
  264. exitnodo = 0;
  265. break;
  266. case 'p': /* --pidfile <pid-file> */
  267. pidfile = optarg;
  268. break;
  269. case 'q': /* --quiet */
  270. quietmode = 1;
  271. break;
  272. case 's': /* --signal <signal> */
  273. signal_str = optarg;
  274. break;
  275. case 't': /* --test */
  276. testmode = 1;
  277. break;
  278. case 'u': /* --user <username>|<uid> */
  279. userspec = optarg;
  280. break;
  281. case 'v': /* --verbose */
  282. quietmode = -1;
  283. break;
  284. case 'x': /* --exec <executable> */
  285. execname = optarg;
  286. break;
  287. case 'c': /* --chuid <username>|<uid> */
  288. /* we copy the string just in case we need the
  289. * argument later. */
  290. changeuser = strdup(optarg);
  291. changeuser = strtok(changeuser, ":");
  292. changegroup = strtok(NULL, ":");
  293. break;
  294. case 'r': /* --chroot /new/root */
  295. changeroot = optarg;
  296. break;
  297. case 'b': /* --background */
  298. background = 1;
  299. break;
  300. case 'm': /* --make-pidfile */
  301. mpidfile = 1;
  302. break;
  303. default:
  304. badusage(NULL); /* message printed by getopt */
  305. }
  306. }
  307. if (signal_str != NULL) {
  308. if (sscanf (signal_str, "%d", &signal_nr) != 1) {
  309. if (parse_signal (signal_str, &signal_nr) != 0) {
  310. badusage ("--signal takes a numeric argument or name of signal (KILL, INTR, ...)");
  311. }
  312. }
  313. }
  314. if (start == stop)
  315. badusage("need one of --start or --stop");
  316. if (!execname && !pidfile && !userspec)
  317. badusage("need at least one of --exec, --pidfile or --user");
  318. if (!startas)
  319. startas = execname;
  320. if (start && !startas)
  321. badusage("--start needs --exec or --startas");
  322. if (mpidfile && pidfile == NULL)
  323. badusage("--make-pidfile is only relevant with --pidfile");
  324. if (background && !start)
  325. badusage("--background is only relevant with --start");
  326. }
  327. #if defined(OSLinux)
  328. static int
  329. pid_is_exec(int pid, const struct stat *esb)
  330. {
  331. struct stat sb;
  332. char buf[32];
  333. sprintf(buf, "/proc/%d/exe", pid);
  334. if (stat(buf, &sb) != 0)
  335. return 0;
  336. return (sb.st_dev == esb->st_dev && sb.st_ino == esb->st_ino);
  337. }
  338. static int
  339. pid_is_user(int pid, int uid)
  340. {
  341. struct stat sb;
  342. char buf[32];
  343. sprintf(buf, "/proc/%d", pid);
  344. if (stat(buf, &sb) != 0)
  345. return 0;
  346. return (sb.st_uid == uid);
  347. }
  348. static int
  349. pid_is_cmd(int pid, const char *name)
  350. {
  351. char buf[32];
  352. FILE *f;
  353. int c;
  354. sprintf(buf, "/proc/%d/stat", pid);
  355. f = fopen(buf, "r");
  356. if (!f)
  357. return 0;
  358. while ((c = getc(f)) != EOF && c != '(')
  359. ;
  360. if (c != '(') {
  361. fclose(f);
  362. return 0;
  363. }
  364. /* this hopefully handles command names containing ')' */
  365. while ((c = getc(f)) != EOF && c == *name)
  366. name++;
  367. fclose(f);
  368. return (c == ')' && *name == '\0');
  369. }
  370. #endif /* OSLinux */
  371. #if defined(OSHURD)
  372. static int
  373. pid_is_user(int pid, int uid)
  374. {
  375. struct stat sb;
  376. char buf[32];
  377. struct proc_stat *pstat;
  378. sprintf(buf, "/proc/%d", pid);
  379. if (stat(buf, &sb) != 0)
  380. return 0;
  381. return (sb.st_uid == uid);
  382. pstat = proc_stat_list_pid_proc_stat (procset, pid);
  383. if (pstat == NULL)
  384. fatal ("Error getting process information: NULL proc_stat struct");
  385. proc_stat_set_flags (pstat, PSTAT_PID | PSTAT_OWNER_UID);
  386. return (pstat->owner_uid == uid);
  387. }
  388. static int
  389. pid_is_cmd(int pid, const char *name)
  390. {
  391. struct proc_stat *pstat;
  392. pstat = proc_stat_list_pid_proc_stat (procset, pid);
  393. if (pstat == NULL)
  394. fatal ("Error getting process information: NULL proc_stat struct");
  395. proc_stat_set_flags (pstat, PSTAT_PID | PSTAT_ARGS);
  396. return (!strcmp (name, pstat->args));
  397. }
  398. #endif /* OSHURD */
  399. static void
  400. check(int pid)
  401. {
  402. #if defined(OSLinux)
  403. if (execname && !pid_is_exec(pid, &exec_stat))
  404. #elif defined(OSHURD)
  405. /* I will try this to see if it works */
  406. if (execname && !pid_is_cmd(pid, execname))
  407. #endif
  408. return;
  409. if (userspec && !pid_is_user(pid, user_id))
  410. return;
  411. if (cmdname && !pid_is_cmd(pid, cmdname))
  412. return;
  413. push(&found, pid);
  414. }
  415. static void
  416. do_pidfile(const char *name)
  417. {
  418. FILE *f;
  419. int pid;
  420. f = fopen(name, "r");
  421. if (f) {
  422. if (fscanf(f, "%d", &pid) == 1)
  423. check(pid);
  424. fclose(f);
  425. }
  426. }
  427. /* WTA: this needs to be an autoconf check for /proc/pid existance.
  428. */
  429. #if defined(OSLinux) || defined (OSsunos)
  430. static void
  431. do_procinit(void)
  432. {
  433. DIR *procdir;
  434. struct dirent *entry;
  435. int foundany, pid;
  436. procdir = opendir("/proc");
  437. if (!procdir)
  438. fatal("opendir /proc: %s", strerror(errno));
  439. foundany = 0;
  440. while ((entry = readdir(procdir)) != NULL) {
  441. if (sscanf(entry->d_name, "%d", &pid) != 1)
  442. continue;
  443. foundany++;
  444. check(pid);
  445. }
  446. closedir(procdir);
  447. if (!foundany)
  448. fatal("nothing in /proc - not mounted?");
  449. }
  450. #endif /* OSLinux */
  451. #if defined(OSHURD)
  452. error_t
  453. check_all (void *ptr)
  454. {
  455. struct proc_stat *pstat = ptr;
  456. check (pstat->pid);
  457. return (0);
  458. }
  459. static void
  460. do_psinit(void)
  461. error_t err;
  462. err = ps_context_create (getproc (), &context);
  463. if (err)
  464. error (1, err, "ps_context_create");
  465. err = proc_stat_list_create (context, &procset);
  466. if (err)
  467. error (1, err, "proc_stat_list_create");
  468. err = proc_stat_list_add_all (procset, 0, 0);
  469. if (err)
  470. error (1, err, "proc_stat_list_add_all");
  471. /* Check all pids */
  472. ihash_iterate (context->procs, check_all);
  473. }
  474. #endif /* OSHURD */
  475. /* return 1 on failure */
  476. static int
  477. do_stop(void)
  478. {
  479. char what[1024];
  480. struct pid_list *p;
  481. int retval = 0;
  482. if (cmdname)
  483. strcpy(what, cmdname);
  484. else if (execname)
  485. strcpy(what, execname);
  486. else if (pidfile)
  487. sprintf(what, "process in pidfile `%s'", pidfile);
  488. else if (userspec)
  489. sprintf(what, "process(es) owned by `%s'", userspec);
  490. else
  491. fatal("internal error, please report");
  492. if (!found) {
  493. if (quietmode <= 0)
  494. printf("No %s found running; none killed.\n", what);
  495. exit(exitnodo);
  496. }
  497. for (p = found; p; p = p->next) {
  498. if (testmode)
  499. printf("Would send signal %d to %d.\n",
  500. signal_nr, p->pid);
  501. else if (kill(p->pid, signal_nr) == 0)
  502. push(&killed, p->pid);
  503. else {
  504. printf("%s: warning: failed to kill %d: %s\n",
  505. progname, p->pid, strerror(errno));
  506. retval += exitnodo;
  507. }
  508. }
  509. if (quietmode < 0 && killed) {
  510. printf("Stopped %s (pid", what);
  511. for (p = killed; p; p = p->next)
  512. printf(" %d", p->pid);
  513. printf(").\n");
  514. }
  515. return retval;
  516. }
  517. int
  518. main(int argc, char **argv)
  519. {
  520. progname = argv[0];
  521. parse_options(argc, argv);
  522. argc -= optind;
  523. argv += optind;
  524. if (execname && stat(execname, &exec_stat))
  525. fatal("stat %s: %s", execname, strerror(errno));
  526. if (userspec && sscanf(userspec, "%d", &user_id) != 1) {
  527. struct passwd *pw;
  528. pw = getpwnam(userspec);
  529. if (!pw)
  530. fatal("user `%s' not found\n", userspec);
  531. user_id = pw->pw_uid;
  532. }
  533. if (changegroup && sscanf(changegroup, "%d", &runas_gid) != 1) {
  534. struct group *gr = getgrnam(changegroup);
  535. if (!gr)
  536. fatal("group `%s' not found\n", changegroup);
  537. runas_gid = gr->gr_gid;
  538. }
  539. if (changeuser && sscanf(changeuser, "%d", &runas_uid) != 1) {
  540. struct passwd *pw = getpwnam(changeuser);
  541. if (!pw)
  542. fatal("user `%s' not found\n", changeuser);
  543. runas_uid = pw->pw_uid;
  544. if (changegroup == NULL) { /* pass the default group of this user */
  545. changegroup = ""; /* just empty */
  546. runas_gid = pw->pw_gid;
  547. }
  548. }
  549. if (pidfile)
  550. do_pidfile(pidfile);
  551. else
  552. do_procinit();
  553. if (stop) {
  554. int i = do_stop();
  555. if (i) {
  556. if (quietmode <= 0)
  557. printf("%d pids were not killed\n", i);
  558. exit(1);
  559. }
  560. exit(0);
  561. }
  562. if (found) {
  563. if (quietmode <= 0)
  564. printf("%s already running.\n", execname);
  565. exit(exitnodo);
  566. }
  567. if (testmode) {
  568. printf("Would start %s ", startas);
  569. while (argc-- > 0)
  570. printf("%s ", *argv++);
  571. if (changeuser != NULL) {
  572. printf(" (as user %s[%d]", changeuser, runas_uid);
  573. if (changegroup != NULL)
  574. printf(", and group %s[%d])", changegroup, runas_gid);
  575. else
  576. printf(")");
  577. }
  578. if (changeroot != NULL)
  579. printf(" in directory %s", changeroot);
  580. printf(".\n");
  581. exit(0);
  582. }
  583. if (quietmode < 0)
  584. printf("Starting %s...\n", startas);
  585. *--argv = startas;
  586. if (changeroot != NULL) {
  587. if (chdir(changeroot) < 0)
  588. fatal("Unable to chdir() to %s", changeroot);
  589. if (chroot(changeroot) < 0)
  590. fatal("Unable to chroot() to %s", changeroot);
  591. }
  592. if (changeuser != NULL) {
  593. if (setgid(runas_gid))
  594. fatal("Unable to set gid to %d", runas_gid);
  595. if (initgroups(changeuser, runas_gid))
  596. fatal("Unable to set initgroups() with gid %d", runas_gid);
  597. if (setuid(runas_uid))
  598. fatal("Unable to set uid to %s", changeuser);
  599. }
  600. if (background) { /* ok, we need to detach this process */
  601. int i, fd;
  602. if (quietmode < 0)
  603. printf("Detatching to start %s...", startas);
  604. i = fork();
  605. if (i<0) {
  606. fatal("Unable to fork.\n");
  607. }
  608. if (i) { /* parent */
  609. if (quietmode < 0)
  610. printf("done.\n");
  611. exit(0);
  612. }
  613. /* child continues here */
  614. /* now close all extra fds */
  615. for (i=getdtablesize()-1; i>=0; --i) close(i);
  616. /* change tty */
  617. fd = open("/dev/tty", O_RDWR);
  618. ioctl(fd, TIOCNOTTY, 0);
  619. close(fd);
  620. chdir("/");
  621. umask(022); /* set a default for dumb programs */
  622. setpgrp(); /* set the process group */
  623. fd=open("/dev/null", O_RDWR); /* stdin */
  624. dup(fd); /* stdout */
  625. dup(fd); /* stderr */
  626. }
  627. if (mpidfile && pidfile != NULL) { /* user wants _us_ to make the pidfile :) */
  628. FILE *pidf = fopen(pidfile, "w");
  629. pid_t pidt = getpid();
  630. if (pidf == NULL)
  631. fatal("Unable to open pidfile `%s' for writing: %s", pidfile,
  632. strerror(errno));
  633. fprintf(pidf, "%d\n", pidt);
  634. fclose(pidf);
  635. }
  636. execv(startas, argv);
  637. fatal("Unable to start %s: %s", startas, strerror(errno));
  638. }