start-stop-daemon.c 38 KB

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