start-stop-daemon.c 31 KB

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