start-stop-daemon.c 40 KB

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