start-stop-daemon.c 15 KB

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