start-stop-daemon.c 33 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406
  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. pid_t pid;
  747. f = fopen(name, "r");
  748. if (f) {
  749. if (fscanf(f, "%d", &pid) == 1)
  750. check(pid);
  751. fclose(f);
  752. } else if (errno != ENOENT)
  753. fatal("open pidfile %s: %s", name, strerror(errno));
  754. }
  755. #if defined(OSLinux) || defined (OSsunos)
  756. static void
  757. do_procinit(void)
  758. {
  759. DIR *procdir;
  760. struct dirent *entry;
  761. int foundany;
  762. pid_t pid;
  763. procdir = opendir("/proc");
  764. if (!procdir)
  765. fatal("opendir /proc: %s", strerror(errno));
  766. foundany = 0;
  767. while ((entry = readdir(procdir)) != NULL) {
  768. if (sscanf(entry->d_name, "%d", &pid) != 1)
  769. continue;
  770. foundany++;
  771. check(pid);
  772. }
  773. closedir(procdir);
  774. if (!foundany)
  775. fatal("nothing in /proc - not mounted?");
  776. }
  777. #endif /* OSLinux */
  778. #if defined(OSHURD)
  779. static int
  780. check_proc_stat(struct proc_stat *ps)
  781. {
  782. check(ps->pid);
  783. return 0;
  784. }
  785. static void
  786. do_procinit(void)
  787. {
  788. if (!procset)
  789. init_procset();
  790. proc_stat_list_for_each(procset, check_proc_stat);
  791. }
  792. #endif /* OSHURD */
  793. #ifdef HAVE_KVM_H
  794. static int
  795. pid_is_cmd(pid_t pid, const char *name)
  796. {
  797. kvm_t *kd;
  798. int nentries, argv_len = 0;
  799. struct kinfo_proc *kp;
  800. char errbuf[_POSIX2_LINE_MAX], buf[_POSIX2_LINE_MAX];
  801. char **pid_argv_p;
  802. char *start_argv_0_p, *end_argv_0_p;
  803. kd = kvm_openfiles(NULL, NULL, NULL, O_RDONLY, errbuf);
  804. if (kd == NULL)
  805. errx(1, "%s", errbuf);
  806. kp = kvm_getprocs(kd, KERN_PROC_PID, pid, &nentries);
  807. if (kp == NULL)
  808. errx(1, "%s", kvm_geterr(kd));
  809. pid_argv_p = kvm_getargv(kd, kp, argv_len);
  810. if (pid_argv_p == NULL)
  811. errx(1, "%s", kvm_geterr(kd));
  812. start_argv_0_p = *pid_argv_p;
  813. /* Find and compare string */
  814. /* Find end of argv[0] then copy and cut of str there. */
  815. end_argv_0_p = strchr(*pid_argv_p, ' ');
  816. if (end_argv_0_p == NULL)
  817. /* There seems to be no space, so we have the command
  818. * allready in its desired form. */
  819. start_argv_0_p = *pid_argv_p;
  820. else {
  821. /* Tests indicate that this never happens, since
  822. * kvm_getargv itselfe cuts of tailing stuff. This is
  823. * not what the manpage says, however. */
  824. strncpy(buf, *pid_argv_p, (end_argv_0_p - start_argv_0_p));
  825. buf[(end_argv_0_p - start_argv_0_p) + 1] = '\0';
  826. start_argv_0_p = buf;
  827. }
  828. if (strlen(name) != strlen(start_argv_0_p))
  829. return 0;
  830. return (strcmp(name, start_argv_0_p) == 0) ? 1 : 0;
  831. }
  832. static int
  833. pid_is_user(pid_t pid, uid_t uid)
  834. {
  835. kvm_t *kd;
  836. int nentries; /* Value not used */
  837. uid_t proc_uid;
  838. struct kinfo_proc *kp;
  839. char errbuf[_POSIX2_LINE_MAX];
  840. kd = kvm_openfiles(NULL, NULL, NULL, O_RDONLY, errbuf);
  841. if (kd == NULL)
  842. errx(1, "%s", errbuf);
  843. kp = kvm_getprocs(kd, KERN_PROC_PID, pid, &nentries);
  844. if (kp == NULL)
  845. errx(1, "%s", kvm_geterr(kd));
  846. if (kp->kp_proc.p_cred)
  847. kvm_read(kd, (u_long)&(kp->kp_proc.p_cred->p_ruid),
  848. &proc_uid, sizeof(uid_t));
  849. else
  850. return 0;
  851. return (proc_uid == (uid_t)uid);
  852. }
  853. static int
  854. pid_is_exec(pid_t pid, const char *name)
  855. {
  856. kvm_t *kd;
  857. int nentries;
  858. struct kinfo_proc *kp;
  859. char errbuf[_POSIX2_LINE_MAX], *pidexec;
  860. kd = kvm_openfiles(NULL, NULL, NULL, O_RDONLY, errbuf);
  861. if (kd == NULL)
  862. errx(1, "%s", errbuf);
  863. kp = kvm_getprocs(kd, KERN_PROC_PID, pid, &nentries);
  864. if (kp == NULL)
  865. errx(1, "%s", kvm_geterr(kd));
  866. pidexec = (&kp->kp_proc)->p_comm;
  867. if (strlen(name) != strlen(pidexec))
  868. return 0;
  869. return (strcmp(name, pidexec) == 0) ? 1 : 0;
  870. }
  871. static void
  872. do_procinit(void)
  873. {
  874. /* Nothing to do */
  875. }
  876. #endif /* OSOpenBSD */
  877. #if defined(OShpux)
  878. static int
  879. pid_is_user(pid_t pid, uid_t uid)
  880. {
  881. struct pst_status pst;
  882. if (pstat_getproc(&pst, sizeof(pst), (size_t)0, (int)pid) < 0)
  883. return 0;
  884. return ((uid_t)pst.pst_uid == uid);
  885. }
  886. static int
  887. pid_is_cmd(pid_t pid, const char *name)
  888. {
  889. struct pst_status pst;
  890. if (pstat_getproc(&pst, sizeof(pst), (size_t)0, (int)pid) < 0)
  891. return 0;
  892. return (strcmp(pst.pst_ucomm, name) == 0);
  893. }
  894. static int
  895. pid_is_exec(pid_t pid, const struct stat *esb)
  896. {
  897. struct pst_status pst;
  898. if (pstat_getproc(&pst, sizeof(pst), (size_t)0, (int)pid) < 0)
  899. return 0;
  900. return ((dev_t)pst.pst_text.psf_fsid.psfs_id == esb->st_dev
  901. && (ino_t)pst.pst_text.psf_fileid == esb->st_ino);
  902. }
  903. static void
  904. do_procinit(void)
  905. {
  906. struct pst_status pst[10];
  907. int i, count;
  908. int idx = 0;
  909. while ((count = pstat_getproc(pst, sizeof(pst[0]), 10, idx)) > 0) {
  910. for (i = 0; i < count; i++)
  911. check(pst[i].pst_pid);
  912. idx = pst[count - 1].pst_idx + 1;
  913. }
  914. }
  915. #endif /* OShpux */
  916. static void
  917. do_findprocs(void)
  918. {
  919. clear(&found);
  920. if (pidfile)
  921. do_pidfile(pidfile);
  922. else
  923. do_procinit();
  924. }
  925. /* return 1 on failure */
  926. static void
  927. do_stop(int signal_nr, int quietmode, int *n_killed, int *n_notkilled, int retry_nr)
  928. {
  929. struct pid_list *p;
  930. do_findprocs();
  931. *n_killed = 0;
  932. *n_notkilled = 0;
  933. if (!found)
  934. return;
  935. clear(&killed);
  936. for (p = found; p; p = p->next) {
  937. if (testmode) {
  938. printf("Would send signal %d to %d.\n",
  939. signal_nr, p->pid);
  940. (*n_killed)++;
  941. } else if (kill(p->pid, signal_nr) == 0) {
  942. push(&killed, p->pid);
  943. (*n_killed)++;
  944. } else {
  945. if (signal_nr)
  946. printf("%s: warning: failed to kill %d: %s\n",
  947. progname, p->pid, strerror(errno));
  948. (*n_notkilled)++;
  949. }
  950. }
  951. if (quietmode < 0 && killed) {
  952. printf("Stopped %s (pid", what_stop);
  953. for (p = killed; p; p = p->next)
  954. printf(" %d", p->pid);
  955. putchar(')');
  956. if (retry_nr > 0)
  957. printf(", retry #%d", retry_nr);
  958. printf(".\n");
  959. }
  960. }
  961. static void
  962. set_what_stop(const char *str)
  963. {
  964. strncpy(what_stop, str, sizeof(what_stop));
  965. what_stop[sizeof(what_stop) - 1] = '\0';
  966. }
  967. static int
  968. run_stop_schedule(void)
  969. {
  970. int r, position, n_killed, n_notkilled, value, ratio, anykilled, retry_nr;
  971. struct timeval stopat, before, after, interval, maxinterval;
  972. if (testmode) {
  973. if (schedule != NULL) {
  974. printf("Ignoring --retry in test mode\n");
  975. schedule = NULL;
  976. }
  977. }
  978. if (cmdname)
  979. set_what_stop(cmdname);
  980. else if (execname)
  981. set_what_stop(execname);
  982. else if (pidfile)
  983. sprintf(what_stop, "process in pidfile `%.200s'", pidfile);
  984. else if (userspec)
  985. sprintf(what_stop, "process(es) owned by `%.200s'", userspec);
  986. else
  987. fatal("internal error, please report");
  988. anykilled = 0;
  989. retry_nr = 0;
  990. if (schedule == NULL) {
  991. do_stop(signal_nr, quietmode, &n_killed, &n_notkilled, 0);
  992. if (n_notkilled > 0 && quietmode <= 0)
  993. printf("%d pids were not killed\n", n_notkilled);
  994. if (n_killed)
  995. anykilled = 1;
  996. goto x_finished;
  997. }
  998. for (position = 0; position < schedule_length; ) {
  999. value= schedule[position].value;
  1000. n_notkilled = 0;
  1001. switch (schedule[position].type) {
  1002. case sched_goto:
  1003. position = value;
  1004. continue;
  1005. case sched_signal:
  1006. do_stop(value, quietmode, &n_killed, &n_notkilled, retry_nr++);
  1007. if (!n_killed)
  1008. goto x_finished;
  1009. else
  1010. anykilled = 1;
  1011. goto next_item;
  1012. case sched_timeout:
  1013. /* We want to keep polling for the processes, to see if they've exited,
  1014. * or until the timeout expires.
  1015. *
  1016. * This is a somewhat complicated algorithm to try to ensure that we
  1017. * notice reasonably quickly when all the processes have exited, but
  1018. * don't spend too much CPU time polling. In particular, on a fast
  1019. * machine with quick-exiting daemons we don't want to delay system
  1020. * shutdown too much, whereas on a slow one, or where processes are
  1021. * taking some time to exit, we want to increase the polling
  1022. * interval.
  1023. *
  1024. * The algorithm is as follows: we measure the elapsed time it takes
  1025. * to do one poll(), and wait a multiple of this time for the next
  1026. * poll. However, if that would put us past the end of the timeout
  1027. * period we wait only as long as the timeout period, but in any case
  1028. * we always wait at least MIN_POLL_INTERVAL (20ms). The multiple
  1029. * (`ratio') starts out as 2, and increases by 1 for each poll to a
  1030. * maximum of 10; so we use up to between 30% and 10% of the
  1031. * machine's resources (assuming a few reasonable things about system
  1032. * performance).
  1033. */
  1034. xgettimeofday(&stopat);
  1035. stopat.tv_sec += value;
  1036. ratio = 1;
  1037. for (;;) {
  1038. xgettimeofday(&before);
  1039. if (timercmp(&before, &stopat, >))
  1040. goto next_item;
  1041. do_stop(0, 1, &n_killed, &n_notkilled, 0);
  1042. if (!n_killed)
  1043. goto x_finished;
  1044. xgettimeofday(&after);
  1045. if (!timercmp(&after, &stopat, <))
  1046. goto next_item;
  1047. if (ratio < 10)
  1048. ratio++;
  1049. TVCALC(interval, TVELEM(&after) * ratio -
  1050. TVELEM(&before) + TVADJUST);
  1051. TVCALC(maxinterval, TVELEM(&stopat) -
  1052. TVELEM(&after) + TVADJUST);
  1053. if (timercmp(&interval, &maxinterval, >))
  1054. interval = maxinterval;
  1055. if (interval.tv_sec == 0 &&
  1056. interval.tv_usec <= MIN_POLL_INTERVAL)
  1057. interval.tv_usec = MIN_POLL_INTERVAL;
  1058. r = select(0, NULL, NULL, NULL, &interval);
  1059. if (r < 0 && errno != EINTR)
  1060. fatal("select() failed for pause: %s",
  1061. strerror(errno));
  1062. }
  1063. default:
  1064. assert(!"schedule[].type value must be valid");
  1065. }
  1066. next_item:
  1067. position++;
  1068. }
  1069. if (quietmode <= 0)
  1070. printf("Program %s, %d process(es), refused to die.\n",
  1071. what_stop, n_killed);
  1072. return 2;
  1073. x_finished:
  1074. if (!anykilled) {
  1075. if (quietmode <= 0)
  1076. printf("No %s found running; none killed.\n", what_stop);
  1077. return exitnodo;
  1078. } else {
  1079. return 0;
  1080. }
  1081. }
  1082. int
  1083. main(int argc, char **argv)
  1084. {
  1085. int devnull_fd = -1;
  1086. #ifdef HAVE_TIOCNOTTY
  1087. int tty_fd = -1;
  1088. #endif
  1089. progname = argv[0];
  1090. parse_options(argc, argv);
  1091. argc -= optind;
  1092. argv += optind;
  1093. if (execname) {
  1094. char *fullexecname;
  1095. if (changeroot) {
  1096. int fullexecname_len = strlen(changeroot) + 1 +
  1097. strlen(execname) + 1;
  1098. fullexecname = xmalloc(fullexecname_len);
  1099. snprintf(fullexecname, fullexecname_len, "%s/%s",
  1100. changeroot, execname);
  1101. } else
  1102. fullexecname = execname;
  1103. if (stat(fullexecname, &exec_stat))
  1104. fatal("stat %s: %s", fullexecname, strerror(errno));
  1105. if (fullexecname != execname)
  1106. free(fullexecname);
  1107. }
  1108. if (userspec && sscanf(userspec, "%d", &user_id) != 1) {
  1109. struct passwd *pw;
  1110. pw = getpwnam(userspec);
  1111. if (!pw)
  1112. fatal("user `%s' not found\n", userspec);
  1113. user_id = pw->pw_uid;
  1114. }
  1115. if (changegroup && sscanf(changegroup, "%d", &runas_gid) != 1) {
  1116. struct group *gr = getgrnam(changegroup);
  1117. if (!gr)
  1118. fatal("group `%s' not found\n", changegroup);
  1119. runas_gid = gr->gr_gid;
  1120. }
  1121. if (changeuser && sscanf(changeuser, "%d", &runas_uid) != 1) {
  1122. struct passwd *pw = getpwnam(changeuser);
  1123. if (!pw)
  1124. fatal("user `%s' not found\n", changeuser);
  1125. runas_uid = pw->pw_uid;
  1126. if (changegroup == NULL) {
  1127. /* Pass the default group of this user */
  1128. changegroup = ""; /* Just empty */
  1129. runas_gid = pw->pw_gid;
  1130. }
  1131. if (access(pw->pw_dir, F_OK) == 0)
  1132. setenv("HOME", pw->pw_dir, 1);
  1133. }
  1134. if (stop) {
  1135. int i = run_stop_schedule();
  1136. exit(i);
  1137. }
  1138. do_findprocs();
  1139. if (found) {
  1140. if (quietmode <= 0)
  1141. printf("%s already running.\n", execname ? execname : "process");
  1142. exit(exitnodo);
  1143. }
  1144. if (testmode) {
  1145. printf("Would start %s ", startas);
  1146. while (argc-- > 0)
  1147. printf("%s ", *argv++);
  1148. if (changeuser != NULL) {
  1149. printf(" (as user %s[%d]", changeuser, runas_uid);
  1150. if (changegroup != NULL)
  1151. printf(", and group %s[%d])", changegroup, runas_gid);
  1152. else
  1153. printf(")");
  1154. }
  1155. if (changeroot != NULL)
  1156. printf(" in directory %s", changeroot);
  1157. if (nicelevel)
  1158. printf(", and add %i to the priority", nicelevel);
  1159. printf(".\n");
  1160. exit(0);
  1161. }
  1162. if (quietmode < 0)
  1163. printf("Starting %s...\n", startas);
  1164. *--argv = startas;
  1165. if (background) { /* ok, we need to detach this process */
  1166. daemonize();
  1167. #ifdef HAVE_TIOCNOTTY
  1168. tty_fd=open("/dev/tty", O_RDWR);
  1169. #endif
  1170. devnull_fd=open("/dev/null", O_RDWR);
  1171. }
  1172. if (nicelevel) {
  1173. errno = 0;
  1174. if ((nice(nicelevel) == -1) && (errno != 0))
  1175. fatal("Unable to alter nice level by %i: %s",
  1176. nicelevel, strerror(errno));
  1177. }
  1178. if (umask_value >= 0)
  1179. umask(umask_value);
  1180. if (mpidfile && pidfile != NULL) {
  1181. /* User wants _us_ to make the pidfile :) */
  1182. FILE *pidf = fopen(pidfile, "w");
  1183. pid_t pidt = getpid();
  1184. if (pidf == NULL)
  1185. fatal("Unable to open pidfile `%s' for writing: %s",
  1186. pidfile, strerror(errno));
  1187. fprintf(pidf, "%d\n", pidt);
  1188. fclose(pidf);
  1189. }
  1190. if (changeroot != NULL) {
  1191. if (chdir(changeroot) < 0)
  1192. fatal("Unable to chdir() to %s", changeroot);
  1193. if (chroot(changeroot) < 0)
  1194. fatal("Unable to chroot() to %s", changeroot);
  1195. }
  1196. if (chdir(changedir) < 0)
  1197. fatal("Unable to chdir() to %s", changedir);
  1198. if (changeuser != NULL) {
  1199. if (setgid(runas_gid))
  1200. fatal("Unable to set gid to %d", runas_gid);
  1201. if (initgroups(changeuser, runas_gid))
  1202. fatal("Unable to set initgroups() with gid %d", runas_gid);
  1203. if (setuid(runas_uid))
  1204. fatal("Unable to set uid to %s", changeuser);
  1205. }
  1206. if (background) {
  1207. /* Continue background setup */
  1208. int i;
  1209. #ifdef HAVE_TIOCNOTTY
  1210. /* Change tty */
  1211. ioctl(tty_fd, TIOCNOTTY, 0);
  1212. close(tty_fd);
  1213. #endif
  1214. if (umask_value < 0)
  1215. umask(022); /* Set a default for dumb programs */
  1216. dup2(devnull_fd, 0); /* stdin */
  1217. dup2(devnull_fd, 1); /* stdout */
  1218. dup2(devnull_fd, 2); /* stderr */
  1219. #if defined(OShpux)
  1220. /* Now close all extra fds */
  1221. for (i = sysconf(_SC_OPEN_MAX) - 1; i >= 3; --i)
  1222. close(i);
  1223. #else
  1224. /* Now close all extra fds */
  1225. for (i = getdtablesize() - 1; i >= 3; --i)
  1226. close(i);
  1227. #endif
  1228. }
  1229. execv(startas, argv);
  1230. fatal("Unable to start %s: %s", startas, strerror(errno));
  1231. }