start-stop-daemon.c 38 KB

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