start-stop-daemon.c 33 KB

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