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 VERSION for Debian - small and fast C version written by\n"
  218. "Marek Michalkiewicz <marekm@i17linuxb.ists.pwr.wroc.pl>, public domain.\n"
  219. "\n"
  220. "Usage:\n"
  221. " start-stop-daemon -S|--start options ... -- arguments ...\n"
  222. " start-stop-daemon -K|--stop options ...\n"
  223. " start-stop-daemon -H|--help\n"
  224. " start-stop-daemon -V|--version\n"
  225. "\n"
  226. "Options (at least one of --exec|--pidfile|--user is required):\n"
  227. " -x|--exec <executable> program to start/check if it is running\n"
  228. " -p|--pidfile <pid-file> pid file to check\n"
  229. " -c|--chuid <name|uid[:group|gid]>\n"
  230. " change to this user/group before starting process\n"
  231. " -u|--user <username>|<uid> stop processes owned by this user\n"
  232. " -n|--name <process-name> stop processes with this name\n"
  233. " -s|--signal <signal> signal to send (default TERM)\n"
  234. " -a|--startas <pathname> program to start (default is <executable>)\n"
  235. " -N|--nicelevel <incr> add incr to the process's nice level\n"
  236. " -b|--background force the process to detach\n"
  237. " -m|--make-pidfile create the pidfile before starting\n"
  238. " -R|--retry <schedule> check whether processes die, and retry\n"
  239. " -t|--test test mode, don't do anything\n"
  240. " -o|--oknodo exit status 0 (not 1) if nothing done\n"
  241. " -q|--quiet be more quiet\n"
  242. " -v|--verbose be more verbose\n"
  243. "Retry <schedule> is <item>|/<item>/... where <item> is one of\n"
  244. " -<signal-num>|[-]<signal-name> send that signal\n"
  245. " <timeout> wait that many seconds\n"
  246. " forever repeat remainder forever\n"
  247. "or <schedule> may be just <timeout>, meaning <signal>/<timeout>/KILL/<timeout>\n"
  248. "\n"
  249. "Exit status: 0 = done 1 = nothing done (=> 0 if --oknodo)\n"
  250. " 3 = trouble 2 = with --retry, processes wouldn't die\n");
  251. }
  252. static void
  253. badusage(const char *msg)
  254. {
  255. if (msg)
  256. fprintf(stderr, "%s: %s\n", progname, msg);
  257. fprintf(stderr, "Try `%s --help' for more information.\n", progname);
  258. exit(3);
  259. }
  260. struct sigpair {
  261. const char *name;
  262. int signal;
  263. };
  264. const struct sigpair siglist[] = {
  265. { "ABRT", SIGABRT },
  266. { "ALRM", SIGALRM },
  267. { "FPE", SIGFPE },
  268. { "HUP", SIGHUP },
  269. { "ILL", SIGILL },
  270. { "INT", SIGINT },
  271. { "KILL", SIGKILL },
  272. { "PIPE", SIGPIPE },
  273. { "QUIT", SIGQUIT },
  274. { "SEGV", SIGSEGV },
  275. { "TERM", SIGTERM },
  276. { "USR1", SIGUSR1 },
  277. { "USR2", SIGUSR2 },
  278. { "CHLD", SIGCHLD },
  279. { "CONT", SIGCONT },
  280. { "STOP", SIGSTOP },
  281. { "TSTP", SIGTSTP },
  282. { "TTIN", SIGTTIN },
  283. { "TTOU", SIGTTOU }
  284. };
  285. static int parse_integer (const char *string, int *value_r) {
  286. unsigned long ul;
  287. char *ep;
  288. if (!string[0])
  289. return -1;
  290. ul= strtoul(string,&ep,10);
  291. if (ul > INT_MAX || *ep != '\0')
  292. return -1;
  293. *value_r= ul;
  294. return 0;
  295. }
  296. static int parse_signal (const char *signal_str, int *signal_nr)
  297. {
  298. int i;
  299. if (parse_integer(signal_str, signal_nr) == 0)
  300. return 0;
  301. for (i = 0; i < sizeof (siglist) / sizeof (siglist[0]); i++) {
  302. if (strcmp (signal_str, siglist[i].name) == 0) {
  303. *signal_nr = siglist[i].signal;
  304. return 0;
  305. }
  306. }
  307. return -1;
  308. }
  309. static void
  310. parse_schedule_item(const char *string, struct schedule_item *item) {
  311. const char *after_hyph;
  312. if (!strcmp(string,"forever")) {
  313. item->type = sched_forever;
  314. } else if (isdigit(string[0])) {
  315. item->type = sched_timeout;
  316. if (parse_integer(string, &item->value) != 0)
  317. badusage("invalid timeout value in schedule");
  318. } else if ((after_hyph = string + (string[0] == '-')) &&
  319. parse_signal(after_hyph, &item->value) == 0) {
  320. item->type = sched_signal;
  321. } else {
  322. badusage("invalid schedule item (must be [-]<signal-name>, "
  323. "-<signal-number>, <timeout> or `forever'");
  324. }
  325. }
  326. static void
  327. parse_schedule(const char *schedule_str) {
  328. char item_buf[20];
  329. const char *slash;
  330. int count, repeatat;
  331. ptrdiff_t str_len;
  332. count = 0;
  333. for (slash = schedule_str; *slash; slash++)
  334. if (*slash == '/')
  335. count++;
  336. schedule_length = (count == 0) ? 4 : count+1;
  337. schedule = xmalloc(sizeof(*schedule) * schedule_length);
  338. if (count == 0) {
  339. schedule[0].type = sched_signal;
  340. schedule[0].value = signal_nr;
  341. parse_schedule_item(schedule_str, &schedule[1]);
  342. if (schedule[1].type != sched_timeout) {
  343. badusage ("--retry takes timeout, or schedule list"
  344. " of at least two items");
  345. }
  346. schedule[2].type = sched_signal;
  347. schedule[2].value = SIGKILL;
  348. schedule[3]= schedule[1];
  349. } else {
  350. count = 0;
  351. repeatat = -1;
  352. while (schedule_str != NULL) {
  353. slash = strchr(schedule_str,'/');
  354. str_len = slash ? slash - schedule_str : strlen(schedule_str);
  355. if (str_len >= sizeof(item_buf))
  356. badusage("invalid schedule item: far too long"
  357. " (you must delimit items with slashes)");
  358. memcpy(item_buf, schedule_str, str_len);
  359. item_buf[str_len] = 0;
  360. schedule_str = slash ? slash+1 : NULL;
  361. parse_schedule_item(item_buf, &schedule[count]);
  362. if (schedule[count].type == sched_forever) {
  363. if (repeatat >= 0)
  364. badusage("invalid schedule: `forever'"
  365. " appears more than once");
  366. repeatat = count;
  367. continue;
  368. }
  369. count++;
  370. }
  371. if (repeatat >= 0) {
  372. schedule[count].type = sched_goto;
  373. schedule[count].value = repeatat;
  374. count++;
  375. }
  376. assert(count == schedule_length);
  377. }
  378. }
  379. static void
  380. parse_options(int argc, char * const *argv)
  381. {
  382. static struct option longopts[] = {
  383. { "help", 0, NULL, 'H'},
  384. { "stop", 0, NULL, 'K'},
  385. { "start", 0, NULL, 'S'},
  386. { "version", 0, NULL, 'V'},
  387. { "startas", 1, NULL, 'a'},
  388. { "name", 1, NULL, 'n'},
  389. { "oknodo", 0, NULL, 'o'},
  390. { "pidfile", 1, NULL, 'p'},
  391. { "quiet", 0, NULL, 'q'},
  392. { "signal", 1, NULL, 's'},
  393. { "test", 0, NULL, 't'},
  394. { "user", 1, NULL, 'u'},
  395. { "chroot", 1, NULL, 'r'},
  396. { "verbose", 0, NULL, 'v'},
  397. { "exec", 1, NULL, 'x'},
  398. { "chuid", 1, NULL, 'c'},
  399. { "nicelevel", 1, NULL, 'N'},
  400. { "background", 0, NULL, 'b'},
  401. { "make-pidfile", 0, NULL, 'm'},
  402. { "retry", 1, NULL, 'R'},
  403. { NULL, 0, NULL, 0}
  404. };
  405. int c;
  406. for (;;) {
  407. c = getopt_long(argc, argv, "HKSVa:n:op:qr:s:tu:vx:c:N:bmR:",
  408. longopts, (int *) 0);
  409. if (c == -1)
  410. break;
  411. switch (c) {
  412. case 'H': /* --help */
  413. do_help();
  414. exit(0);
  415. case 'K': /* --stop */
  416. stop = 1;
  417. break;
  418. case 'S': /* --start */
  419. start = 1;
  420. break;
  421. case 'V': /* --version */
  422. printf("start-stop-daemon " VERSION "\n");
  423. exit(0);
  424. case 'a': /* --startas <pathname> */
  425. startas = optarg;
  426. break;
  427. case 'n': /* --name <process-name> */
  428. cmdname = optarg;
  429. break;
  430. case 'o': /* --oknodo */
  431. exitnodo = 0;
  432. break;
  433. case 'p': /* --pidfile <pid-file> */
  434. pidfile = optarg;
  435. break;
  436. case 'q': /* --quiet */
  437. quietmode = 1;
  438. break;
  439. case 's': /* --signal <signal> */
  440. signal_str = optarg;
  441. break;
  442. case 't': /* --test */
  443. testmode = 1;
  444. break;
  445. case 'u': /* --user <username>|<uid> */
  446. userspec = optarg;
  447. break;
  448. case 'v': /* --verbose */
  449. quietmode = -1;
  450. break;
  451. case 'x': /* --exec <executable> */
  452. execname = optarg;
  453. break;
  454. case 'c': /* --chuid <username>|<uid> */
  455. /* we copy the string just in case we need the
  456. * argument later. */
  457. changeuser = strdup(optarg);
  458. changeuser = strtok(changeuser, ":");
  459. changegroup = strtok(NULL, ":");
  460. break;
  461. case 'r': /* --chroot /new/root */
  462. changeroot = optarg;
  463. break;
  464. case 'N': /* --nice */
  465. nicelevel = atoi(optarg);
  466. break;
  467. case 'b': /* --background */
  468. background = 1;
  469. break;
  470. case 'm': /* --make-pidfile */
  471. mpidfile = 1;
  472. break;
  473. case 'R': /* --retry <schedule>|<timeout> */
  474. schedule_str = optarg;
  475. break;
  476. default:
  477. badusage(NULL); /* message printed by getopt */
  478. }
  479. }
  480. if (signal_str != NULL) {
  481. if (parse_signal (signal_str, &signal_nr) != 0)
  482. badusage("signal value must be numeric or name"
  483. " of signal (KILL, INTR, ...)");
  484. }
  485. if (schedule_str != NULL) {
  486. parse_schedule(schedule_str);
  487. }
  488. if (start == stop)
  489. badusage("need one of --start or --stop");
  490. if (!execname && !pidfile && !userspec && !cmdname)
  491. badusage("need at least one of --exec, --pidfile, --user or --name");
  492. if (!startas)
  493. startas = execname;
  494. if (start && !startas)
  495. badusage("--start needs --exec or --startas");
  496. if (mpidfile && pidfile == NULL)
  497. badusage("--make-pidfile is only relevant with --pidfile");
  498. if (background && !start)
  499. badusage("--background is only relevant with --start");
  500. }
  501. #if defined(OSLinux)
  502. static int
  503. pid_is_exec(int pid, const struct stat *esb)
  504. {
  505. struct stat sb;
  506. char buf[32];
  507. sprintf(buf, "/proc/%d/exe", pid);
  508. if (stat(buf, &sb) != 0)
  509. return 0;
  510. return (sb.st_dev == esb->st_dev && sb.st_ino == esb->st_ino);
  511. }
  512. static int
  513. pid_is_user(int pid, int uid)
  514. {
  515. struct stat sb;
  516. char buf[32];
  517. sprintf(buf, "/proc/%d", pid);
  518. if (stat(buf, &sb) != 0)
  519. return 0;
  520. return (sb.st_uid == uid);
  521. }
  522. static int
  523. pid_is_cmd(int pid, const char *name)
  524. {
  525. char buf[32];
  526. FILE *f;
  527. int c;
  528. sprintf(buf, "/proc/%d/stat", pid);
  529. f = fopen(buf, "r");
  530. if (!f)
  531. return 0;
  532. while ((c = getc(f)) != EOF && c != '(')
  533. ;
  534. if (c != '(') {
  535. fclose(f);
  536. return 0;
  537. }
  538. /* this hopefully handles command names containing ')' */
  539. while ((c = getc(f)) != EOF && c == *name)
  540. name++;
  541. fclose(f);
  542. return (c == ')' && *name == '\0');
  543. }
  544. #endif /* OSLinux */
  545. #if defined(OSHURD)
  546. static int
  547. pid_is_user(int pid, int uid)
  548. {
  549. struct stat sb;
  550. char buf[32];
  551. struct proc_stat *pstat;
  552. sprintf(buf, "/proc/%d", pid);
  553. if (stat(buf, &sb) != 0)
  554. return 0;
  555. return (sb.st_uid == uid);
  556. pstat = proc_stat_list_pid_proc_stat (procset, pid);
  557. if (pstat == NULL)
  558. fatal ("Error getting process information: NULL proc_stat struct");
  559. proc_stat_set_flags (pstat, PSTAT_PID | PSTAT_OWNER_UID);
  560. return (pstat->owner_uid == uid);
  561. }
  562. static int
  563. pid_is_cmd(int pid, const char *name)
  564. {
  565. struct proc_stat *pstat;
  566. pstat = proc_stat_list_pid_proc_stat (procset, pid);
  567. if (pstat == NULL)
  568. fatal ("Error getting process information: NULL proc_stat struct");
  569. proc_stat_set_flags (pstat, PSTAT_PID | PSTAT_ARGS);
  570. return (!strcmp (name, pstat->args));
  571. }
  572. #endif /* OSHURD */
  573. static void
  574. check(int pid)
  575. {
  576. #if defined(OSLinux)
  577. if (execname && !pid_is_exec(pid, &exec_stat))
  578. #elif defined(OSHURD)
  579. /* I will try this to see if it works */
  580. if (execname && !pid_is_cmd(pid, execname))
  581. #endif
  582. return;
  583. if (userspec && !pid_is_user(pid, user_id))
  584. return;
  585. if (cmdname && !pid_is_cmd(pid, cmdname))
  586. return;
  587. push(&found, pid);
  588. }
  589. static void
  590. do_pidfile(const char *name)
  591. {
  592. FILE *f;
  593. int pid;
  594. f = fopen(name, "r");
  595. if (f) {
  596. if (fscanf(f, "%d", &pid) == 1)
  597. check(pid);
  598. fclose(f);
  599. } else if (errno != ENOENT)
  600. fatal("open pidfile %s: %s", name, strerror(errno));
  601. }
  602. /* WTA: this needs to be an autoconf check for /proc/pid existance.
  603. */
  604. #if defined(OSLinux) || defined (OSsunos)
  605. static void
  606. do_procinit(void)
  607. {
  608. DIR *procdir;
  609. struct dirent *entry;
  610. int foundany, pid;
  611. procdir = opendir("/proc");
  612. if (!procdir)
  613. fatal("opendir /proc: %s", strerror(errno));
  614. foundany = 0;
  615. while ((entry = readdir(procdir)) != NULL) {
  616. if (sscanf(entry->d_name, "%d", &pid) != 1)
  617. continue;
  618. foundany++;
  619. check(pid);
  620. }
  621. closedir(procdir);
  622. if (!foundany)
  623. fatal("nothing in /proc - not mounted?");
  624. }
  625. #endif /* OSLinux */
  626. #if defined(OSHURD)
  627. error_t
  628. check_all (void *ptr)
  629. {
  630. struct proc_stat *pstat = ptr;
  631. check (pstat->pid);
  632. return (0);
  633. }
  634. static void
  635. do_procinit(void)
  636. {
  637. struct ps_context *context;
  638. error_t err;
  639. err = ps_context_create (getproc (), &context);
  640. if (err)
  641. error (1, err, "ps_context_create");
  642. err = proc_stat_list_create (context, &procset);
  643. if (err)
  644. error (1, err, "proc_stat_list_create");
  645. err = proc_stat_list_add_all (procset, 0, 0);
  646. if (err)
  647. error (1, err, "proc_stat_list_add_all");
  648. /* Check all pids */
  649. ihash_iterate (context->procs, check_all);
  650. }
  651. #endif /* OSHURD */
  652. #if defined(OSOpenBSD)
  653. int
  654. pid_is_cmd(int pid, const char *name)
  655. {
  656. kvm_t *kd;
  657. int nentries, argv_len=0;
  658. struct kinfo_proc *kp;
  659. char errbuf[_POSIX2_LINE_MAX], buf[_POSIX2_LINE_MAX];
  660. char **pid_argv_p;
  661. char *start_argv_0_p, *end_argv_0_p;
  662. kd = kvm_openfiles(NULL, NULL, NULL, O_RDONLY, errbuf);
  663. if (kd == 0)
  664. errx(1, "%s", errbuf);
  665. if ((kp = kvm_getprocs(kd, KERN_PROC_PID, pid, &nentries)) == 0)
  666. errx(1, "%s", kvm_geterr(kd));
  667. if ( ( pid_argv_p = kvm_getargv(kd, kp, argv_len)) == 0)
  668. errx(1, "%s", kvm_geterr(kd));
  669. start_argv_0_p = *pid_argv_p;
  670. /* find and compare string */
  671. /* find end of argv[0] then copy and cut of str there. */
  672. if ( (end_argv_0_p = strchr(*pid_argv_p, ' ')) == 0 )
  673. /* There seems to be no space, so we have the command
  674. * allready in its desired form. */
  675. start_argv_0_p = *pid_argv_p;
  676. else {
  677. /* Tests indicate that this never happens, since
  678. * kvm_getargv itselfe cuts of tailing stuff. This is
  679. * not what the manpage says, however. */
  680. strncpy(buf, *pid_argv_p, (end_argv_0_p - start_argv_0_p));
  681. buf[(end_argv_0_p - start_argv_0_p) + 1] = '\0';
  682. start_argv_0_p = buf;
  683. }
  684. if (strlen(name) != strlen(start_argv_0_p))
  685. return 0;
  686. return (strcmp(name, start_argv_0_p) == 0) ? 1 : 0;
  687. }
  688. int
  689. pid_is_user(int pid, int uid)
  690. {
  691. kvm_t *kd;
  692. int nentries; /* Value not used */
  693. uid_t proc_uid;
  694. struct kinfo_proc *kp;
  695. char errbuf[_POSIX2_LINE_MAX];
  696. kd = kvm_openfiles(NULL, NULL, NULL, O_RDONLY, errbuf);
  697. if (kd == 0)
  698. errx(1, "%s", errbuf);
  699. if ((kp = kvm_getprocs(kd, KERN_PROC_PID, pid, &nentries)) == 0)
  700. errx(1, "%s", kvm_geterr(kd));
  701. if ( kp->kp_proc.p_cred )
  702. kvm_read(kd, (u_long)&(kp->kp_proc.p_cred->p_ruid),
  703. &proc_uid, sizeof(uid_t));
  704. else
  705. return 0;
  706. return (proc_uid == (uid_t)uid);
  707. }
  708. int
  709. pid_is_exec(int pid, const char *name)
  710. {
  711. kvm_t *kd;
  712. int nentries;
  713. struct kinfo_proc *kp;
  714. char errbuf[_POSIX2_LINE_MAX], *pidexec;
  715. kd = kvm_openfiles(NULL, NULL, NULL, O_RDONLY, errbuf);
  716. if (kd == 0)
  717. errx(1, "%s", errbuf);
  718. if ((kp = kvm_getprocs(kd, KERN_PROC_PID, pid, &nentries)) == 0)
  719. errx(1, "%s", kvm_geterr(kd));
  720. pidexec = (&kp->kp_proc)->p_comm;
  721. if (strlen(name) != strlen(pidexec))
  722. return 0;
  723. return (strcmp(name, pidexec) == 0) ? 1 : 0;
  724. }
  725. static void
  726. do_procinit(void)
  727. {
  728. /* Nothing to do */
  729. }
  730. #endif /* OSOpenBSD */
  731. static void
  732. do_findprocs(void)
  733. {
  734. clear(&found);
  735. if (pidfile)
  736. do_pidfile(pidfile);
  737. else
  738. do_procinit();
  739. }
  740. /* return 1 on failure */
  741. static void
  742. do_stop(int signal_nr, int quietmode, int *n_killed, int *n_notkilled, int retry_nr)
  743. {
  744. struct pid_list *p;
  745. do_findprocs();
  746. *n_killed = 0;
  747. *n_notkilled = 0;
  748. if (!found)
  749. return;
  750. clear(&killed);
  751. for (p = found; p; p = p->next) {
  752. if (testmode)
  753. printf("Would send signal %d to %d.\n",
  754. signal_nr, p->pid);
  755. else if (kill(p->pid, signal_nr) == 0) {
  756. push(&killed, p->pid);
  757. (*n_killed)++;
  758. } else {
  759. printf("%s: warning: failed to kill %d: %s\n",
  760. progname, p->pid, strerror(errno));
  761. (*n_notkilled)++;
  762. }
  763. }
  764. if (quietmode < 0 && killed) {
  765. printf("Stopped %s (pid", what_stop);
  766. for (p = killed; p; p = p->next)
  767. printf(" %d", p->pid);
  768. putchar(')');
  769. if (retry_nr > 0)
  770. printf(", retry #%d", retry_nr);
  771. printf(".\n");
  772. }
  773. }
  774. static void
  775. set_what_stop(const char *str)
  776. {
  777. strncpy(what_stop, str, sizeof(what_stop));
  778. what_stop[sizeof(what_stop)-1] = '\0';
  779. }
  780. static int
  781. run_stop_schedule(void)
  782. {
  783. int r, position, n_killed, n_notkilled, value, ratio, anykilled, retry_nr;
  784. struct timeval stopat, before, after, interval, maxinterval;
  785. if (testmode) {
  786. if (schedule != NULL) {
  787. printf("Ignoring --retry in test mode\n");
  788. schedule = NULL;
  789. }
  790. }
  791. if (cmdname)
  792. set_what_stop(cmdname);
  793. else if (execname)
  794. set_what_stop(execname);
  795. else if (pidfile)
  796. sprintf(what_stop, "process in pidfile `%.200s'", pidfile);
  797. else if (userspec)
  798. sprintf(what_stop, "process(es) owned by `%.200s'", userspec);
  799. else
  800. fatal("internal error, please report");
  801. anykilled = 0;
  802. retry_nr = 0;
  803. if (schedule == NULL) {
  804. do_stop(signal_nr, quietmode, &n_killed, &n_notkilled, 0);
  805. if (n_notkilled > 0 && quietmode <= 0)
  806. printf("%d pids were not killed\n", n_notkilled);
  807. if (n_killed)
  808. anykilled = 1;
  809. goto x_finished;
  810. }
  811. for (position = 0; position < schedule_length; ) {
  812. value= schedule[position].value;
  813. n_notkilled = 0;
  814. switch (schedule[position].type) {
  815. case sched_goto:
  816. position = value;
  817. continue;
  818. case sched_signal:
  819. do_stop(value, quietmode, &n_killed, &n_notkilled, retry_nr++);
  820. if (!n_killed)
  821. goto x_finished;
  822. else
  823. anykilled = 1;
  824. goto next_item;
  825. case sched_timeout:
  826. /* We want to keep polling for the processes, to see if they've exited,
  827. * or until the timeout expires.
  828. *
  829. * This is a somewhat complicated algorithm to try to ensure that we
  830. * notice reasonably quickly when all the processes have exited, but
  831. * don't spend too much CPU time polling. In particular, on a fast
  832. * machine with quick-exiting daemons we don't want to delay system
  833. * shutdown too much, whereas on a slow one, or where processes are
  834. * taking some time to exit, we want to increase the polling
  835. * interval.
  836. *
  837. * The algorithm is as follows: we measure the elapsed time it takes
  838. * to do one poll(), and wait a multiple of this time for the next
  839. * poll. However, if that would put us past the end of the timeout
  840. * period we wait only as long as the timeout period, but in any case
  841. * we always wait at least MIN_POLL_INTERVAL (20ms). The multiple
  842. * (`ratio') starts out as 2, and increases by 1 for each poll to a
  843. * maximum of 10; so we use up to between 30% and 10% of the
  844. * machine's resources (assuming a few reasonable things about system
  845. * performance).
  846. */
  847. xgettimeofday(&stopat);
  848. stopat.tv_sec += value;
  849. ratio = 1;
  850. for (;;) {
  851. xgettimeofday(&before);
  852. if (timercmp(&before,&stopat,>))
  853. goto next_item;
  854. do_stop(0, 1, &n_killed, &n_notkilled, 0);
  855. if (!n_killed)
  856. goto x_finished;
  857. xgettimeofday(&after);
  858. if (!timercmp(&after,&stopat,<))
  859. goto next_item;
  860. if (ratio < 10)
  861. ratio++;
  862. TVCALC(interval, ratio * (TVELEM(&after) - TVELEM(&before) + TVADJUST));
  863. TVCALC(maxinterval, TVELEM(&stopat) - TVELEM(&after) + TVADJUST);
  864. if (timercmp(&interval,&maxinterval,>))
  865. interval = maxinterval;
  866. if (interval.tv_sec == 0 &&
  867. interval.tv_usec <= MIN_POLL_INTERVAL)
  868. interval.tv_usec = MIN_POLL_INTERVAL;
  869. r = select(0,0,0,0,&interval);
  870. if (r < 0 && errno != EINTR)
  871. fatal("select() failed for pause: %s",
  872. strerror(errno));
  873. }
  874. default:
  875. assert(!"schedule[].type value must be valid");
  876. }
  877. next_item:
  878. position++;
  879. }
  880. if (quietmode <= 0)
  881. printf("Program %s, %d process(es), refused to die.\n",
  882. what_stop, n_killed);
  883. return 2;
  884. x_finished:
  885. if (!anykilled) {
  886. if (quietmode <= 0)
  887. printf("No %s found running; none killed.\n", what_stop);
  888. return exitnodo;
  889. } else {
  890. return 0;
  891. }
  892. }
  893. int main(int argc, char **argv) NONRETURNING;
  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. }