start-stop-daemon.c 33 KB

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