start-stop-daemon.c 32 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342
  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 %s 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. " -d|--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. VERSION);
  283. }
  284. static void
  285. badusage(const char *msg)
  286. {
  287. if (msg)
  288. fprintf(stderr, "%s: %s\n", progname, msg);
  289. fprintf(stderr, "Try `%s --help' for more information.\n", progname);
  290. exit(3);
  291. }
  292. struct sigpair {
  293. const char *name;
  294. int signal;
  295. };
  296. const struct sigpair siglist[] = {
  297. { "ABRT", SIGABRT },
  298. { "ALRM", SIGALRM },
  299. { "FPE", SIGFPE },
  300. { "HUP", SIGHUP },
  301. { "ILL", SIGILL },
  302. { "INT", SIGINT },
  303. { "KILL", SIGKILL },
  304. { "PIPE", SIGPIPE },
  305. { "QUIT", SIGQUIT },
  306. { "SEGV", SIGSEGV },
  307. { "TERM", SIGTERM },
  308. { "USR1", SIGUSR1 },
  309. { "USR2", SIGUSR2 },
  310. { "CHLD", SIGCHLD },
  311. { "CONT", SIGCONT },
  312. { "STOP", SIGSTOP },
  313. { "TSTP", SIGTSTP },
  314. { "TTIN", SIGTTIN },
  315. { "TTOU", SIGTTOU }
  316. };
  317. static int parse_integer(const char *string, int *value_r) {
  318. unsigned long ul;
  319. char *ep;
  320. if (!string[0])
  321. return -1;
  322. ul= strtoul(string,&ep,10);
  323. if (ul > INT_MAX || *ep != '\0')
  324. return -1;
  325. *value_r= ul;
  326. return 0;
  327. }
  328. static int parse_signal(const char *signal_str, int *signal_nr)
  329. {
  330. unsigned int i;
  331. if (parse_integer(signal_str, signal_nr) == 0)
  332. return 0;
  333. for (i = 0; i < sizeof (siglist) / sizeof (siglist[0]); i++) {
  334. if (strcmp (signal_str, siglist[i].name) == 0) {
  335. *signal_nr = siglist[i].signal;
  336. return 0;
  337. }
  338. }
  339. return -1;
  340. }
  341. static void
  342. parse_schedule_item(const char *string, struct schedule_item *item) {
  343. const char *after_hyph;
  344. if (!strcmp(string,"forever")) {
  345. item->type = sched_forever;
  346. } else if (isdigit(string[0])) {
  347. item->type = sched_timeout;
  348. if (parse_integer(string, &item->value) != 0)
  349. badusage("invalid timeout value in schedule");
  350. } else if ((after_hyph = string + (string[0] == '-')) &&
  351. parse_signal(after_hyph, &item->value) == 0) {
  352. item->type = sched_signal;
  353. } else {
  354. badusage("invalid schedule item (must be [-]<signal-name>, "
  355. "-<signal-number>, <timeout> or `forever'");
  356. }
  357. }
  358. static void
  359. parse_schedule(const char *schedule_str) {
  360. char item_buf[20];
  361. const char *slash;
  362. int count, repeatat;
  363. ptrdiff_t str_len;
  364. count = 0;
  365. for (slash = schedule_str; *slash; slash++)
  366. if (*slash == '/')
  367. count++;
  368. schedule_length = (count == 0) ? 4 : count+1;
  369. schedule = xmalloc(sizeof(*schedule) * schedule_length);
  370. if (count == 0) {
  371. schedule[0].type = sched_signal;
  372. schedule[0].value = signal_nr;
  373. parse_schedule_item(schedule_str, &schedule[1]);
  374. if (schedule[1].type != sched_timeout) {
  375. badusage ("--retry takes timeout, or schedule list"
  376. " of at least two items");
  377. }
  378. schedule[2].type = sched_signal;
  379. schedule[2].value = SIGKILL;
  380. schedule[3]= schedule[1];
  381. } else {
  382. count = 0;
  383. repeatat = -1;
  384. while (schedule_str != NULL) {
  385. slash = strchr(schedule_str,'/');
  386. str_len = slash ? slash - schedule_str : strlen(schedule_str);
  387. if (str_len >= (ptrdiff_t)sizeof(item_buf))
  388. badusage("invalid schedule item: far too long"
  389. " (you must delimit items with slashes)");
  390. memcpy(item_buf, schedule_str, str_len);
  391. item_buf[str_len] = 0;
  392. schedule_str = slash ? slash+1 : NULL;
  393. parse_schedule_item(item_buf, &schedule[count]);
  394. if (schedule[count].type == sched_forever) {
  395. if (repeatat >= 0)
  396. badusage("invalid schedule: `forever'"
  397. " appears more than once");
  398. repeatat = count;
  399. continue;
  400. }
  401. count++;
  402. }
  403. if (repeatat >= 0) {
  404. schedule[count].type = sched_goto;
  405. schedule[count].value = repeatat;
  406. count++;
  407. }
  408. assert(count == schedule_length);
  409. }
  410. }
  411. static void
  412. parse_options(int argc, char * const *argv)
  413. {
  414. static struct option longopts[] = {
  415. { "help", 0, NULL, 'H'},
  416. { "stop", 0, NULL, 'K'},
  417. { "start", 0, NULL, 'S'},
  418. { "version", 0, NULL, 'V'},
  419. { "startas", 1, NULL, 'a'},
  420. { "name", 1, NULL, 'n'},
  421. { "oknodo", 0, NULL, 'o'},
  422. { "pidfile", 1, NULL, 'p'},
  423. { "quiet", 0, NULL, 'q'},
  424. { "signal", 1, NULL, 's'},
  425. { "test", 0, NULL, 't'},
  426. { "user", 1, NULL, 'u'},
  427. { "group", 1, NULL, 'g'},
  428. { "chroot", 1, NULL, 'r'},
  429. { "verbose", 0, NULL, 'v'},
  430. { "exec", 1, NULL, 'x'},
  431. { "chuid", 1, NULL, 'c'},
  432. { "nicelevel", 1, NULL, 'N'},
  433. { "background", 0, NULL, 'b'},
  434. { "make-pidfile", 0, NULL, 'm'},
  435. { "retry", 1, NULL, 'R'},
  436. { "chdir", 1, NULL, 'd'},
  437. { NULL, 0, NULL, 0}
  438. };
  439. int c;
  440. for (;;) {
  441. c = getopt_long(argc, argv, "HKSVa:n:op:qr:s:tu:vx:c:N:bmR:g:d:",
  442. longopts, (int *) 0);
  443. if (c == -1)
  444. break;
  445. switch (c) {
  446. case 'H': /* --help */
  447. do_help();
  448. exit(0);
  449. case 'K': /* --stop */
  450. stop = 1;
  451. break;
  452. case 'S': /* --start */
  453. start = 1;
  454. break;
  455. case 'V': /* --version */
  456. printf("start-stop-daemon " VERSION "\n");
  457. exit(0);
  458. case 'a': /* --startas <pathname> */
  459. startas = optarg;
  460. break;
  461. case 'n': /* --name <process-name> */
  462. cmdname = optarg;
  463. break;
  464. case 'o': /* --oknodo */
  465. exitnodo = 0;
  466. break;
  467. case 'p': /* --pidfile <pid-file> */
  468. pidfile = optarg;
  469. break;
  470. case 'q': /* --quiet */
  471. quietmode = 1;
  472. break;
  473. case 's': /* --signal <signal> */
  474. signal_str = optarg;
  475. break;
  476. case 't': /* --test */
  477. testmode = 1;
  478. break;
  479. case 'u': /* --user <username>|<uid> */
  480. userspec = optarg;
  481. break;
  482. case 'v': /* --verbose */
  483. quietmode = -1;
  484. break;
  485. case 'x': /* --exec <executable> */
  486. execname = optarg;
  487. break;
  488. case 'c': /* --chuid <username>|<uid> */
  489. /* we copy the string just in case we need the
  490. * argument later. */
  491. changeuser = strdup(optarg);
  492. changeuser = strtok(changeuser, ":");
  493. changegroup = strtok(NULL, ":");
  494. break;
  495. case 'g': /* --group <group>|<gid> */
  496. changegroup = optarg;
  497. break;
  498. case 'r': /* --chroot /new/root */
  499. changeroot = optarg;
  500. break;
  501. case 'N': /* --nice */
  502. nicelevel = atoi(optarg);
  503. break;
  504. case 'b': /* --background */
  505. background = 1;
  506. break;
  507. case 'm': /* --make-pidfile */
  508. mpidfile = 1;
  509. break;
  510. case 'R': /* --retry <schedule>|<timeout> */
  511. schedule_str = optarg;
  512. break;
  513. case 'd': /* --chdir /new/dir */
  514. changedir = optarg;
  515. break;
  516. default:
  517. badusage(NULL); /* message printed by getopt */
  518. }
  519. }
  520. if (signal_str != NULL) {
  521. if (parse_signal (signal_str, &signal_nr) != 0)
  522. badusage("signal value must be numeric or name"
  523. " of signal (KILL, INT, ...)");
  524. }
  525. if (schedule_str != NULL) {
  526. parse_schedule(schedule_str);
  527. }
  528. if (start == stop)
  529. badusage("need one of --start or --stop");
  530. if (!execname && !pidfile && !userspec && !cmdname)
  531. badusage("need at least one of --exec, --pidfile, --user or --name");
  532. if (!startas)
  533. startas = execname;
  534. if (start && !startas)
  535. badusage("--start needs --exec or --startas");
  536. if (mpidfile && pidfile == NULL)
  537. badusage("--make-pidfile is only relevant with --pidfile");
  538. if (background && !start)
  539. badusage("--background is only relevant with --start");
  540. }
  541. #if defined(OSLinux)
  542. static int
  543. pid_is_exec(pid_t pid, const struct stat *esb)
  544. {
  545. char lname[32];
  546. char lcontents[_POSIX_PATH_MAX];
  547. const char deleted[] = " (deleted)";
  548. int nread;
  549. struct stat sb;
  550. sprintf(lname, "/proc/%d/exe", pid);
  551. nread = readlink(lname, lcontents, sizeof(lcontents));
  552. if (nread == -1)
  553. return 0;
  554. lcontents[nread] = '\0';
  555. if (strcmp(lcontents + nread - strlen(deleted), deleted) == 0)
  556. lcontents[nread - strlen(deleted)] = '\0';
  557. if (stat(lcontents, &sb) != 0)
  558. return 0;
  559. return (sb.st_dev == esb->st_dev && sb.st_ino == esb->st_ino);
  560. }
  561. static int
  562. pid_is_user(pid_t pid, uid_t uid)
  563. {
  564. struct stat sb;
  565. char buf[32];
  566. sprintf(buf, "/proc/%d", pid);
  567. if (stat(buf, &sb) != 0)
  568. return 0;
  569. return (sb.st_uid == uid);
  570. }
  571. static int
  572. pid_is_cmd(pid_t pid, const char *name)
  573. {
  574. char buf[32];
  575. FILE *f;
  576. int c;
  577. sprintf(buf, "/proc/%d/stat", pid);
  578. f = fopen(buf, "r");
  579. if (!f)
  580. return 0;
  581. while ((c = getc(f)) != EOF && c != '(')
  582. ;
  583. if (c != '(') {
  584. fclose(f);
  585. return 0;
  586. }
  587. /* this hopefully handles command names containing ')' */
  588. while ((c = getc(f)) != EOF && c == *name)
  589. name++;
  590. fclose(f);
  591. return (c == ')' && *name == '\0');
  592. }
  593. #endif /* OSLinux */
  594. #if defined(OSHURD)
  595. static void
  596. init_procset(void)
  597. {
  598. struct ps_context *context;
  599. error_t err;
  600. err = ps_context_create(getproc(), &context);
  601. if (err)
  602. error(1, err, "ps_context_create");
  603. err = proc_stat_list_create(context, &procset);
  604. if (err)
  605. error(1, err, "proc_stat_list_create");
  606. err = proc_stat_list_add_all(procset, 0, 0);
  607. if (err)
  608. error(1, err, "proc_stat_list_add_all");
  609. }
  610. static struct proc_stat *
  611. get_proc_stat (pid_t pid, ps_flags_t flags)
  612. {
  613. struct proc_stat *ps;
  614. ps_flags_t wanted_flags = PSTAT_PID | flags;
  615. if (!procset)
  616. init_procset();
  617. ps = proc_stat_list_pid_proc_stat(procset, pid);
  618. if (!ps)
  619. return NULL;
  620. if (proc_stat_set_flags(ps, wanted_flags))
  621. return NULL;
  622. if ((proc_stat_flags(ps) & wanted_flags) != wanted_flags)
  623. return NULL;
  624. return ps;
  625. }
  626. static int
  627. pid_is_user(pid_t pid, uid_t uid)
  628. {
  629. struct proc_stat *ps;
  630. ps = get_proc_stat(pid, PSTAT_OWNER_UID);
  631. return ps && proc_stat_owner_uid(ps) == uid;
  632. }
  633. static int
  634. pid_is_cmd(pid_t pid, const char *name)
  635. {
  636. struct proc_stat *ps;
  637. ps = get_proc_stat(pid, PSTAT_ARGS);
  638. return ps && !strcmp(proc_stat_args(ps), name);
  639. }
  640. static int
  641. pid_is_running(pid_t pid)
  642. {
  643. return get_proc_stat(pid, 0) != NULL;
  644. }
  645. #else /* !OSHURD */
  646. static int
  647. pid_is_running(pid_t pid)
  648. {
  649. struct stat sb;
  650. char buf[32];
  651. sprintf(buf, "/proc/%d", pid);
  652. if (stat(buf, &sb) != 0) {
  653. if (errno!=ENOENT)
  654. fatal("Error stating %s: %s", buf, strerror(errno));
  655. return 0;
  656. }
  657. return 1;
  658. }
  659. #endif /* OSHURD */
  660. static void
  661. check(pid_t pid)
  662. {
  663. #if defined(OSLinux) || defined(OShpux)
  664. if (execname && !pid_is_exec(pid, &exec_stat))
  665. #elif defined(OSHURD) || defined(OSFreeBSD) || defined(OSNetBSD)
  666. /* I will try this to see if it works */
  667. if (execname && !pid_is_cmd(pid, execname))
  668. #endif
  669. return;
  670. if (userspec && !pid_is_user(pid, user_id))
  671. return;
  672. if (cmdname && !pid_is_cmd(pid, cmdname))
  673. return;
  674. if (start && !pid_is_running(pid))
  675. return;
  676. push(&found, pid);
  677. }
  678. static void
  679. do_pidfile(const char *name)
  680. {
  681. FILE *f;
  682. pid_t pid;
  683. f = fopen(name, "r");
  684. if (f) {
  685. if (fscanf(f, "%d", &pid) == 1)
  686. check(pid);
  687. fclose(f);
  688. } else if (errno != ENOENT)
  689. fatal("open pidfile %s: %s", name, strerror(errno));
  690. }
  691. /* WTA: this needs to be an autoconf check for /proc/pid existance.
  692. */
  693. #if defined(OSLinux) || defined (OSsunos)
  694. static void
  695. do_procinit(void)
  696. {
  697. DIR *procdir;
  698. struct dirent *entry;
  699. int foundany;
  700. pid_t pid;
  701. procdir = opendir("/proc");
  702. if (!procdir)
  703. fatal("opendir /proc: %s", strerror(errno));
  704. foundany = 0;
  705. while ((entry = readdir(procdir)) != NULL) {
  706. if (sscanf(entry->d_name, "%d", &pid) != 1)
  707. continue;
  708. foundany++;
  709. check(pid);
  710. }
  711. closedir(procdir);
  712. if (!foundany)
  713. fatal("nothing in /proc - not mounted?");
  714. }
  715. #endif /* OSLinux */
  716. #if defined(OSHURD)
  717. static int
  718. check_proc_stat (struct proc_stat *ps)
  719. {
  720. check(ps->pid);
  721. return 0;
  722. }
  723. static void
  724. do_procinit(void)
  725. {
  726. if (!procset)
  727. init_procset();
  728. proc_stat_list_for_each (procset, check_proc_stat);
  729. }
  730. #endif /* OSHURD */
  731. #ifdef HAVE_KVM_H
  732. static int
  733. pid_is_cmd(pid_t pid, const char *name)
  734. {
  735. kvm_t *kd;
  736. int nentries, argv_len=0;
  737. struct kinfo_proc *kp;
  738. char errbuf[_POSIX2_LINE_MAX], buf[_POSIX2_LINE_MAX];
  739. char **pid_argv_p;
  740. char *start_argv_0_p, *end_argv_0_p;
  741. kd = kvm_openfiles(NULL, NULL, NULL, O_RDONLY, errbuf);
  742. if (kd == 0)
  743. errx(1, "%s", errbuf);
  744. if ((kp = kvm_getprocs(kd, KERN_PROC_PID, pid, &nentries)) == 0)
  745. errx(1, "%s", kvm_geterr(kd));
  746. if ((pid_argv_p = kvm_getargv(kd, kp, argv_len)) == 0)
  747. errx(1, "%s", kvm_geterr(kd));
  748. start_argv_0_p = *pid_argv_p;
  749. /* find and compare string */
  750. /* find end of argv[0] then copy and cut of str there. */
  751. if ((end_argv_0_p = strchr(*pid_argv_p, ' ')) == 0 )
  752. /* There seems to be no space, so we have the command
  753. * allready in its desired form. */
  754. start_argv_0_p = *pid_argv_p;
  755. else {
  756. /* Tests indicate that this never happens, since
  757. * kvm_getargv itselfe cuts of tailing stuff. This is
  758. * not what the manpage says, however. */
  759. strncpy(buf, *pid_argv_p, (end_argv_0_p - start_argv_0_p));
  760. buf[(end_argv_0_p - start_argv_0_p) + 1] = '\0';
  761. start_argv_0_p = buf;
  762. }
  763. if (strlen(name) != strlen(start_argv_0_p))
  764. return 0;
  765. return (strcmp(name, start_argv_0_p) == 0) ? 1 : 0;
  766. }
  767. static int
  768. pid_is_user(pid_t pid, uid_t uid)
  769. {
  770. kvm_t *kd;
  771. int nentries; /* Value not used */
  772. uid_t proc_uid;
  773. struct kinfo_proc *kp;
  774. char errbuf[_POSIX2_LINE_MAX];
  775. kd = kvm_openfiles(NULL, NULL, NULL, O_RDONLY, errbuf);
  776. if (kd == 0)
  777. errx(1, "%s", errbuf);
  778. if ((kp = kvm_getprocs(kd, KERN_PROC_PID, pid, &nentries)) == 0)
  779. errx(1, "%s", kvm_geterr(kd));
  780. if (kp->kp_proc.p_cred )
  781. kvm_read(kd, (u_long)&(kp->kp_proc.p_cred->p_ruid),
  782. &proc_uid, sizeof(uid_t));
  783. else
  784. return 0;
  785. return (proc_uid == (uid_t)uid);
  786. }
  787. static int
  788. pid_is_exec(pid_t pid, const char *name)
  789. {
  790. kvm_t *kd;
  791. int nentries;
  792. struct kinfo_proc *kp;
  793. char errbuf[_POSIX2_LINE_MAX], *pidexec;
  794. kd = kvm_openfiles(NULL, NULL, NULL, O_RDONLY, errbuf);
  795. if (kd == 0)
  796. errx(1, "%s", errbuf);
  797. if ((kp = kvm_getprocs(kd, KERN_PROC_PID, pid, &nentries)) == 0)
  798. errx(1, "%s", kvm_geterr(kd));
  799. pidexec = (&kp->kp_proc)->p_comm;
  800. if (strlen(name) != strlen(pidexec))
  801. return 0;
  802. return (strcmp(name, pidexec) == 0) ? 1 : 0;
  803. }
  804. static void
  805. do_procinit(void)
  806. {
  807. /* Nothing to do */
  808. }
  809. #endif /* OSOpenBSD */
  810. #if defined(OShpux)
  811. static int
  812. pid_is_user(pid_t pid, uid_t uid)
  813. {
  814. struct pst_status pst;
  815. if (pstat_getproc(&pst, sizeof(pst), (size_t) 0, (int) pid) < 0)
  816. return 0;
  817. return ((uid_t) pst.pst_uid == uid);
  818. }
  819. static int
  820. pid_is_cmd(pid_t pid, const char *name)
  821. {
  822. struct pst_status pst;
  823. if (pstat_getproc(&pst, sizeof(pst), (size_t) 0, (int) pid) < 0)
  824. return 0;
  825. return (strcmp(pst.pst_ucomm, name) == 0);
  826. }
  827. static int
  828. pid_is_exec(pid_t pid, const struct stat *esb)
  829. {
  830. struct pst_status pst;
  831. if (pstat_getproc(&pst, sizeof(pst), (size_t) 0, (int) pid) < 0)
  832. return 0;
  833. return ((dev_t) pst.pst_text.psf_fsid.psfs_id == esb->st_dev
  834. && (ino_t) pst.pst_text.psf_fileid == esb->st_ino);
  835. }
  836. static void
  837. do_procinit(void)
  838. {
  839. struct pst_status pst[10];
  840. int i, count;
  841. int idx = 0;
  842. while ((count = pstat_getproc(pst, sizeof(pst[0]), 10, idx)) > 0) {
  843. for (i = 0; i < count; i++)
  844. check(pst[i].pst_pid);
  845. idx = pst[count - 1].pst_idx + 1;
  846. }
  847. }
  848. #endif /* OShpux */
  849. static void
  850. do_findprocs(void)
  851. {
  852. clear(&found);
  853. if (pidfile)
  854. do_pidfile(pidfile);
  855. else
  856. do_procinit();
  857. }
  858. /* return 1 on failure */
  859. static void
  860. do_stop(int signal_nr, int quietmode, int *n_killed, int *n_notkilled, int retry_nr)
  861. {
  862. struct pid_list *p;
  863. do_findprocs();
  864. *n_killed = 0;
  865. *n_notkilled = 0;
  866. if (!found)
  867. return;
  868. clear(&killed);
  869. for (p = found; p; p = p->next) {
  870. if (testmode) {
  871. printf("Would send signal %d to %d.\n",
  872. signal_nr, p->pid);
  873. (*n_killed)++;
  874. } else if (kill(p->pid, signal_nr) == 0) {
  875. push(&killed, p->pid);
  876. (*n_killed)++;
  877. } else {
  878. printf("%s: warning: failed to kill %d: %s\n",
  879. progname, p->pid, strerror(errno));
  880. (*n_notkilled)++;
  881. }
  882. }
  883. if (quietmode < 0 && killed) {
  884. printf("Stopped %s (pid", what_stop);
  885. for (p = killed; p; p = p->next)
  886. printf(" %d", p->pid);
  887. putchar(')');
  888. if (retry_nr > 0)
  889. printf(", retry #%d", retry_nr);
  890. printf(".\n");
  891. }
  892. }
  893. static void
  894. set_what_stop(const char *str)
  895. {
  896. strncpy(what_stop, str, sizeof(what_stop));
  897. what_stop[sizeof(what_stop)-1] = '\0';
  898. }
  899. static int
  900. run_stop_schedule(void)
  901. {
  902. int r, position, n_killed, n_notkilled, value, ratio, anykilled, retry_nr;
  903. struct timeval stopat, before, after, interval, maxinterval;
  904. if (testmode) {
  905. if (schedule != NULL) {
  906. printf("Ignoring --retry in test mode\n");
  907. schedule = NULL;
  908. }
  909. }
  910. if (cmdname)
  911. set_what_stop(cmdname);
  912. else if (execname)
  913. set_what_stop(execname);
  914. else if (pidfile)
  915. sprintf(what_stop, "process in pidfile `%.200s'", pidfile);
  916. else if (userspec)
  917. sprintf(what_stop, "process(es) owned by `%.200s'", userspec);
  918. else
  919. fatal("internal error, please report");
  920. anykilled = 0;
  921. retry_nr = 0;
  922. if (schedule == NULL) {
  923. do_stop(signal_nr, quietmode, &n_killed, &n_notkilled, 0);
  924. if (n_notkilled > 0 && quietmode <= 0)
  925. printf("%d pids were not killed\n", n_notkilled);
  926. if (n_killed)
  927. anykilled = 1;
  928. goto x_finished;
  929. }
  930. for (position = 0; position < schedule_length; ) {
  931. value= schedule[position].value;
  932. n_notkilled = 0;
  933. switch (schedule[position].type) {
  934. case sched_goto:
  935. position = value;
  936. continue;
  937. case sched_signal:
  938. do_stop(value, quietmode, &n_killed, &n_notkilled, retry_nr++);
  939. if (!n_killed)
  940. goto x_finished;
  941. else
  942. anykilled = 1;
  943. goto next_item;
  944. case sched_timeout:
  945. /* We want to keep polling for the processes, to see if they've exited,
  946. * or until the timeout expires.
  947. *
  948. * This is a somewhat complicated algorithm to try to ensure that we
  949. * notice reasonably quickly when all the processes have exited, but
  950. * don't spend too much CPU time polling. In particular, on a fast
  951. * machine with quick-exiting daemons we don't want to delay system
  952. * shutdown too much, whereas on a slow one, or where processes are
  953. * taking some time to exit, we want to increase the polling
  954. * interval.
  955. *
  956. * The algorithm is as follows: we measure the elapsed time it takes
  957. * to do one poll(), and wait a multiple of this time for the next
  958. * poll. However, if that would put us past the end of the timeout
  959. * period we wait only as long as the timeout period, but in any case
  960. * we always wait at least MIN_POLL_INTERVAL (20ms). The multiple
  961. * (`ratio') starts out as 2, and increases by 1 for each poll to a
  962. * maximum of 10; so we use up to between 30% and 10% of the
  963. * machine's resources (assuming a few reasonable things about system
  964. * performance).
  965. */
  966. xgettimeofday(&stopat);
  967. stopat.tv_sec += value;
  968. ratio = 1;
  969. for (;;) {
  970. xgettimeofday(&before);
  971. if (timercmp(&before,&stopat,>))
  972. goto next_item;
  973. do_stop(0, 1, &n_killed, &n_notkilled, 0);
  974. if (!n_killed)
  975. goto x_finished;
  976. xgettimeofday(&after);
  977. if (!timercmp(&after,&stopat,<))
  978. goto next_item;
  979. if (ratio < 10)
  980. ratio++;
  981. TVCALC(interval, ratio * (TVELEM(&after) - TVELEM(&before) + TVADJUST));
  982. TVCALC(maxinterval, TVELEM(&stopat) - TVELEM(&after) + TVADJUST);
  983. if (timercmp(&interval,&maxinterval,>))
  984. interval = maxinterval;
  985. if (interval.tv_sec == 0 &&
  986. interval.tv_usec <= MIN_POLL_INTERVAL)
  987. interval.tv_usec = MIN_POLL_INTERVAL;
  988. r = select(0,0,0,0,&interval);
  989. if (r < 0 && errno != EINTR)
  990. fatal("select() failed for pause: %s",
  991. strerror(errno));
  992. }
  993. default:
  994. assert(!"schedule[].type value must be valid");
  995. }
  996. next_item:
  997. position++;
  998. }
  999. if (quietmode <= 0)
  1000. printf("Program %s, %d process(es), refused to die.\n",
  1001. what_stop, n_killed);
  1002. return 2;
  1003. x_finished:
  1004. if (!anykilled) {
  1005. if (quietmode <= 0)
  1006. printf("No %s found running; none killed.\n", what_stop);
  1007. return exitnodo;
  1008. } else {
  1009. return 0;
  1010. }
  1011. }
  1012. int
  1013. main(int argc, char **argv)
  1014. {
  1015. int devnull_fd = -1;
  1016. #ifdef HAVE_TIOCNOTTY
  1017. int tty_fd = -1;
  1018. #endif
  1019. progname = argv[0];
  1020. parse_options(argc, argv);
  1021. argc -= optind;
  1022. argv += optind;
  1023. if (execname && stat(execname, &exec_stat))
  1024. fatal("stat %s: %s", execname, strerror(errno));
  1025. if (userspec && sscanf(userspec, "%d", &user_id) != 1) {
  1026. struct passwd *pw;
  1027. pw = getpwnam(userspec);
  1028. if (!pw)
  1029. fatal("user `%s' not found\n", userspec);
  1030. user_id = pw->pw_uid;
  1031. }
  1032. if (changegroup && sscanf(changegroup, "%d", &runas_gid) != 1) {
  1033. struct group *gr = getgrnam(changegroup);
  1034. if (!gr)
  1035. fatal("group `%s' not found\n", changegroup);
  1036. runas_gid = gr->gr_gid;
  1037. }
  1038. if (changeuser && sscanf(changeuser, "%d", &runas_uid) != 1) {
  1039. struct passwd *pw = getpwnam(changeuser);
  1040. if (!pw)
  1041. fatal("user `%s' not found\n", changeuser);
  1042. runas_uid = pw->pw_uid;
  1043. if (changegroup == NULL) { /* pass the default group of this user */
  1044. changegroup = ""; /* just empty */
  1045. runas_gid = pw->pw_gid;
  1046. }
  1047. if (access(pw->pw_dir, F_OK) == 0)
  1048. setenv("HOME", pw->pw_dir, 1);
  1049. }
  1050. if (stop) {
  1051. int i = run_stop_schedule();
  1052. exit(i);
  1053. }
  1054. do_findprocs();
  1055. if (found) {
  1056. if (quietmode <= 0)
  1057. printf("%s already running.\n", execname ? execname : "process");
  1058. exit(exitnodo);
  1059. }
  1060. if (testmode) {
  1061. printf("Would start %s ", startas);
  1062. while (argc-- > 0)
  1063. printf("%s ", *argv++);
  1064. if (changeuser != NULL) {
  1065. printf(" (as user %s[%d]", changeuser, runas_uid);
  1066. if (changegroup != NULL)
  1067. printf(", and group %s[%d])", changegroup, runas_gid);
  1068. else
  1069. printf(")");
  1070. }
  1071. if (changeroot != NULL)
  1072. printf(" in directory %s", changeroot);
  1073. if (nicelevel)
  1074. printf(", and add %i to the priority", nicelevel);
  1075. printf(".\n");
  1076. exit(0);
  1077. }
  1078. if (quietmode < 0)
  1079. printf("Starting %s...\n", startas);
  1080. *--argv = startas;
  1081. if (background) { /* ok, we need to detach this process */
  1082. int i;
  1083. if (quietmode < 0)
  1084. printf("Detaching to start %s...", startas);
  1085. i = fork();
  1086. if (i<0) {
  1087. fatal("Unable to fork.\n");
  1088. }
  1089. if (i) { /* parent */
  1090. if (quietmode < 0)
  1091. printf("done.\n");
  1092. exit(0);
  1093. }
  1094. /* child continues here */
  1095. #ifdef HAVE_TIOCNOTTY
  1096. tty_fd=open("/dev/tty", O_RDWR);
  1097. #endif
  1098. devnull_fd=open("/dev/null", O_RDWR);
  1099. }
  1100. if (nicelevel) {
  1101. errno=0;
  1102. if ((nice(nicelevel)==-1) && (errno!=0))
  1103. fatal("Unable to alter nice level by %i: %s", nicelevel,
  1104. strerror(errno));
  1105. }
  1106. if (mpidfile && pidfile != NULL) { /* user wants _us_ to make the pidfile :) */
  1107. FILE *pidf = fopen(pidfile, "w");
  1108. pid_t pidt = getpid();
  1109. if (pidf == NULL)
  1110. fatal("Unable to open pidfile `%s' for writing: %s", pidfile,
  1111. strerror(errno));
  1112. fprintf(pidf, "%d\n", pidt);
  1113. fclose(pidf);
  1114. }
  1115. if (changeroot != NULL) {
  1116. if (chdir(changeroot) < 0)
  1117. fatal("Unable to chdir() to %s", changeroot);
  1118. if (chroot(changeroot) < 0)
  1119. fatal("Unable to chroot() to %s", changeroot);
  1120. }
  1121. if (chdir(changedir) < 0)
  1122. fatal("Unable to chdir() to %s", changedir);
  1123. if (changeuser != NULL) {
  1124. if (setgid(runas_gid))
  1125. fatal("Unable to set gid to %d", runas_gid);
  1126. if (initgroups(changeuser, runas_gid))
  1127. fatal("Unable to set initgroups() with gid %d", runas_gid);
  1128. if (setuid(runas_uid))
  1129. fatal("Unable to set uid to %s", changeuser);
  1130. }
  1131. if (background) { /* continue background setup */
  1132. int i;
  1133. #ifdef HAVE_TIOCNOTTY
  1134. /* change tty */
  1135. ioctl(tty_fd, TIOCNOTTY, 0);
  1136. close(tty_fd);
  1137. #endif
  1138. umask(022); /* set a default for dumb programs */
  1139. dup2(devnull_fd,0); /* stdin */
  1140. dup2(devnull_fd,1); /* stdout */
  1141. dup2(devnull_fd,2); /* stderr */
  1142. #if defined(OShpux)
  1143. /* now close all extra fds */
  1144. for (i=sysconf(_SC_OPEN_MAX)-1; i>=3; --i) close(i);
  1145. #else
  1146. /* now close all extra fds */
  1147. for (i=getdtablesize()-1; i>=3; --i) close(i);
  1148. #endif
  1149. /* create a new session */
  1150. #ifdef HAVE_SETSID
  1151. setsid();
  1152. #else
  1153. setpgid(0,0);
  1154. #endif
  1155. }
  1156. execv(startas, argv);
  1157. fatal("Unable to start %s: %s", startas, strerror(errno));
  1158. }