start-stop-daemon.c 38 KB

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