start-stop-daemon.c 37 KB

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