start-stop-daemon.c 31 KB

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