start-stop-daemon.c 41 KB

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