start-stop-daemon.c 33 KB

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