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 <dpkg/macros.h>
  24. #if defined(linux) || (defined(__FreeBSD_kernel__) && defined(__GLIBC__))
  25. # define OSLinux
  26. #elif defined(__GNU__)
  27. # define OSHurd
  28. #elif defined(__sun)
  29. # define OSsunos
  30. #elif defined(OPENBSD) || defined(__OpenBSD__)
  31. # define OSOpenBSD
  32. #elif defined(hpux)
  33. # define OShpux
  34. #elif defined(__FreeBSD__)
  35. # define OSFreeBSD
  36. #elif defined(__NetBSD__)
  37. # define OSNetBSD
  38. #else
  39. # error Unknown architecture - cannot build start-stop-daemon
  40. #endif
  41. #define MIN_POLL_INTERVAL 20000 /* µs */
  42. #ifdef HAVE_SYS_CDEFS_H
  43. #include <sys/cdefs.h>
  44. #endif
  45. #ifdef HAVE_SYS_SYSCALL_H
  46. #include <sys/syscall.h>
  47. #endif
  48. #if defined(OSHurd)
  49. #include <hurd.h>
  50. #include <ps.h>
  51. #endif
  52. #if defined(OSOpenBSD) || defined(OSFreeBSD) || defined(OSNetBSD)
  53. #include <sys/param.h>
  54. #include <sys/proc.h>
  55. #include <err.h>
  56. #endif
  57. #ifdef HAVE_KVM_H
  58. #include <sys/sysctl.h>
  59. #include <sys/user.h>
  60. #include <kvm.h>
  61. #endif
  62. #if defined(OShpux)
  63. #include <sys/param.h>
  64. #include <sys/pstat.h>
  65. #endif
  66. #include <sys/types.h>
  67. #include <sys/time.h>
  68. #include <sys/stat.h>
  69. #include <sys/ioctl.h>
  70. #include <sys/termios.h>
  71. #include <assert.h>
  72. #include <errno.h>
  73. #include <limits.h>
  74. #include <fcntl.h>
  75. #include <dirent.h>
  76. #include <ctype.h>
  77. #include <string.h>
  78. #include <pwd.h>
  79. #include <grp.h>
  80. #include <signal.h>
  81. #include <unistd.h>
  82. #ifdef HAVE_STDDEF_H
  83. #include <stddef.h>
  84. #endif
  85. #include <stdbool.h>
  86. #include <stdarg.h>
  87. #include <stdlib.h>
  88. #include <stdio.h>
  89. #include <getopt.h>
  90. #ifdef HAVE_ERROR_H
  91. #include <error.h>
  92. #endif
  93. #ifdef _POSIX_PRIORITY_SCHEDULING
  94. #include <sched.h>
  95. #else
  96. #define SCHED_OTHER -1
  97. #define SCHED_FIFO -1
  98. #define SCHED_RR -1
  99. #endif
  100. #if defined(OSLinux)
  101. /* This comes from TASK_COMM_LEN defined in linux's include/linux/sched.h. */
  102. #define PROCESS_NAME_SIZE 15
  103. #endif
  104. #if defined(SYS_ioprio_set) && defined(linux)
  105. #define HAVE_IOPRIO_SET
  106. #endif
  107. enum {
  108. IOPRIO_WHO_PROCESS = 1,
  109. IOPRIO_WHO_PGRP,
  110. IOPRIO_WHO_USER,
  111. };
  112. enum {
  113. IOPRIO_CLASS_NONE,
  114. IOPRIO_CLASS_RT,
  115. IOPRIO_CLASS_BE,
  116. IOPRIO_CLASS_IDLE,
  117. };
  118. static int testmode = 0;
  119. static int quietmode = 0;
  120. static int exitnodo = 1;
  121. static int start = 0;
  122. static int stop = 0;
  123. static int background = 0;
  124. static int mpidfile = 0;
  125. static int signal_nr = SIGTERM;
  126. static int user_id = -1;
  127. static int runas_uid = -1;
  128. static int runas_gid = -1;
  129. static const char *userspec = NULL;
  130. static char *changeuser = NULL;
  131. static const char *changegroup = NULL;
  132. static char *changeroot = NULL;
  133. static const char *changedir = "/";
  134. static const char *cmdname = NULL;
  135. static char *execname = NULL;
  136. static char *startas = NULL;
  137. static const char *pidfile = NULL;
  138. static char what_stop[1024];
  139. static const char *progname = "";
  140. static int nicelevel = 0;
  141. static int umask_value = -1;
  142. #define IOPRIO_CLASS_SHIFT 13
  143. #define IOPRIO_PRIO_VALUE(class, prio) (((class) << IOPRIO_CLASS_SHIFT) | (prio))
  144. #define IO_SCHED_PRIO_MIN 0
  145. #define IO_SCHED_PRIO_MAX 7
  146. static struct stat exec_stat;
  147. #if defined(OSHurd)
  148. static struct proc_stat_list *procset = NULL;
  149. #endif
  150. struct pid_list {
  151. struct pid_list *next;
  152. pid_t pid;
  153. };
  154. static struct pid_list *found = NULL;
  155. static struct pid_list *killed = NULL;
  156. /* Resource scheduling policy. */
  157. struct res_schedule {
  158. const char *policy_name;
  159. int policy;
  160. int priority;
  161. };
  162. struct schedule_item {
  163. enum {
  164. sched_timeout,
  165. sched_signal,
  166. sched_goto,
  167. sched_forever /* Only seen within parse_schedule and callees */
  168. } type;
  169. int value; /* Seconds, signal no., or index into array. */
  170. };
  171. static struct res_schedule *proc_sched = NULL;
  172. static struct res_schedule *io_sched = NULL;
  173. static int schedule_length;
  174. static struct schedule_item *schedule = NULL;
  175. static void *xmalloc(int size);
  176. static void push(struct pid_list **list, pid_t pid);
  177. static void do_help(void);
  178. static void parse_options(int argc, char * const *argv);
  179. static bool pid_is_user(pid_t pid, uid_t uid);
  180. static bool pid_is_cmd(pid_t pid, const char *name);
  181. static void check(pid_t pid);
  182. static void do_pidfile(const char *name);
  183. static void do_stop(int signal_nr, int quietmode,
  184. int *n_killed, int *n_notkilled, int retry_nr);
  185. #if defined(OSLinux) || defined(OShpux)
  186. static bool pid_is_exec(pid_t pid, const struct stat *esb);
  187. #endif
  188. static void fatal(const char *format, ...)
  189. DPKG_ATTR_NORET DPKG_ATTR_PRINTF(1);
  190. static void badusage(const char *msg)
  191. DPKG_ATTR_NORET;
  192. static void
  193. warning(const char *format, ...)
  194. {
  195. va_list arglist;
  196. fprintf(stderr, "%s: warning: ", progname);
  197. va_start(arglist, format);
  198. vfprintf(stderr, format, arglist);
  199. va_end(arglist);
  200. }
  201. static void
  202. fatal(const char *format, ...)
  203. {
  204. va_list arglist;
  205. int errno_fatal = errno;
  206. fprintf(stderr, "%s: ", progname);
  207. va_start(arglist, format);
  208. vfprintf(stderr, format, arglist);
  209. va_end(arglist);
  210. if (errno_fatal)
  211. fprintf(stderr, " (%s)\n", strerror(errno_fatal));
  212. else
  213. fprintf(stderr, "\n");
  214. exit(2);
  215. }
  216. static void *
  217. xmalloc(int size)
  218. {
  219. void *ptr;
  220. ptr = malloc(size);
  221. if (ptr)
  222. return ptr;
  223. fatal("malloc(%d) failed", size);
  224. }
  225. static char *
  226. xstrdup(const char *str)
  227. {
  228. char *new_str;
  229. new_str = strdup(str);
  230. if (new_str)
  231. return new_str;
  232. fatal("strdup(%s) failed", str);
  233. }
  234. static void
  235. xgettimeofday(struct timeval *tv)
  236. {
  237. if (gettimeofday(tv, NULL) != 0)
  238. fatal("gettimeofday failed: %s", strerror(errno));
  239. }
  240. static void
  241. tmul(struct timeval *a, int b)
  242. {
  243. a->tv_sec *= b;
  244. a->tv_usec *= b;
  245. a->tv_sec = a->tv_sec + a->tv_usec / 1000000;
  246. a->tv_usec %= 1000000;
  247. }
  248. static long
  249. get_open_fd_max(void)
  250. {
  251. #ifdef HAVE_GETDTABLESIZE
  252. return getdtablesize();
  253. #else
  254. return sysconf(_SC_OPEN_MAX);
  255. #endif
  256. }
  257. static void
  258. daemonize(void)
  259. {
  260. pid_t pid;
  261. if (quietmode < 0)
  262. printf("Detaching to start %s...", startas);
  263. pid = fork();
  264. if (pid < 0)
  265. fatal("Unable to do first fork.\n");
  266. else if (pid) /* Parent. */
  267. _exit(0);
  268. /* Create a new session. */
  269. #ifdef HAVE_SETSID
  270. setsid();
  271. #else
  272. setpgid(0, 0);
  273. #endif
  274. pid = fork();
  275. if (pid < 0)
  276. fatal("Unable to do second fork.\n");
  277. else if (pid) /* Parent. */
  278. _exit(0);
  279. if (quietmode < 0)
  280. printf("done.\n");
  281. }
  282. static void
  283. push(struct pid_list **list, pid_t pid)
  284. {
  285. struct pid_list *p;
  286. p = xmalloc(sizeof(*p));
  287. p->next = *list;
  288. p->pid = pid;
  289. *list = p;
  290. }
  291. static void
  292. clear(struct pid_list **list)
  293. {
  294. struct pid_list *here, *next;
  295. for (here = *list; here != NULL; here = next) {
  296. next = here->next;
  297. free(here);
  298. }
  299. *list = NULL;
  300. }
  301. static void
  302. do_help(void)
  303. {
  304. printf(
  305. "Usage: start-stop-daemon [<option> ...] <command>\n"
  306. "\n"
  307. "Commands:\n"
  308. " -S|--start -- <argument> ... start a program and pass <arguments> to it\n"
  309. " -K|--stop stop a program\n"
  310. " -H|--help print help information\n"
  311. " -V|--version print version\n"
  312. "\n"
  313. "Matching options (at least one is required):\n"
  314. " -p|--pidfile <pid-file> pid file to check\n"
  315. " -x|--exec <executable> program to start/check if it is running\n"
  316. " -n|--name <process-name> process name to check\n"
  317. " -u|--user <username|uid> process owner to check\n"
  318. "\n"
  319. "Options:\n"
  320. " -g|--group <group|gid> run process as this group\n"
  321. " -c|--chuid <name|uid[:group|gid]>\n"
  322. " change to this user/group before starting\n"
  323. " process\n"
  324. " -s|--signal <signal> signal to send (default TERM)\n"
  325. " -a|--startas <pathname> program to start (default is <executable>)\n"
  326. " -r|--chroot <directory> chroot to <directory> before starting\n"
  327. " -d|--chdir <directory> change to <directory> (default is /)\n"
  328. " -N|--nicelevel <incr> add incr to the process's nice level\n"
  329. " -P|--procsched <policy[:prio]>\n"
  330. " use <policy> with <prio> for the kernel\n"
  331. " process scheduler (default prio is 0)\n"
  332. " -I|--iosched <class[:prio]> use <class> with <prio> to set the IO\n"
  333. " scheduler (default prio is 4)\n"
  334. " -k|--umask <mask> change the umask to <mask> before starting\n"
  335. " -b|--background force the process to detach\n"
  336. " -m|--make-pidfile create the pidfile before starting\n"
  337. " -R|--retry <schedule> check whether processes die, and retry\n"
  338. " -t|--test test mode, don't do anything\n"
  339. " -o|--oknodo exit status 0 (not 1) if nothing done\n"
  340. " -q|--quiet be more quiet\n"
  341. " -v|--verbose be more verbose\n"
  342. "\n"
  343. "Retry <schedule> is <item>|/<item>/... where <item> is one of\n"
  344. " -<signal-num>|[-]<signal-name> send that signal\n"
  345. " <timeout> wait that many seconds\n"
  346. " forever repeat remainder forever\n"
  347. "or <schedule> may be just <timeout>, meaning <signal>/<timeout>/KILL/<timeout>\n"
  348. "\n"
  349. "The process scheduler <policy> can be one of:\n"
  350. " other, fifo or rr\n"
  351. "\n"
  352. "The IO scheduler <class> can be one of:\n"
  353. " real-time, best-effort or idle\n"
  354. "\n"
  355. "Exit status: 0 = done 1 = nothing done (=> 0 if --oknodo)\n"
  356. " 3 = trouble 2 = with --retry, processes wouldn't die\n");
  357. }
  358. static void
  359. do_version(void)
  360. {
  361. printf("start-stop-daemon %s for Debian\n\n", VERSION);
  362. printf("Written by Marek Michalkiewicz, public domain.\n");
  363. }
  364. static void
  365. badusage(const char *msg)
  366. {
  367. if (msg)
  368. fprintf(stderr, "%s: %s\n", progname, msg);
  369. fprintf(stderr, "Try '%s --help' for more information.\n", progname);
  370. exit(3);
  371. }
  372. struct sigpair {
  373. const char *name;
  374. int signal;
  375. };
  376. static const struct sigpair siglist[] = {
  377. { "ABRT", SIGABRT },
  378. { "ALRM", SIGALRM },
  379. { "FPE", SIGFPE },
  380. { "HUP", SIGHUP },
  381. { "ILL", SIGILL },
  382. { "INT", SIGINT },
  383. { "KILL", SIGKILL },
  384. { "PIPE", SIGPIPE },
  385. { "QUIT", SIGQUIT },
  386. { "SEGV", SIGSEGV },
  387. { "TERM", SIGTERM },
  388. { "USR1", SIGUSR1 },
  389. { "USR2", SIGUSR2 },
  390. { "CHLD", SIGCHLD },
  391. { "CONT", SIGCONT },
  392. { "STOP", SIGSTOP },
  393. { "TSTP", SIGTSTP },
  394. { "TTIN", SIGTTIN },
  395. { "TTOU", SIGTTOU }
  396. };
  397. static int
  398. parse_integer(const char *string, int *value_r)
  399. {
  400. unsigned long ul;
  401. char *ep;
  402. if (!string[0])
  403. return -1;
  404. ul = strtoul(string, &ep, 10);
  405. if (string == ep || ul > INT_MAX || *ep != '\0')
  406. return -1;
  407. *value_r = ul;
  408. return 0;
  409. }
  410. static int
  411. parse_signal(const char *signal_str, int *signal_nr)
  412. {
  413. unsigned int i;
  414. if (parse_integer(signal_str, signal_nr) == 0)
  415. return 0;
  416. for (i = 0; i < sizeof_array(siglist); i++) {
  417. if (strcmp(signal_str, siglist[i].name) == 0) {
  418. *signal_nr = siglist[i].signal;
  419. return 0;
  420. }
  421. }
  422. return -1;
  423. }
  424. static int
  425. parse_umask(const char *string, int *value_r)
  426. {
  427. if (!string[0])
  428. return -1;
  429. errno = 0;
  430. *value_r = strtoul(string, NULL, 0);
  431. if (errno)
  432. return -1;
  433. else
  434. return 0;
  435. }
  436. static void
  437. validate_proc_schedule(void)
  438. {
  439. #ifdef _POSIX_PRIORITY_SCHEDULING
  440. int prio_min, prio_max;
  441. prio_min = sched_get_priority_min(proc_sched->policy);
  442. prio_max = sched_get_priority_max(proc_sched->policy);
  443. if (proc_sched->priority < prio_min)
  444. badusage("process scheduler priority less than min");
  445. if (proc_sched->priority > prio_max)
  446. badusage("process scheduler priority greater than max");
  447. #endif
  448. }
  449. static void
  450. parse_proc_schedule(const char *string)
  451. {
  452. char *policy_str, *prio_str;
  453. int prio = 0;
  454. policy_str = xstrdup(string);
  455. policy_str = strtok(policy_str, ":");
  456. prio_str = strtok(NULL, ":");
  457. if (prio_str && parse_integer(prio_str, &prio) != 0)
  458. fatal("invalid process scheduler priority");
  459. proc_sched = xmalloc(sizeof(*proc_sched));
  460. proc_sched->policy_name = policy_str;
  461. if (strcmp(policy_str, "other") == 0) {
  462. proc_sched->policy = SCHED_OTHER;
  463. proc_sched->priority = 0;
  464. } else if (strcmp(policy_str, "fifo") == 0) {
  465. proc_sched->policy = SCHED_FIFO;
  466. proc_sched->priority = prio;
  467. } else if (strcmp(policy_str, "rr") == 0) {
  468. proc_sched->policy = SCHED_RR;
  469. proc_sched->priority = prio;
  470. } else
  471. badusage("invalid process scheduler policy");
  472. validate_proc_schedule();
  473. }
  474. static void
  475. parse_io_schedule(const char *string)
  476. {
  477. char *class_str, *prio_str;
  478. int prio = 4;
  479. class_str = xstrdup(string);
  480. class_str = strtok(class_str, ":");
  481. prio_str = strtok(NULL, ":");
  482. if (prio_str && parse_integer(prio_str, &prio) != 0)
  483. fatal("invalid IO scheduler priority");
  484. io_sched = xmalloc(sizeof(*io_sched));
  485. io_sched->policy_name = class_str;
  486. if (strcmp(class_str, "real-time") == 0) {
  487. io_sched->policy = IOPRIO_CLASS_RT;
  488. io_sched->priority = prio;
  489. } else if (strcmp(class_str, "best-effort") == 0) {
  490. io_sched->policy = IOPRIO_CLASS_BE;
  491. io_sched->priority = prio;
  492. } else if (strcmp(class_str, "idle") == 0) {
  493. io_sched->policy = IOPRIO_CLASS_IDLE;
  494. io_sched->priority = 7;
  495. } else
  496. badusage("invalid IO scheduler policy");
  497. if (io_sched->priority < IO_SCHED_PRIO_MIN)
  498. badusage("IO scheduler priority less than min");
  499. if (io_sched->priority > IO_SCHED_PRIO_MAX)
  500. badusage("IO scheduler priority greater than max");
  501. }
  502. static void
  503. set_proc_schedule(struct res_schedule *sched)
  504. {
  505. #ifdef _POSIX_PRIORITY_SCHEDULING
  506. struct sched_param param;
  507. param.sched_priority = sched->priority;
  508. if (sched_setscheduler(getpid(), sched->policy, &param) == -1)
  509. fatal("Unable to set process scheduler");
  510. #endif
  511. }
  512. #ifdef HAVE_IOPRIO_SET
  513. static inline int
  514. ioprio_set(int which, int who, int ioprio)
  515. {
  516. return syscall(SYS_ioprio_set, which, who, ioprio);
  517. }
  518. #endif
  519. static void
  520. set_io_schedule(struct res_schedule *sched)
  521. {
  522. #ifdef HAVE_IOPRIO_SET
  523. int io_sched_mask;
  524. io_sched_mask = IOPRIO_PRIO_VALUE(sched->policy, sched->priority);
  525. if (ioprio_set(IOPRIO_WHO_PROCESS, getpid(), io_sched_mask) == -1)
  526. warning("Unable to alter IO priority to mask %i (%s)\n",
  527. io_sched_mask, strerror(errno));
  528. #endif
  529. }
  530. static void
  531. parse_schedule_item(const char *string, struct schedule_item *item)
  532. {
  533. const char *after_hyph;
  534. if (!strcmp(string, "forever")) {
  535. item->type = sched_forever;
  536. } else if (isdigit(string[0])) {
  537. item->type = sched_timeout;
  538. if (parse_integer(string, &item->value) != 0)
  539. badusage("invalid timeout value in schedule");
  540. } else if ((after_hyph = string + (string[0] == '-')) &&
  541. parse_signal(after_hyph, &item->value) == 0) {
  542. item->type = sched_signal;
  543. } else {
  544. badusage("invalid schedule item (must be [-]<signal-name>, "
  545. "-<signal-number>, <timeout> or 'forever'");
  546. }
  547. }
  548. static void
  549. parse_schedule(const char *schedule_str)
  550. {
  551. char item_buf[20];
  552. const char *slash;
  553. int count, repeatat;
  554. size_t str_len;
  555. count = 0;
  556. for (slash = schedule_str; *slash; slash++)
  557. if (*slash == '/')
  558. count++;
  559. schedule_length = (count == 0) ? 4 : count + 1;
  560. schedule = xmalloc(sizeof(*schedule) * schedule_length);
  561. if (count == 0) {
  562. schedule[0].type = sched_signal;
  563. schedule[0].value = signal_nr;
  564. parse_schedule_item(schedule_str, &schedule[1]);
  565. if (schedule[1].type != sched_timeout) {
  566. badusage ("--retry takes timeout, or schedule list"
  567. " of at least two items");
  568. }
  569. schedule[2].type = sched_signal;
  570. schedule[2].value = SIGKILL;
  571. schedule[3] = schedule[1];
  572. } else {
  573. count = 0;
  574. repeatat = -1;
  575. while (schedule_str != NULL) {
  576. slash = strchr(schedule_str, '/');
  577. str_len = slash ? (size_t)(slash - schedule_str) : strlen(schedule_str);
  578. if (str_len >= sizeof(item_buf))
  579. badusage("invalid schedule item: far too long"
  580. " (you must delimit items with slashes)");
  581. memcpy(item_buf, schedule_str, str_len);
  582. item_buf[str_len] = '\0';
  583. schedule_str = slash ? slash + 1 : NULL;
  584. parse_schedule_item(item_buf, &schedule[count]);
  585. if (schedule[count].type == sched_forever) {
  586. if (repeatat >= 0)
  587. badusage("invalid schedule: 'forever'"
  588. " appears more than once");
  589. repeatat = count;
  590. continue;
  591. }
  592. count++;
  593. }
  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: %s", pid, strerror(errno));
  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("open pidfile %s: %s", name, strerror(errno));
  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("opendir /proc: %s", strerror(errno));
  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 signal_nr, int quietmode, int *n_killed, int *n_notkilled,
  1103. int retry_nr)
  1104. {
  1105. struct pid_list *p;
  1106. do_findprocs();
  1107. *n_killed = 0;
  1108. *n_notkilled = 0;
  1109. if (!found)
  1110. return;
  1111. clear(&killed);
  1112. for (p = found; p; p = p->next) {
  1113. if (testmode) {
  1114. if (quietmode <= 0)
  1115. printf("Would send signal %d to %d.\n",
  1116. signal_nr, p->pid);
  1117. (*n_killed)++;
  1118. } else if (kill(p->pid, signal_nr) == 0) {
  1119. push(&killed, p->pid);
  1120. (*n_killed)++;
  1121. } else {
  1122. if (signal_nr)
  1123. warning("failed to kill %d: %s\n",
  1124. p->pid, strerror(errno));
  1125. (*n_notkilled)++;
  1126. }
  1127. }
  1128. if (quietmode < 0 && killed) {
  1129. printf("Stopped %s (pid", what_stop);
  1130. for (p = killed; p; p = p->next)
  1131. printf(" %d", p->pid);
  1132. putchar(')');
  1133. if (retry_nr > 0)
  1134. printf(", retry #%d", retry_nr);
  1135. printf(".\n");
  1136. }
  1137. }
  1138. static void
  1139. set_what_stop(const char *str)
  1140. {
  1141. strncpy(what_stop, str, sizeof(what_stop));
  1142. what_stop[sizeof(what_stop) - 1] = '\0';
  1143. }
  1144. static int
  1145. run_stop_schedule(void)
  1146. {
  1147. int r, position, n_killed, n_notkilled, value, ratio, anykilled, retry_nr;
  1148. struct timeval stopat, before, after, interval, maxinterval;
  1149. if (testmode) {
  1150. if (schedule != NULL) {
  1151. if (quietmode <= 0)
  1152. printf("Ignoring --retry in test mode\n");
  1153. schedule = NULL;
  1154. }
  1155. }
  1156. if (cmdname)
  1157. set_what_stop(cmdname);
  1158. else if (execname)
  1159. set_what_stop(execname);
  1160. else if (pidfile)
  1161. sprintf(what_stop, "process in pidfile '%.200s'", pidfile);
  1162. else if (userspec)
  1163. sprintf(what_stop, "process(es) owned by '%.200s'", userspec);
  1164. else
  1165. fatal("internal error, please report");
  1166. anykilled = 0;
  1167. retry_nr = 0;
  1168. if (schedule == NULL) {
  1169. do_stop(signal_nr, quietmode, &n_killed, &n_notkilled, 0);
  1170. if (n_notkilled > 0 && quietmode <= 0)
  1171. printf("%d pids were not killed\n", n_notkilled);
  1172. if (n_killed)
  1173. anykilled = 1;
  1174. goto x_finished;
  1175. }
  1176. for (position = 0; position < schedule_length; ) {
  1177. value = schedule[position].value;
  1178. n_notkilled = 0;
  1179. switch (schedule[position].type) {
  1180. case sched_goto:
  1181. position = value;
  1182. continue;
  1183. case sched_signal:
  1184. do_stop(value, quietmode, &n_killed, &n_notkilled, retry_nr++);
  1185. if (!n_killed)
  1186. goto x_finished;
  1187. else
  1188. anykilled = 1;
  1189. goto next_item;
  1190. case sched_timeout:
  1191. /* We want to keep polling for the processes, to see if they've exited,
  1192. * or until the timeout expires.
  1193. *
  1194. * This is a somewhat complicated algorithm to try to ensure that we
  1195. * notice reasonably quickly when all the processes have exited, but
  1196. * don't spend too much CPU time polling. In particular, on a fast
  1197. * machine with quick-exiting daemons we don't want to delay system
  1198. * shutdown too much, whereas on a slow one, or where processes are
  1199. * taking some time to exit, we want to increase the polling
  1200. * interval.
  1201. *
  1202. * The algorithm is as follows: we measure the elapsed time it takes
  1203. * to do one poll(), and wait a multiple of this time for the next
  1204. * poll. However, if that would put us past the end of the timeout
  1205. * period we wait only as long as the timeout period, but in any case
  1206. * we always wait at least MIN_POLL_INTERVAL (20ms). The multiple
  1207. * (‘ratio’) starts out as 2, and increases by 1 for each poll to a
  1208. * maximum of 10; so we use up to between 30% and 10% of the
  1209. * machine's resources (assuming a few reasonable things about system
  1210. * performance).
  1211. */
  1212. xgettimeofday(&stopat);
  1213. stopat.tv_sec += value;
  1214. ratio = 1;
  1215. for (;;) {
  1216. xgettimeofday(&before);
  1217. if (timercmp(&before, &stopat, >))
  1218. goto next_item;
  1219. do_stop(0, 1, &n_killed, &n_notkilled, 0);
  1220. if (!n_killed)
  1221. goto x_finished;
  1222. xgettimeofday(&after);
  1223. if (!timercmp(&after, &stopat, <))
  1224. goto next_item;
  1225. if (ratio < 10)
  1226. ratio++;
  1227. timersub(&stopat, &after, &maxinterval);
  1228. timersub(&after, &before, &interval);
  1229. tmul(&interval, ratio);
  1230. if (interval.tv_sec < 0 || interval.tv_usec < 0)
  1231. interval.tv_sec = interval.tv_usec = 0;
  1232. if (timercmp(&interval, &maxinterval, >))
  1233. interval = maxinterval;
  1234. if (interval.tv_sec == 0 &&
  1235. interval.tv_usec <= MIN_POLL_INTERVAL)
  1236. interval.tv_usec = MIN_POLL_INTERVAL;
  1237. r = select(0, NULL, NULL, NULL, &interval);
  1238. if (r < 0 && errno != EINTR)
  1239. fatal("select() failed for pause: %s",
  1240. strerror(errno));
  1241. }
  1242. default:
  1243. assert(!"schedule[].type value must be valid");
  1244. }
  1245. next_item:
  1246. position++;
  1247. }
  1248. if (quietmode <= 0)
  1249. printf("Program %s, %d process(es), refused to die.\n",
  1250. what_stop, n_killed);
  1251. return 2;
  1252. x_finished:
  1253. if (!anykilled) {
  1254. if (quietmode <= 0)
  1255. printf("No %s found running; none killed.\n", what_stop);
  1256. return exitnodo;
  1257. } else {
  1258. return 0;
  1259. }
  1260. }
  1261. int
  1262. main(int argc, char **argv)
  1263. {
  1264. int devnull_fd = -1;
  1265. gid_t rgid;
  1266. uid_t ruid;
  1267. #ifdef HAVE_TIOCNOTTY
  1268. int tty_fd = -1;
  1269. #endif
  1270. progname = argv[0];
  1271. parse_options(argc, argv);
  1272. argc -= optind;
  1273. argv += optind;
  1274. if (execname) {
  1275. char *fullexecname;
  1276. if (changeroot) {
  1277. int fullexecname_len = strlen(changeroot) + 1 +
  1278. strlen(execname) + 1;
  1279. fullexecname = xmalloc(fullexecname_len);
  1280. snprintf(fullexecname, fullexecname_len, "%s/%s",
  1281. changeroot, execname);
  1282. } else
  1283. fullexecname = execname;
  1284. if (stat(fullexecname, &exec_stat))
  1285. fatal("stat %s: %s", fullexecname, strerror(errno));
  1286. if (fullexecname != execname)
  1287. free(fullexecname);
  1288. }
  1289. if (userspec && sscanf(userspec, "%d", &user_id) != 1) {
  1290. struct passwd *pw;
  1291. pw = getpwnam(userspec);
  1292. if (!pw)
  1293. fatal("user '%s' not found\n", userspec);
  1294. user_id = pw->pw_uid;
  1295. }
  1296. if (changegroup && sscanf(changegroup, "%d", &runas_gid) != 1) {
  1297. struct group *gr = getgrnam(changegroup);
  1298. if (!gr)
  1299. fatal("group '%s' not found\n", changegroup);
  1300. runas_gid = gr->gr_gid;
  1301. }
  1302. if (changeuser) {
  1303. struct passwd *pw;
  1304. struct stat st;
  1305. if (sscanf(changeuser, "%d", &runas_uid) == 1)
  1306. pw = getpwuid(runas_uid);
  1307. else
  1308. pw = getpwnam(changeuser);
  1309. if (!pw)
  1310. fatal("user '%s' not found\n", changeuser);
  1311. runas_uid = pw->pw_uid;
  1312. if (changegroup == NULL) {
  1313. /* Pass the default group of this user. */
  1314. changegroup = ""; /* Just empty. */
  1315. runas_gid = pw->pw_gid;
  1316. }
  1317. if (stat(pw->pw_dir, &st) == 0)
  1318. setenv("HOME", pw->pw_dir, 1);
  1319. }
  1320. if (stop) {
  1321. int i = run_stop_schedule();
  1322. exit(i);
  1323. }
  1324. do_findprocs();
  1325. if (found) {
  1326. if (quietmode <= 0)
  1327. printf("%s already running.\n", execname ? execname : "process");
  1328. exit(exitnodo);
  1329. }
  1330. if (testmode && quietmode <= 0) {
  1331. printf("Would start %s ", startas);
  1332. while (argc-- > 0)
  1333. printf("%s ", *argv++);
  1334. if (changeuser != NULL) {
  1335. printf(" (as user %s[%d]", changeuser, runas_uid);
  1336. if (changegroup != NULL)
  1337. printf(", and group %s[%d])", changegroup, runas_gid);
  1338. else
  1339. printf(")");
  1340. }
  1341. if (changeroot != NULL)
  1342. printf(" in directory %s", changeroot);
  1343. if (nicelevel)
  1344. printf(", and add %i to the priority", nicelevel);
  1345. if (proc_sched)
  1346. printf(", with scheduling policy %s with priority %i",
  1347. proc_sched->policy_name, proc_sched->priority);
  1348. if (io_sched)
  1349. printf(", with IO scheduling class %s with priority %i",
  1350. io_sched->policy_name, io_sched->priority);
  1351. printf(".\n");
  1352. }
  1353. if (testmode)
  1354. exit(0);
  1355. if (quietmode < 0)
  1356. printf("Starting %s...\n", startas);
  1357. *--argv = startas;
  1358. if (background) {
  1359. /* Ok, we need to detach this process. */
  1360. daemonize();
  1361. #ifdef HAVE_TIOCNOTTY
  1362. tty_fd = open("/dev/tty", O_RDWR);
  1363. #endif
  1364. devnull_fd = open("/dev/null", O_RDWR);
  1365. }
  1366. if (nicelevel) {
  1367. errno = 0;
  1368. if ((nice(nicelevel) == -1) && (errno != 0))
  1369. fatal("Unable to alter nice level by %i: %s",
  1370. nicelevel, strerror(errno));
  1371. }
  1372. if (proc_sched)
  1373. set_proc_schedule(proc_sched);
  1374. if (io_sched)
  1375. set_io_schedule(io_sched);
  1376. if (umask_value >= 0)
  1377. umask(umask_value);
  1378. if (mpidfile && pidfile != NULL) {
  1379. /* User wants _us_ to make the pidfile. :) */
  1380. FILE *pidf = fopen(pidfile, "w");
  1381. pid_t pidt = getpid();
  1382. if (pidf == NULL)
  1383. fatal("Unable to open pidfile '%s' for writing: %s",
  1384. pidfile, strerror(errno));
  1385. fprintf(pidf, "%d\n", pidt);
  1386. fclose(pidf);
  1387. }
  1388. if (changeroot != NULL) {
  1389. if (chdir(changeroot) < 0)
  1390. fatal("Unable to chdir() to %s", changeroot);
  1391. if (chroot(changeroot) < 0)
  1392. fatal("Unable to chroot() to %s", changeroot);
  1393. }
  1394. if (chdir(changedir) < 0)
  1395. fatal("Unable to chdir() to %s", changedir);
  1396. rgid = getgid();
  1397. ruid = getuid();
  1398. if (changegroup != NULL) {
  1399. if (rgid != (gid_t)runas_gid)
  1400. if (setgid(runas_gid))
  1401. fatal("Unable to set gid to %d", runas_gid);
  1402. }
  1403. if (changeuser != NULL) {
  1404. /* We assume that if our real user and group are the same as
  1405. * the ones we should switch to, the supplementary groups
  1406. * will be already in place. */
  1407. if (rgid != (gid_t)runas_gid || ruid != (uid_t)runas_uid)
  1408. if (initgroups(changeuser, runas_gid))
  1409. fatal("Unable to set initgroups() with gid %d",
  1410. runas_gid);
  1411. if (ruid != (uid_t)runas_uid)
  1412. if (setuid(runas_uid))
  1413. fatal("Unable to set uid to %s", changeuser);
  1414. }
  1415. if (background) {
  1416. /* Continue background setup. */
  1417. int i;
  1418. #ifdef HAVE_TIOCNOTTY
  1419. /* Change tty. */
  1420. ioctl(tty_fd, TIOCNOTTY, 0);
  1421. close(tty_fd);
  1422. #endif
  1423. if (umask_value < 0)
  1424. umask(022); /* Set a default for dumb programs. */
  1425. dup2(devnull_fd, 0); /* stdin */
  1426. dup2(devnull_fd, 1); /* stdout */
  1427. dup2(devnull_fd, 2); /* stderr */
  1428. /* Now close all extra fds. */
  1429. for (i = get_open_fd_max() - 1; i >= 3; --i)
  1430. close(i);
  1431. }
  1432. execv(startas, argv);
  1433. fatal("Unable to start %s: %s", startas, strerror(errno));
  1434. }