start-stop-daemon.c 16 KB

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