start-stop-daemon.c 32 KB

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