start-stop-daemon.c 28 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171
  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. pid_t 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, pid_t pid);
  119. static void do_help(void);
  120. static void parse_options(int argc, char * const *argv);
  121. static int pid_is_user(pid_t pid, uid_t uid);
  122. static int pid_is_cmd(pid_t pid, const char *name);
  123. static void check(pid_t 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(pid_t 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, pid_t 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. unsigned 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 >= (ptrdiff_t)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(pid_t 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(pid_t pid, uid_t 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(pid_t 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(pid_t pid, uid_t 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(pid_t 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(pid_t 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. pid_t 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;
  611. pid_t 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(pid_t 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(pid_t 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(pid_t 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 main(int argc, char **argv) NONRETURNING;
  895. int
  896. main(int argc, char **argv)
  897. {
  898. progname = argv[0];
  899. parse_options(argc, argv);
  900. argc -= optind;
  901. argv += optind;
  902. if (execname && stat(execname, &exec_stat))
  903. fatal("stat %s: %s", execname, strerror(errno));
  904. if (userspec && sscanf(userspec, "%d", &user_id) != 1) {
  905. struct passwd *pw;
  906. pw = getpwnam(userspec);
  907. if (!pw)
  908. fatal("user `%s' not found\n", userspec);
  909. user_id = pw->pw_uid;
  910. }
  911. if (changegroup && sscanf(changegroup, "%d", &runas_gid) != 1) {
  912. struct group *gr = getgrnam(changegroup);
  913. if (!gr)
  914. fatal("group `%s' not found\n", changegroup);
  915. runas_gid = gr->gr_gid;
  916. }
  917. if (changeuser && sscanf(changeuser, "%d", &runas_uid) != 1) {
  918. struct passwd *pw = getpwnam(changeuser);
  919. if (!pw)
  920. fatal("user `%s' not found\n", changeuser);
  921. runas_uid = pw->pw_uid;
  922. if (changegroup == NULL) { /* pass the default group of this user */
  923. changegroup = ""; /* just empty */
  924. runas_gid = pw->pw_gid;
  925. }
  926. }
  927. if (stop) {
  928. int i = run_stop_schedule();
  929. exit(i);
  930. }
  931. do_findprocs();
  932. if (found) {
  933. if (quietmode <= 0)
  934. printf("%s already running.\n", execname);
  935. exit(exitnodo);
  936. }
  937. if (testmode) {
  938. printf("Would start %s ", startas);
  939. while (argc-- > 0)
  940. printf("%s ", *argv++);
  941. if (changeuser != NULL) {
  942. printf(" (as user %s[%d]", changeuser, runas_uid);
  943. if (changegroup != NULL)
  944. printf(", and group %s[%d])", changegroup, runas_gid);
  945. else
  946. printf(")");
  947. }
  948. if (changeroot != NULL)
  949. printf(" in directory %s", changeroot);
  950. if (nicelevel)
  951. printf(", and add %i to the priority", nicelevel);
  952. printf(".\n");
  953. exit(0);
  954. }
  955. if (quietmode < 0)
  956. printf("Starting %s...\n", startas);
  957. *--argv = startas;
  958. if (changeroot != NULL) {
  959. if (chdir(changeroot) < 0)
  960. fatal("Unable to chdir() to %s", changeroot);
  961. if (chroot(changeroot) < 0)
  962. fatal("Unable to chroot() to %s", changeroot);
  963. }
  964. if (changeuser != NULL) {
  965. if (setgid(runas_gid))
  966. fatal("Unable to set gid to %d", runas_gid);
  967. if (initgroups(changeuser, runas_gid))
  968. fatal("Unable to set initgroups() with gid %d", runas_gid);
  969. if (setuid(runas_uid))
  970. fatal("Unable to set uid to %s", changeuser);
  971. }
  972. if (background) { /* ok, we need to detach this process */
  973. int i, fd;
  974. if (quietmode < 0)
  975. printf("Detatching to start %s...", startas);
  976. i = fork();
  977. if (i<0) {
  978. fatal("Unable to fork.\n");
  979. }
  980. if (i) { /* parent */
  981. if (quietmode < 0)
  982. printf("done.\n");
  983. exit(0);
  984. }
  985. /* child continues here */
  986. /* now close all extra fds */
  987. for (i=getdtablesize()-1; i>=0; --i) close(i);
  988. /* change tty */
  989. fd = open("/dev/tty", O_RDWR);
  990. ioctl(fd, TIOCNOTTY, 0);
  991. close(fd);
  992. chdir("/");
  993. umask(022); /* set a default for dumb programs */
  994. setpgid(0,0); /* set the process group */
  995. fd=open("/dev/null", O_RDWR); /* stdin */
  996. dup(fd); /* stdout */
  997. dup(fd); /* stderr */
  998. }
  999. if (nicelevel) {
  1000. if (nice(nicelevel))
  1001. fatal("Unable to alter nice level by %i: %s", nicelevel,
  1002. strerror(errno));
  1003. }
  1004. if (mpidfile && pidfile != NULL) { /* user wants _us_ to make the pidfile :) */
  1005. FILE *pidf = fopen(pidfile, "w");
  1006. pid_t pidt = getpid();
  1007. if (pidf == NULL)
  1008. fatal("Unable to open pidfile `%s' for writing: %s", pidfile,
  1009. strerror(errno));
  1010. fprintf(pidf, "%d\n", pidt);
  1011. fclose(pidf);
  1012. }
  1013. execv(startas, argv);
  1014. fatal("Unable to start %s: %s", startas, strerror(errno));
  1015. }