start-stop-daemon.c 32 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345
  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 VERSION 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. " -C|--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. }
  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 char *name)
  545. {
  546. char lname[32];
  547. char *lcontents;
  548. int lcontlen, nread, res;
  549. /* Allow one extra character for the link contents, which should
  550. * be enough to determine if the file names are the same. */
  551. lcontlen = strlen(name) + 1;
  552. lcontents = xmalloc(lcontlen);
  553. sprintf(lname, "/proc/%d/exe", pid);
  554. nread = readlink(lname, lcontents, lcontlen);
  555. if (nread == -1) {
  556. free(lcontents);
  557. return 0;
  558. }
  559. if (nread < lcontlen)
  560. lcontents[nread] = '\0';
  561. res = (strncmp(lcontents, name, lcontlen) == 0);
  562. free(lcontents);
  563. return res;
  564. }
  565. static int
  566. pid_is_user(pid_t pid, uid_t uid)
  567. {
  568. struct stat sb;
  569. char buf[32];
  570. sprintf(buf, "/proc/%d", pid);
  571. if (stat(buf, &sb) != 0)
  572. return 0;
  573. return (sb.st_uid == uid);
  574. }
  575. static int
  576. pid_is_cmd(pid_t pid, const char *name)
  577. {
  578. char buf[32];
  579. FILE *f;
  580. int c;
  581. sprintf(buf, "/proc/%d/stat", pid);
  582. f = fopen(buf, "r");
  583. if (!f)
  584. return 0;
  585. while ((c = getc(f)) != EOF && c != '(')
  586. ;
  587. if (c != '(') {
  588. fclose(f);
  589. return 0;
  590. }
  591. /* this hopefully handles command names containing ')' */
  592. while ((c = getc(f)) != EOF && c == *name)
  593. name++;
  594. fclose(f);
  595. return (c == ')' && *name == '\0');
  596. }
  597. #endif /* OSLinux */
  598. #if defined(OSHURD)
  599. static void
  600. init_procset(void)
  601. {
  602. struct ps_context *context;
  603. error_t err;
  604. err = ps_context_create(getproc(), &context);
  605. if (err)
  606. error(1, err, "ps_context_create");
  607. err = proc_stat_list_create(context, &procset);
  608. if (err)
  609. error(1, err, "proc_stat_list_create");
  610. err = proc_stat_list_add_all(procset, 0, 0);
  611. if (err)
  612. error(1, err, "proc_stat_list_add_all");
  613. }
  614. static struct proc_stat *
  615. get_proc_stat (pid_t pid, ps_flags_t flags)
  616. {
  617. struct proc_stat *ps;
  618. ps_flags_t wanted_flags = PSTAT_PID | flags;
  619. if (!procset)
  620. init_procset();
  621. ps = proc_stat_list_pid_proc_stat(procset, pid);
  622. if (!ps)
  623. return NULL;
  624. if (proc_stat_set_flags(ps, wanted_flags))
  625. return NULL;
  626. if ((proc_stat_flags(ps) & wanted_flags) != wanted_flags)
  627. return NULL;
  628. return ps;
  629. }
  630. static int
  631. pid_is_user(pid_t pid, uid_t uid)
  632. {
  633. struct proc_stat *ps;
  634. ps = get_proc_stat(pid, PSTAT_OWNER_UID);
  635. return ps && proc_stat_owner_uid(ps) == uid;
  636. }
  637. static int
  638. pid_is_cmd(pid_t pid, const char *name)
  639. {
  640. struct proc_stat *ps;
  641. ps = get_proc_stat(pid, PSTAT_ARGS);
  642. return ps && !strcmp(proc_stat_args(ps), name);
  643. }
  644. static int
  645. pid_is_running(pid_t pid)
  646. {
  647. return get_proc_stat(pid, 0) != NULL;
  648. }
  649. #else /* !OSHURD */
  650. static int
  651. pid_is_running(pid_t pid)
  652. {
  653. struct stat sb;
  654. char buf[32];
  655. sprintf(buf, "/proc/%d", pid);
  656. if (stat(buf, &sb) != 0) {
  657. if (errno!=ENOENT)
  658. fatal("Error stating %s: %s", buf, strerror(errno));
  659. return 0;
  660. }
  661. return 1;
  662. }
  663. #endif /* OSHURD */
  664. static void
  665. check(pid_t pid)
  666. {
  667. #if defined(OSLinux)
  668. if (execname && !pid_is_exec(pid, execname))
  669. #elif defined(OShpux)
  670. if (execname && !pid_is_exec(pid, &exec_stat))
  671. #elif defined(OSHURD) || defined(OSFreeBSD) || defined(OSNetBSD)
  672. /* I will try this to see if it works */
  673. if (execname && !pid_is_cmd(pid, execname))
  674. #endif
  675. return;
  676. if (userspec && !pid_is_user(pid, user_id))
  677. return;
  678. if (cmdname && !pid_is_cmd(pid, cmdname))
  679. return;
  680. if (start && !pid_is_running(pid))
  681. return;
  682. push(&found, pid);
  683. }
  684. static void
  685. do_pidfile(const char *name)
  686. {
  687. FILE *f;
  688. pid_t pid;
  689. f = fopen(name, "r");
  690. if (f) {
  691. if (fscanf(f, "%d", &pid) == 1)
  692. check(pid);
  693. fclose(f);
  694. } else if (errno != ENOENT)
  695. fatal("open pidfile %s: %s", name, strerror(errno));
  696. }
  697. /* WTA: this needs to be an autoconf check for /proc/pid existance.
  698. */
  699. #if defined(OSLinux) || defined (OSsunos)
  700. static void
  701. do_procinit(void)
  702. {
  703. DIR *procdir;
  704. struct dirent *entry;
  705. int foundany;
  706. pid_t pid;
  707. procdir = opendir("/proc");
  708. if (!procdir)
  709. fatal("opendir /proc: %s", strerror(errno));
  710. foundany = 0;
  711. while ((entry = readdir(procdir)) != NULL) {
  712. if (sscanf(entry->d_name, "%d", &pid) != 1)
  713. continue;
  714. foundany++;
  715. check(pid);
  716. }
  717. closedir(procdir);
  718. if (!foundany)
  719. fatal("nothing in /proc - not mounted?");
  720. }
  721. #endif /* OSLinux */
  722. #if defined(OSHURD)
  723. static int
  724. check_proc_stat (struct proc_stat *ps)
  725. {
  726. check(ps->pid);
  727. return 0;
  728. }
  729. static void
  730. do_procinit(void)
  731. {
  732. if (!procset)
  733. init_procset();
  734. proc_stat_list_for_each (procset, check_proc_stat);
  735. }
  736. #endif /* OSHURD */
  737. #ifdef HAVE_KVM_H
  738. static int
  739. pid_is_cmd(pid_t pid, const char *name)
  740. {
  741. kvm_t *kd;
  742. int nentries, argv_len=0;
  743. struct kinfo_proc *kp;
  744. char errbuf[_POSIX2_LINE_MAX], buf[_POSIX2_LINE_MAX];
  745. char **pid_argv_p;
  746. char *start_argv_0_p, *end_argv_0_p;
  747. kd = kvm_openfiles(NULL, NULL, NULL, O_RDONLY, errbuf);
  748. if (kd == 0)
  749. errx(1, "%s", errbuf);
  750. if ((kp = kvm_getprocs(kd, KERN_PROC_PID, pid, &nentries)) == 0)
  751. errx(1, "%s", kvm_geterr(kd));
  752. if ((pid_argv_p = kvm_getargv(kd, kp, argv_len)) == 0)
  753. errx(1, "%s", kvm_geterr(kd));
  754. start_argv_0_p = *pid_argv_p;
  755. /* find and compare string */
  756. /* find end of argv[0] then copy and cut of str there. */
  757. if ((end_argv_0_p = strchr(*pid_argv_p, ' ')) == 0 )
  758. /* There seems to be no space, so we have the command
  759. * allready in its desired form. */
  760. start_argv_0_p = *pid_argv_p;
  761. else {
  762. /* Tests indicate that this never happens, since
  763. * kvm_getargv itselfe cuts of tailing stuff. This is
  764. * not what the manpage says, however. */
  765. strncpy(buf, *pid_argv_p, (end_argv_0_p - start_argv_0_p));
  766. buf[(end_argv_0_p - start_argv_0_p) + 1] = '\0';
  767. start_argv_0_p = buf;
  768. }
  769. if (strlen(name) != strlen(start_argv_0_p))
  770. return 0;
  771. return (strcmp(name, start_argv_0_p) == 0) ? 1 : 0;
  772. }
  773. static int
  774. pid_is_user(pid_t pid, uid_t uid)
  775. {
  776. kvm_t *kd;
  777. int nentries; /* Value not used */
  778. uid_t proc_uid;
  779. struct kinfo_proc *kp;
  780. char errbuf[_POSIX2_LINE_MAX];
  781. kd = kvm_openfiles(NULL, NULL, NULL, O_RDONLY, errbuf);
  782. if (kd == 0)
  783. errx(1, "%s", errbuf);
  784. if ((kp = kvm_getprocs(kd, KERN_PROC_PID, pid, &nentries)) == 0)
  785. errx(1, "%s", kvm_geterr(kd));
  786. if (kp->kp_proc.p_cred )
  787. kvm_read(kd, (u_long)&(kp->kp_proc.p_cred->p_ruid),
  788. &proc_uid, sizeof(uid_t));
  789. else
  790. return 0;
  791. return (proc_uid == (uid_t)uid);
  792. }
  793. static int
  794. pid_is_exec(pid_t pid, const char *name)
  795. {
  796. kvm_t *kd;
  797. int nentries;
  798. struct kinfo_proc *kp;
  799. char errbuf[_POSIX2_LINE_MAX], *pidexec;
  800. kd = kvm_openfiles(NULL, NULL, NULL, O_RDONLY, errbuf);
  801. if (kd == 0)
  802. errx(1, "%s", errbuf);
  803. if ((kp = kvm_getprocs(kd, KERN_PROC_PID, pid, &nentries)) == 0)
  804. errx(1, "%s", kvm_geterr(kd));
  805. pidexec = (&kp->kp_proc)->p_comm;
  806. if (strlen(name) != strlen(pidexec))
  807. return 0;
  808. return (strcmp(name, pidexec) == 0) ? 1 : 0;
  809. }
  810. static void
  811. do_procinit(void)
  812. {
  813. /* Nothing to do */
  814. }
  815. #endif /* OSOpenBSD */
  816. #if defined(OShpux)
  817. static int
  818. pid_is_user(pid_t pid, uid_t uid)
  819. {
  820. struct pst_status pst;
  821. if (pstat_getproc(&pst, sizeof(pst), (size_t) 0, (int) pid) < 0)
  822. return 0;
  823. return ((uid_t) pst.pst_uid == uid);
  824. }
  825. static int
  826. pid_is_cmd(pid_t pid, const char *name)
  827. {
  828. struct pst_status pst;
  829. if (pstat_getproc(&pst, sizeof(pst), (size_t) 0, (int) pid) < 0)
  830. return 0;
  831. return (strcmp(pst.pst_ucomm, name) == 0);
  832. }
  833. static int
  834. pid_is_exec(pid_t pid, const struct stat *esb)
  835. {
  836. struct pst_status pst;
  837. if (pstat_getproc(&pst, sizeof(pst), (size_t) 0, (int) pid) < 0)
  838. return 0;
  839. return ((dev_t) pst.pst_text.psf_fsid.psfs_id == esb->st_dev
  840. && (ino_t) pst.pst_text.psf_fileid == esb->st_ino);
  841. }
  842. static void
  843. do_procinit(void)
  844. {
  845. struct pst_status pst[10];
  846. int i, count;
  847. int idx = 0;
  848. while ((count = pstat_getproc(pst, sizeof(pst[0]), 10, idx)) > 0) {
  849. for (i = 0; i < count; i++)
  850. check(pst[i].pst_pid);
  851. idx = pst[count - 1].pst_idx + 1;
  852. }
  853. }
  854. #endif /* OShpux */
  855. static void
  856. do_findprocs(void)
  857. {
  858. clear(&found);
  859. if (pidfile)
  860. do_pidfile(pidfile);
  861. else
  862. do_procinit();
  863. }
  864. /* return 1 on failure */
  865. static void
  866. do_stop(int signal_nr, int quietmode, int *n_killed, int *n_notkilled, int retry_nr)
  867. {
  868. struct pid_list *p;
  869. do_findprocs();
  870. *n_killed = 0;
  871. *n_notkilled = 0;
  872. if (!found)
  873. return;
  874. clear(&killed);
  875. for (p = found; p; p = p->next) {
  876. if (testmode) {
  877. printf("Would send signal %d to %d.\n",
  878. signal_nr, p->pid);
  879. (*n_killed)++;
  880. } else if (kill(p->pid, signal_nr) == 0) {
  881. push(&killed, p->pid);
  882. (*n_killed)++;
  883. } else {
  884. printf("%s: warning: failed to kill %d: %s\n",
  885. progname, p->pid, strerror(errno));
  886. (*n_notkilled)++;
  887. }
  888. }
  889. if (quietmode < 0 && killed) {
  890. printf("Stopped %s (pid", what_stop);
  891. for (p = killed; p; p = p->next)
  892. printf(" %d", p->pid);
  893. putchar(')');
  894. if (retry_nr > 0)
  895. printf(", retry #%d", retry_nr);
  896. printf(".\n");
  897. }
  898. }
  899. static void
  900. set_what_stop(const char *str)
  901. {
  902. strncpy(what_stop, str, sizeof(what_stop));
  903. what_stop[sizeof(what_stop)-1] = '\0';
  904. }
  905. static int
  906. run_stop_schedule(void)
  907. {
  908. int r, position, n_killed, n_notkilled, value, ratio, anykilled, retry_nr;
  909. struct timeval stopat, before, after, interval, maxinterval;
  910. if (testmode) {
  911. if (schedule != NULL) {
  912. printf("Ignoring --retry in test mode\n");
  913. schedule = NULL;
  914. }
  915. }
  916. if (cmdname)
  917. set_what_stop(cmdname);
  918. else if (execname)
  919. set_what_stop(execname);
  920. else if (pidfile)
  921. sprintf(what_stop, "process in pidfile `%.200s'", pidfile);
  922. else if (userspec)
  923. sprintf(what_stop, "process(es) owned by `%.200s'", userspec);
  924. else
  925. fatal("internal error, please report");
  926. anykilled = 0;
  927. retry_nr = 0;
  928. if (schedule == NULL) {
  929. do_stop(signal_nr, quietmode, &n_killed, &n_notkilled, 0);
  930. if (n_notkilled > 0 && quietmode <= 0)
  931. printf("%d pids were not killed\n", n_notkilled);
  932. if (n_killed)
  933. anykilled = 1;
  934. goto x_finished;
  935. }
  936. for (position = 0; position < schedule_length; ) {
  937. value= schedule[position].value;
  938. n_notkilled = 0;
  939. switch (schedule[position].type) {
  940. case sched_goto:
  941. position = value;
  942. continue;
  943. case sched_signal:
  944. do_stop(value, quietmode, &n_killed, &n_notkilled, retry_nr++);
  945. if (!n_killed)
  946. goto x_finished;
  947. else
  948. anykilled = 1;
  949. goto next_item;
  950. case sched_timeout:
  951. /* We want to keep polling for the processes, to see if they've exited,
  952. * or until the timeout expires.
  953. *
  954. * This is a somewhat complicated algorithm to try to ensure that we
  955. * notice reasonably quickly when all the processes have exited, but
  956. * don't spend too much CPU time polling. In particular, on a fast
  957. * machine with quick-exiting daemons we don't want to delay system
  958. * shutdown too much, whereas on a slow one, or where processes are
  959. * taking some time to exit, we want to increase the polling
  960. * interval.
  961. *
  962. * The algorithm is as follows: we measure the elapsed time it takes
  963. * to do one poll(), and wait a multiple of this time for the next
  964. * poll. However, if that would put us past the end of the timeout
  965. * period we wait only as long as the timeout period, but in any case
  966. * we always wait at least MIN_POLL_INTERVAL (20ms). The multiple
  967. * (`ratio') starts out as 2, and increases by 1 for each poll to a
  968. * maximum of 10; so we use up to between 30% and 10% of the
  969. * machine's resources (assuming a few reasonable things about system
  970. * performance).
  971. */
  972. xgettimeofday(&stopat);
  973. stopat.tv_sec += value;
  974. ratio = 1;
  975. for (;;) {
  976. xgettimeofday(&before);
  977. if (timercmp(&before,&stopat,>))
  978. goto next_item;
  979. do_stop(0, 1, &n_killed, &n_notkilled, 0);
  980. if (!n_killed)
  981. goto x_finished;
  982. xgettimeofday(&after);
  983. if (!timercmp(&after,&stopat,<))
  984. goto next_item;
  985. if (ratio < 10)
  986. ratio++;
  987. TVCALC(interval, ratio * (TVELEM(&after) - TVELEM(&before) + TVADJUST));
  988. TVCALC(maxinterval, TVELEM(&stopat) - TVELEM(&after) + TVADJUST);
  989. if (timercmp(&interval,&maxinterval,>))
  990. interval = maxinterval;
  991. if (interval.tv_sec == 0 &&
  992. interval.tv_usec <= MIN_POLL_INTERVAL)
  993. interval.tv_usec = MIN_POLL_INTERVAL;
  994. r = select(0,0,0,0,&interval);
  995. if (r < 0 && errno != EINTR)
  996. fatal("select() failed for pause: %s",
  997. strerror(errno));
  998. }
  999. default:
  1000. assert(!"schedule[].type value must be valid");
  1001. }
  1002. next_item:
  1003. position++;
  1004. }
  1005. if (quietmode <= 0)
  1006. printf("Program %s, %d process(es), refused to die.\n",
  1007. what_stop, n_killed);
  1008. return 2;
  1009. x_finished:
  1010. if (!anykilled) {
  1011. if (quietmode <= 0)
  1012. printf("No %s found running; none killed.\n", what_stop);
  1013. return exitnodo;
  1014. } else {
  1015. return 0;
  1016. }
  1017. }
  1018. int
  1019. main(int argc, char **argv)
  1020. {
  1021. int devnull_fd = -1;
  1022. #ifdef HAVE_TIOCNOTTY
  1023. int tty_fd = -1;
  1024. #endif
  1025. progname = argv[0];
  1026. parse_options(argc, argv);
  1027. argc -= optind;
  1028. argv += optind;
  1029. if (execname && stat(execname, &exec_stat))
  1030. fatal("stat %s: %s", execname, strerror(errno));
  1031. if (userspec && sscanf(userspec, "%d", &user_id) != 1) {
  1032. struct passwd *pw;
  1033. pw = getpwnam(userspec);
  1034. if (!pw)
  1035. fatal("user `%s' not found\n", userspec);
  1036. user_id = pw->pw_uid;
  1037. }
  1038. if (changegroup && sscanf(changegroup, "%d", &runas_gid) != 1) {
  1039. struct group *gr = getgrnam(changegroup);
  1040. if (!gr)
  1041. fatal("group `%s' not found\n", changegroup);
  1042. runas_gid = gr->gr_gid;
  1043. }
  1044. if (changeuser && sscanf(changeuser, "%d", &runas_uid) != 1) {
  1045. struct passwd *pw = getpwnam(changeuser);
  1046. if (!pw)
  1047. fatal("user `%s' not found\n", changeuser);
  1048. runas_uid = pw->pw_uid;
  1049. if (changegroup == NULL) { /* pass the default group of this user */
  1050. changegroup = ""; /* just empty */
  1051. runas_gid = pw->pw_gid;
  1052. }
  1053. }
  1054. if (stop) {
  1055. int i = run_stop_schedule();
  1056. exit(i);
  1057. }
  1058. do_findprocs();
  1059. if (found) {
  1060. if (quietmode <= 0)
  1061. printf("%s already running.\n", execname ? execname : "process");
  1062. exit(exitnodo);
  1063. }
  1064. if (testmode) {
  1065. printf("Would start %s ", startas);
  1066. while (argc-- > 0)
  1067. printf("%s ", *argv++);
  1068. if (changeuser != NULL) {
  1069. printf(" (as user %s[%d]", changeuser, runas_uid);
  1070. if (changegroup != NULL)
  1071. printf(", and group %s[%d])", changegroup, runas_gid);
  1072. else
  1073. printf(")");
  1074. }
  1075. if (changeroot != NULL)
  1076. printf(" in directory %s", changeroot);
  1077. if (nicelevel)
  1078. printf(", and add %i to the priority", nicelevel);
  1079. printf(".\n");
  1080. exit(0);
  1081. }
  1082. if (quietmode < 0)
  1083. printf("Starting %s...\n", startas);
  1084. *--argv = startas;
  1085. if (background) { /* ok, we need to detach this process */
  1086. int i;
  1087. if (quietmode < 0)
  1088. printf("Detaching to start %s...", startas);
  1089. i = fork();
  1090. if (i<0) {
  1091. fatal("Unable to fork.\n");
  1092. }
  1093. if (i) { /* parent */
  1094. if (quietmode < 0)
  1095. printf("done.\n");
  1096. exit(0);
  1097. }
  1098. /* child continues here */
  1099. #ifdef HAVE_TIOCNOTTY
  1100. tty_fd=open("/dev/tty", O_RDWR);
  1101. #endif
  1102. devnull_fd=open("/dev/null", O_RDWR);
  1103. }
  1104. if (nicelevel) {
  1105. errno=0;
  1106. if ((nice(nicelevel)==-1) && (errno!=0))
  1107. fatal("Unable to alter nice level by %i: %s", nicelevel,
  1108. strerror(errno));
  1109. }
  1110. if (mpidfile && pidfile != NULL) { /* user wants _us_ to make the pidfile :) */
  1111. FILE *pidf = fopen(pidfile, "w");
  1112. pid_t pidt = getpid();
  1113. if (pidf == NULL)
  1114. fatal("Unable to open pidfile `%s' for writing: %s", pidfile,
  1115. strerror(errno));
  1116. fprintf(pidf, "%d\n", pidt);
  1117. fclose(pidf);
  1118. }
  1119. if (changeroot != NULL) {
  1120. if (chdir(changeroot) < 0)
  1121. fatal("Unable to chdir() to %s", changeroot);
  1122. if (chroot(changeroot) < 0)
  1123. fatal("Unable to chroot() to %s", changeroot);
  1124. }
  1125. if (chdir(changedir) < 0)
  1126. fatal("Unable to chdir() to %s", changedir);
  1127. if (changeuser != NULL) {
  1128. if (setgid(runas_gid))
  1129. fatal("Unable to set gid to %d", runas_gid);
  1130. if (initgroups(changeuser, runas_gid))
  1131. fatal("Unable to set initgroups() with gid %d", runas_gid);
  1132. if (setuid(runas_uid))
  1133. fatal("Unable to set uid to %s", changeuser);
  1134. }
  1135. if (background) { /* continue background setup */
  1136. int i;
  1137. #ifdef HAVE_TIOCNOTTY
  1138. /* change tty */
  1139. ioctl(tty_fd, TIOCNOTTY, 0);
  1140. close(tty_fd);
  1141. #endif
  1142. umask(022); /* set a default for dumb programs */
  1143. dup2(devnull_fd,0); /* stdin */
  1144. dup2(devnull_fd,1); /* stdout */
  1145. dup2(devnull_fd,2); /* stderr */
  1146. #if defined(OShpux)
  1147. /* now close all extra fds */
  1148. for (i=sysconf(_SC_OPEN_MAX)-1; i>=3; --i) close(i);
  1149. #else
  1150. /* now close all extra fds */
  1151. for (i=getdtablesize()-1; i>=3; --i) close(i);
  1152. #endif
  1153. /* create a new session */
  1154. #ifdef HAVE_SETSID
  1155. setsid();
  1156. #else
  1157. setpgid(0,0);
  1158. #endif
  1159. }
  1160. execv(startas, argv);
  1161. fatal("Unable to start %s: %s", startas, strerror(errno));
  1162. }