start-stop-daemon.c 33 KB

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