start-stop-daemon.c 33 KB

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