start-stop-daemon.c 16 KB

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