daemon.c 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826
  1. /*-
  2. * SPDX-License-Identifier: BSD-3-Clause
  3. *
  4. * Copyright (c) 1999 Berkeley Software Design, Inc. All rights reserved.
  5. *
  6. * Redistribution and use in source and binary forms, with or without
  7. * modification, are permitted provided that the following conditions
  8. * are met:
  9. * 1. Redistributions of source code must retain the above copyright
  10. * notice, this list of conditions and the following disclaimer.
  11. * 2. Redistributions in binary form must reproduce the above copyright
  12. * notice, this list of conditions and the following disclaimer in the
  13. * documentation and/or other materials provided with the distribution.
  14. * 3. Berkeley Software Design Inc's name may not be used to endorse or
  15. * promote products derived from this software without specific prior
  16. * written permission.
  17. *
  18. * THIS SOFTWARE IS PROVIDED BY BERKELEY SOFTWARE DESIGN INC ``AS IS'' AND
  19. * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  20. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  21. * ARE DISCLAIMED. IN NO EVENT SHALL BERKELEY SOFTWARE DESIGN INC BE LIABLE
  22. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  23. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  24. * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  25. * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  26. * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  27. * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  28. * SUCH DAMAGE.
  29. *
  30. * From BSDI: daemon.c,v 1.2 1996/08/15 01:11:09 jch Exp
  31. */
  32. #include <sys/event.h>
  33. #include <sys/mman.h>
  34. #include <sys/wait.h>
  35. #include <fcntl.h>
  36. #include <err.h>
  37. #include <errno.h>
  38. #include <getopt.h>
  39. #include <libutil.h>
  40. #include <login_cap.h>
  41. #include <paths.h>
  42. #include <pwd.h>
  43. #include <signal.h>
  44. #include <stdio.h>
  45. #include <stdbool.h>
  46. #include <stdlib.h>
  47. #include <unistd.h>
  48. #include <string.h>
  49. #define SYSLOG_NAMES
  50. #include <syslog.h>
  51. #include <time.h>
  52. #include <assert.h>
  53. /* 1 year in seconds */
  54. #define MAX_RESTART_DELAY 60*60*24*365
  55. /* Maximum number of restarts */
  56. #define MAX_RESTART_COUNT 128
  57. #define LBUF_SIZE 4096
  58. enum daemon_mode {
  59. MODE_DAEMON = 0, /* simply daemonize, no supervision */
  60. MODE_SUPERVISE, /* initial supervision state */
  61. MODE_TERMINATING, /* user requested termination */
  62. MODE_NOCHILD, /* child is terminated, final state of the event loop */
  63. };
  64. struct daemon_state {
  65. unsigned char buf[LBUF_SIZE];
  66. size_t pos;
  67. char **argv;
  68. const char *child_pidfile;
  69. const char *parent_pidfile;
  70. const char *output_filename;
  71. const char *syslog_tag;
  72. const char *title;
  73. const char *user;
  74. struct pidfh *parent_pidfh;
  75. struct pidfh *child_pidfh;
  76. enum daemon_mode mode;
  77. int pid;
  78. int pipe_rd;
  79. int pipe_wr;
  80. int keep_cur_workdir;
  81. int restart_delay;
  82. int stdmask;
  83. int syslog_priority;
  84. int syslog_facility;
  85. int keep_fds_open;
  86. int output_fd;
  87. bool restart_enabled;
  88. bool syslog_enabled;
  89. bool log_reopen;
  90. int restart_count;
  91. int restarted_count;
  92. };
  93. static void restrict_process(const char *);
  94. static int open_log(const char *);
  95. static void reopen_log(struct daemon_state *);
  96. static bool listen_child(struct daemon_state *);
  97. static int get_log_mapping(const char *, const CODE *);
  98. static void open_pid_files(struct daemon_state *);
  99. static void do_output(const unsigned char *, size_t, struct daemon_state *);
  100. static void daemon_sleep(struct daemon_state *);
  101. static void daemon_state_init(struct daemon_state *);
  102. static void daemon_eventloop(struct daemon_state *);
  103. static void daemon_terminate(struct daemon_state *);
  104. static void daemon_exec(struct daemon_state *);
  105. static bool daemon_is_child_dead(struct daemon_state *);
  106. static void daemon_set_child_pipe(struct daemon_state *);
  107. static const char shortopts[] = "+cfHSp:P:ru:o:s:l:t:m:R:T:C:h";
  108. static const struct option longopts[] = {
  109. { "change-dir", no_argument, NULL, 'c' },
  110. { "close-fds", no_argument, NULL, 'f' },
  111. { "sighup", no_argument, NULL, 'H' },
  112. { "syslog", no_argument, NULL, 'S' },
  113. { "output-file", required_argument, NULL, 'o' },
  114. { "output-mask", required_argument, NULL, 'm' },
  115. { "child-pidfile", required_argument, NULL, 'p' },
  116. { "supervisor-pidfile", required_argument, NULL, 'P' },
  117. { "restart", no_argument, NULL, 'r' },
  118. { "restart-count", required_argument, NULL, 'C' },
  119. { "restart-delay", required_argument, NULL, 'R' },
  120. { "title", required_argument, NULL, 't' },
  121. { "user", required_argument, NULL, 'u' },
  122. { "syslog-priority", required_argument, NULL, 's' },
  123. { "syslog-facility", required_argument, NULL, 'l' },
  124. { "syslog-tag", required_argument, NULL, 'T' },
  125. { "help", no_argument, NULL, 'h' },
  126. { NULL, 0, NULL, 0 }
  127. };
  128. static _Noreturn void
  129. usage(int exitcode)
  130. {
  131. (void)fprintf(stderr,
  132. "usage: daemon [-cfHrS] [-p child_pidfile] [-P supervisor_pidfile]\n"
  133. " [-u user] [-o output_file] [-t title]\n"
  134. " [-l syslog_facility] [-s syslog_priority]\n"
  135. " [-T syslog_tag] [-m output_mask] [-R restart_delay_secs]\n"
  136. " [-C restart_count]\n"
  137. "command arguments ...\n");
  138. (void)fprintf(stderr,
  139. " --change-dir -c Change the current working directory to root\n"
  140. " --close-fds -f Set stdin, stdout, stderr to /dev/null\n"
  141. " --sighup -H Close and re-open output file on SIGHUP\n"
  142. " --syslog -S Send output to syslog\n"
  143. " --output-file -o <file> Append output of the child process to file\n"
  144. " --output-mask -m <mask> What to send to syslog/file\n"
  145. " 1=stdout, 2=stderr, 3=both\n"
  146. " --child-pidfile -p <file> Write PID of the child process to file\n"
  147. " --supervisor-pidfile -P <file> Write PID of the supervisor process to file\n"
  148. " --restart -r Restart child if it terminates (1 sec delay)\n"
  149. " --restart-count -C <N> Restart child at most N times, then exit\n"
  150. " --restart-delay -R <N> Restart child if it terminates after N sec\n"
  151. " --title -t <title> Set the title of the supervisor process\n"
  152. " --user -u <user> Drop privileges, run as given user\n"
  153. " --syslog-priority -s <prio> Set syslog priority\n"
  154. " --syslog-facility -l <flty> Set syslog facility\n"
  155. " --syslog-tag -T <tag> Set syslog tag\n"
  156. " --help -h Show this help\n");
  157. exit(exitcode);
  158. }
  159. int
  160. main(int argc, char *argv[])
  161. {
  162. const char *e = NULL;
  163. int ch = 0;
  164. struct daemon_state state;
  165. daemon_state_init(&state);
  166. /* Signals are processed via kqueue */
  167. signal(SIGHUP, SIG_IGN);
  168. signal(SIGTERM, SIG_IGN);
  169. /*
  170. * Supervision mode is enabled if one of the following options are used:
  171. * --child-pidfile -p
  172. * --supervisor-pidfile -P
  173. * --restart -r / --restart-delay -R
  174. * --syslog -S
  175. * --syslog-facility -l
  176. * --syslog-priority -s
  177. * --syslog-tag -T
  178. *
  179. * In supervision mode daemon executes the command in a forked process
  180. * and observes the child by waiting for SIGCHILD. In supervision mode
  181. * daemon must never exit before the child, this is necessary to prevent
  182. * orphaning the child and leaving a stale pid file.
  183. * To achieve this daemon catches SIGTERM and
  184. * forwards it to the child, expecting to get SIGCHLD eventually.
  185. */
  186. while ((ch = getopt_long(argc, argv, shortopts, longopts, NULL)) != -1) {
  187. switch (ch) {
  188. case 'c':
  189. state.keep_cur_workdir = 0;
  190. break;
  191. case 'C':
  192. state.restart_count = (int)strtonum(optarg, 0,
  193. MAX_RESTART_COUNT, &e);
  194. if (e != NULL) {
  195. errx(6, "invalid restart count: %s", e);
  196. }
  197. break;
  198. case 'f':
  199. state.keep_fds_open = 0;
  200. break;
  201. case 'H':
  202. state.log_reopen = true;
  203. break;
  204. case 'l':
  205. state.syslog_facility = get_log_mapping(optarg,
  206. facilitynames);
  207. if (state.syslog_facility == -1) {
  208. errx(5, "unrecognized syslog facility");
  209. }
  210. state.syslog_enabled = true;
  211. state.mode = MODE_SUPERVISE;
  212. break;
  213. case 'm':
  214. state.stdmask = (int)strtonum(optarg, 0, 3, &e);
  215. if (e != NULL) {
  216. errx(6, "unrecognized listening mask: %s", e);
  217. }
  218. break;
  219. case 'o':
  220. state.output_filename = optarg;
  221. /*
  222. * TODO: setting output filename doesn't have to turn
  223. * the supervision mode on. For non-supervised mode
  224. * daemon could open the specified file and set it's
  225. * descriptor as both stderr and stout before execve()
  226. */
  227. state.mode = MODE_SUPERVISE;
  228. break;
  229. case 'p':
  230. state.child_pidfile = optarg;
  231. state.mode = MODE_SUPERVISE;
  232. break;
  233. case 'P':
  234. state.parent_pidfile = optarg;
  235. state.mode = MODE_SUPERVISE;
  236. break;
  237. case 'r':
  238. state.restart_enabled = true;
  239. state.mode = MODE_SUPERVISE;
  240. break;
  241. case 'R':
  242. state.restart_enabled = true;
  243. state.restart_delay = (int)strtonum(optarg, 1,
  244. MAX_RESTART_DELAY, &e);
  245. if (e != NULL) {
  246. errx(6, "invalid restart delay: %s", e);
  247. }
  248. state.mode = MODE_SUPERVISE;
  249. break;
  250. case 's':
  251. state.syslog_priority = get_log_mapping(optarg,
  252. prioritynames);
  253. if (state.syslog_priority == -1) {
  254. errx(4, "unrecognized syslog priority");
  255. }
  256. state.syslog_enabled = true;
  257. state.mode = MODE_SUPERVISE;
  258. break;
  259. case 'S':
  260. state.syslog_enabled = true;
  261. state.mode = MODE_SUPERVISE;
  262. break;
  263. case 't':
  264. state.title = optarg;
  265. break;
  266. case 'T':
  267. state.syslog_tag = optarg;
  268. state.syslog_enabled = true;
  269. state.mode = MODE_SUPERVISE;
  270. break;
  271. case 'u':
  272. state.user = optarg;
  273. break;
  274. case 'h':
  275. usage(0);
  276. __unreachable();
  277. default:
  278. usage(1);
  279. }
  280. }
  281. argc -= optind;
  282. argv += optind;
  283. state.argv = argv;
  284. if (argc == 0) {
  285. usage(1);
  286. }
  287. if (!state.title) {
  288. state.title = argv[0];
  289. }
  290. if (state.output_filename) {
  291. state.output_fd = open_log(state.output_filename);
  292. if (state.output_fd == -1) {
  293. err(7, "open");
  294. }
  295. }
  296. if (state.syslog_enabled) {
  297. openlog(state.syslog_tag, LOG_PID | LOG_NDELAY,
  298. state.syslog_facility);
  299. }
  300. /*
  301. * Try to open the pidfile before calling daemon(3),
  302. * to be able to report the error intelligently
  303. */
  304. open_pid_files(&state);
  305. /*
  306. * TODO: add feature to avoid backgrounding
  307. * i.e. --foreground, -f
  308. */
  309. if (daemon(state.keep_cur_workdir, state.keep_fds_open) == -1) {
  310. warn("daemon");
  311. daemon_terminate(&state);
  312. }
  313. if (state.mode == MODE_DAEMON) {
  314. daemon_exec(&state);
  315. }
  316. /* Write out parent pidfile if needed. */
  317. pidfile_write(state.parent_pidfh);
  318. do {
  319. state.mode = MODE_SUPERVISE;
  320. daemon_eventloop(&state);
  321. daemon_sleep(&state);
  322. if (state.restart_enabled && state.restart_count > -1) {
  323. if (state.restarted_count >= state.restart_count) {
  324. state.restart_enabled = false;
  325. }
  326. state.restarted_count++;
  327. }
  328. } while (state.restart_enabled);
  329. daemon_terminate(&state);
  330. }
  331. static void
  332. daemon_exec(struct daemon_state *state)
  333. {
  334. pidfile_write(state->child_pidfh);
  335. if (state->user != NULL) {
  336. restrict_process(state->user);
  337. }
  338. /* Ignored signals remain ignored after execve, unignore them */
  339. signal(SIGHUP, SIG_DFL);
  340. signal(SIGTERM, SIG_DFL);
  341. execvp(state->argv[0], state->argv);
  342. /* execvp() failed - report error and exit this process */
  343. err(1, "%s", state->argv[0]);
  344. }
  345. /* Main event loop: fork the child and watch for events.
  346. * After SIGTERM is received and propagated to the child there are
  347. * several options on what to do next:
  348. * - read until EOF
  349. * - read until EOF but only for a while
  350. * - bail immediately
  351. * Currently the third option is used, because otherwise there is no
  352. * guarantee that read() won't block indefinitely if the child refuses
  353. * to depart. To handle the second option, a different approach
  354. * would be needed (procctl()?).
  355. */
  356. static void
  357. daemon_eventloop(struct daemon_state *state)
  358. {
  359. struct kevent event;
  360. int kq;
  361. int ret;
  362. int pipe_fd[2];
  363. /*
  364. * Try to protect against pageout kill. Ignore the
  365. * error, madvise(2) will fail only if a process does
  366. * not have superuser privileges.
  367. */
  368. (void)madvise(NULL, 0, MADV_PROTECT);
  369. if (pipe(pipe_fd)) {
  370. err(1, "pipe");
  371. }
  372. state->pipe_rd = pipe_fd[0];
  373. state->pipe_wr = pipe_fd[1];
  374. kq = kqueuex(KQUEUE_CLOEXEC);
  375. EV_SET(&event, state->pipe_rd, EVFILT_READ, EV_ADD|EV_CLEAR, 0, 0,
  376. NULL);
  377. if (kevent(kq, &event, 1, NULL, 0, NULL) == -1) {
  378. err(EXIT_FAILURE, "failed to register kevent");
  379. }
  380. EV_SET(&event, SIGHUP, EVFILT_SIGNAL, EV_ADD, 0, 0, NULL);
  381. if (kevent(kq, &event, 1, NULL, 0, NULL) == -1) {
  382. err(EXIT_FAILURE, "failed to register kevent");
  383. }
  384. EV_SET(&event, SIGTERM, EVFILT_SIGNAL, EV_ADD, 0, 0, NULL);
  385. if (kevent(kq, &event, 1, NULL, 0, NULL) == -1) {
  386. err(EXIT_FAILURE, "failed to register kevent");
  387. }
  388. EV_SET(&event, SIGCHLD, EVFILT_SIGNAL, EV_ADD, 0, 0, NULL);
  389. if (kevent(kq, &event, 1, NULL, 0, NULL) == -1) {
  390. err(EXIT_FAILURE, "failed to register kevent");
  391. }
  392. memset(&event, 0, sizeof(struct kevent));
  393. /* Spawn a child to exec the command. */
  394. state->pid = fork();
  395. /* fork failed, this can only happen when supervision is enabled */
  396. switch (state->pid) {
  397. case -1:
  398. warn("fork");
  399. state->mode = MODE_NOCHILD;
  400. return;
  401. /* fork succeeded, this is child's branch */
  402. case 0:
  403. close(kq);
  404. daemon_set_child_pipe(state);
  405. daemon_exec(state);
  406. break;
  407. }
  408. /* case: pid > 0; fork succeeded */
  409. close(state->pipe_wr);
  410. state->pipe_wr = -1;
  411. setproctitle("%s[%d]", state->title, (int)state->pid);
  412. setbuf(stdout, NULL);
  413. while (state->mode != MODE_NOCHILD) {
  414. ret = kevent(kq, NULL, 0, &event, 1, NULL);
  415. switch (ret) {
  416. case -1:
  417. if (errno == EINTR)
  418. continue;
  419. err(EXIT_FAILURE, "kevent wait");
  420. case 0:
  421. continue;
  422. }
  423. if (event.flags & EV_ERROR) {
  424. errx(EXIT_FAILURE, "Event error: %s",
  425. strerror((int)event.data));
  426. }
  427. switch (event.filter) {
  428. case EVFILT_SIGNAL:
  429. switch (event.ident) {
  430. case SIGCHLD:
  431. if (daemon_is_child_dead(state)) {
  432. /* child is dead, read all until EOF */
  433. state->pid = -1;
  434. state->mode = MODE_NOCHILD;
  435. while (listen_child(state)) {
  436. continue;
  437. }
  438. }
  439. continue;
  440. case SIGTERM:
  441. if (state->mode != MODE_SUPERVISE) {
  442. /* user is impatient */
  443. /* TODO: warn about repeated SIGTERM? */
  444. continue;
  445. }
  446. state->mode = MODE_TERMINATING;
  447. state->restart_enabled = false;
  448. if (state->pid > 0) {
  449. kill(state->pid, SIGTERM);
  450. }
  451. /*
  452. * TODO set kevent timer to exit
  453. * unconditionally after some time
  454. */
  455. continue;
  456. case SIGHUP:
  457. if (state->log_reopen && state->output_fd >= 0) {
  458. reopen_log(state);
  459. }
  460. continue;
  461. }
  462. break;
  463. case EVFILT_READ:
  464. /*
  465. * detecting EOF is no longer necessary
  466. * if child closes the pipe daemon will stop getting
  467. * EVFILT_READ events
  468. */
  469. if (event.data > 0) {
  470. (void)listen_child(state);
  471. }
  472. continue;
  473. default:
  474. continue;
  475. }
  476. }
  477. close(kq);
  478. close(state->pipe_rd);
  479. state->pipe_rd = -1;
  480. }
  481. static void
  482. daemon_sleep(struct daemon_state *state)
  483. {
  484. struct timespec ts = { state->restart_delay, 0 };
  485. if (!state->restart_enabled) {
  486. return;
  487. }
  488. while (nanosleep(&ts, &ts) == -1) {
  489. if (errno != EINTR) {
  490. err(1, "nanosleep");
  491. }
  492. }
  493. }
  494. static void
  495. open_pid_files(struct daemon_state *state)
  496. {
  497. pid_t fpid;
  498. int serrno;
  499. if (state->child_pidfile) {
  500. state->child_pidfh = pidfile_open(state->child_pidfile, 0600, &fpid);
  501. if (state->child_pidfh == NULL) {
  502. if (errno == EEXIST) {
  503. errx(3, "process already running, pid: %d",
  504. fpid);
  505. }
  506. err(2, "pidfile ``%s''", state->child_pidfile);
  507. }
  508. }
  509. /* Do the same for the actual daemon process. */
  510. if (state->parent_pidfile) {
  511. state->parent_pidfh= pidfile_open(state->parent_pidfile, 0600, &fpid);
  512. if (state->parent_pidfh == NULL) {
  513. serrno = errno;
  514. pidfile_remove(state->child_pidfh);
  515. errno = serrno;
  516. if (errno == EEXIST) {
  517. errx(3, "process already running, pid: %d",
  518. fpid);
  519. }
  520. err(2, "ppidfile ``%s''", state->parent_pidfile);
  521. }
  522. }
  523. }
  524. static int
  525. get_log_mapping(const char *str, const CODE *c)
  526. {
  527. const CODE *cp;
  528. for (cp = c; cp->c_name; cp++)
  529. if (strcmp(cp->c_name, str) == 0) {
  530. return cp->c_val;
  531. }
  532. return -1;
  533. }
  534. static void
  535. restrict_process(const char *user)
  536. {
  537. struct passwd *pw = NULL;
  538. pw = getpwnam(user);
  539. if (pw == NULL) {
  540. errx(1, "unknown user: %s", user);
  541. }
  542. if (setusercontext(NULL, pw, pw->pw_uid, LOGIN_SETALL) != 0) {
  543. errx(1, "failed to set user environment");
  544. }
  545. setenv("USER", pw->pw_name, 1);
  546. setenv("HOME", pw->pw_dir, 1);
  547. setenv("SHELL", *pw->pw_shell ? pw->pw_shell : _PATH_BSHELL, 1);
  548. }
  549. /*
  550. * We try to collect whole lines terminated by '\n'. Otherwise we collect a
  551. * full buffer, and then output it.
  552. *
  553. * Return value of false is assumed to mean EOF or error, and true indicates to
  554. * continue reading.
  555. */
  556. static bool
  557. listen_child(struct daemon_state *state)
  558. {
  559. ssize_t rv;
  560. unsigned char *cp;
  561. assert(state != NULL);
  562. assert(state->pos < LBUF_SIZE - 1);
  563. rv = read(state->pipe_rd, state->buf + state->pos,
  564. LBUF_SIZE - state->pos - 1);
  565. if (rv > 0) {
  566. state->pos += rv;
  567. assert(state->pos <= LBUF_SIZE - 1);
  568. /* Always NUL-terminate just in case. */
  569. state->buf[LBUF_SIZE - 1] = '\0';
  570. /*
  571. * Find position of the last newline in the buffer.
  572. * The buffer is guaranteed to have one or more complete lines
  573. * if at least one newline was found when searching in reverse.
  574. * All complete lines are flushed.
  575. * This does not take NUL characters into account.
  576. */
  577. cp = memrchr(state->buf, '\n', state->pos);
  578. if (cp != NULL) {
  579. size_t bytes_line = cp - state->buf + 1;
  580. assert(bytes_line <= state->pos);
  581. do_output(state->buf, bytes_line, state);
  582. state->pos -= bytes_line;
  583. memmove(state->buf, cp + 1, state->pos);
  584. }
  585. /* Wait until the buffer is full. */
  586. if (state->pos < LBUF_SIZE - 1) {
  587. return true;
  588. }
  589. do_output(state->buf, state->pos, state);
  590. state->pos = 0;
  591. return true;
  592. } else if (rv == -1) {
  593. /* EINTR should trigger another read. */
  594. if (errno == EINTR) {
  595. return true;
  596. } else {
  597. warn("read");
  598. return false;
  599. }
  600. }
  601. /* Upon EOF, we have to flush what's left of the buffer. */
  602. if (state->pos > 0) {
  603. do_output(state->buf, state->pos, state);
  604. state->pos = 0;
  605. }
  606. return false;
  607. }
  608. /*
  609. * The default behavior is to stay silent if the user wants to redirect
  610. * output to a file and/or syslog. If neither are provided, then we bounce
  611. * everything back to parent's stdout.
  612. */
  613. static void
  614. do_output(const unsigned char *buf, size_t len, struct daemon_state *state)
  615. {
  616. assert(len <= LBUF_SIZE);
  617. assert(state != NULL);
  618. if (len < 1) {
  619. return;
  620. }
  621. if (state->syslog_enabled) {
  622. syslog(state->syslog_priority, "%.*s", (int)len, buf);
  623. }
  624. if (state->output_fd != -1) {
  625. if (write(state->output_fd, buf, len) == -1)
  626. warn("write");
  627. }
  628. if (state->keep_fds_open &&
  629. !state->syslog_enabled &&
  630. state->output_fd == -1) {
  631. printf("%.*s", (int)len, buf);
  632. }
  633. }
  634. static int
  635. open_log(const char *outfn)
  636. {
  637. return open(outfn, O_CREAT | O_WRONLY | O_APPEND | O_CLOEXEC, 0600);
  638. }
  639. static void
  640. reopen_log(struct daemon_state *state)
  641. {
  642. int outfd;
  643. outfd = open_log(state->output_filename);
  644. if (state->output_fd >= 0) {
  645. close(state->output_fd);
  646. }
  647. state->output_fd = outfd;
  648. }
  649. static void
  650. daemon_state_init(struct daemon_state *state)
  651. {
  652. *state = (struct daemon_state) {
  653. .buf = {0},
  654. .pos = 0,
  655. .argv = NULL,
  656. .parent_pidfh = NULL,
  657. .child_pidfh = NULL,
  658. .child_pidfile = NULL,
  659. .parent_pidfile = NULL,
  660. .title = NULL,
  661. .user = NULL,
  662. .mode = MODE_DAEMON,
  663. .restart_enabled = false,
  664. .pid = 0,
  665. .pipe_rd = -1,
  666. .pipe_wr = -1,
  667. .keep_cur_workdir = 1,
  668. .restart_delay = 1,
  669. .stdmask = STDOUT_FILENO | STDERR_FILENO,
  670. .syslog_enabled = false,
  671. .log_reopen = false,
  672. .syslog_priority = LOG_NOTICE,
  673. .syslog_tag = "daemon",
  674. .syslog_facility = LOG_DAEMON,
  675. .keep_fds_open = 1,
  676. .output_fd = -1,
  677. .output_filename = NULL,
  678. .restart_count = -1,
  679. .restarted_count = 0
  680. };
  681. }
  682. static _Noreturn void
  683. daemon_terminate(struct daemon_state *state)
  684. {
  685. assert(state != NULL);
  686. if (state->output_fd >= 0) {
  687. close(state->output_fd);
  688. }
  689. if (state->pipe_rd >= 0) {
  690. close(state->pipe_rd);
  691. }
  692. if (state->pipe_wr >= 0) {
  693. close(state->pipe_wr);
  694. }
  695. if (state->syslog_enabled) {
  696. closelog();
  697. }
  698. pidfile_remove(state->child_pidfh);
  699. pidfile_remove(state->parent_pidfh);
  700. /*
  701. * Note that the exit value here doesn't matter in the case of a clean
  702. * exit; daemon(3) already detached us from the caller, nothing is left
  703. * to care about this one.
  704. */
  705. exit(1);
  706. }
  707. /*
  708. * Returns true if SIGCHILD came from state->pid due to its exit.
  709. */
  710. static bool
  711. daemon_is_child_dead(struct daemon_state *state)
  712. {
  713. int status;
  714. for (;;) {
  715. int who = waitpid(-1, &status, WNOHANG);
  716. if (state->pid == who && (WIFEXITED(status) ||
  717. WIFSIGNALED(status))) {
  718. return true;
  719. }
  720. if (who == 0) {
  721. return false;
  722. }
  723. if (who == -1 && errno != EINTR) {
  724. warn("waitpid");
  725. return false;
  726. }
  727. }
  728. }
  729. static void
  730. daemon_set_child_pipe(struct daemon_state *state)
  731. {
  732. if (state->stdmask & STDERR_FILENO) {
  733. if (dup2(state->pipe_wr, STDERR_FILENO) == -1) {
  734. err(1, "dup2");
  735. }
  736. }
  737. if (state->stdmask & STDOUT_FILENO) {
  738. if (dup2(state->pipe_wr, STDOUT_FILENO) == -1) {
  739. err(1, "dup2");
  740. }
  741. }
  742. if (state->pipe_wr != STDERR_FILENO &&
  743. state->pipe_wr != STDOUT_FILENO) {
  744. close(state->pipe_wr);
  745. }
  746. /* The child gets dup'd pipes. */
  747. close(state->pipe_rd);
  748. }