start-stop-daemon.c 32 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423
  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. static void
  165. fatal(const char *format, ...)
  166. {
  167. va_list arglist;
  168. fprintf(stderr, "%s: ", progname);
  169. va_start(arglist, format);
  170. vfprintf(stderr, format, arglist);
  171. va_end(arglist);
  172. fprintf(stderr, " (%s)\n", strerror (errno));
  173. exit(2);
  174. }
  175. static void *
  176. xmalloc(int size)
  177. {
  178. void *ptr;
  179. ptr = malloc(size);
  180. if (ptr)
  181. return ptr;
  182. fatal("malloc(%d) failed", size);
  183. }
  184. static void
  185. xgettimeofday(struct timeval *tv)
  186. {
  187. if (gettimeofday(tv, NULL) != 0)
  188. fatal("gettimeofday failed: %s", strerror(errno));
  189. }
  190. static void
  191. tsub(struct timeval *r, struct timeval *a, struct timeval *b)
  192. {
  193. r->tv_sec = (time_t)(a->tv_sec - b->tv_sec);
  194. r->tv_usec = (suseconds_t)(a->tv_usec - b->tv_usec);
  195. if (r->tv_usec < 0) {
  196. --r->tv_sec;
  197. r->tv_usec += 1000000;
  198. }
  199. }
  200. static void
  201. tmul(struct timeval *a, int b)
  202. {
  203. a->tv_sec *= b;
  204. a->tv_usec *= b;
  205. if (a->tv_usec >= 1000000) {
  206. ++a->tv_sec;
  207. a->tv_usec -= 1000000;
  208. }
  209. }
  210. static long
  211. get_open_fd_max(void)
  212. {
  213. #ifdef HAVE_GETDTABLESIZE
  214. return getdtablesize();
  215. #else
  216. return sysconf(_SC_OPEN_MAX);
  217. #endif
  218. }
  219. static void
  220. daemonize(void)
  221. {
  222. pid_t pid;
  223. if (quietmode < 0)
  224. printf("Detaching to start %s...", startas);
  225. pid = fork();
  226. if (pid < 0)
  227. fatal("Unable to do first fork.\n");
  228. else if (pid) /* Parent */
  229. _exit(0);
  230. /* Create a new session */
  231. #ifdef HAVE_SETSID
  232. setsid();
  233. #else
  234. setpgid(0, 0);
  235. #endif
  236. pid = fork();
  237. if (pid < 0)
  238. fatal("Unable to do second fork.\n");
  239. else if (pid) /* Parent */
  240. _exit(0);
  241. if (quietmode < 0)
  242. printf("done.\n");
  243. }
  244. static void
  245. push(struct pid_list **list, pid_t pid)
  246. {
  247. struct pid_list *p;
  248. p = xmalloc(sizeof(*p));
  249. p->next = *list;
  250. p->pid = pid;
  251. *list = p;
  252. }
  253. static void
  254. clear(struct pid_list **list)
  255. {
  256. struct pid_list *here, *next;
  257. for (here = *list; here != NULL; here = next) {
  258. next = here->next;
  259. free(here);
  260. }
  261. *list = NULL;
  262. }
  263. static void
  264. do_help(void)
  265. {
  266. printf(
  267. "Usage: start-stop-daemon [<option> ...] <command>\n"
  268. "\n"
  269. "Commands:\n"
  270. " -S|--start -- <argument> ... start a program and pass <arguments> to it\n"
  271. " -K|--stop stop a program\n"
  272. " -H|--help print help information\n"
  273. " -V|--version print version\n"
  274. "\n"
  275. "Matching options (at least one is required):\n"
  276. " -p|--pidfile <pid-file> pid file to check\n"
  277. " -x|--exec <executable> program to start/check if it is running\n"
  278. " -n|--name <process-name> stop processes with this name\n"
  279. " -u|--user <username|uid> stop processes owned by this user\n"
  280. "\n"
  281. "Options:\n"
  282. " -g|--group <group|gid> run process as this group\n"
  283. " -c|--chuid <name|uid[:group|gid]>\n"
  284. " change to this user/group before starting\n"
  285. " process\n"
  286. " -s|--signal <signal> signal to send (default TERM)\n"
  287. " -a|--startas <pathname> program to start (default is <executable>)\n"
  288. " -r|--chroot <directory> chroot to <directory> before starting\n"
  289. " -d|--chdir <directory> change to <directory> (default is /)\n"
  290. " -N|--nicelevel <incr> add incr to the process's nice level\n"
  291. " -k|--umask <mask> change the umask to <mask> before starting\n"
  292. " -b|--background force the process to detach\n"
  293. " -m|--make-pidfile create the pidfile before starting\n"
  294. " -R|--retry <schedule> check whether processes die, and retry\n"
  295. " -t|--test test mode, don't do anything\n"
  296. " -o|--oknodo exit status 0 (not 1) if nothing done\n"
  297. " -q|--quiet be more quiet\n"
  298. " -v|--verbose be more verbose\n"
  299. "\n"
  300. "Retry <schedule> is <item>|/<item>/... where <item> is one of\n"
  301. " -<signal-num>|[-]<signal-name> send that signal\n"
  302. " <timeout> wait that many seconds\n"
  303. " forever repeat remainder forever\n"
  304. "or <schedule> may be just <timeout>, meaning <signal>/<timeout>/KILL/<timeout>\n"
  305. "\n"
  306. "Exit status: 0 = done 1 = nothing done (=> 0 if --oknodo)\n"
  307. " 3 = trouble 2 = with --retry, processes wouldn't die\n");
  308. }
  309. static void
  310. do_version(void)
  311. {
  312. printf("start-stop-daemon %s for Debian\n\n", VERSION);
  313. printf("Written by Marek Michalkiewicz, public domain.\n");
  314. }
  315. static void
  316. badusage(const char *msg)
  317. {
  318. if (msg)
  319. fprintf(stderr, "%s: %s\n", progname, msg);
  320. fprintf(stderr, "Try `%s --help' for more information.\n", progname);
  321. exit(3);
  322. }
  323. struct sigpair {
  324. const char *name;
  325. int signal;
  326. };
  327. static const struct sigpair siglist[] = {
  328. { "ABRT", SIGABRT },
  329. { "ALRM", SIGALRM },
  330. { "FPE", SIGFPE },
  331. { "HUP", SIGHUP },
  332. { "ILL", SIGILL },
  333. { "INT", SIGINT },
  334. { "KILL", SIGKILL },
  335. { "PIPE", SIGPIPE },
  336. { "QUIT", SIGQUIT },
  337. { "SEGV", SIGSEGV },
  338. { "TERM", SIGTERM },
  339. { "USR1", SIGUSR1 },
  340. { "USR2", SIGUSR2 },
  341. { "CHLD", SIGCHLD },
  342. { "CONT", SIGCONT },
  343. { "STOP", SIGSTOP },
  344. { "TSTP", SIGTSTP },
  345. { "TTIN", SIGTTIN },
  346. { "TTOU", SIGTTOU }
  347. };
  348. static int
  349. parse_integer(const char *string, int *value_r)
  350. {
  351. unsigned long ul;
  352. char *ep;
  353. if (!string[0])
  354. return -1;
  355. ul = strtoul(string, &ep, 10);
  356. if (ul > INT_MAX || *ep != '\0')
  357. return -1;
  358. *value_r = ul;
  359. return 0;
  360. }
  361. static int
  362. parse_signal(const char *signal_str, int *signal_nr)
  363. {
  364. unsigned int i;
  365. if (parse_integer(signal_str, signal_nr) == 0)
  366. return 0;
  367. for (i = 0; i < sizeof(siglist) / sizeof(siglist[0]); i++) {
  368. if (strcmp(signal_str, siglist[i].name) == 0) {
  369. *signal_nr = siglist[i].signal;
  370. return 0;
  371. }
  372. }
  373. return -1;
  374. }
  375. static int
  376. parse_umask(const char *string, int *value_r)
  377. {
  378. if (!string[0])
  379. return -1;
  380. errno = 0;
  381. *value_r = strtoul(string, NULL, 0);
  382. if (errno)
  383. return -1;
  384. else
  385. return 0;
  386. }
  387. static void
  388. parse_schedule_item(const char *string, struct schedule_item *item)
  389. {
  390. const char *after_hyph;
  391. if (!strcmp(string, "forever")) {
  392. item->type = sched_forever;
  393. } else if (isdigit(string[0])) {
  394. item->type = sched_timeout;
  395. if (parse_integer(string, &item->value) != 0)
  396. badusage("invalid timeout value in schedule");
  397. } else if ((after_hyph = string + (string[0] == '-')) &&
  398. parse_signal(after_hyph, &item->value) == 0) {
  399. item->type = sched_signal;
  400. } else {
  401. badusage("invalid schedule item (must be [-]<signal-name>, "
  402. "-<signal-number>, <timeout> or `forever'");
  403. }
  404. }
  405. static void
  406. parse_schedule(const char *schedule_str)
  407. {
  408. char item_buf[20];
  409. const char *slash;
  410. int count, repeatat;
  411. size_t str_len;
  412. count = 0;
  413. for (slash = schedule_str; *slash; slash++)
  414. if (*slash == '/')
  415. count++;
  416. schedule_length = (count == 0) ? 4 : count + 1;
  417. schedule = xmalloc(sizeof(*schedule) * schedule_length);
  418. if (count == 0) {
  419. schedule[0].type = sched_signal;
  420. schedule[0].value = signal_nr;
  421. parse_schedule_item(schedule_str, &schedule[1]);
  422. if (schedule[1].type != sched_timeout) {
  423. badusage ("--retry takes timeout, or schedule list"
  424. " of at least two items");
  425. }
  426. schedule[2].type = sched_signal;
  427. schedule[2].value = SIGKILL;
  428. schedule[3] = schedule[1];
  429. } else {
  430. count = 0;
  431. repeatat = -1;
  432. while (schedule_str != NULL) {
  433. slash = strchr(schedule_str, '/');
  434. str_len = slash ? (size_t)(slash - schedule_str) : strlen(schedule_str);
  435. if (str_len >= sizeof(item_buf))
  436. badusage("invalid schedule item: far too long"
  437. " (you must delimit items with slashes)");
  438. memcpy(item_buf, schedule_str, str_len);
  439. item_buf[str_len] = 0;
  440. schedule_str = slash ? slash + 1 : NULL;
  441. parse_schedule_item(item_buf, &schedule[count]);
  442. if (schedule[count].type == sched_forever) {
  443. if (repeatat >= 0)
  444. badusage("invalid schedule: `forever'"
  445. " appears more than once");
  446. repeatat = count;
  447. continue;
  448. }
  449. count++;
  450. }
  451. if (repeatat >= 0) {
  452. schedule[count].type = sched_goto;
  453. schedule[count].value = repeatat;
  454. count++;
  455. }
  456. assert(count == schedule_length);
  457. }
  458. }
  459. static void
  460. parse_options(int argc, char * const *argv)
  461. {
  462. static struct option longopts[] = {
  463. { "help", 0, NULL, 'H'},
  464. { "stop", 0, NULL, 'K'},
  465. { "start", 0, NULL, 'S'},
  466. { "version", 0, NULL, 'V'},
  467. { "startas", 1, NULL, 'a'},
  468. { "name", 1, NULL, 'n'},
  469. { "oknodo", 0, NULL, 'o'},
  470. { "pidfile", 1, NULL, 'p'},
  471. { "quiet", 0, NULL, 'q'},
  472. { "signal", 1, NULL, 's'},
  473. { "test", 0, NULL, 't'},
  474. { "user", 1, NULL, 'u'},
  475. { "group", 1, NULL, 'g'},
  476. { "chroot", 1, NULL, 'r'},
  477. { "verbose", 0, NULL, 'v'},
  478. { "exec", 1, NULL, 'x'},
  479. { "chuid", 1, NULL, 'c'},
  480. { "nicelevel", 1, NULL, 'N'},
  481. { "umask", 1, NULL, 'k'},
  482. { "background", 0, NULL, 'b'},
  483. { "make-pidfile", 0, NULL, 'm'},
  484. { "retry", 1, NULL, 'R'},
  485. { "chdir", 1, NULL, 'd'},
  486. { NULL, 0, NULL, 0 }
  487. };
  488. const char *umask_str = NULL;
  489. const char *signal_str = NULL;
  490. const char *schedule_str = NULL;
  491. int c;
  492. for (;;) {
  493. c = getopt_long(argc, argv,
  494. "HKSVa:n:op:qr:s:tu:vx:c:N:k:bmR:g:d:",
  495. longopts, NULL);
  496. if (c == -1)
  497. break;
  498. switch (c) {
  499. case 'H': /* --help */
  500. do_help();
  501. exit(0);
  502. case 'K': /* --stop */
  503. stop = 1;
  504. break;
  505. case 'S': /* --start */
  506. start = 1;
  507. break;
  508. case 'V': /* --version */
  509. do_version();
  510. exit(0);
  511. case 'a': /* --startas <pathname> */
  512. startas = optarg;
  513. break;
  514. case 'n': /* --name <process-name> */
  515. cmdname = optarg;
  516. break;
  517. case 'o': /* --oknodo */
  518. exitnodo = 0;
  519. break;
  520. case 'p': /* --pidfile <pid-file> */
  521. pidfile = optarg;
  522. break;
  523. case 'q': /* --quiet */
  524. quietmode = 1;
  525. break;
  526. case 's': /* --signal <signal> */
  527. signal_str = optarg;
  528. break;
  529. case 't': /* --test */
  530. testmode = 1;
  531. break;
  532. case 'u': /* --user <username>|<uid> */
  533. userspec = optarg;
  534. break;
  535. case 'v': /* --verbose */
  536. quietmode = -1;
  537. break;
  538. case 'x': /* --exec <executable> */
  539. execname = optarg;
  540. break;
  541. case 'c': /* --chuid <username>|<uid> */
  542. /* we copy the string just in case we need the
  543. * argument later. */
  544. changeuser = strdup(optarg);
  545. changeuser = strtok(changeuser, ":");
  546. changegroup = strtok(NULL, ":");
  547. break;
  548. case 'g': /* --group <group>|<gid> */
  549. changegroup = optarg;
  550. break;
  551. case 'r': /* --chroot /new/root */
  552. changeroot = optarg;
  553. break;
  554. case 'N': /* --nice */
  555. nicelevel = atoi(optarg);
  556. break;
  557. case 'k': /* --umask <mask> */
  558. umask_str = optarg;
  559. break;
  560. case 'b': /* --background */
  561. background = 1;
  562. break;
  563. case 'm': /* --make-pidfile */
  564. mpidfile = 1;
  565. break;
  566. case 'R': /* --retry <schedule>|<timeout> */
  567. schedule_str = optarg;
  568. break;
  569. case 'd': /* --chdir /new/dir */
  570. changedir = optarg;
  571. break;
  572. default:
  573. badusage(NULL); /* message printed by getopt */
  574. }
  575. }
  576. if (signal_str != NULL) {
  577. if (parse_signal(signal_str, &signal_nr) != 0)
  578. badusage("signal value must be numeric or name"
  579. " of signal (KILL, INT, ...)");
  580. }
  581. if (schedule_str != NULL) {
  582. parse_schedule(schedule_str);
  583. }
  584. if (umask_str != NULL) {
  585. if (parse_umask(umask_str, &umask_value) != 0)
  586. badusage("umask value must be a positive number");
  587. }
  588. if (start == stop)
  589. badusage("need one of --start or --stop");
  590. if (!execname && !pidfile && !userspec && !cmdname)
  591. badusage("need at least one of --exec, --pidfile, --user or --name");
  592. if (!startas)
  593. startas = execname;
  594. if (start && !startas)
  595. badusage("--start needs --exec or --startas");
  596. if (mpidfile && pidfile == NULL)
  597. badusage("--make-pidfile is only relevant with --pidfile");
  598. if (background && !start)
  599. badusage("--background is only relevant with --start");
  600. }
  601. #if defined(OSLinux)
  602. static int
  603. pid_is_exec(pid_t pid, const struct stat *esb)
  604. {
  605. char lname[32];
  606. char lcontents[_POSIX_PATH_MAX];
  607. const char deleted[] = " (deleted)";
  608. int nread;
  609. struct stat sb;
  610. sprintf(lname, "/proc/%d/exe", pid);
  611. nread = readlink(lname, lcontents, sizeof(lcontents));
  612. if (nread == -1)
  613. return 0;
  614. lcontents[nread] = '\0';
  615. if (strcmp(lcontents + nread - strlen(deleted), deleted) == 0)
  616. lcontents[nread - strlen(deleted)] = '\0';
  617. if (stat(lcontents, &sb) != 0)
  618. return 0;
  619. return (sb.st_dev == esb->st_dev && sb.st_ino == esb->st_ino);
  620. }
  621. static int
  622. pid_is_user(pid_t pid, uid_t uid)
  623. {
  624. struct stat sb;
  625. char buf[32];
  626. sprintf(buf, "/proc/%d", pid);
  627. if (stat(buf, &sb) != 0)
  628. return 0;
  629. return (sb.st_uid == uid);
  630. }
  631. static int
  632. pid_is_cmd(pid_t pid, const char *name)
  633. {
  634. char buf[32];
  635. FILE *f;
  636. int c;
  637. sprintf(buf, "/proc/%d/stat", pid);
  638. f = fopen(buf, "r");
  639. if (!f)
  640. return 0;
  641. while ((c = getc(f)) != EOF && c != '(')
  642. ;
  643. if (c != '(') {
  644. fclose(f);
  645. return 0;
  646. }
  647. /* this hopefully handles command names containing ')' */
  648. while ((c = getc(f)) != EOF && c == *name)
  649. name++;
  650. fclose(f);
  651. return (c == ')' && *name == '\0');
  652. }
  653. #endif /* OSLinux */
  654. #if defined(OSHURD)
  655. static void
  656. init_procset(void)
  657. {
  658. struct ps_context *context;
  659. error_t err;
  660. err = ps_context_create(getproc(), &context);
  661. if (err)
  662. error(1, err, "ps_context_create");
  663. err = proc_stat_list_create(context, &procset);
  664. if (err)
  665. error(1, err, "proc_stat_list_create");
  666. err = proc_stat_list_add_all(procset, 0, 0);
  667. if (err)
  668. error(1, err, "proc_stat_list_add_all");
  669. }
  670. static struct proc_stat *
  671. get_proc_stat (pid_t pid, ps_flags_t flags)
  672. {
  673. struct proc_stat *ps;
  674. ps_flags_t wanted_flags = PSTAT_PID | flags;
  675. if (!procset)
  676. init_procset();
  677. ps = proc_stat_list_pid_proc_stat(procset, pid);
  678. if (!ps)
  679. return NULL;
  680. if (proc_stat_set_flags(ps, wanted_flags))
  681. return NULL;
  682. if ((proc_stat_flags(ps) & wanted_flags) != wanted_flags)
  683. return NULL;
  684. return ps;
  685. }
  686. static int
  687. pid_is_user(pid_t pid, uid_t uid)
  688. {
  689. struct proc_stat *ps;
  690. ps = get_proc_stat(pid, PSTAT_OWNER_UID);
  691. return ps && proc_stat_owner_uid(ps) == uid;
  692. }
  693. static int
  694. pid_is_cmd(pid_t pid, const char *name)
  695. {
  696. struct proc_stat *ps;
  697. ps = get_proc_stat(pid, PSTAT_ARGS);
  698. return ps && !strcmp(proc_stat_args(ps), name);
  699. }
  700. static int
  701. pid_is_running(pid_t pid)
  702. {
  703. return get_proc_stat(pid, 0) != NULL;
  704. }
  705. #else /* !OSHURD */
  706. static int
  707. pid_is_running(pid_t pid)
  708. {
  709. struct stat sb;
  710. char buf[32];
  711. sprintf(buf, "/proc/%d", pid);
  712. if (stat(buf, &sb) != 0) {
  713. if (errno != ENOENT)
  714. fatal("Error stating %s: %s", buf, strerror(errno));
  715. return 0;
  716. }
  717. return 1;
  718. }
  719. #endif /* OSHURD */
  720. static void
  721. check(pid_t pid)
  722. {
  723. #if defined(OSLinux) || defined(OShpux)
  724. if (execname && !pid_is_exec(pid, &exec_stat))
  725. #elif defined(OSHURD) || defined(OSFreeBSD) || defined(OSNetBSD)
  726. /* Let's try this to see if it works */
  727. if (execname && !pid_is_cmd(pid, execname))
  728. #endif
  729. return;
  730. if (userspec && !pid_is_user(pid, user_id))
  731. return;
  732. if (cmdname && !pid_is_cmd(pid, cmdname))
  733. return;
  734. if (start && !pid_is_running(pid))
  735. return;
  736. push(&found, pid);
  737. }
  738. static void
  739. do_pidfile(const char *name)
  740. {
  741. FILE *f;
  742. static pid_t pid = 0;
  743. if (pid) {
  744. check(pid);
  745. return;
  746. }
  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. if (quietmode <= 0)
  939. printf("Would send signal %d to %d.\n",
  940. signal_nr, p->pid);
  941. (*n_killed)++;
  942. } else if (kill(p->pid, signal_nr) == 0) {
  943. push(&killed, p->pid);
  944. (*n_killed)++;
  945. } else {
  946. if (signal_nr)
  947. printf("%s: warning: failed to kill %d: %s\n",
  948. progname, p->pid, strerror(errno));
  949. (*n_notkilled)++;
  950. }
  951. }
  952. if (quietmode < 0 && killed) {
  953. printf("Stopped %s (pid", what_stop);
  954. for (p = killed; p; p = p->next)
  955. printf(" %d", p->pid);
  956. putchar(')');
  957. if (retry_nr > 0)
  958. printf(", retry #%d", retry_nr);
  959. printf(".\n");
  960. }
  961. }
  962. static void
  963. set_what_stop(const char *str)
  964. {
  965. strncpy(what_stop, str, sizeof(what_stop));
  966. what_stop[sizeof(what_stop) - 1] = '\0';
  967. }
  968. static int
  969. run_stop_schedule(void)
  970. {
  971. int r, position, n_killed, n_notkilled, value, ratio, anykilled, retry_nr;
  972. struct timeval stopat, before, after, interval, maxinterval;
  973. if (testmode) {
  974. if (schedule != NULL) {
  975. if (quietmode <= 0)
  976. printf("Ignoring --retry in test mode\n");
  977. schedule = NULL;
  978. }
  979. }
  980. if (cmdname)
  981. set_what_stop(cmdname);
  982. else if (execname)
  983. set_what_stop(execname);
  984. else if (pidfile)
  985. sprintf(what_stop, "process in pidfile `%.200s'", pidfile);
  986. else if (userspec)
  987. sprintf(what_stop, "process(es) owned by `%.200s'", userspec);
  988. else
  989. fatal("internal error, please report");
  990. anykilled = 0;
  991. retry_nr = 0;
  992. if (schedule == NULL) {
  993. do_stop(signal_nr, quietmode, &n_killed, &n_notkilled, 0);
  994. if (n_notkilled > 0 && quietmode <= 0)
  995. printf("%d pids were not killed\n", n_notkilled);
  996. if (n_killed)
  997. anykilled = 1;
  998. goto x_finished;
  999. }
  1000. for (position = 0; position < schedule_length; ) {
  1001. value= schedule[position].value;
  1002. n_notkilled = 0;
  1003. switch (schedule[position].type) {
  1004. case sched_goto:
  1005. position = value;
  1006. continue;
  1007. case sched_signal:
  1008. do_stop(value, quietmode, &n_killed, &n_notkilled, retry_nr++);
  1009. if (!n_killed)
  1010. goto x_finished;
  1011. else
  1012. anykilled = 1;
  1013. goto next_item;
  1014. case sched_timeout:
  1015. /* We want to keep polling for the processes, to see if they've exited,
  1016. * or until the timeout expires.
  1017. *
  1018. * This is a somewhat complicated algorithm to try to ensure that we
  1019. * notice reasonably quickly when all the processes have exited, but
  1020. * don't spend too much CPU time polling. In particular, on a fast
  1021. * machine with quick-exiting daemons we don't want to delay system
  1022. * shutdown too much, whereas on a slow one, or where processes are
  1023. * taking some time to exit, we want to increase the polling
  1024. * interval.
  1025. *
  1026. * The algorithm is as follows: we measure the elapsed time it takes
  1027. * to do one poll(), and wait a multiple of this time for the next
  1028. * poll. However, if that would put us past the end of the timeout
  1029. * period we wait only as long as the timeout period, but in any case
  1030. * we always wait at least MIN_POLL_INTERVAL (20ms). The multiple
  1031. * (`ratio') starts out as 2, and increases by 1 for each poll to a
  1032. * maximum of 10; so we use up to between 30% and 10% of the
  1033. * machine's resources (assuming a few reasonable things about system
  1034. * performance).
  1035. */
  1036. xgettimeofday(&stopat);
  1037. stopat.tv_sec += value;
  1038. ratio = 1;
  1039. for (;;) {
  1040. xgettimeofday(&before);
  1041. if (timercmp(&before, &stopat, >))
  1042. goto next_item;
  1043. do_stop(0, 1, &n_killed, &n_notkilled, 0);
  1044. if (!n_killed)
  1045. goto x_finished;
  1046. xgettimeofday(&after);
  1047. if (!timercmp(&after, &stopat, <))
  1048. goto next_item;
  1049. if (ratio < 10)
  1050. ratio++;
  1051. tsub(&maxinterval, &stopat, &after);
  1052. tsub(&interval, &after, &before);
  1053. tmul(&interval, ratio);
  1054. if (interval.tv_sec < 0 || interval.tv_usec < 0)
  1055. interval.tv_sec = interval.tv_usec = 0;
  1056. if (timercmp(&interval, &maxinterval, >))
  1057. interval = maxinterval;
  1058. if (interval.tv_sec == 0 &&
  1059. interval.tv_usec <= MIN_POLL_INTERVAL)
  1060. interval.tv_usec = MIN_POLL_INTERVAL;
  1061. r = select(0, NULL, NULL, NULL, &interval);
  1062. if (r < 0 && errno != EINTR)
  1063. fatal("select() failed for pause: %s",
  1064. strerror(errno));
  1065. }
  1066. default:
  1067. assert(!"schedule[].type value must be valid");
  1068. }
  1069. next_item:
  1070. position++;
  1071. }
  1072. if (quietmode <= 0)
  1073. printf("Program %s, %d process(es), refused to die.\n",
  1074. what_stop, n_killed);
  1075. return 2;
  1076. x_finished:
  1077. if (!anykilled) {
  1078. if (quietmode <= 0)
  1079. printf("No %s found running; none killed.\n", what_stop);
  1080. return exitnodo;
  1081. } else {
  1082. return 0;
  1083. }
  1084. }
  1085. int
  1086. main(int argc, char **argv)
  1087. {
  1088. int devnull_fd = -1;
  1089. gid_t rgid;
  1090. uid_t ruid;
  1091. #ifdef HAVE_TIOCNOTTY
  1092. int tty_fd = -1;
  1093. #endif
  1094. progname = argv[0];
  1095. parse_options(argc, argv);
  1096. argc -= optind;
  1097. argv += optind;
  1098. if (execname) {
  1099. char *fullexecname;
  1100. if (changeroot) {
  1101. int fullexecname_len = strlen(changeroot) + 1 +
  1102. strlen(execname) + 1;
  1103. fullexecname = xmalloc(fullexecname_len);
  1104. snprintf(fullexecname, fullexecname_len, "%s/%s",
  1105. changeroot, execname);
  1106. } else
  1107. fullexecname = execname;
  1108. if (stat(fullexecname, &exec_stat))
  1109. fatal("stat %s: %s", fullexecname, strerror(errno));
  1110. if (fullexecname != execname)
  1111. free(fullexecname);
  1112. }
  1113. if (userspec && sscanf(userspec, "%d", &user_id) != 1) {
  1114. struct passwd *pw;
  1115. pw = getpwnam(userspec);
  1116. if (!pw)
  1117. fatal("user `%s' not found\n", userspec);
  1118. user_id = pw->pw_uid;
  1119. }
  1120. if (changegroup && sscanf(changegroup, "%d", &runas_gid) != 1) {
  1121. struct group *gr = getgrnam(changegroup);
  1122. if (!gr)
  1123. fatal("group `%s' not found\n", changegroup);
  1124. runas_gid = gr->gr_gid;
  1125. }
  1126. if (changeuser && sscanf(changeuser, "%d", &runas_uid) != 1) {
  1127. struct passwd *pw = getpwnam(changeuser);
  1128. if (!pw)
  1129. fatal("user `%s' not found\n", changeuser);
  1130. runas_uid = pw->pw_uid;
  1131. if (changegroup == NULL) {
  1132. /* Pass the default group of this user */
  1133. changegroup = ""; /* Just empty */
  1134. runas_gid = pw->pw_gid;
  1135. }
  1136. if (access(pw->pw_dir, F_OK) == 0)
  1137. setenv("HOME", pw->pw_dir, 1);
  1138. }
  1139. if (stop) {
  1140. int i = run_stop_schedule();
  1141. exit(i);
  1142. }
  1143. do_findprocs();
  1144. if (found) {
  1145. if (quietmode <= 0)
  1146. printf("%s already running.\n", execname ? execname : "process");
  1147. exit(exitnodo);
  1148. }
  1149. if (testmode && quietmode <= 0) {
  1150. printf("Would start %s ", startas);
  1151. while (argc-- > 0)
  1152. printf("%s ", *argv++);
  1153. if (changeuser != NULL) {
  1154. printf(" (as user %s[%d]", changeuser, runas_uid);
  1155. if (changegroup != NULL)
  1156. printf(", and group %s[%d])", changegroup, runas_gid);
  1157. else
  1158. printf(")");
  1159. }
  1160. if (changeroot != NULL)
  1161. printf(" in directory %s", changeroot);
  1162. if (nicelevel)
  1163. printf(", and add %i to the priority", nicelevel);
  1164. printf(".\n");
  1165. }
  1166. if (testmode)
  1167. exit(0);
  1168. if (quietmode < 0)
  1169. printf("Starting %s...\n", startas);
  1170. *--argv = startas;
  1171. if (background) { /* ok, we need to detach this process */
  1172. daemonize();
  1173. #ifdef HAVE_TIOCNOTTY
  1174. tty_fd=open("/dev/tty", O_RDWR);
  1175. #endif
  1176. devnull_fd=open("/dev/null", O_RDWR);
  1177. }
  1178. if (nicelevel) {
  1179. errno = 0;
  1180. if ((nice(nicelevel) == -1) && (errno != 0))
  1181. fatal("Unable to alter nice level by %i: %s",
  1182. nicelevel, strerror(errno));
  1183. }
  1184. if (umask_value >= 0)
  1185. umask(umask_value);
  1186. if (mpidfile && pidfile != NULL) {
  1187. /* User wants _us_ to make the pidfile :) */
  1188. FILE *pidf = fopen(pidfile, "w");
  1189. pid_t pidt = getpid();
  1190. if (pidf == NULL)
  1191. fatal("Unable to open pidfile `%s' for writing: %s",
  1192. pidfile, strerror(errno));
  1193. fprintf(pidf, "%d\n", pidt);
  1194. fclose(pidf);
  1195. }
  1196. if (changeroot != NULL) {
  1197. if (chdir(changeroot) < 0)
  1198. fatal("Unable to chdir() to %s", changeroot);
  1199. if (chroot(changeroot) < 0)
  1200. fatal("Unable to chroot() to %s", changeroot);
  1201. }
  1202. if (chdir(changedir) < 0)
  1203. fatal("Unable to chdir() to %s", changedir);
  1204. rgid = getgid();
  1205. ruid = getuid();
  1206. if (changegroup != NULL) {
  1207. if (rgid != (gid_t)runas_gid)
  1208. if (setgid(runas_gid))
  1209. fatal("Unable to set gid to %d", runas_gid);
  1210. }
  1211. if (changeuser != NULL) {
  1212. /* We assume that if our real user and group are the same as
  1213. * the ones we should switch to, the supplementary groups
  1214. * will be already in place. */
  1215. if (rgid != (gid_t)runas_gid || ruid != (uid_t)runas_uid)
  1216. if (initgroups(changeuser, runas_gid))
  1217. fatal("Unable to set initgroups() with gid %d",
  1218. runas_gid);
  1219. if (ruid != (uid_t)runas_uid)
  1220. if (setuid(runas_uid))
  1221. fatal("Unable to set uid to %s", changeuser);
  1222. }
  1223. if (background) {
  1224. /* Continue background setup */
  1225. int i;
  1226. #ifdef HAVE_TIOCNOTTY
  1227. /* Change tty */
  1228. ioctl(tty_fd, TIOCNOTTY, 0);
  1229. close(tty_fd);
  1230. #endif
  1231. if (umask_value < 0)
  1232. umask(022); /* Set a default for dumb programs */
  1233. dup2(devnull_fd, 0); /* stdin */
  1234. dup2(devnull_fd, 1); /* stdout */
  1235. dup2(devnull_fd, 2); /* stderr */
  1236. /* Now close all extra fds */
  1237. for (i = get_open_fd_max() - 1; i >= 3; --i)
  1238. close(i);
  1239. }
  1240. execv(startas, argv);
  1241. fatal("Unable to start %s: %s", startas, strerror(errno));
  1242. }