start-stop-daemon.c 16 KB

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