start-stop-daemon.c 38 KB

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