start-stop-daemon.c 30 KB

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