start-stop-daemon.c 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653
  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. #include <compat.h>
  24. #include <dpkg/macros.h>
  25. #if defined(linux) || (defined(__FreeBSD_kernel__) && defined(__GLIBC__))
  26. # define OSLinux
  27. #elif defined(__GNU__)
  28. # define OSHurd
  29. #elif defined(__sun)
  30. # define OSsunos
  31. #elif defined(OPENBSD) || defined(__OpenBSD__)
  32. # define OSOpenBSD
  33. #elif defined(hpux)
  34. # define OShpux
  35. #elif defined(__FreeBSD__)
  36. # define OSFreeBSD
  37. #elif defined(__NetBSD__)
  38. # define OSNetBSD
  39. #else
  40. # error Unknown architecture - cannot build start-stop-daemon
  41. #endif
  42. #define MIN_POLL_INTERVAL 20000 /* µs */
  43. #ifdef HAVE_SYS_CDEFS_H
  44. #include <sys/cdefs.h>
  45. #endif
  46. #ifdef HAVE_SYS_SYSCALL_H
  47. #include <sys/syscall.h>
  48. #endif
  49. #if defined(OSHurd)
  50. #include <hurd.h>
  51. #include <ps.h>
  52. #endif
  53. #if defined(OSOpenBSD) || defined(OSFreeBSD) || defined(OSNetBSD)
  54. #include <sys/param.h>
  55. #include <sys/proc.h>
  56. #include <err.h>
  57. #endif
  58. #ifdef HAVE_KVM_H
  59. #include <sys/sysctl.h>
  60. #include <sys/user.h>
  61. #include <kvm.h>
  62. #endif
  63. #if defined(OShpux)
  64. #include <sys/param.h>
  65. #include <sys/pstat.h>
  66. #endif
  67. #include <sys/types.h>
  68. #include <sys/time.h>
  69. #include <sys/stat.h>
  70. #include <sys/ioctl.h>
  71. #include <sys/termios.h>
  72. #include <assert.h>
  73. #include <errno.h>
  74. #include <limits.h>
  75. #include <fcntl.h>
  76. #include <dirent.h>
  77. #include <ctype.h>
  78. #include <string.h>
  79. #include <pwd.h>
  80. #include <grp.h>
  81. #include <signal.h>
  82. #include <unistd.h>
  83. #ifdef HAVE_STDDEF_H
  84. #include <stddef.h>
  85. #endif
  86. #include <stdbool.h>
  87. #include <stdarg.h>
  88. #include <stdlib.h>
  89. #include <stdio.h>
  90. #include <getopt.h>
  91. #ifdef HAVE_ERROR_H
  92. #include <error.h>
  93. #endif
  94. #ifdef _POSIX_PRIORITY_SCHEDULING
  95. #include <sched.h>
  96. #else
  97. #define SCHED_OTHER -1
  98. #define SCHED_FIFO -1
  99. #define SCHED_RR -1
  100. #endif
  101. #if defined(OSLinux)
  102. /* This comes from TASK_COMM_LEN defined in linux's include/linux/sched.h. */
  103. #define PROCESS_NAME_SIZE 15
  104. #endif
  105. #if defined(SYS_ioprio_set) && defined(linux)
  106. #define HAVE_IOPRIO_SET
  107. #endif
  108. enum {
  109. IOPRIO_WHO_PROCESS = 1,
  110. IOPRIO_WHO_PGRP,
  111. IOPRIO_WHO_USER,
  112. };
  113. enum {
  114. IOPRIO_CLASS_NONE,
  115. IOPRIO_CLASS_RT,
  116. IOPRIO_CLASS_BE,
  117. IOPRIO_CLASS_IDLE,
  118. };
  119. static int testmode = 0;
  120. static int quietmode = 0;
  121. static int exitnodo = 1;
  122. static int start = 0;
  123. static int stop = 0;
  124. static int background = 0;
  125. static int mpidfile = 0;
  126. static int signal_nr = SIGTERM;
  127. static int user_id = -1;
  128. static int runas_uid = -1;
  129. static int runas_gid = -1;
  130. static const char *userspec = NULL;
  131. static char *changeuser = NULL;
  132. static const char *changegroup = NULL;
  133. static char *changeroot = NULL;
  134. static const char *changedir = "/";
  135. static const char *cmdname = NULL;
  136. static char *execname = NULL;
  137. static char *startas = NULL;
  138. static const char *pidfile = NULL;
  139. static char what_stop[1024];
  140. static const char *progname = "";
  141. static int nicelevel = 0;
  142. static int umask_value = -1;
  143. #define IOPRIO_CLASS_SHIFT 13
  144. #define IOPRIO_PRIO_VALUE(class, prio) (((class) << IOPRIO_CLASS_SHIFT) | (prio))
  145. #define IO_SCHED_PRIO_MIN 0
  146. #define IO_SCHED_PRIO_MAX 7
  147. static struct stat exec_stat;
  148. #if defined(OSHurd)
  149. static struct proc_stat_list *procset = NULL;
  150. #endif
  151. struct pid_list {
  152. struct pid_list *next;
  153. pid_t pid;
  154. };
  155. static struct pid_list *found = NULL;
  156. static struct pid_list *killed = NULL;
  157. /* Resource scheduling policy. */
  158. struct res_schedule {
  159. const char *policy_name;
  160. int policy;
  161. int priority;
  162. };
  163. struct schedule_item {
  164. enum {
  165. sched_timeout,
  166. sched_signal,
  167. sched_goto,
  168. sched_forever /* Only seen within parse_schedule and callees */
  169. } type;
  170. int value; /* Seconds, signal no., or index into array. */
  171. };
  172. static struct res_schedule *proc_sched = NULL;
  173. static struct res_schedule *io_sched = NULL;
  174. static int schedule_length;
  175. static struct schedule_item *schedule = NULL;
  176. static void *xmalloc(int size);
  177. static void push(struct pid_list **list, pid_t pid);
  178. static void do_help(void);
  179. static void parse_options(int argc, char * const *argv);
  180. static bool pid_is_user(pid_t pid, uid_t uid);
  181. static bool pid_is_cmd(pid_t pid, const char *name);
  182. static void check(pid_t pid);
  183. static void do_pidfile(const char *name);
  184. static void do_stop(int sig_num, int quiet,
  185. int *n_killed, int *n_notkilled, int retry_nr);
  186. #if defined(OSLinux) || defined(OShpux)
  187. static bool pid_is_exec(pid_t pid, const struct stat *esb);
  188. #endif
  189. static void DPKG_ATTR_PRINTF(1)
  190. warning(const char *format, ...)
  191. {
  192. va_list arglist;
  193. fprintf(stderr, "%s: warning: ", progname);
  194. va_start(arglist, format);
  195. vfprintf(stderr, format, arglist);
  196. va_end(arglist);
  197. }
  198. static void DPKG_ATTR_NORET DPKG_ATTR_PRINTF(1)
  199. fatal(const char *format, ...)
  200. {
  201. va_list arglist;
  202. int errno_fatal = errno;
  203. fprintf(stderr, "%s: ", progname);
  204. va_start(arglist, format);
  205. vfprintf(stderr, format, arglist);
  206. va_end(arglist);
  207. if (errno_fatal)
  208. fprintf(stderr, " (%s)\n", strerror(errno_fatal));
  209. else
  210. fprintf(stderr, "\n");
  211. exit(2);
  212. }
  213. static void *
  214. xmalloc(int size)
  215. {
  216. void *ptr;
  217. ptr = malloc(size);
  218. if (ptr)
  219. return ptr;
  220. fatal("malloc(%d) failed", size);
  221. }
  222. static char *
  223. xstrdup(const char *str)
  224. {
  225. char *new_str;
  226. new_str = strdup(str);
  227. if (new_str)
  228. return new_str;
  229. fatal("strdup(%s) failed", str);
  230. }
  231. static void
  232. xgettimeofday(struct timeval *tv)
  233. {
  234. if (gettimeofday(tv, NULL) != 0)
  235. fatal("gettimeofday failed");
  236. }
  237. static void
  238. tmul(struct timeval *a, int b)
  239. {
  240. a->tv_sec *= b;
  241. a->tv_usec *= b;
  242. a->tv_sec = a->tv_sec + a->tv_usec / 1000000;
  243. a->tv_usec %= 1000000;
  244. }
  245. static long
  246. get_open_fd_max(void)
  247. {
  248. #ifdef HAVE_GETDTABLESIZE
  249. return getdtablesize();
  250. #else
  251. return sysconf(_SC_OPEN_MAX);
  252. #endif
  253. }
  254. #ifndef HAVE_SETSID
  255. static void
  256. detach_controlling_tty(void)
  257. {
  258. #ifdef HAVE_TIOCNOTTY
  259. int tty_fd;
  260. tty_fd = open("/dev/tty", O_RDWR);
  261. /* The current process does not have a controlling tty. */
  262. if (tty_fd < 0)
  263. return;
  264. if (ioctl(tty_fd, TIOCNOTTY, 0) != 0)
  265. fatal("unable to detach controlling tty");
  266. close(tty_fd);
  267. #endif
  268. }
  269. #endif
  270. static void
  271. daemonize(void)
  272. {
  273. pid_t pid;
  274. if (quietmode < 0)
  275. printf("Detaching to start %s...", startas);
  276. pid = fork();
  277. if (pid < 0)
  278. fatal("unable to do first fork");
  279. else if (pid) /* Parent. */
  280. _exit(0);
  281. /* Create a new session. */
  282. #ifdef HAVE_SETSID
  283. setsid();
  284. #else
  285. setpgid(0, 0);
  286. detach_controlling_tty();
  287. #endif
  288. pid = fork();
  289. if (pid < 0)
  290. fatal("unable to do second fork");
  291. else if (pid) /* Parent. */
  292. _exit(0);
  293. if (quietmode < 0)
  294. printf("done.\n");
  295. }
  296. static void
  297. push(struct pid_list **list, pid_t pid)
  298. {
  299. struct pid_list *p;
  300. p = xmalloc(sizeof(*p));
  301. p->next = *list;
  302. p->pid = pid;
  303. *list = p;
  304. }
  305. static void
  306. clear(struct pid_list **list)
  307. {
  308. struct pid_list *here, *next;
  309. for (here = *list; here != NULL; here = next) {
  310. next = here->next;
  311. free(here);
  312. }
  313. *list = NULL;
  314. }
  315. static void
  316. do_help(void)
  317. {
  318. printf(
  319. "Usage: start-stop-daemon [<option> ...] <command>\n"
  320. "\n"
  321. "Commands:\n"
  322. " -S|--start -- <argument> ... start a program and pass <arguments> to it\n"
  323. " -K|--stop stop a program\n"
  324. " -H|--help print help information\n"
  325. " -V|--version print version\n"
  326. "\n"
  327. "Matching options (at least one is required):\n"
  328. " -p|--pidfile <pid-file> pid file to check\n"
  329. " -x|--exec <executable> program to start/check if it is running\n"
  330. " -n|--name <process-name> process name to check\n"
  331. " -u|--user <username|uid> process owner to check\n"
  332. "\n"
  333. "Options:\n"
  334. " -g|--group <group|gid> run process as this group\n"
  335. " -c|--chuid <name|uid[:group|gid]>\n"
  336. " change to this user/group before starting\n"
  337. " process\n"
  338. " -s|--signal <signal> signal to send (default TERM)\n"
  339. " -a|--startas <pathname> program to start (default is <executable>)\n"
  340. " -r|--chroot <directory> chroot to <directory> before starting\n"
  341. " -d|--chdir <directory> change to <directory> (default is /)\n"
  342. " -N|--nicelevel <incr> add incr to the process's nice level\n"
  343. " -P|--procsched <policy[:prio]>\n"
  344. " use <policy> with <prio> for the kernel\n"
  345. " process scheduler (default prio is 0)\n"
  346. " -I|--iosched <class[:prio]> use <class> with <prio> to set the IO\n"
  347. " scheduler (default prio is 4)\n"
  348. " -k|--umask <mask> change the umask to <mask> before starting\n"
  349. " -b|--background force the process to detach\n"
  350. " -m|--make-pidfile create the pidfile before starting\n"
  351. " -R|--retry <schedule> check whether processes die, and retry\n"
  352. " -t|--test test mode, don't do anything\n"
  353. " -o|--oknodo exit status 0 (not 1) if nothing done\n"
  354. " -q|--quiet be more quiet\n"
  355. " -v|--verbose be more verbose\n"
  356. "\n"
  357. "Retry <schedule> is <item>|/<item>/... where <item> is one of\n"
  358. " -<signal-num>|[-]<signal-name> send that signal\n"
  359. " <timeout> wait that many seconds\n"
  360. " forever repeat remainder forever\n"
  361. "or <schedule> may be just <timeout>, meaning <signal>/<timeout>/KILL/<timeout>\n"
  362. "\n"
  363. "The process scheduler <policy> can be one of:\n"
  364. " other, fifo or rr\n"
  365. "\n"
  366. "The IO scheduler <class> can be one of:\n"
  367. " real-time, best-effort or idle\n"
  368. "\n"
  369. "Exit status: 0 = done 1 = nothing done (=> 0 if --oknodo)\n"
  370. " 3 = trouble 2 = with --retry, processes wouldn't die\n");
  371. }
  372. static void
  373. do_version(void)
  374. {
  375. printf("start-stop-daemon %s for Debian\n\n", VERSION);
  376. printf("Written by Marek Michalkiewicz, public domain.\n");
  377. }
  378. static void DPKG_ATTR_NORET
  379. badusage(const char *msg)
  380. {
  381. if (msg)
  382. fprintf(stderr, "%s: %s\n", progname, msg);
  383. fprintf(stderr, "Try '%s --help' for more information.\n", progname);
  384. exit(3);
  385. }
  386. struct sigpair {
  387. const char *name;
  388. int signal;
  389. };
  390. static const struct sigpair siglist[] = {
  391. { "ABRT", SIGABRT },
  392. { "ALRM", SIGALRM },
  393. { "FPE", SIGFPE },
  394. { "HUP", SIGHUP },
  395. { "ILL", SIGILL },
  396. { "INT", SIGINT },
  397. { "KILL", SIGKILL },
  398. { "PIPE", SIGPIPE },
  399. { "QUIT", SIGQUIT },
  400. { "SEGV", SIGSEGV },
  401. { "TERM", SIGTERM },
  402. { "USR1", SIGUSR1 },
  403. { "USR2", SIGUSR2 },
  404. { "CHLD", SIGCHLD },
  405. { "CONT", SIGCONT },
  406. { "STOP", SIGSTOP },
  407. { "TSTP", SIGTSTP },
  408. { "TTIN", SIGTTIN },
  409. { "TTOU", SIGTTOU }
  410. };
  411. static int
  412. parse_integer(const char *string, int *value_r)
  413. {
  414. unsigned long ul;
  415. char *ep;
  416. if (!string[0])
  417. return -1;
  418. ul = strtoul(string, &ep, 10);
  419. if (string == ep || ul > INT_MAX || *ep != '\0')
  420. return -1;
  421. *value_r = ul;
  422. return 0;
  423. }
  424. static int
  425. parse_signal(const char *sig_str, int *sig_num)
  426. {
  427. unsigned int i;
  428. if (parse_integer(sig_str, sig_num) == 0)
  429. return 0;
  430. for (i = 0; i < array_count(siglist); i++) {
  431. if (strcmp(sig_str, siglist[i].name) == 0) {
  432. *sig_num = siglist[i].signal;
  433. return 0;
  434. }
  435. }
  436. return -1;
  437. }
  438. static int
  439. parse_umask(const char *string, int *value_r)
  440. {
  441. if (!string[0])
  442. return -1;
  443. errno = 0;
  444. *value_r = strtoul(string, NULL, 0);
  445. if (errno)
  446. return -1;
  447. else
  448. return 0;
  449. }
  450. static void
  451. validate_proc_schedule(void)
  452. {
  453. #ifdef _POSIX_PRIORITY_SCHEDULING
  454. int prio_min, prio_max;
  455. prio_min = sched_get_priority_min(proc_sched->policy);
  456. prio_max = sched_get_priority_max(proc_sched->policy);
  457. if (proc_sched->priority < prio_min)
  458. badusage("process scheduler priority less than min");
  459. if (proc_sched->priority > prio_max)
  460. badusage("process scheduler priority greater than max");
  461. #endif
  462. }
  463. static void
  464. parse_proc_schedule(const char *string)
  465. {
  466. char *policy_str, *prio_str;
  467. int prio = 0;
  468. policy_str = xstrdup(string);
  469. policy_str = strtok(policy_str, ":");
  470. prio_str = strtok(NULL, ":");
  471. if (prio_str && parse_integer(prio_str, &prio) != 0)
  472. fatal("invalid process scheduler priority");
  473. proc_sched = xmalloc(sizeof(*proc_sched));
  474. proc_sched->policy_name = policy_str;
  475. if (strcmp(policy_str, "other") == 0) {
  476. proc_sched->policy = SCHED_OTHER;
  477. proc_sched->priority = 0;
  478. } else if (strcmp(policy_str, "fifo") == 0) {
  479. proc_sched->policy = SCHED_FIFO;
  480. proc_sched->priority = prio;
  481. } else if (strcmp(policy_str, "rr") == 0) {
  482. proc_sched->policy = SCHED_RR;
  483. proc_sched->priority = prio;
  484. } else
  485. badusage("invalid process scheduler policy");
  486. validate_proc_schedule();
  487. }
  488. static void
  489. parse_io_schedule(const char *string)
  490. {
  491. char *class_str, *prio_str;
  492. int prio = 4;
  493. class_str = xstrdup(string);
  494. class_str = strtok(class_str, ":");
  495. prio_str = strtok(NULL, ":");
  496. if (prio_str && parse_integer(prio_str, &prio) != 0)
  497. fatal("invalid IO scheduler priority");
  498. io_sched = xmalloc(sizeof(*io_sched));
  499. io_sched->policy_name = class_str;
  500. if (strcmp(class_str, "real-time") == 0) {
  501. io_sched->policy = IOPRIO_CLASS_RT;
  502. io_sched->priority = prio;
  503. } else if (strcmp(class_str, "best-effort") == 0) {
  504. io_sched->policy = IOPRIO_CLASS_BE;
  505. io_sched->priority = prio;
  506. } else if (strcmp(class_str, "idle") == 0) {
  507. io_sched->policy = IOPRIO_CLASS_IDLE;
  508. io_sched->priority = 7;
  509. } else
  510. badusage("invalid IO scheduler policy");
  511. if (io_sched->priority < IO_SCHED_PRIO_MIN)
  512. badusage("IO scheduler priority less than min");
  513. if (io_sched->priority > IO_SCHED_PRIO_MAX)
  514. badusage("IO scheduler priority greater than max");
  515. }
  516. static void
  517. set_proc_schedule(struct res_schedule *sched)
  518. {
  519. #ifdef _POSIX_PRIORITY_SCHEDULING
  520. struct sched_param param;
  521. param.sched_priority = sched->priority;
  522. if (sched_setscheduler(getpid(), sched->policy, &param) == -1)
  523. fatal("unable to set process scheduler");
  524. #endif
  525. }
  526. #ifdef HAVE_IOPRIO_SET
  527. static inline int
  528. ioprio_set(int which, int who, int ioprio)
  529. {
  530. return syscall(SYS_ioprio_set, which, who, ioprio);
  531. }
  532. #endif
  533. static void
  534. set_io_schedule(struct res_schedule *sched)
  535. {
  536. #ifdef HAVE_IOPRIO_SET
  537. int io_sched_mask;
  538. io_sched_mask = IOPRIO_PRIO_VALUE(sched->policy, sched->priority);
  539. if (ioprio_set(IOPRIO_WHO_PROCESS, getpid(), io_sched_mask) == -1)
  540. warning("unable to alter IO priority to mask %i (%s)\n",
  541. io_sched_mask, strerror(errno));
  542. #endif
  543. }
  544. static void
  545. parse_schedule_item(const char *string, struct schedule_item *item)
  546. {
  547. const char *after_hyph;
  548. if (!strcmp(string, "forever")) {
  549. item->type = sched_forever;
  550. } else if (isdigit(string[0])) {
  551. item->type = sched_timeout;
  552. if (parse_integer(string, &item->value) != 0)
  553. badusage("invalid timeout value in schedule");
  554. } else if ((after_hyph = string + (string[0] == '-')) &&
  555. parse_signal(after_hyph, &item->value) == 0) {
  556. item->type = sched_signal;
  557. } else {
  558. badusage("invalid schedule item (must be [-]<signal-name>, "
  559. "-<signal-number>, <timeout> or 'forever'");
  560. }
  561. }
  562. static void
  563. parse_schedule(const char *schedule_str)
  564. {
  565. char item_buf[20];
  566. const char *slash;
  567. int count, repeatat;
  568. size_t str_len;
  569. count = 0;
  570. for (slash = schedule_str; *slash; slash++)
  571. if (*slash == '/')
  572. count++;
  573. schedule_length = (count == 0) ? 4 : count + 1;
  574. schedule = xmalloc(sizeof(*schedule) * schedule_length);
  575. if (count == 0) {
  576. schedule[0].type = sched_signal;
  577. schedule[0].value = signal_nr;
  578. parse_schedule_item(schedule_str, &schedule[1]);
  579. if (schedule[1].type != sched_timeout) {
  580. badusage ("--retry takes timeout, or schedule list"
  581. " of at least two items");
  582. }
  583. schedule[2].type = sched_signal;
  584. schedule[2].value = SIGKILL;
  585. schedule[3] = schedule[1];
  586. } else {
  587. count = 0;
  588. repeatat = -1;
  589. while (schedule_str != NULL) {
  590. slash = strchr(schedule_str, '/');
  591. str_len = slash ? (size_t)(slash - schedule_str) : strlen(schedule_str);
  592. if (str_len >= sizeof(item_buf))
  593. badusage("invalid schedule item: far too long"
  594. " (you must delimit items with slashes)");
  595. memcpy(item_buf, schedule_str, str_len);
  596. item_buf[str_len] = '\0';
  597. schedule_str = slash ? slash + 1 : NULL;
  598. parse_schedule_item(item_buf, &schedule[count]);
  599. if (schedule[count].type == sched_forever) {
  600. if (repeatat >= 0)
  601. badusage("invalid schedule: 'forever'"
  602. " appears more than once");
  603. repeatat = count;
  604. continue;
  605. }
  606. count++;
  607. }
  608. if (repeatat == count)
  609. badusage("invalid schedule: 'forever' appears last, "
  610. "nothing to repeat");
  611. if (repeatat >= 0) {
  612. schedule[count].type = sched_goto;
  613. schedule[count].value = repeatat;
  614. count++;
  615. }
  616. assert(count == schedule_length);
  617. }
  618. }
  619. static void
  620. parse_options(int argc, char * const *argv)
  621. {
  622. static struct option longopts[] = {
  623. { "help", 0, NULL, 'H'},
  624. { "stop", 0, NULL, 'K'},
  625. { "start", 0, NULL, 'S'},
  626. { "version", 0, NULL, 'V'},
  627. { "startas", 1, NULL, 'a'},
  628. { "name", 1, NULL, 'n'},
  629. { "oknodo", 0, NULL, 'o'},
  630. { "pidfile", 1, NULL, 'p'},
  631. { "quiet", 0, NULL, 'q'},
  632. { "signal", 1, NULL, 's'},
  633. { "test", 0, NULL, 't'},
  634. { "user", 1, NULL, 'u'},
  635. { "group", 1, NULL, 'g'},
  636. { "chroot", 1, NULL, 'r'},
  637. { "verbose", 0, NULL, 'v'},
  638. { "exec", 1, NULL, 'x'},
  639. { "chuid", 1, NULL, 'c'},
  640. { "nicelevel", 1, NULL, 'N'},
  641. { "procsched", 1, NULL, 'P'},
  642. { "iosched", 1, NULL, 'I'},
  643. { "umask", 1, NULL, 'k'},
  644. { "background", 0, NULL, 'b'},
  645. { "make-pidfile", 0, NULL, 'm'},
  646. { "retry", 1, NULL, 'R'},
  647. { "chdir", 1, NULL, 'd'},
  648. { NULL, 0, NULL, 0 }
  649. };
  650. const char *umask_str = NULL;
  651. const char *signal_str = NULL;
  652. const char *schedule_str = NULL;
  653. const char *proc_schedule_str = NULL;
  654. const char *io_schedule_str = NULL;
  655. int c;
  656. for (;;) {
  657. c = getopt_long(argc, argv,
  658. "HKSVa:n:op:qr:s:tu:vx:c:N:P:I:k:bmR:g:d:",
  659. longopts, NULL);
  660. if (c == -1)
  661. break;
  662. switch (c) {
  663. case 'H': /* --help */
  664. do_help();
  665. exit(0);
  666. case 'K': /* --stop */
  667. stop = 1;
  668. break;
  669. case 'S': /* --start */
  670. start = 1;
  671. break;
  672. case 'V': /* --version */
  673. do_version();
  674. exit(0);
  675. case 'a': /* --startas <pathname> */
  676. startas = optarg;
  677. break;
  678. case 'n': /* --name <process-name> */
  679. cmdname = optarg;
  680. break;
  681. case 'o': /* --oknodo */
  682. exitnodo = 0;
  683. break;
  684. case 'p': /* --pidfile <pid-file> */
  685. pidfile = optarg;
  686. break;
  687. case 'q': /* --quiet */
  688. quietmode = 1;
  689. break;
  690. case 's': /* --signal <signal> */
  691. signal_str = optarg;
  692. break;
  693. case 't': /* --test */
  694. testmode = 1;
  695. break;
  696. case 'u': /* --user <username>|<uid> */
  697. userspec = optarg;
  698. break;
  699. case 'v': /* --verbose */
  700. quietmode = -1;
  701. break;
  702. case 'x': /* --exec <executable> */
  703. execname = optarg;
  704. break;
  705. case 'c': /* --chuid <username>|<uid> */
  706. /* we copy the string just in case we need the
  707. * argument later. */
  708. changeuser = xstrdup(optarg);
  709. changeuser = strtok(changeuser, ":");
  710. changegroup = strtok(NULL, ":");
  711. break;
  712. case 'g': /* --group <group>|<gid> */
  713. changegroup = optarg;
  714. break;
  715. case 'r': /* --chroot /new/root */
  716. changeroot = optarg;
  717. break;
  718. case 'N': /* --nice */
  719. nicelevel = atoi(optarg);
  720. break;
  721. case 'P': /* --procsched */
  722. proc_schedule_str = optarg;
  723. break;
  724. case 'I': /* --iosched */
  725. io_schedule_str = optarg;
  726. break;
  727. case 'k': /* --umask <mask> */
  728. umask_str = optarg;
  729. break;
  730. case 'b': /* --background */
  731. background = 1;
  732. break;
  733. case 'm': /* --make-pidfile */
  734. mpidfile = 1;
  735. break;
  736. case 'R': /* --retry <schedule>|<timeout> */
  737. schedule_str = optarg;
  738. break;
  739. case 'd': /* --chdir /new/dir */
  740. changedir = optarg;
  741. break;
  742. default:
  743. /* Message printed by getopt. */
  744. badusage(NULL);
  745. }
  746. }
  747. if (signal_str != NULL) {
  748. if (parse_signal(signal_str, &signal_nr) != 0)
  749. badusage("signal value must be numeric or name"
  750. " of signal (KILL, INT, ...)");
  751. }
  752. if (schedule_str != NULL) {
  753. parse_schedule(schedule_str);
  754. }
  755. if (proc_schedule_str != NULL)
  756. parse_proc_schedule(proc_schedule_str);
  757. if (io_schedule_str != NULL)
  758. parse_io_schedule(io_schedule_str);
  759. if (umask_str != NULL) {
  760. if (parse_umask(umask_str, &umask_value) != 0)
  761. badusage("umask value must be a positive number");
  762. }
  763. if (start == stop)
  764. badusage("need one of --start or --stop");
  765. if (!execname && !pidfile && !userspec && !cmdname)
  766. badusage("need at least one of --exec, --pidfile, --user or --name");
  767. #ifdef PROCESS_NAME_SIZE
  768. if (cmdname && strlen(cmdname) > PROCESS_NAME_SIZE)
  769. warning("this system is not able to track process names\n"
  770. "longer than %d characters, please use --exec "
  771. "instead of --name.\n", PROCESS_NAME_SIZE);
  772. #endif
  773. if (!startas)
  774. startas = execname;
  775. if (start && !startas)
  776. badusage("--start needs --exec or --startas");
  777. if (mpidfile && pidfile == NULL)
  778. badusage("--make-pidfile requires --pidfile");
  779. if (background && !start)
  780. badusage("--background is only relevant with --start");
  781. }
  782. #if defined(OSHurd)
  783. static void
  784. init_procset(void)
  785. {
  786. struct ps_context *context;
  787. error_t err;
  788. err = ps_context_create(getproc(), &context);
  789. if (err)
  790. error(1, err, "ps_context_create");
  791. err = proc_stat_list_create(context, &procset);
  792. if (err)
  793. error(1, err, "proc_stat_list_create");
  794. err = proc_stat_list_add_all(procset, 0, 0);
  795. if (err)
  796. error(1, err, "proc_stat_list_add_all");
  797. }
  798. static struct proc_stat *
  799. get_proc_stat (pid_t pid, ps_flags_t flags)
  800. {
  801. struct proc_stat *ps;
  802. ps_flags_t wanted_flags = PSTAT_PID | flags;
  803. if (!procset)
  804. init_procset();
  805. ps = proc_stat_list_pid_proc_stat(procset, pid);
  806. if (!ps)
  807. return NULL;
  808. if (proc_stat_set_flags(ps, wanted_flags))
  809. return NULL;
  810. if ((proc_stat_flags(ps) & wanted_flags) != wanted_flags)
  811. return NULL;
  812. return ps;
  813. }
  814. #endif
  815. #if defined(OSLinux)
  816. static bool
  817. pid_is_exec(pid_t pid, const struct stat *esb)
  818. {
  819. char lname[32];
  820. char lcontents[_POSIX_PATH_MAX];
  821. const char deleted[] = " (deleted)";
  822. int nread;
  823. struct stat sb;
  824. sprintf(lname, "/proc/%d/exe", pid);
  825. nread = readlink(lname, lcontents, sizeof(lcontents));
  826. if (nread == -1)
  827. return false;
  828. lcontents[nread] = '\0';
  829. if (strcmp(lcontents + nread - strlen(deleted), deleted) == 0)
  830. lcontents[nread - strlen(deleted)] = '\0';
  831. if (stat(lcontents, &sb) != 0)
  832. return false;
  833. return (sb.st_dev == esb->st_dev && sb.st_ino == esb->st_ino);
  834. }
  835. #elif defined(OShpux)
  836. static bool
  837. pid_is_exec(pid_t pid, const struct stat *esb)
  838. {
  839. struct pst_status pst;
  840. if (pstat_getproc(&pst, sizeof(pst), (size_t)0, (int)pid) < 0)
  841. return false;
  842. return ((dev_t)pst.pst_text.psf_fsid.psfs_id == esb->st_dev &&
  843. (ino_t)pst.pst_text.psf_fileid == esb->st_ino);
  844. }
  845. #elif defined(HAVE_KVM_H)
  846. static bool
  847. pid_is_exec(pid_t pid, const char *name)
  848. {
  849. kvm_t *kd;
  850. int nentries;
  851. struct kinfo_proc *kp;
  852. char errbuf[_POSIX2_LINE_MAX], *pidexec;
  853. kd = kvm_openfiles(NULL, NULL, NULL, O_RDONLY, errbuf);
  854. if (kd == NULL)
  855. errx(1, "%s", errbuf);
  856. kp = kvm_getprocs(kd, KERN_PROC_PID, pid, &nentries);
  857. if (kp == NULL)
  858. errx(1, "%s", kvm_geterr(kd));
  859. pidexec = (&kp->kp_proc)->p_comm;
  860. if (strlen(name) != strlen(pidexec))
  861. return false;
  862. return (strcmp(name, pidexec) == 0) ? 1 : 0;
  863. }
  864. #endif
  865. #if defined(OSLinux)
  866. static bool
  867. pid_is_user(pid_t pid, uid_t uid)
  868. {
  869. struct stat sb;
  870. char buf[32];
  871. sprintf(buf, "/proc/%d", pid);
  872. if (stat(buf, &sb) != 0)
  873. return false;
  874. return (sb.st_uid == uid);
  875. }
  876. #elif defined(OSHurd)
  877. static bool
  878. pid_is_user(pid_t pid, uid_t uid)
  879. {
  880. struct proc_stat *ps;
  881. ps = get_proc_stat(pid, PSTAT_OWNER_UID);
  882. return ps && proc_stat_owner_uid(ps) == uid;
  883. }
  884. #elif defined(OShpux)
  885. static bool
  886. pid_is_user(pid_t pid, uid_t uid)
  887. {
  888. struct pst_status pst;
  889. if (pstat_getproc(&pst, sizeof(pst), (size_t)0, (int)pid) < 0)
  890. return false;
  891. return ((uid_t)pst.pst_uid == uid);
  892. }
  893. #elif defined(HAVE_KVM_H)
  894. static bool
  895. pid_is_user(pid_t pid, uid_t uid)
  896. {
  897. kvm_t *kd;
  898. int nentries; /* Value not used. */
  899. uid_t proc_uid;
  900. struct kinfo_proc *kp;
  901. char errbuf[_POSIX2_LINE_MAX];
  902. kd = kvm_openfiles(NULL, NULL, NULL, O_RDONLY, errbuf);
  903. if (kd == NULL)
  904. errx(1, "%s", errbuf);
  905. kp = kvm_getprocs(kd, KERN_PROC_PID, pid, &nentries);
  906. if (kp == NULL)
  907. errx(1, "%s", kvm_geterr(kd));
  908. if (kp->kp_proc.p_cred)
  909. kvm_read(kd, (u_long)&(kp->kp_proc.p_cred->p_ruid),
  910. &proc_uid, sizeof(uid_t));
  911. else
  912. return false;
  913. return (proc_uid == (uid_t)uid);
  914. }
  915. #endif
  916. #if defined(OSLinux)
  917. static bool
  918. pid_is_cmd(pid_t pid, const char *name)
  919. {
  920. char buf[32];
  921. FILE *f;
  922. int c;
  923. sprintf(buf, "/proc/%d/stat", pid);
  924. f = fopen(buf, "r");
  925. if (!f)
  926. return false;
  927. while ((c = getc(f)) != EOF && c != '(')
  928. ;
  929. if (c != '(') {
  930. fclose(f);
  931. return false;
  932. }
  933. /* This hopefully handles command names containing ')'. */
  934. while ((c = getc(f)) != EOF && c == *name)
  935. name++;
  936. fclose(f);
  937. return (c == ')' && *name == '\0');
  938. }
  939. #elif defined(OSHurd)
  940. static bool
  941. pid_is_cmd(pid_t pid, const char *name)
  942. {
  943. struct proc_stat *ps;
  944. ps = get_proc_stat(pid, PSTAT_ARGS);
  945. return ps && !strcmp(proc_stat_args(ps), name);
  946. }
  947. #elif defined(OShpux)
  948. static bool
  949. pid_is_cmd(pid_t pid, const char *name)
  950. {
  951. struct pst_status pst;
  952. if (pstat_getproc(&pst, sizeof(pst), (size_t)0, (int)pid) < 0)
  953. return false;
  954. return (strcmp(pst.pst_ucomm, name) == 0);
  955. }
  956. #elif defined(HAVE_KVM_H)
  957. static bool
  958. pid_is_cmd(pid_t pid, const char *name)
  959. {
  960. kvm_t *kd;
  961. int nentries, argv_len = 0;
  962. struct kinfo_proc *kp;
  963. char errbuf[_POSIX2_LINE_MAX], buf[_POSIX2_LINE_MAX];
  964. char **pid_argv_p;
  965. char *start_argv_0_p, *end_argv_0_p;
  966. kd = kvm_openfiles(NULL, NULL, NULL, O_RDONLY, errbuf);
  967. if (kd == NULL)
  968. errx(1, "%s", errbuf);
  969. kp = kvm_getprocs(kd, KERN_PROC_PID, pid, &nentries);
  970. if (kp == NULL)
  971. errx(1, "%s", kvm_geterr(kd));
  972. pid_argv_p = kvm_getargv(kd, kp, argv_len);
  973. if (pid_argv_p == NULL)
  974. errx(1, "%s", kvm_geterr(kd));
  975. start_argv_0_p = *pid_argv_p;
  976. /* Find and compare string. */
  977. /* Find end of argv[0] then copy and cut of str there. */
  978. end_argv_0_p = strchr(*pid_argv_p, ' ');
  979. if (end_argv_0_p == NULL)
  980. /* There seems to be no space, so we have the command
  981. * allready in its desired form. */
  982. start_argv_0_p = *pid_argv_p;
  983. else {
  984. /* Tests indicate that this never happens, since
  985. * kvm_getargv itself cuts of tailing stuff. This is
  986. * not what the manpage says, however. */
  987. strncpy(buf, *pid_argv_p, (end_argv_0_p - start_argv_0_p));
  988. buf[(end_argv_0_p - start_argv_0_p) + 1] = '\0';
  989. start_argv_0_p = buf;
  990. }
  991. if (strlen(name) != strlen(start_argv_0_p))
  992. return false;
  993. return (strcmp(name, start_argv_0_p) == 0) ? 1 : 0;
  994. }
  995. #endif
  996. #if defined(OSHurd)
  997. static bool
  998. pid_is_running(pid_t pid)
  999. {
  1000. return get_proc_stat(pid, 0) != NULL;
  1001. }
  1002. #else /* !OSHurd */
  1003. static bool
  1004. pid_is_running(pid_t pid)
  1005. {
  1006. if (kill(pid, 0) == 0 || errno == EPERM)
  1007. return true;
  1008. else if (errno == ESRCH)
  1009. return false;
  1010. else
  1011. fatal("error checking pid %u status", pid);
  1012. }
  1013. #endif
  1014. static void
  1015. check(pid_t pid)
  1016. {
  1017. #if defined(OSLinux) || defined(OShpux)
  1018. if (execname && !pid_is_exec(pid, &exec_stat))
  1019. return;
  1020. #elif defined(HAVE_KVM_H)
  1021. if (execname && !pid_is_exec(pid, execname))
  1022. return;
  1023. #elif defined(OSHurd) || defined(OSFreeBSD) || defined(OSNetBSD)
  1024. /* Let's try this to see if it works. */
  1025. if (execname && !pid_is_cmd(pid, execname))
  1026. return;
  1027. #endif
  1028. if (userspec && !pid_is_user(pid, user_id))
  1029. return;
  1030. if (cmdname && !pid_is_cmd(pid, cmdname))
  1031. return;
  1032. if (start && !pid_is_running(pid))
  1033. return;
  1034. push(&found, pid);
  1035. }
  1036. static void
  1037. do_pidfile(const char *name)
  1038. {
  1039. FILE *f;
  1040. static pid_t pid = 0;
  1041. if (pid) {
  1042. check(pid);
  1043. return;
  1044. }
  1045. f = fopen(name, "r");
  1046. if (f) {
  1047. if (fscanf(f, "%d", &pid) == 1)
  1048. check(pid);
  1049. fclose(f);
  1050. } else if (errno != ENOENT)
  1051. fatal("unable to open pidfile %s", name);
  1052. }
  1053. #if defined(OSLinux) || defined (OSsunos)
  1054. static void
  1055. do_procinit(void)
  1056. {
  1057. DIR *procdir;
  1058. struct dirent *entry;
  1059. int foundany;
  1060. pid_t pid;
  1061. procdir = opendir("/proc");
  1062. if (!procdir)
  1063. fatal("unable to opendir /proc");
  1064. foundany = 0;
  1065. while ((entry = readdir(procdir)) != NULL) {
  1066. if (sscanf(entry->d_name, "%d", &pid) != 1)
  1067. continue;
  1068. foundany++;
  1069. check(pid);
  1070. }
  1071. closedir(procdir);
  1072. if (!foundany)
  1073. fatal("nothing in /proc - not mounted?");
  1074. }
  1075. #elif defined(OSHurd)
  1076. static int
  1077. check_proc_stat(struct proc_stat *ps)
  1078. {
  1079. check(ps->pid);
  1080. return 0;
  1081. }
  1082. static void
  1083. do_procinit(void)
  1084. {
  1085. if (!procset)
  1086. init_procset();
  1087. proc_stat_list_for_each(procset, check_proc_stat);
  1088. }
  1089. #elif defined(OShpux)
  1090. static void
  1091. do_procinit(void)
  1092. {
  1093. struct pst_status pst[10];
  1094. int i, count;
  1095. int idx = 0;
  1096. while ((count = pstat_getproc(pst, sizeof(pst[0]), 10, idx)) > 0) {
  1097. for (i = 0; i < count; i++)
  1098. check(pst[i].pst_pid);
  1099. idx = pst[count - 1].pst_idx + 1;
  1100. }
  1101. }
  1102. #elif defined(HAVE_KVM_H)
  1103. static void
  1104. do_procinit(void)
  1105. {
  1106. /* Nothing to do. */
  1107. }
  1108. #endif
  1109. static void
  1110. do_findprocs(void)
  1111. {
  1112. clear(&found);
  1113. if (pidfile)
  1114. do_pidfile(pidfile);
  1115. else
  1116. do_procinit();
  1117. }
  1118. static void
  1119. do_stop(int sig_num, int quiet, int *n_killed, int *n_notkilled, int retry_nr)
  1120. {
  1121. struct pid_list *p;
  1122. do_findprocs();
  1123. *n_killed = 0;
  1124. *n_notkilled = 0;
  1125. if (!found)
  1126. return;
  1127. clear(&killed);
  1128. for (p = found; p; p = p->next) {
  1129. if (testmode) {
  1130. if (quietmode <= 0)
  1131. printf("Would send signal %d to %d.\n",
  1132. sig_num, p->pid);
  1133. (*n_killed)++;
  1134. } else if (kill(p->pid, sig_num) == 0) {
  1135. push(&killed, p->pid);
  1136. (*n_killed)++;
  1137. } else {
  1138. if (sig_num)
  1139. warning("failed to kill %d: %s\n",
  1140. p->pid, strerror(errno));
  1141. (*n_notkilled)++;
  1142. }
  1143. }
  1144. if (quietmode < 0 && killed) {
  1145. printf("Stopped %s (pid", what_stop);
  1146. for (p = killed; p; p = p->next)
  1147. printf(" %d", p->pid);
  1148. putchar(')');
  1149. if (retry_nr > 0)
  1150. printf(", retry #%d", retry_nr);
  1151. printf(".\n");
  1152. }
  1153. }
  1154. static void
  1155. set_what_stop(const char *str)
  1156. {
  1157. strncpy(what_stop, str, sizeof(what_stop));
  1158. what_stop[sizeof(what_stop) - 1] = '\0';
  1159. }
  1160. static int
  1161. run_stop_schedule(void)
  1162. {
  1163. int r, position, n_killed, n_notkilled, value, ratio, retry_nr;
  1164. bool anykilled;
  1165. struct timeval stopat, before, after, interval, maxinterval;
  1166. if (testmode) {
  1167. if (schedule != NULL) {
  1168. if (quietmode <= 0)
  1169. printf("Ignoring --retry in test mode\n");
  1170. schedule = NULL;
  1171. }
  1172. }
  1173. if (cmdname)
  1174. set_what_stop(cmdname);
  1175. else if (execname)
  1176. set_what_stop(execname);
  1177. else if (pidfile)
  1178. sprintf(what_stop, "process in pidfile '%.200s'", pidfile);
  1179. else if (userspec)
  1180. sprintf(what_stop, "process(es) owned by '%.200s'", userspec);
  1181. else
  1182. fatal("internal error, no match option, please report");
  1183. anykilled = false;
  1184. retry_nr = 0;
  1185. if (schedule == NULL) {
  1186. do_stop(signal_nr, quietmode, &n_killed, &n_notkilled, 0);
  1187. if (n_notkilled > 0 && quietmode <= 0)
  1188. printf("%d pids were not killed\n", n_notkilled);
  1189. if (n_killed)
  1190. anykilled = true;
  1191. goto x_finished;
  1192. }
  1193. for (position = 0; position < schedule_length; ) {
  1194. value = schedule[position].value;
  1195. n_notkilled = 0;
  1196. switch (schedule[position].type) {
  1197. case sched_goto:
  1198. position = value;
  1199. continue;
  1200. case sched_signal:
  1201. do_stop(value, quietmode, &n_killed, &n_notkilled, retry_nr++);
  1202. if (!n_killed)
  1203. goto x_finished;
  1204. else
  1205. anykilled = true;
  1206. goto next_item;
  1207. case sched_timeout:
  1208. /* We want to keep polling for the processes, to see if they've exited,
  1209. * or until the timeout expires.
  1210. *
  1211. * This is a somewhat complicated algorithm to try to ensure that we
  1212. * notice reasonably quickly when all the processes have exited, but
  1213. * don't spend too much CPU time polling. In particular, on a fast
  1214. * machine with quick-exiting daemons we don't want to delay system
  1215. * shutdown too much, whereas on a slow one, or where processes are
  1216. * taking some time to exit, we want to increase the polling
  1217. * interval.
  1218. *
  1219. * The algorithm is as follows: we measure the elapsed time it takes
  1220. * to do one poll(), and wait a multiple of this time for the next
  1221. * poll. However, if that would put us past the end of the timeout
  1222. * period we wait only as long as the timeout period, but in any case
  1223. * we always wait at least MIN_POLL_INTERVAL (20ms). The multiple
  1224. * (‘ratio’) starts out as 2, and increases by 1 for each poll to a
  1225. * maximum of 10; so we use up to between 30% and 10% of the
  1226. * machine's resources (assuming a few reasonable things about system
  1227. * performance).
  1228. */
  1229. xgettimeofday(&stopat);
  1230. stopat.tv_sec += value;
  1231. ratio = 1;
  1232. for (;;) {
  1233. xgettimeofday(&before);
  1234. if (timercmp(&before, &stopat, >))
  1235. goto next_item;
  1236. do_stop(0, 1, &n_killed, &n_notkilled, 0);
  1237. if (!n_killed)
  1238. goto x_finished;
  1239. xgettimeofday(&after);
  1240. if (!timercmp(&after, &stopat, <))
  1241. goto next_item;
  1242. if (ratio < 10)
  1243. ratio++;
  1244. timersub(&stopat, &after, &maxinterval);
  1245. timersub(&after, &before, &interval);
  1246. tmul(&interval, ratio);
  1247. if (interval.tv_sec < 0 || interval.tv_usec < 0)
  1248. interval.tv_sec = interval.tv_usec = 0;
  1249. if (timercmp(&interval, &maxinterval, >))
  1250. interval = maxinterval;
  1251. if (interval.tv_sec == 0 &&
  1252. interval.tv_usec <= MIN_POLL_INTERVAL)
  1253. interval.tv_usec = MIN_POLL_INTERVAL;
  1254. r = select(0, NULL, NULL, NULL, &interval);
  1255. if (r < 0 && errno != EINTR)
  1256. fatal("select() failed for pause");
  1257. }
  1258. default:
  1259. assert(!"schedule[].type value must be valid");
  1260. }
  1261. next_item:
  1262. position++;
  1263. }
  1264. if (quietmode <= 0)
  1265. printf("Program %s, %d process(es), refused to die.\n",
  1266. what_stop, n_killed);
  1267. return 2;
  1268. x_finished:
  1269. if (!anykilled) {
  1270. if (quietmode <= 0)
  1271. printf("No %s found running; none killed.\n", what_stop);
  1272. return exitnodo;
  1273. } else {
  1274. return 0;
  1275. }
  1276. }
  1277. int
  1278. main(int argc, char **argv)
  1279. {
  1280. int devnull_fd = -1;
  1281. gid_t rgid;
  1282. uid_t ruid;
  1283. progname = argv[0];
  1284. parse_options(argc, argv);
  1285. argc -= optind;
  1286. argv += optind;
  1287. if (execname) {
  1288. char *fullexecname;
  1289. if (changeroot) {
  1290. int fullexecname_len = strlen(changeroot) + 1 +
  1291. strlen(execname) + 1;
  1292. fullexecname = xmalloc(fullexecname_len);
  1293. snprintf(fullexecname, fullexecname_len, "%s/%s",
  1294. changeroot, execname);
  1295. } else
  1296. fullexecname = execname;
  1297. if (stat(fullexecname, &exec_stat))
  1298. fatal("unable to stat %s", fullexecname);
  1299. if (fullexecname != execname)
  1300. free(fullexecname);
  1301. }
  1302. if (userspec && sscanf(userspec, "%d", &user_id) != 1) {
  1303. struct passwd *pw;
  1304. pw = getpwnam(userspec);
  1305. if (!pw)
  1306. fatal("user '%s' not found", userspec);
  1307. user_id = pw->pw_uid;
  1308. }
  1309. if (changegroup && sscanf(changegroup, "%d", &runas_gid) != 1) {
  1310. struct group *gr = getgrnam(changegroup);
  1311. if (!gr)
  1312. fatal("group '%s' not found", changegroup);
  1313. runas_gid = gr->gr_gid;
  1314. }
  1315. if (changeuser) {
  1316. struct passwd *pw;
  1317. struct stat st;
  1318. if (sscanf(changeuser, "%d", &runas_uid) == 1)
  1319. pw = getpwuid(runas_uid);
  1320. else
  1321. pw = getpwnam(changeuser);
  1322. if (!pw)
  1323. fatal("user '%s' not found", changeuser);
  1324. runas_uid = pw->pw_uid;
  1325. if (changegroup == NULL) {
  1326. /* Pass the default group of this user. */
  1327. changegroup = ""; /* Just empty. */
  1328. runas_gid = pw->pw_gid;
  1329. }
  1330. if (stat(pw->pw_dir, &st) == 0)
  1331. setenv("HOME", pw->pw_dir, 1);
  1332. }
  1333. if (stop) {
  1334. int i = run_stop_schedule();
  1335. exit(i);
  1336. }
  1337. do_findprocs();
  1338. if (found) {
  1339. if (quietmode <= 0)
  1340. printf("%s already running.\n", execname ? execname : "process");
  1341. exit(exitnodo);
  1342. }
  1343. if (testmode && quietmode <= 0) {
  1344. printf("Would start %s ", startas);
  1345. while (argc-- > 0)
  1346. printf("%s ", *argv++);
  1347. if (changeuser != NULL) {
  1348. printf(" (as user %s[%d]", changeuser, runas_uid);
  1349. if (changegroup != NULL)
  1350. printf(", and group %s[%d])", changegroup, runas_gid);
  1351. else
  1352. printf(")");
  1353. }
  1354. if (changeroot != NULL)
  1355. printf(" in directory %s", changeroot);
  1356. if (nicelevel)
  1357. printf(", and add %i to the priority", nicelevel);
  1358. if (proc_sched)
  1359. printf(", with scheduling policy %s with priority %i",
  1360. proc_sched->policy_name, proc_sched->priority);
  1361. if (io_sched)
  1362. printf(", with IO scheduling class %s with priority %i",
  1363. io_sched->policy_name, io_sched->priority);
  1364. printf(".\n");
  1365. }
  1366. if (testmode)
  1367. exit(0);
  1368. if (quietmode < 0)
  1369. printf("Starting %s...\n", startas);
  1370. *--argv = startas;
  1371. if (background) {
  1372. /* Ok, we need to detach this process. */
  1373. daemonize();
  1374. devnull_fd = open("/dev/null", O_RDWR);
  1375. if (devnull_fd < 0)
  1376. fatal("unable to open '%s'", "/dev/null");
  1377. }
  1378. if (nicelevel) {
  1379. errno = 0;
  1380. if ((nice(nicelevel) == -1) && (errno != 0))
  1381. fatal("unable to alter nice level by %i", nicelevel);
  1382. }
  1383. if (proc_sched)
  1384. set_proc_schedule(proc_sched);
  1385. if (io_sched)
  1386. set_io_schedule(io_sched);
  1387. if (umask_value >= 0)
  1388. umask(umask_value);
  1389. if (mpidfile && pidfile != NULL) {
  1390. /* User wants _us_ to make the pidfile. :) */
  1391. FILE *pidf = fopen(pidfile, "w");
  1392. pid_t pidt = getpid();
  1393. if (pidf == NULL)
  1394. fatal("unable to open pidfile '%s' for writing",
  1395. pidfile);
  1396. fprintf(pidf, "%d\n", pidt);
  1397. if (fflush(pidf))
  1398. fatal("unable to flush pidfile '%s'", pidfile);
  1399. if (fsync(fileno(pidf)))
  1400. fatal("unable to sync pidfile '%s'", pidfile);
  1401. fclose(pidf);
  1402. }
  1403. if (changeroot != NULL) {
  1404. if (chdir(changeroot) < 0)
  1405. fatal("unable to chdir() to %s", changeroot);
  1406. if (chroot(changeroot) < 0)
  1407. fatal("unable to chroot() to %s", changeroot);
  1408. }
  1409. if (chdir(changedir) < 0)
  1410. fatal("unable to chdir() to %s", changedir);
  1411. rgid = getgid();
  1412. ruid = getuid();
  1413. if (changegroup != NULL) {
  1414. if (rgid != (gid_t)runas_gid)
  1415. if (setgid(runas_gid))
  1416. fatal("unable to set gid to %d", runas_gid);
  1417. }
  1418. if (changeuser != NULL) {
  1419. /* We assume that if our real user and group are the same as
  1420. * the ones we should switch to, the supplementary groups
  1421. * will be already in place. */
  1422. if (rgid != (gid_t)runas_gid || ruid != (uid_t)runas_uid)
  1423. if (initgroups(changeuser, runas_gid))
  1424. fatal("unable to set initgroups() with gid %d",
  1425. runas_gid);
  1426. if (ruid != (uid_t)runas_uid)
  1427. if (setuid(runas_uid))
  1428. fatal("unable to set uid to %s", changeuser);
  1429. }
  1430. if (background) {
  1431. /* Continue background setup. */
  1432. int i;
  1433. if (umask_value < 0)
  1434. umask(022); /* Set a default for dumb programs. */
  1435. dup2(devnull_fd, 0); /* stdin */
  1436. dup2(devnull_fd, 1); /* stdout */
  1437. dup2(devnull_fd, 2); /* stderr */
  1438. /* Now close all extra fds. */
  1439. for (i = get_open_fd_max() - 1; i >= 3; --i)
  1440. close(i);
  1441. }
  1442. execv(startas, argv);
  1443. fatal("unable to start %s", startas);
  1444. }