start-stop-daemon.c 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170
  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. * Port to OpenBSD by Sontri Tomo Huynh <huynh.29@osu.edu>
  18. * and Andreas Schuldei <andreas@schuldei.org>
  19. *
  20. * Changes by Ian Jackson: added --retry (and associated rearrangements).
  21. */
  22. #include "config.h"
  23. #if defined(linux)
  24. # define OSLinux
  25. #elif defined(__GNU__)
  26. # define OSHURD
  27. #elif defined(__sparc__)
  28. # define OSsunos
  29. #elif defined(OPENBSD)
  30. # define OSOpenBSD
  31. #else
  32. # error Unknown architecture - cannot build start-stop-daemon
  33. #endif
  34. #define MIN_POLL_INTERVAL 20000 /*us*/
  35. #if defined(OSHURD)
  36. # include <hurd.h>
  37. # include <ps.h>
  38. #endif
  39. #if defined(OSOpenBSD)
  40. #include <sys/param.h>
  41. #include <sys/user.h>
  42. #include <sys/proc.h>
  43. #include <sys/stat.h>
  44. #include <sys/sysctl.h>
  45. #include <sys/types.h>
  46. #include <err.h>
  47. #include <kvm.h>
  48. #include <limits.h>
  49. #endif
  50. #include <errno.h>
  51. #include <stdio.h>
  52. #include <stdlib.h>
  53. #include <string.h>
  54. #include <stdarg.h>
  55. #include <signal.h>
  56. #include <sys/stat.h>
  57. #include <dirent.h>
  58. #include <sys/time.h>
  59. #include <unistd.h>
  60. #include <getopt.h>
  61. #include <pwd.h>
  62. #include <grp.h>
  63. #include <sys/ioctl.h>
  64. #include <sys/types.h>
  65. #include <sys/termios.h>
  66. #include <fcntl.h>
  67. #include <limits.h>
  68. #include <assert.h>
  69. #include <ctype.h>
  70. #ifdef HAVE_ERROR_H
  71. # include <error.h>
  72. #endif
  73. #ifdef HURD_IHASH_H
  74. #include <hurd/ihash.h>
  75. #endif
  76. static int testmode = 0;
  77. static int quietmode = 0;
  78. static int exitnodo = 1;
  79. static int start = 0;
  80. static int stop = 0;
  81. static int background = 0;
  82. static int mpidfile = 0;
  83. static int signal_nr = 15;
  84. static const char *signal_str = NULL;
  85. static int user_id = -1;
  86. static int runas_uid = -1;
  87. static int runas_gid = -1;
  88. static const char *userspec = NULL;
  89. static char *changeuser = NULL;
  90. static const char *changegroup = NULL;
  91. static char *changeroot = NULL;
  92. static const char *cmdname = NULL;
  93. static char *execname = NULL;
  94. static char *startas = NULL;
  95. static const char *pidfile = NULL;
  96. static char what_stop[1024];
  97. static const char *schedule_str = NULL;
  98. static const char *progname = "";
  99. static int nicelevel = 0;
  100. static struct stat exec_stat;
  101. #if defined(OSHURD)
  102. static struct proc_stat_list *procset;
  103. #endif
  104. struct pid_list {
  105. struct pid_list *next;
  106. int pid;
  107. };
  108. static struct pid_list *found = NULL;
  109. static struct pid_list *killed = NULL;
  110. struct schedule_item {
  111. enum { sched_timeout, sched_signal, sched_goto, sched_forever } type;
  112. int value; /* seconds, signal no., or index into array */
  113. /* sched_forever is only seen within parse_schedule and callees */
  114. };
  115. static int schedule_length;
  116. static struct schedule_item *schedule = NULL;
  117. static void *xmalloc(int size);
  118. static void push(struct pid_list **list, int pid);
  119. static void do_help(void);
  120. static void parse_options(int argc, char * const *argv);
  121. static int pid_is_user(int pid, int uid);
  122. static int pid_is_cmd(int pid, const char *name);
  123. static void check(int pid);
  124. static void do_pidfile(const char *name);
  125. static void do_stop(int signal_nr, int quietmode,
  126. int *n_killed, int *n_notkilled, int retry_nr);
  127. #if defined(OSLinux)
  128. static int pid_is_exec(int pid, const struct stat *esb);
  129. #endif
  130. #ifdef __GNUC__
  131. static void fatal(const char *format, ...)
  132. __attribute__((noreturn, format(printf, 1, 2)));
  133. static void badusage(const char *msg)
  134. __attribute__((noreturn));
  135. #else
  136. static void fatal(const char *format, ...);
  137. static void badusage(const char *msg);
  138. #endif
  139. /* This next part serves only to construct the TVCALC macro, which
  140. * is used for doing arithmetic on struct timeval's. It works like this:
  141. * TVCALC(result, expression);
  142. * where result is a struct timeval (and must be an lvalue) and
  143. * expression is the single expression for both components. In this
  144. * expression you can use the special values TVELEM, which when fed a
  145. * const struct timeval* gives you the relevant component, and
  146. * TVADJUST. TVADJUST is necessary when subtracting timevals, to make
  147. * it easier to renormalise. Whenver you subtract timeval elements,
  148. * you must make sure that TVADJUST is added to the result of the
  149. * subtraction (before any resulting multiplication or what have you).
  150. * TVELEM must be linear in TVADJUST.
  151. */
  152. typedef long tvselector(const struct timeval*);
  153. static long tvselector_sec(const struct timeval *tv) { return tv->tv_sec; }
  154. static long tvselector_usec(const struct timeval *tv) { return tv->tv_usec; }
  155. #define TVCALC_ELEM(result, expr, sec, adj) \
  156. { \
  157. const long TVADJUST = adj; \
  158. long (*const TVELEM)(const struct timeval*) = tvselector_##sec; \
  159. (result).tv_##sec = (expr); \
  160. }
  161. #define TVCALC(result,expr) \
  162. do { \
  163. TVCALC_ELEM(result, expr, sec, (-1)); \
  164. TVCALC_ELEM(result, expr, usec, (+1000000)); \
  165. (result).tv_sec += (result).tv_usec / 1000000; \
  166. (result).tv_usec %= 1000000; \
  167. } while(0)
  168. static void
  169. fatal(const char *format, ...)
  170. {
  171. va_list arglist;
  172. fprintf(stderr, "%s: ", progname);
  173. va_start(arglist, format);
  174. vfprintf(stderr, format, arglist);
  175. va_end(arglist);
  176. putc('\n', stderr);
  177. exit(2);
  178. }
  179. static void *
  180. xmalloc(int size)
  181. {
  182. void *ptr;
  183. ptr = malloc(size);
  184. if (ptr)
  185. return ptr;
  186. fatal("malloc(%d) failed", size);
  187. }
  188. static void
  189. xgettimeofday(struct timeval *tv)
  190. {
  191. if (gettimeofday(tv,0) != 0)
  192. fatal("gettimeofday failed: %s", strerror(errno));
  193. }
  194. static void
  195. push(struct pid_list **list, int pid)
  196. {
  197. struct pid_list *p;
  198. p = xmalloc(sizeof(*p));
  199. p->next = *list;
  200. p->pid = pid;
  201. *list = p;
  202. }
  203. static void
  204. clear(struct pid_list **list)
  205. {
  206. struct pid_list *here, *next;
  207. for (here = *list; here != NULL; here = next) {
  208. next = here->next;
  209. free(here);
  210. }
  211. *list = NULL;
  212. }
  213. static void
  214. do_help(void)
  215. {
  216. printf("\
  217. start-stop-daemon for Debian GNU/Linux - small and fast C version written by\n\
  218. Marek Michalkiewicz <marekm@i17linuxb.ists.pwr.wroc.pl>, public domain.\n"
  219. VERSION "\n\
  220. \n\
  221. Usage:
  222. start-stop-daemon -S|--start options ... -- arguments ...\n\
  223. start-stop-daemon -K|--stop options ...\n\
  224. start-stop-daemon -H|--help\n\
  225. start-stop-daemon -V|--version\n\
  226. \n\
  227. Options (at least one of --exec|--pidfile|--user is required):
  228. -x|--exec <executable> program to start/check if it is running\n\
  229. -p|--pidfile <pid-file> pid file to check\n\
  230. -c|--chuid <name|uid[:group|gid]>
  231. change to this user/group before starting process\n\
  232. -u|--user <username>|<uid> stop processes owned by this user\n\
  233. -n|--name <process-name> stop processes with this name\n\
  234. -s|--signal <signal> signal to send (default TERM)\n\
  235. -a|--startas <pathname> program to start (default is <executable>)\n\
  236. -N|--nicelevel <incr> add incr to the process's nice level\n\
  237. -b|--background force the process to detach\n\
  238. -m|--make-pidfile create the pidfile before starting\n\
  239. -R|--retry <schedule> check whether processes die, and retry\n\
  240. -t|--test test mode, don't do anything\n\
  241. -o|--oknodo exit status 0 (not 1) if nothing done\n\
  242. -q|--quiet be more quiet\n\
  243. -v|--verbose be more verbose\n\
  244. Retry <schedule> is <item>|/<item>/... where <item> is one of
  245. -<signal-num>|[-]<signal-name> send that signal
  246. <timeout> wait that many seconds
  247. forever repeat remainder forever
  248. or <schedule> may be just <timeout>, meaning <signal>/<timeout>/KILL/<timeout>
  249. \n\
  250. Exit status: 0 = done 1 = nothing done (=> 0 if --oknodo)
  251. 3 = trouble 2 = with --retry, processes wouldn't die\n");
  252. }
  253. static void
  254. badusage(const char *msg)
  255. {
  256. if (msg)
  257. fprintf(stderr, "%s: %s\n", progname, msg);
  258. fprintf(stderr, "Try `%s --help' for more information.\n", progname);
  259. exit(3);
  260. }
  261. struct sigpair {
  262. const char *name;
  263. int signal;
  264. };
  265. const struct sigpair siglist[] = {
  266. { "ABRT", SIGABRT },
  267. { "ALRM", SIGALRM },
  268. { "FPE", SIGFPE },
  269. { "HUP", SIGHUP },
  270. { "ILL", SIGILL },
  271. { "INT", SIGINT },
  272. { "KILL", SIGKILL },
  273. { "PIPE", SIGPIPE },
  274. { "QUIT", SIGQUIT },
  275. { "SEGV", SIGSEGV },
  276. { "TERM", SIGTERM },
  277. { "USR1", SIGUSR1 },
  278. { "USR2", SIGUSR2 },
  279. { "CHLD", SIGCHLD },
  280. { "CONT", SIGCONT },
  281. { "STOP", SIGSTOP },
  282. { "TSTP", SIGTSTP },
  283. { "TTIN", SIGTTIN },
  284. { "TTOU", SIGTTOU }
  285. };
  286. static int parse_integer (const char *string, int *value_r) {
  287. unsigned long ul;
  288. char *ep;
  289. if (!string[0])
  290. return -1;
  291. ul= strtoul(string,&ep,10);
  292. if (ul > INT_MAX || *ep != '\0')
  293. return -1;
  294. *value_r= ul;
  295. return 0;
  296. }
  297. static int parse_signal (const char *signal_str, int *signal_nr)
  298. {
  299. int i;
  300. if (parse_integer(signal_str, signal_nr) == 0)
  301. return 0;
  302. for (i = 0; i < sizeof (siglist) / sizeof (siglist[0]); i++) {
  303. if (strcmp (signal_str, siglist[i].name) == 0) {
  304. *signal_nr = siglist[i].signal;
  305. return 0;
  306. }
  307. }
  308. return -1;
  309. }
  310. static void
  311. parse_schedule_item(const char *string, struct schedule_item *item) {
  312. const char *after_hyph;
  313. if (!strcmp(string,"forever")) {
  314. item->type = sched_forever;
  315. } else if (isdigit(string[0])) {
  316. item->type = sched_timeout;
  317. if (parse_integer(string, &item->value) != 0)
  318. badusage("invalid timeout value in schedule");
  319. } else if ((after_hyph = string + (string[0] == '-')) &&
  320. parse_signal(after_hyph, &item->value) == 0) {
  321. item->type = sched_signal;
  322. } else {
  323. badusage("invalid schedule item (must be [-]<signal-name>, "
  324. "-<signal-number>, <timeout> or `forever'");
  325. }
  326. }
  327. static void
  328. parse_schedule(const char *schedule_str) {
  329. char item_buf[20];
  330. const char *slash;
  331. int count, repeatat;
  332. ptrdiff_t str_len;
  333. count = 0;
  334. for (slash = schedule_str; *slash; slash++)
  335. if (*slash == '/')
  336. count++;
  337. schedule_length = (count == 0) ? 4 : count+1;
  338. schedule = xmalloc(sizeof(*schedule) * schedule_length);
  339. if (count == 0) {
  340. schedule[0].type = sched_signal;
  341. schedule[0].value = signal_nr;
  342. parse_schedule_item(schedule_str, &schedule[1]);
  343. if (schedule[1].type != sched_timeout) {
  344. badusage ("--retry takes timeout, or schedule list"
  345. " of at least two items");
  346. }
  347. schedule[2].type = sched_signal;
  348. schedule[2].value = SIGKILL;
  349. schedule[3]= schedule[1];
  350. } else {
  351. count = 0;
  352. repeatat = -1;
  353. while (schedule_str != NULL) {
  354. slash = strchr(schedule_str,'/');
  355. str_len = slash ? slash - schedule_str : strlen(schedule_str);
  356. if (str_len >= sizeof(item_buf))
  357. badusage("invalid schedule item: far too long"
  358. " (you must delimit items with slashes)");
  359. memcpy(item_buf, schedule_str, str_len);
  360. item_buf[str_len] = 0;
  361. schedule_str = slash ? slash+1 : NULL;
  362. parse_schedule_item(item_buf, &schedule[count]);
  363. if (schedule[count].type == sched_forever) {
  364. if (repeatat >= 0)
  365. badusage("invalid schedule: `forever'"
  366. " appears more than once");
  367. repeatat = count;
  368. continue;
  369. }
  370. count++;
  371. }
  372. if (repeatat >= 0) {
  373. schedule[count].type = sched_goto;
  374. schedule[count].value = repeatat;
  375. count++;
  376. }
  377. assert(count == schedule_length);
  378. }
  379. }
  380. static void
  381. parse_options(int argc, char * const *argv)
  382. {
  383. static struct option longopts[] = {
  384. { "help", 0, NULL, 'H'},
  385. { "stop", 0, NULL, 'K'},
  386. { "start", 0, NULL, 'S'},
  387. { "version", 0, NULL, 'V'},
  388. { "startas", 1, NULL, 'a'},
  389. { "name", 1, NULL, 'n'},
  390. { "oknodo", 0, NULL, 'o'},
  391. { "pidfile", 1, NULL, 'p'},
  392. { "quiet", 0, NULL, 'q'},
  393. { "signal", 1, NULL, 's'},
  394. { "test", 0, NULL, 't'},
  395. { "user", 1, NULL, 'u'},
  396. { "chroot", 1, NULL, 'r'},
  397. { "verbose", 0, NULL, 'v'},
  398. { "exec", 1, NULL, 'x'},
  399. { "chuid", 1, NULL, 'c'},
  400. { "nicelevel", 1, NULL, 'N'},
  401. { "background", 0, NULL, 'b'},
  402. { "make-pidfile", 0, NULL, 'm'},
  403. { "retry", 1, NULL, 'R'},
  404. { NULL, 0, NULL, 0}
  405. };
  406. int c;
  407. for (;;) {
  408. c = getopt_long(argc, argv, "HKSVa:n:op:qr:s:tu:vx:c:N:bmR:",
  409. longopts, (int *) 0);
  410. if (c == -1)
  411. break;
  412. switch (c) {
  413. case 'H': /* --help */
  414. do_help();
  415. exit(0);
  416. case 'K': /* --stop */
  417. stop = 1;
  418. break;
  419. case 'S': /* --start */
  420. start = 1;
  421. break;
  422. case 'V': /* --version */
  423. printf("start-stop-daemon " VERSION "\n");
  424. exit(0);
  425. case 'a': /* --startas <pathname> */
  426. startas = optarg;
  427. break;
  428. case 'n': /* --name <process-name> */
  429. cmdname = optarg;
  430. break;
  431. case 'o': /* --oknodo */
  432. exitnodo = 0;
  433. break;
  434. case 'p': /* --pidfile <pid-file> */
  435. pidfile = optarg;
  436. break;
  437. case 'q': /* --quiet */
  438. quietmode = 1;
  439. break;
  440. case 's': /* --signal <signal> */
  441. signal_str = optarg;
  442. break;
  443. case 't': /* --test */
  444. testmode = 1;
  445. break;
  446. case 'u': /* --user <username>|<uid> */
  447. userspec = optarg;
  448. break;
  449. case 'v': /* --verbose */
  450. quietmode = -1;
  451. break;
  452. case 'x': /* --exec <executable> */
  453. execname = optarg;
  454. break;
  455. case 'c': /* --chuid <username>|<uid> */
  456. /* we copy the string just in case we need the
  457. * argument later. */
  458. changeuser = strdup(optarg);
  459. changeuser = strtok(changeuser, ":");
  460. changegroup = strtok(NULL, ":");
  461. break;
  462. case 'r': /* --chroot /new/root */
  463. changeroot = optarg;
  464. break;
  465. case 'N': /* --nice */
  466. nicelevel = atoi(optarg);
  467. break;
  468. case 'b': /* --background */
  469. background = 1;
  470. break;
  471. case 'm': /* --make-pidfile */
  472. mpidfile = 1;
  473. break;
  474. case 'R': /* --retry <schedule>|<timeout> */
  475. schedule_str = optarg;
  476. break;
  477. default:
  478. badusage(NULL); /* message printed by getopt */
  479. }
  480. }
  481. if (signal_str != NULL) {
  482. if (parse_signal (signal_str, &signal_nr) != 0)
  483. badusage("signal value must be numeric or name"
  484. " of signal (KILL, INTR, ...)");
  485. }
  486. if (schedule_str != NULL) {
  487. parse_schedule(schedule_str);
  488. }
  489. if (start == stop)
  490. badusage("need one of --start or --stop");
  491. if (!execname && !pidfile && !userspec && !cmdname)
  492. badusage("need at least one of --exec, --pidfile, --user or --name");
  493. if (!startas)
  494. startas = execname;
  495. if (start && !startas)
  496. badusage("--start needs --exec or --startas");
  497. if (mpidfile && pidfile == NULL)
  498. badusage("--make-pidfile is only relevant with --pidfile");
  499. if (background && !start)
  500. badusage("--background is only relevant with --start");
  501. }
  502. #if defined(OSLinux)
  503. static int
  504. pid_is_exec(int pid, const struct stat *esb)
  505. {
  506. struct stat sb;
  507. char buf[32];
  508. sprintf(buf, "/proc/%d/exe", pid);
  509. if (stat(buf, &sb) != 0)
  510. return 0;
  511. return (sb.st_dev == esb->st_dev && sb.st_ino == esb->st_ino);
  512. }
  513. static int
  514. pid_is_user(int pid, int uid)
  515. {
  516. struct stat sb;
  517. char buf[32];
  518. sprintf(buf, "/proc/%d", pid);
  519. if (stat(buf, &sb) != 0)
  520. return 0;
  521. return (sb.st_uid == uid);
  522. }
  523. static int
  524. pid_is_cmd(int pid, const char *name)
  525. {
  526. char buf[32];
  527. FILE *f;
  528. int c;
  529. sprintf(buf, "/proc/%d/stat", pid);
  530. f = fopen(buf, "r");
  531. if (!f)
  532. return 0;
  533. while ((c = getc(f)) != EOF && c != '(')
  534. ;
  535. if (c != '(') {
  536. fclose(f);
  537. return 0;
  538. }
  539. /* this hopefully handles command names containing ')' */
  540. while ((c = getc(f)) != EOF && c == *name)
  541. name++;
  542. fclose(f);
  543. return (c == ')' && *name == '\0');
  544. }
  545. #endif /* OSLinux */
  546. #if defined(OSHURD)
  547. static int
  548. pid_is_user(int pid, int uid)
  549. {
  550. struct stat sb;
  551. char buf[32];
  552. struct proc_stat *pstat;
  553. sprintf(buf, "/proc/%d", pid);
  554. if (stat(buf, &sb) != 0)
  555. return 0;
  556. return (sb.st_uid == uid);
  557. pstat = proc_stat_list_pid_proc_stat (procset, pid);
  558. if (pstat == NULL)
  559. fatal ("Error getting process information: NULL proc_stat struct");
  560. proc_stat_set_flags (pstat, PSTAT_PID | PSTAT_OWNER_UID);
  561. return (pstat->owner_uid == uid);
  562. }
  563. static int
  564. pid_is_cmd(int pid, const char *name)
  565. {
  566. struct proc_stat *pstat;
  567. pstat = proc_stat_list_pid_proc_stat (procset, pid);
  568. if (pstat == NULL)
  569. fatal ("Error getting process information: NULL proc_stat struct");
  570. proc_stat_set_flags (pstat, PSTAT_PID | PSTAT_ARGS);
  571. return (!strcmp (name, pstat->args));
  572. }
  573. #endif /* OSHURD */
  574. static void
  575. check(int pid)
  576. {
  577. #if defined(OSLinux)
  578. if (execname && !pid_is_exec(pid, &exec_stat))
  579. #elif defined(OSHURD)
  580. /* I will try this to see if it works */
  581. if (execname && !pid_is_cmd(pid, execname))
  582. #endif
  583. return;
  584. if (userspec && !pid_is_user(pid, user_id))
  585. return;
  586. if (cmdname && !pid_is_cmd(pid, cmdname))
  587. return;
  588. push(&found, pid);
  589. }
  590. static void
  591. do_pidfile(const char *name)
  592. {
  593. FILE *f;
  594. int pid;
  595. f = fopen(name, "r");
  596. if (f) {
  597. if (fscanf(f, "%d", &pid) == 1)
  598. check(pid);
  599. fclose(f);
  600. } else if (errno != ENOENT)
  601. fatal("open pidfile %s: %s", name, strerror(errno));
  602. }
  603. /* WTA: this needs to be an autoconf check for /proc/pid existance.
  604. */
  605. #if defined(OSLinux) || defined (OSsunos)
  606. static void
  607. do_procinit(void)
  608. {
  609. DIR *procdir;
  610. struct dirent *entry;
  611. int foundany, pid;
  612. procdir = opendir("/proc");
  613. if (!procdir)
  614. fatal("opendir /proc: %s", strerror(errno));
  615. foundany = 0;
  616. while ((entry = readdir(procdir)) != NULL) {
  617. if (sscanf(entry->d_name, "%d", &pid) != 1)
  618. continue;
  619. foundany++;
  620. check(pid);
  621. }
  622. closedir(procdir);
  623. if (!foundany)
  624. fatal("nothing in /proc - not mounted?");
  625. }
  626. #endif /* OSLinux */
  627. #if defined(OSHURD)
  628. error_t
  629. check_all (void *ptr)
  630. {
  631. struct proc_stat *pstat = ptr;
  632. check (pstat->pid);
  633. return (0);
  634. }
  635. static void
  636. do_procinit(void)
  637. {
  638. struct ps_context *context;
  639. error_t err;
  640. err = ps_context_create (getproc (), &context);
  641. if (err)
  642. error (1, err, "ps_context_create");
  643. err = proc_stat_list_create (context, &procset);
  644. if (err)
  645. error (1, err, "proc_stat_list_create");
  646. err = proc_stat_list_add_all (procset, 0, 0);
  647. if (err)
  648. error (1, err, "proc_stat_list_add_all");
  649. /* Check all pids */
  650. ihash_iterate (context->procs, check_all);
  651. }
  652. #endif /* OSHURD */
  653. #if defined(OSOpenBSD)
  654. int
  655. pid_is_cmd(int pid, const char *name)
  656. {
  657. kvm_t *kd;
  658. int nentries, argv_len=0;
  659. struct kinfo_proc *kp;
  660. char errbuf[_POSIX2_LINE_MAX], buf[_POSIX2_LINE_MAX];
  661. char **pid_argv_p;
  662. char *start_argv_0_p, *end_argv_0_p;
  663. kd = kvm_openfiles(NULL, NULL, NULL, O_RDONLY, errbuf);
  664. if (kd == 0)
  665. errx(1, "%s", errbuf);
  666. if ((kp = kvm_getprocs(kd, KERN_PROC_PID, pid, &nentries)) == 0)
  667. errx(1, "%s", kvm_geterr(kd));
  668. if ( ( pid_argv_p = kvm_getargv(kd, kp, argv_len)) == 0)
  669. errx(1, "%s", kvm_geterr(kd));
  670. start_argv_0_p = *pid_argv_p;
  671. /* find and compare string */
  672. /* find end of argv[0] then copy and cut of str there. */
  673. if ( (end_argv_0_p = strchr(*pid_argv_p, ' ')) == 0 )
  674. /* There seems to be no space, so we have the command
  675. * allready in its desired form. */
  676. start_argv_0_p = *pid_argv_p;
  677. else {
  678. /* Tests indicate that this never happens, since
  679. * kvm_getargv itselfe cuts of tailing stuff. This is
  680. * not what the manpage says, however. */
  681. strncpy(buf, *pid_argv_p, (end_argv_0_p - start_argv_0_p));
  682. buf[(end_argv_0_p - start_argv_0_p) + 1] = '\0';
  683. start_argv_0_p = buf;
  684. }
  685. if (strlen(name) != strlen(start_argv_0_p))
  686. return 0;
  687. return (strcmp(name, start_argv_0_p) == 0) ? 1 : 0;
  688. }
  689. int
  690. pid_is_user(int pid, int uid)
  691. {
  692. kvm_t *kd;
  693. int nentries; /* Value not used */
  694. uid_t proc_uid;
  695. struct kinfo_proc *kp;
  696. char errbuf[_POSIX2_LINE_MAX];
  697. kd = kvm_openfiles(NULL, NULL, NULL, O_RDONLY, errbuf);
  698. if (kd == 0)
  699. errx(1, "%s", errbuf);
  700. if ((kp = kvm_getprocs(kd, KERN_PROC_PID, pid, &nentries)) == 0)
  701. errx(1, "%s", kvm_geterr(kd));
  702. if ( kp->kp_proc.p_cred )
  703. kvm_read(kd, (u_long)&(kp->kp_proc.p_cred->p_ruid),
  704. &proc_uid, sizeof(uid_t));
  705. else
  706. return 0;
  707. return (proc_uid == (uid_t)uid);
  708. }
  709. int
  710. pid_is_exec(int pid, const char *name)
  711. {
  712. kvm_t *kd;
  713. int nentries;
  714. struct kinfo_proc *kp;
  715. char errbuf[_POSIX2_LINE_MAX], *pidexec;
  716. kd = kvm_openfiles(NULL, NULL, NULL, O_RDONLY, errbuf);
  717. if (kd == 0)
  718. errx(1, "%s", errbuf);
  719. if ((kp = kvm_getprocs(kd, KERN_PROC_PID, pid, &nentries)) == 0)
  720. errx(1, "%s", kvm_geterr(kd));
  721. pidexec = (&kp->kp_proc)->p_comm;
  722. if (strlen(name) != strlen(pidexec))
  723. return 0;
  724. return (strcmp(name, pidexec) == 0) ? 1 : 0;
  725. }
  726. static void
  727. do_procinit(void)
  728. {
  729. /* Nothing to do */
  730. }
  731. #endif /* OSOpenBSD */
  732. static void
  733. do_findprocs(void)
  734. {
  735. clear(&found);
  736. if (pidfile)
  737. do_pidfile(pidfile);
  738. else
  739. do_procinit();
  740. }
  741. /* return 1 on failure */
  742. static void
  743. do_stop(int signal_nr, int quietmode, int *n_killed, int *n_notkilled, int retry_nr)
  744. {
  745. struct pid_list *p;
  746. do_findprocs();
  747. *n_killed = 0;
  748. *n_notkilled = 0;
  749. if (!found)
  750. return;
  751. clear(&killed);
  752. for (p = found; p; p = p->next) {
  753. if (testmode)
  754. printf("Would send signal %d to %d.\n",
  755. signal_nr, p->pid);
  756. else if (kill(p->pid, signal_nr) == 0) {
  757. push(&killed, p->pid);
  758. (*n_killed)++;
  759. } else {
  760. printf("%s: warning: failed to kill %d: %s\n",
  761. progname, p->pid, strerror(errno));
  762. (*n_notkilled)++;
  763. }
  764. }
  765. if (quietmode < 0 && killed) {
  766. printf("Stopped %s (pid", what_stop);
  767. for (p = killed; p; p = p->next)
  768. printf(" %d", p->pid);
  769. putchar(')');
  770. if (retry_nr > 0)
  771. printf(", retry #%d", retry_nr);
  772. printf(".\n");
  773. }
  774. }
  775. static void
  776. set_what_stop(const char *str)
  777. {
  778. strncpy(what_stop, str, sizeof(what_stop));
  779. what_stop[sizeof(what_stop)-1] = '\0';
  780. }
  781. static int
  782. run_stop_schedule(void)
  783. {
  784. int r, position, n_killed, n_notkilled, value, ratio, anykilled, retry_nr;
  785. struct timeval stopat, before, after, interval, maxinterval;
  786. if (testmode) {
  787. if (schedule != NULL) {
  788. printf("Ignoring --retry in test mode\n");
  789. schedule = NULL;
  790. }
  791. }
  792. if (cmdname)
  793. set_what_stop(cmdname);
  794. else if (execname)
  795. set_what_stop(execname);
  796. else if (pidfile)
  797. sprintf(what_stop, "process in pidfile `%.200s'", pidfile);
  798. else if (userspec)
  799. sprintf(what_stop, "process(es) owned by `%.200s'", userspec);
  800. else
  801. fatal("internal error, please report");
  802. anykilled = 0;
  803. retry_nr = 0;
  804. if (schedule == NULL) {
  805. do_stop(signal_nr, quietmode, &n_killed, &n_notkilled, 0);
  806. if (n_notkilled > 0 && quietmode <= 0)
  807. printf("%d pids were not killed\n", n_notkilled);
  808. if (n_killed)
  809. anykilled = 1;
  810. goto x_finished;
  811. }
  812. for (position = 0; position < schedule_length; ) {
  813. value= schedule[position].value;
  814. n_notkilled = 0;
  815. switch (schedule[position].type) {
  816. case sched_goto:
  817. position = value;
  818. continue;
  819. case sched_signal:
  820. do_stop(value, quietmode, &n_killed, &n_notkilled, retry_nr++);
  821. if (!n_killed)
  822. goto x_finished;
  823. else
  824. anykilled = 1;
  825. goto next_item;
  826. case sched_timeout:
  827. /* We want to keep polling for the processes, to see if they've exited,
  828. * or until the timeout expires.
  829. *
  830. * This is a somewhat complicated algorithm to try to ensure that we
  831. * notice reasonably quickly when all the processes have exited, but
  832. * don't spend too much CPU time polling. In particular, on a fast
  833. * machine with quick-exiting daemons we don't want to delay system
  834. * shutdown too much, whereas on a slow one, or where processes are
  835. * taking some time to exit, we want to increase the polling
  836. * interval.
  837. *
  838. * The algorithm is as follows: we measure the elapsed time it takes
  839. * to do one poll(), and wait a multiple of this time for the next
  840. * poll. However, if that would put us past the end of the timeout
  841. * period we wait only as long as the timeout period, but in any case
  842. * we always wait at least MIN_POLL_INTERVAL (20ms). The multiple
  843. * (`ratio') starts out as 2, and increases by 1 for each poll to a
  844. * maximum of 10; so we use up to between 30% and 10% of the
  845. * machine's resources (assuming a few reasonable things about system
  846. * performance).
  847. */
  848. xgettimeofday(&stopat);
  849. stopat.tv_sec += value;
  850. ratio = 1;
  851. for (;;) {
  852. xgettimeofday(&before);
  853. if (timercmp(&before,&stopat,>))
  854. goto next_item;
  855. do_stop(0, 1, &n_killed, &n_notkilled, 0);
  856. if (!n_killed)
  857. goto x_finished;
  858. xgettimeofday(&after);
  859. if (!timercmp(&after,&stopat,<))
  860. goto next_item;
  861. if (ratio < 10)
  862. ratio++;
  863. TVCALC(interval, ratio * (TVELEM(&after) - TVELEM(&before) + TVADJUST));
  864. TVCALC(maxinterval, TVELEM(&stopat) - TVELEM(&after) + TVADJUST);
  865. if (timercmp(&interval,&maxinterval,>))
  866. interval = maxinterval;
  867. if (interval.tv_sec == 0 &&
  868. interval.tv_usec <= MIN_POLL_INTERVAL)
  869. interval.tv_usec = MIN_POLL_INTERVAL;
  870. r = select(0,0,0,0,&interval);
  871. if (r < 0 && errno != EINTR)
  872. fatal("select() failed for pause: %s",
  873. strerror(errno));
  874. }
  875. default:
  876. assert(!"schedule[].type value must be valid");
  877. }
  878. next_item:
  879. position++;
  880. }
  881. if (quietmode <= 0)
  882. printf("Program %s, %d process(es), refused to die.\n",
  883. what_stop, n_killed);
  884. return 2;
  885. x_finished:
  886. if (!anykilled) {
  887. if (quietmode <= 0)
  888. printf("No %s found running; none killed.\n", what_stop);
  889. return exitnodo;
  890. } else {
  891. return 0;
  892. }
  893. }
  894. int
  895. main(int argc, char **argv)
  896. {
  897. progname = argv[0];
  898. parse_options(argc, argv);
  899. argc -= optind;
  900. argv += optind;
  901. if (execname && stat(execname, &exec_stat))
  902. fatal("stat %s: %s", execname, strerror(errno));
  903. if (userspec && sscanf(userspec, "%d", &user_id) != 1) {
  904. struct passwd *pw;
  905. pw = getpwnam(userspec);
  906. if (!pw)
  907. fatal("user `%s' not found\n", userspec);
  908. user_id = pw->pw_uid;
  909. }
  910. if (changegroup && sscanf(changegroup, "%d", &runas_gid) != 1) {
  911. struct group *gr = getgrnam(changegroup);
  912. if (!gr)
  913. fatal("group `%s' not found\n", changegroup);
  914. runas_gid = gr->gr_gid;
  915. }
  916. if (changeuser && sscanf(changeuser, "%d", &runas_uid) != 1) {
  917. struct passwd *pw = getpwnam(changeuser);
  918. if (!pw)
  919. fatal("user `%s' not found\n", changeuser);
  920. runas_uid = pw->pw_uid;
  921. if (changegroup == NULL) { /* pass the default group of this user */
  922. changegroup = ""; /* just empty */
  923. runas_gid = pw->pw_gid;
  924. }
  925. }
  926. if (stop) {
  927. int i = run_stop_schedule();
  928. exit(i);
  929. }
  930. do_findprocs();
  931. if (found) {
  932. if (quietmode <= 0)
  933. printf("%s already running.\n", execname);
  934. exit(exitnodo);
  935. }
  936. if (testmode) {
  937. printf("Would start %s ", startas);
  938. while (argc-- > 0)
  939. printf("%s ", *argv++);
  940. if (changeuser != NULL) {
  941. printf(" (as user %s[%d]", changeuser, runas_uid);
  942. if (changegroup != NULL)
  943. printf(", and group %s[%d])", changegroup, runas_gid);
  944. else
  945. printf(")");
  946. }
  947. if (changeroot != NULL)
  948. printf(" in directory %s", changeroot);
  949. if (nicelevel)
  950. printf(", and add %i to the priority", nicelevel);
  951. printf(".\n");
  952. exit(0);
  953. }
  954. if (quietmode < 0)
  955. printf("Starting %s...\n", startas);
  956. *--argv = startas;
  957. if (changeroot != NULL) {
  958. if (chdir(changeroot) < 0)
  959. fatal("Unable to chdir() to %s", changeroot);
  960. if (chroot(changeroot) < 0)
  961. fatal("Unable to chroot() to %s", changeroot);
  962. }
  963. if (changeuser != NULL) {
  964. if (setgid(runas_gid))
  965. fatal("Unable to set gid to %d", runas_gid);
  966. if (initgroups(changeuser, runas_gid))
  967. fatal("Unable to set initgroups() with gid %d", runas_gid);
  968. if (setuid(runas_uid))
  969. fatal("Unable to set uid to %s", changeuser);
  970. }
  971. if (background) { /* ok, we need to detach this process */
  972. int i, fd;
  973. if (quietmode < 0)
  974. printf("Detatching to start %s...", startas);
  975. i = fork();
  976. if (i<0) {
  977. fatal("Unable to fork.\n");
  978. }
  979. if (i) { /* parent */
  980. if (quietmode < 0)
  981. printf("done.\n");
  982. exit(0);
  983. }
  984. /* child continues here */
  985. /* now close all extra fds */
  986. for (i=getdtablesize()-1; i>=0; --i) close(i);
  987. /* change tty */
  988. fd = open("/dev/tty", O_RDWR);
  989. ioctl(fd, TIOCNOTTY, 0);
  990. close(fd);
  991. chdir("/");
  992. umask(022); /* set a default for dumb programs */
  993. setpgid(0,0); /* set the process group */
  994. fd=open("/dev/null", O_RDWR); /* stdin */
  995. dup(fd); /* stdout */
  996. dup(fd); /* stderr */
  997. }
  998. if (nicelevel) {
  999. if (nice(nicelevel))
  1000. fatal("Unable to alter nice level by %i: %s", nicelevel,
  1001. strerror(errno));
  1002. }
  1003. if (mpidfile && pidfile != NULL) { /* user wants _us_ to make the pidfile :) */
  1004. FILE *pidf = fopen(pidfile, "w");
  1005. pid_t pidt = getpid();
  1006. if (pidf == NULL)
  1007. fatal("Unable to open pidfile `%s' for writing: %s", pidfile,
  1008. strerror(errno));
  1009. fprintf(pidf, "%d\n", pidt);
  1010. fclose(pidf);
  1011. }
  1012. execv(startas, argv);
  1013. fatal("Unable to start %s: %s", startas, strerror(errno));
  1014. }