start-stop-daemon.c 32 KB

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