start-stop-daemon.c 33 KB

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