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