start-stop-daemon.c 31 KB

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