start-stop-daemon.c 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635
  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. fatal("Unable to alter IO priority to mask %i", io_sched_mask);
  529. #endif
  530. }
  531. static void
  532. parse_schedule_item(const char *string, struct schedule_item *item)
  533. {
  534. const char *after_hyph;
  535. if (!strcmp(string, "forever")) {
  536. item->type = sched_forever;
  537. } else if (isdigit(string[0])) {
  538. item->type = sched_timeout;
  539. if (parse_integer(string, &item->value) != 0)
  540. badusage("invalid timeout value in schedule");
  541. } else if ((after_hyph = string + (string[0] == '-')) &&
  542. parse_signal(after_hyph, &item->value) == 0) {
  543. item->type = sched_signal;
  544. } else {
  545. badusage("invalid schedule item (must be [-]<signal-name>, "
  546. "-<signal-number>, <timeout> or `forever'");
  547. }
  548. }
  549. static void
  550. parse_schedule(const char *schedule_str)
  551. {
  552. char item_buf[20];
  553. const char *slash;
  554. int count, repeatat;
  555. size_t str_len;
  556. count = 0;
  557. for (slash = schedule_str; *slash; slash++)
  558. if (*slash == '/')
  559. count++;
  560. schedule_length = (count == 0) ? 4 : count + 1;
  561. schedule = xmalloc(sizeof(*schedule) * schedule_length);
  562. if (count == 0) {
  563. schedule[0].type = sched_signal;
  564. schedule[0].value = signal_nr;
  565. parse_schedule_item(schedule_str, &schedule[1]);
  566. if (schedule[1].type != sched_timeout) {
  567. badusage ("--retry takes timeout, or schedule list"
  568. " of at least two items");
  569. }
  570. schedule[2].type = sched_signal;
  571. schedule[2].value = SIGKILL;
  572. schedule[3] = schedule[1];
  573. } else {
  574. count = 0;
  575. repeatat = -1;
  576. while (schedule_str != NULL) {
  577. slash = strchr(schedule_str, '/');
  578. str_len = slash ? (size_t)(slash - schedule_str) : strlen(schedule_str);
  579. if (str_len >= sizeof(item_buf))
  580. badusage("invalid schedule item: far too long"
  581. " (you must delimit items with slashes)");
  582. memcpy(item_buf, schedule_str, str_len);
  583. item_buf[str_len] = '\0';
  584. schedule_str = slash ? slash + 1 : NULL;
  585. parse_schedule_item(item_buf, &schedule[count]);
  586. if (schedule[count].type == sched_forever) {
  587. if (repeatat >= 0)
  588. badusage("invalid schedule: `forever'"
  589. " appears more than once");
  590. repeatat = count;
  591. continue;
  592. }
  593. count++;
  594. }
  595. if (repeatat >= 0) {
  596. schedule[count].type = sched_goto;
  597. schedule[count].value = repeatat;
  598. count++;
  599. }
  600. assert(count == schedule_length);
  601. }
  602. }
  603. static void
  604. parse_options(int argc, char * const *argv)
  605. {
  606. static struct option longopts[] = {
  607. { "help", 0, NULL, 'H'},
  608. { "stop", 0, NULL, 'K'},
  609. { "start", 0, NULL, 'S'},
  610. { "version", 0, NULL, 'V'},
  611. { "startas", 1, NULL, 'a'},
  612. { "name", 1, NULL, 'n'},
  613. { "oknodo", 0, NULL, 'o'},
  614. { "pidfile", 1, NULL, 'p'},
  615. { "quiet", 0, NULL, 'q'},
  616. { "signal", 1, NULL, 's'},
  617. { "test", 0, NULL, 't'},
  618. { "user", 1, NULL, 'u'},
  619. { "group", 1, NULL, 'g'},
  620. { "chroot", 1, NULL, 'r'},
  621. { "verbose", 0, NULL, 'v'},
  622. { "exec", 1, NULL, 'x'},
  623. { "chuid", 1, NULL, 'c'},
  624. { "nicelevel", 1, NULL, 'N'},
  625. { "procsched", 1, NULL, 'P'},
  626. { "iosched", 1, NULL, 'I'},
  627. { "umask", 1, NULL, 'k'},
  628. { "background", 0, NULL, 'b'},
  629. { "make-pidfile", 0, NULL, 'm'},
  630. { "retry", 1, NULL, 'R'},
  631. { "chdir", 1, NULL, 'd'},
  632. { NULL, 0, NULL, 0 }
  633. };
  634. const char *umask_str = NULL;
  635. const char *signal_str = NULL;
  636. const char *schedule_str = NULL;
  637. const char *proc_schedule_str = NULL;
  638. const char *io_schedule_str = NULL;
  639. int c;
  640. for (;;) {
  641. c = getopt_long(argc, argv,
  642. "HKSVa:n:op:qr:s:tu:vx:c:N:P:I:k:bmR:g:d:",
  643. longopts, NULL);
  644. if (c == -1)
  645. break;
  646. switch (c) {
  647. case 'H': /* --help */
  648. do_help();
  649. exit(0);
  650. case 'K': /* --stop */
  651. stop = 1;
  652. break;
  653. case 'S': /* --start */
  654. start = 1;
  655. break;
  656. case 'V': /* --version */
  657. do_version();
  658. exit(0);
  659. case 'a': /* --startas <pathname> */
  660. startas = optarg;
  661. break;
  662. case 'n': /* --name <process-name> */
  663. cmdname = optarg;
  664. break;
  665. case 'o': /* --oknodo */
  666. exitnodo = 0;
  667. break;
  668. case 'p': /* --pidfile <pid-file> */
  669. pidfile = optarg;
  670. break;
  671. case 'q': /* --quiet */
  672. quietmode = 1;
  673. break;
  674. case 's': /* --signal <signal> */
  675. signal_str = optarg;
  676. break;
  677. case 't': /* --test */
  678. testmode = 1;
  679. break;
  680. case 'u': /* --user <username>|<uid> */
  681. userspec = optarg;
  682. break;
  683. case 'v': /* --verbose */
  684. quietmode = -1;
  685. break;
  686. case 'x': /* --exec <executable> */
  687. execname = optarg;
  688. break;
  689. case 'c': /* --chuid <username>|<uid> */
  690. /* we copy the string just in case we need the
  691. * argument later. */
  692. changeuser = xstrdup(optarg);
  693. changeuser = strtok(changeuser, ":");
  694. changegroup = strtok(NULL, ":");
  695. break;
  696. case 'g': /* --group <group>|<gid> */
  697. changegroup = optarg;
  698. break;
  699. case 'r': /* --chroot /new/root */
  700. changeroot = optarg;
  701. break;
  702. case 'N': /* --nice */
  703. nicelevel = atoi(optarg);
  704. break;
  705. case 'P': /* --procsched */
  706. proc_schedule_str = optarg;
  707. break;
  708. case 'I': /* --iosched */
  709. io_schedule_str = optarg;
  710. break;
  711. case 'k': /* --umask <mask> */
  712. umask_str = optarg;
  713. break;
  714. case 'b': /* --background */
  715. background = 1;
  716. break;
  717. case 'm': /* --make-pidfile */
  718. mpidfile = 1;
  719. break;
  720. case 'R': /* --retry <schedule>|<timeout> */
  721. schedule_str = optarg;
  722. break;
  723. case 'd': /* --chdir /new/dir */
  724. changedir = optarg;
  725. break;
  726. default:
  727. badusage(NULL); /* message printed by getopt */
  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 int
  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 0;
  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 0;
  816. return (sb.st_dev == esb->st_dev && sb.st_ino == esb->st_ino);
  817. }
  818. #elif defined(OShpux)
  819. static int
  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 0;
  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 int
  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 0;
  845. return (strcmp(name, pidexec) == 0) ? 1 : 0;
  846. }
  847. #endif
  848. #if defined(OSLinux)
  849. static int
  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 0;
  857. return (sb.st_uid == uid);
  858. }
  859. #elif defined(OSHurd)
  860. static int
  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 int
  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 0;
  874. return ((uid_t)pst.pst_uid == uid);
  875. }
  876. #elif defined(HAVE_KVM_H)
  877. static int
  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 0;
  896. return (proc_uid == (uid_t)uid);
  897. }
  898. #endif
  899. #if defined(OSLinux)
  900. static int
  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 0;
  910. while ((c = getc(f)) != EOF && c != '(')
  911. ;
  912. if (c != '(') {
  913. fclose(f);
  914. return 0;
  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 int
  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 int
  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 0;
  937. return (strcmp(pst.pst_ucomm, name) == 0);
  938. }
  939. #elif defined(HAVE_KVM_H)
  940. static int
  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 0;
  976. return (strcmp(name, start_argv_0_p) == 0) ? 1 : 0;
  977. }
  978. #endif
  979. #if defined(OSHurd)
  980. static int
  981. pid_is_running(pid_t pid)
  982. {
  983. return get_proc_stat(pid, 0) != NULL;
  984. }
  985. #else /* !OSHurd */
  986. static int
  987. pid_is_running(pid_t pid)
  988. {
  989. if (kill(pid, 0) == 0 || errno == EPERM)
  990. return 1;
  991. else if (errno == ESRCH)
  992. return 0;
  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. /* return 1 on failure */
  1102. static void
  1103. do_stop(int signal_nr, int quietmode, int *n_killed, int *n_notkilled, 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. if (sscanf(changeuser, "%d", &runas_uid) == 1)
  1305. pw = getpwuid(runas_uid);
  1306. else
  1307. pw = getpwnam(changeuser);
  1308. if (!pw)
  1309. fatal("user `%s' not found\n", changeuser);
  1310. runas_uid = pw->pw_uid;
  1311. if (changegroup == NULL) {
  1312. /* Pass the default group of this user */
  1313. changegroup = ""; /* Just empty */
  1314. runas_gid = pw->pw_gid;
  1315. }
  1316. if (access(pw->pw_dir, F_OK) == 0)
  1317. setenv("HOME", pw->pw_dir, 1);
  1318. }
  1319. if (stop) {
  1320. int i = run_stop_schedule();
  1321. exit(i);
  1322. }
  1323. do_findprocs();
  1324. if (found) {
  1325. if (quietmode <= 0)
  1326. printf("%s already running.\n", execname ? execname : "process");
  1327. exit(exitnodo);
  1328. }
  1329. if (testmode && quietmode <= 0) {
  1330. printf("Would start %s ", startas);
  1331. while (argc-- > 0)
  1332. printf("%s ", *argv++);
  1333. if (changeuser != NULL) {
  1334. printf(" (as user %s[%d]", changeuser, runas_uid);
  1335. if (changegroup != NULL)
  1336. printf(", and group %s[%d])", changegroup, runas_gid);
  1337. else
  1338. printf(")");
  1339. }
  1340. if (changeroot != NULL)
  1341. printf(" in directory %s", changeroot);
  1342. if (nicelevel)
  1343. printf(", and add %i to the priority", nicelevel);
  1344. if (proc_sched)
  1345. printf(", with scheduling policy %s with priority %i",
  1346. proc_sched->policy_name, proc_sched->priority);
  1347. if (io_sched)
  1348. printf(", with IO scheduling class %s with priority %i",
  1349. io_sched->policy_name, io_sched->priority);
  1350. printf(".\n");
  1351. }
  1352. if (testmode)
  1353. exit(0);
  1354. if (quietmode < 0)
  1355. printf("Starting %s...\n", startas);
  1356. *--argv = startas;
  1357. if (background) { /* ok, we need to detach this process */
  1358. daemonize();
  1359. #ifdef HAVE_TIOCNOTTY
  1360. tty_fd=open("/dev/tty", O_RDWR);
  1361. #endif
  1362. devnull_fd=open("/dev/null", O_RDWR);
  1363. }
  1364. if (nicelevel) {
  1365. errno = 0;
  1366. if ((nice(nicelevel) == -1) && (errno != 0))
  1367. fatal("Unable to alter nice level by %i: %s",
  1368. nicelevel, strerror(errno));
  1369. }
  1370. if (proc_sched)
  1371. set_proc_schedule(proc_sched);
  1372. if (io_sched)
  1373. set_io_schedule(io_sched);
  1374. if (umask_value >= 0)
  1375. umask(umask_value);
  1376. if (mpidfile && pidfile != NULL) {
  1377. /* User wants _us_ to make the pidfile :) */
  1378. FILE *pidf = fopen(pidfile, "w");
  1379. pid_t pidt = getpid();
  1380. if (pidf == NULL)
  1381. fatal("Unable to open pidfile `%s' for writing: %s",
  1382. pidfile, strerror(errno));
  1383. fprintf(pidf, "%d\n", pidt);
  1384. fclose(pidf);
  1385. }
  1386. if (changeroot != NULL) {
  1387. if (chdir(changeroot) < 0)
  1388. fatal("Unable to chdir() to %s", changeroot);
  1389. if (chroot(changeroot) < 0)
  1390. fatal("Unable to chroot() to %s", changeroot);
  1391. }
  1392. if (chdir(changedir) < 0)
  1393. fatal("Unable to chdir() to %s", changedir);
  1394. rgid = getgid();
  1395. ruid = getuid();
  1396. if (changegroup != NULL) {
  1397. if (rgid != (gid_t)runas_gid)
  1398. if (setgid(runas_gid))
  1399. fatal("Unable to set gid to %d", runas_gid);
  1400. }
  1401. if (changeuser != NULL) {
  1402. /* We assume that if our real user and group are the same as
  1403. * the ones we should switch to, the supplementary groups
  1404. * will be already in place. */
  1405. if (rgid != (gid_t)runas_gid || ruid != (uid_t)runas_uid)
  1406. if (initgroups(changeuser, runas_gid))
  1407. fatal("Unable to set initgroups() with gid %d",
  1408. runas_gid);
  1409. if (ruid != (uid_t)runas_uid)
  1410. if (setuid(runas_uid))
  1411. fatal("Unable to set uid to %s", changeuser);
  1412. }
  1413. if (background) {
  1414. /* Continue background setup */
  1415. int i;
  1416. #ifdef HAVE_TIOCNOTTY
  1417. /* Change tty */
  1418. ioctl(tty_fd, TIOCNOTTY, 0);
  1419. close(tty_fd);
  1420. #endif
  1421. if (umask_value < 0)
  1422. umask(022); /* Set a default for dumb programs */
  1423. dup2(devnull_fd, 0); /* stdin */
  1424. dup2(devnull_fd, 1); /* stdout */
  1425. dup2(devnull_fd, 2); /* stderr */
  1426. /* Now close all extra fds */
  1427. for (i = get_open_fd_max() - 1; i >= 3; --i)
  1428. close(i);
  1429. }
  1430. execv(startas, argv);
  1431. fatal("Unable to start %s: %s", startas, strerror(errno));
  1432. }