start-stop-daemon.c 35 KB

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