1 /* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*- */
2 /* dbus-spawn.c Wrapper around fork/exec
4 * Copyright (C) 2002, 2003, 2004 Red Hat, Inc.
5 * Copyright (C) 2003 CodeFactory AB
7 * Licensed under the Academic Free License version 2.1
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
19 * You should have received a copy of the GNU General Public License
20 * along with this program; if not, write to the Free Software
21 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
27 #include "dbus-spawn.h"
28 #include "dbus-sysdeps-unix.h"
29 #include "dbus-internals.h"
30 #include "dbus-test.h"
31 #include "dbus-protocol.h"
45 #include <systemd/sd-journal.h>
48 #if defined(__APPLE__)
49 # include <crt_externs.h>
50 # define environ (*_NSGetEnviron ())
51 #elif !HAVE_DECL_ENVIRON
52 extern char **environ;
56 * @addtogroup DBusInternalsUtils
61 * I'm pretty sure this whole spawn file could be made simpler,
62 * if you thought about it a bit.
66 * Enumeration for status of a read()
70 READ_STATUS_OK, /**< Read succeeded */
71 READ_STATUS_ERROR, /**< Some kind of error */
72 READ_STATUS_EOF /**< EOF returned */
85 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
87 retval = READ_STATUS_OK;
94 to_read = sizeof (int) * n_ints_in_buf - bytes;
102 ((char*)buf) + bytes,
105 if (chunk < 0 && errno == EINTR)
110 dbus_set_error (error,
111 DBUS_ERROR_SPAWN_FAILED,
112 "Failed to read from child pipe (%s)",
113 _dbus_strerror (errno));
115 retval = READ_STATUS_ERROR;
120 retval = READ_STATUS_EOF;
127 *n_ints_read = (int)(bytes / sizeof(int));
140 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
142 retval = READ_STATUS_OK;
149 to_read = sizeof (pid_t) - bytes;
157 ((char*)buf) + bytes,
159 if (chunk < 0 && errno == EINTR)
164 dbus_set_error (error,
165 DBUS_ERROR_SPAWN_FAILED,
166 "Failed to read from child pipe (%s)",
167 _dbus_strerror (errno));
169 retval = READ_STATUS_ERROR;
174 retval = READ_STATUS_EOF;
184 /* The implementation uses an intermediate child between the main process
185 * and the grandchild. The grandchild is our spawned process. The intermediate
186 * child is a babysitter process; it keeps track of when the grandchild
187 * exits/crashes, and reaps the grandchild.
189 * We automatically reap the babysitter process, killing it if necessary,
190 * when the DBusBabysitter's refcount goes to zero.
198 * \- grandchild --> exec --> spawned process
201 * child_err_report_pipe
202 * /-----------<---------<--------------\
205 * main process babysitter grandchild
208 * \-------<->-------/
211 * child_err_report_pipe is genuinely a pipe.
212 * The READ_END (also called error_pipe_from_child) is used in the main
213 * process. The WRITE_END (also called child_err_report_fd) is used in
214 * the grandchild process.
216 * On failure, the grandchild process sends CHILD_EXEC_FAILED + errno.
217 * On success, the pipe just closes (because it's close-on-exec) without
220 * babysitter_pipe is mis-named: it's really a bidirectional socketpair.
221 * The [0] end (also called socket_to_babysitter) is used in the main
222 * process, the [1] end (also called parent_pipe) is used in the babysitter.
224 * If the fork() labelled B in the diagram above fails, the babysitter sends
225 * CHILD_FORK_FAILED + errno.
226 * On success, the babysitter sends CHILD_PID + the grandchild's pid.
227 * On SIGCHLD, the babysitter sends CHILD_EXITED + the exit status.
228 * The main process doesn't explicitly send anything, but when it exits,
229 * the babysitter gets POLLHUP or POLLERR.
232 /* Messages from children to parents */
235 CHILD_EXITED, /* This message is followed by the exit status int */
236 CHILD_FORK_FAILED, /* Followed by errno */
237 CHILD_EXEC_FAILED, /* Followed by errno */
238 CHILD_PID /* Followed by pid_t */
242 * Babysitter implementation details
244 struct DBusBabysitter
246 int refcount; /**< Reference count */
248 char *log_name; /**< the name under which to log messages about this
249 process being spawned */
251 DBusSocket socket_to_babysitter; /**< Connection to the babysitter process */
252 int error_pipe_from_child; /**< Connection to the process that does the exec() */
254 pid_t sitter_pid; /**< PID Of the babysitter */
255 pid_t grandchild_pid; /**< PID of the grandchild */
257 DBusWatchList *watches; /**< Watches */
259 DBusWatch *error_watch; /**< Error pipe watch */
260 DBusWatch *sitter_watch; /**< Sitter pipe watch */
262 DBusBabysitterFinishedFunc finished_cb;
265 int errnum; /**< Error number */
266 int status; /**< Exit status code */
267 unsigned int have_child_status : 1; /**< True if child status has been reaped */
268 unsigned int have_fork_errnum : 1; /**< True if we have an error code from fork() */
269 unsigned int have_exec_errnum : 1; /**< True if we have an error code from exec() */
272 static DBusBabysitter*
273 _dbus_babysitter_new (void)
275 DBusBabysitter *sitter;
277 sitter = dbus_new0 (DBusBabysitter, 1);
281 sitter->refcount = 1;
283 sitter->socket_to_babysitter.fd = -1;
284 sitter->error_pipe_from_child = -1;
286 sitter->sitter_pid = -1;
287 sitter->grandchild_pid = -1;
289 sitter->watches = _dbus_watch_list_new ();
290 if (sitter->watches == NULL)
296 _dbus_babysitter_unref (sitter);
301 * Increment the reference count on the babysitter object.
303 * @param sitter the babysitter
304 * @returns the babysitter
307 _dbus_babysitter_ref (DBusBabysitter *sitter)
309 _dbus_assert (sitter != NULL);
310 _dbus_assert (sitter->refcount > 0);
312 sitter->refcount += 1;
317 static void close_socket_to_babysitter (DBusBabysitter *sitter);
318 static void close_error_pipe_from_child (DBusBabysitter *sitter);
321 * Decrement the reference count on the babysitter object.
322 * When the reference count of the babysitter object reaches
323 * zero, the babysitter is killed and the child that was being
324 * babysat gets emancipated.
326 * @param sitter the babysitter
329 _dbus_babysitter_unref (DBusBabysitter *sitter)
331 _dbus_assert (sitter != NULL);
332 _dbus_assert (sitter->refcount > 0);
334 sitter->refcount -= 1;
335 if (sitter->refcount == 0)
337 /* If we haven't forked other babysitters
338 * since this babysitter and socket were
339 * created then this close will cause the
340 * babysitter to wake up from poll with
341 * a hangup and then the babysitter will
344 close_socket_to_babysitter (sitter);
346 close_error_pipe_from_child (sitter);
348 if (sitter->sitter_pid > 0)
353 /* It's possible the babysitter died on its own above
354 * from the close, or was killed randomly
355 * by some other process, so first try to reap it
357 ret = waitpid (sitter->sitter_pid, &status, WNOHANG);
359 /* If we couldn't reap the child then kill it, and
363 kill (sitter->sitter_pid, SIGKILL);
369 ret = waitpid (sitter->sitter_pid, &status, 0);
371 while (_DBUS_UNLIKELY (ret < 0 && errno == EINTR));
377 _dbus_warn ("Babysitter process not available to be reaped; should not happen");
379 _dbus_warn ("Unexpected error %d in waitpid() for babysitter: %s",
380 errno, _dbus_strerror (errno));
384 _dbus_verbose ("Reaped %ld, waiting for babysitter %ld\n",
385 (long) ret, (long) sitter->sitter_pid);
387 if (WIFEXITED (sitter->status))
388 _dbus_verbose ("Babysitter exited with status %d\n",
389 WEXITSTATUS (sitter->status));
390 else if (WIFSIGNALED (sitter->status))
391 _dbus_verbose ("Babysitter received signal %d\n",
392 WTERMSIG (sitter->status));
394 _dbus_verbose ("Babysitter exited abnormally\n");
397 sitter->sitter_pid = -1;
401 _dbus_watch_list_free (sitter->watches);
403 dbus_free (sitter->log_name);
410 read_data (DBusBabysitter *sitter,
415 DBusError error = DBUS_ERROR_INIT;
418 r = read_ints (fd, &what, 1, &got, &error);
422 case READ_STATUS_ERROR:
423 _dbus_warn ("Failed to read data from fd %d: %s", fd, error.message);
424 dbus_error_free (&error);
427 case READ_STATUS_EOF:
439 case CHILD_FORK_FAILED:
440 case CHILD_EXEC_FAILED:
444 r = read_ints (fd, &arg, 1, &got, &error);
448 case READ_STATUS_ERROR:
449 _dbus_warn ("Failed to read arg from fd %d: %s", fd, error.message);
450 dbus_error_free (&error);
452 case READ_STATUS_EOF:
460 if (what == CHILD_EXITED)
462 /* Do not reset sitter->errnum to 0 here. We get here if
463 * the babysitter reports that the grandchild process has
464 * exited, and there are two ways that can happen:
466 * 1. grandchild successfully exec()s the desired process,
467 * but then the desired process exits or is terminated
468 * by a signal. The babysitter observes this and reports
471 * 2. grandchild fails to exec() the desired process,
472 * attempts to report the exec() failure (which
473 * we will receive as CHILD_EXEC_FAILED), and then
474 * exits itself (which will prompt the babysitter to
475 * send CHILD_EXITED). We want the CHILD_EXEC_FAILED
476 * to take precedence (and have its errno logged),
477 * which _dbus_babysitter_set_child_exit_error() does.
479 sitter->have_child_status = TRUE;
480 sitter->status = arg;
481 _dbus_verbose ("recorded child status exited = %d signaled = %d exitstatus = %d termsig = %d\n",
482 WIFEXITED (sitter->status), WIFSIGNALED (sitter->status),
483 WEXITSTATUS (sitter->status), WTERMSIG (sitter->status));
485 else if (what == CHILD_FORK_FAILED)
487 sitter->have_fork_errnum = TRUE;
488 sitter->errnum = arg;
489 _dbus_verbose ("recorded fork errnum %d\n", sitter->errnum);
491 else if (what == CHILD_EXEC_FAILED)
493 sitter->have_exec_errnum = TRUE;
494 sitter->errnum = arg;
495 _dbus_verbose ("recorded exec errnum %d\n", sitter->errnum);
504 r = read_pid (fd, &pid, &error);
508 case READ_STATUS_ERROR:
509 _dbus_warn ("Failed to read PID from fd %d: %s", fd, error.message);
510 dbus_error_free (&error);
512 case READ_STATUS_EOF:
518 sitter->grandchild_pid = pid;
520 _dbus_verbose ("recorded grandchild pid %d\n", sitter->grandchild_pid);
524 _dbus_warn ("Unknown message received from babysitter process");
533 close_socket_to_babysitter (DBusBabysitter *sitter)
535 _dbus_verbose ("Closing babysitter\n");
537 if (sitter->sitter_watch != NULL)
539 _dbus_assert (sitter->watches != NULL);
540 _dbus_watch_list_remove_watch (sitter->watches, sitter->sitter_watch);
541 _dbus_watch_invalidate (sitter->sitter_watch);
542 _dbus_watch_unref (sitter->sitter_watch);
543 sitter->sitter_watch = NULL;
546 if (sitter->socket_to_babysitter.fd >= 0)
548 _dbus_close_socket (sitter->socket_to_babysitter, NULL);
549 sitter->socket_to_babysitter.fd = -1;
554 close_error_pipe_from_child (DBusBabysitter *sitter)
556 _dbus_verbose ("Closing child error\n");
558 if (sitter->error_watch != NULL)
560 _dbus_assert (sitter->watches != NULL);
561 _dbus_watch_list_remove_watch (sitter->watches, sitter->error_watch);
562 _dbus_watch_invalidate (sitter->error_watch);
563 _dbus_watch_unref (sitter->error_watch);
564 sitter->error_watch = NULL;
567 if (sitter->error_pipe_from_child >= 0)
569 _dbus_close (sitter->error_pipe_from_child, NULL);
570 sitter->error_pipe_from_child = -1;
575 handle_babysitter_socket (DBusBabysitter *sitter,
578 /* Even if we have POLLHUP, we want to keep reading
579 * data until POLLIN goes away; so this function only
580 * looks at HUP/ERR if no IN is set.
582 if (revents & _DBUS_POLLIN)
584 _dbus_verbose ("Reading data from babysitter\n");
585 if (read_data (sitter, sitter->socket_to_babysitter.fd) != READ_STATUS_OK)
586 close_socket_to_babysitter (sitter);
588 else if (revents & (_DBUS_POLLERR | _DBUS_POLLHUP))
590 close_socket_to_babysitter (sitter);
595 handle_error_pipe (DBusBabysitter *sitter,
598 if (revents & _DBUS_POLLIN)
600 _dbus_verbose ("Reading data from child error\n");
601 if (read_data (sitter, sitter->error_pipe_from_child) != READ_STATUS_OK)
602 close_error_pipe_from_child (sitter);
604 else if (revents & (_DBUS_POLLERR | _DBUS_POLLHUP))
606 close_error_pipe_from_child (sitter);
610 /* returns whether there were any poll events handled */
612 babysitter_iteration (DBusBabysitter *sitter,
617 dbus_bool_t descriptors_ready;
619 descriptors_ready = FALSE;
623 if (sitter->error_pipe_from_child >= 0)
625 fds[i].fd = sitter->error_pipe_from_child;
626 fds[i].events = _DBUS_POLLIN;
631 if (sitter->socket_to_babysitter.fd >= 0)
633 fds[i].fd = sitter->socket_to_babysitter.fd;
634 fds[i].events = _DBUS_POLLIN;
645 ret = _dbus_poll (fds, i, 0);
647 while (ret < 0 && errno == EINTR);
649 if (ret == 0 && block)
653 ret = _dbus_poll (fds, i, -1);
655 while (ret < 0 && errno == EINTR);
660 descriptors_ready = TRUE;
665 if (fds[i].fd == sitter->error_pipe_from_child)
666 handle_error_pipe (sitter, fds[i].revents);
667 else if (fds[i].fd == sitter->socket_to_babysitter.fd)
668 handle_babysitter_socket (sitter, fds[i].revents);
673 return descriptors_ready;
677 * Macro returns #TRUE if the babysitter still has live sockets open to the
678 * babysitter child or the grandchild.
680 #define LIVE_CHILDREN(sitter) ((sitter)->socket_to_babysitter.fd >= 0 || (sitter)->error_pipe_from_child >= 0)
683 * Blocks until the babysitter process gives us the PID of the spawned grandchild,
684 * then kills the spawned grandchild.
686 * @param sitter the babysitter object
689 _dbus_babysitter_kill_child (DBusBabysitter *sitter)
691 /* be sure we have the PID of the child */
692 while (LIVE_CHILDREN (sitter) &&
693 sitter->grandchild_pid == -1)
694 babysitter_iteration (sitter, TRUE);
696 _dbus_verbose ("Got child PID %ld for killing\n",
697 (long) sitter->grandchild_pid);
699 if (sitter->grandchild_pid == -1)
700 return; /* child is already dead, or we're so hosed we'll never recover */
702 kill (sitter->grandchild_pid, SIGKILL);
706 * Checks whether the child has exited, without blocking.
708 * @param sitter the babysitter
711 _dbus_babysitter_get_child_exited (DBusBabysitter *sitter)
714 /* Be sure we're up-to-date */
715 while (LIVE_CHILDREN (sitter) &&
716 babysitter_iteration (sitter, FALSE))
719 /* We will have exited the babysitter when the child has exited */
720 return sitter->socket_to_babysitter.fd < 0;
724 * Gets the exit status of the child. We do this so implementation specific
725 * detail is not cluttering up dbus, for example the system launcher code.
726 * This can only be called if the child has exited, i.e. call
727 * _dbus_babysitter_get_child_exited(). It returns FALSE if the child
728 * did not return a status code, e.g. because the child was signaled
729 * or we failed to ever launch the child in the first place.
731 * @param sitter the babysitter
732 * @param status the returned status code
733 * @returns #FALSE on failure
736 _dbus_babysitter_get_child_exit_status (DBusBabysitter *sitter,
739 if (!_dbus_babysitter_get_child_exited (sitter))
740 _dbus_assert_not_reached ("Child has not exited");
742 if (!sitter->have_child_status ||
743 !(WIFEXITED (sitter->status)))
746 *status = WEXITSTATUS (sitter->status);
751 * Sets the #DBusError with an explanation of why the spawned
752 * child process exited (on a signal, or whatever). If
753 * the child process has not exited, does nothing (error
754 * will remain unset).
756 * @param sitter the babysitter
757 * @param error an error to fill in
760 _dbus_babysitter_set_child_exit_error (DBusBabysitter *sitter,
763 if (!_dbus_babysitter_get_child_exited (sitter))
766 /* Note that if exec fails, we will also get a child status
767 * from the babysitter saying the child exited,
768 * so we need to give priority to the exec error
770 if (sitter->have_exec_errnum)
772 dbus_set_error (error, DBUS_ERROR_SPAWN_EXEC_FAILED,
773 "Failed to execute program %s: %s",
774 sitter->log_name, _dbus_strerror (sitter->errnum));
776 else if (sitter->have_fork_errnum)
778 dbus_set_error (error, DBUS_ERROR_NO_MEMORY,
779 "Failed to fork a new process %s: %s",
780 sitter->log_name, _dbus_strerror (sitter->errnum));
782 else if (sitter->have_child_status)
784 if (WIFEXITED (sitter->status))
785 dbus_set_error (error, DBUS_ERROR_SPAWN_CHILD_EXITED,
786 "Process %s exited with status %d",
787 sitter->log_name, WEXITSTATUS (sitter->status));
788 else if (WIFSIGNALED (sitter->status))
789 dbus_set_error (error, DBUS_ERROR_SPAWN_CHILD_SIGNALED,
790 "Process %s received signal %d",
791 sitter->log_name, WTERMSIG (sitter->status));
793 dbus_set_error (error, DBUS_ERROR_FAILED,
794 "Process %s exited abnormally",
799 dbus_set_error (error, DBUS_ERROR_FAILED,
800 "Process %s exited, reason unknown",
806 * Sets watch functions to notify us when the
807 * babysitter object needs to read/write file descriptors.
809 * @param sitter the babysitter
810 * @param add_function function to begin monitoring a new descriptor.
811 * @param remove_function function to stop monitoring a descriptor.
812 * @param toggled_function function to notify when the watch is enabled/disabled
813 * @param data data to pass to add_function and remove_function.
814 * @param free_data_function function to be called to free the data.
815 * @returns #FALSE on failure (no memory)
818 _dbus_babysitter_set_watch_functions (DBusBabysitter *sitter,
819 DBusAddWatchFunction add_function,
820 DBusRemoveWatchFunction remove_function,
821 DBusWatchToggledFunction toggled_function,
823 DBusFreeFunction free_data_function)
825 return _dbus_watch_list_set_functions (sitter->watches,
834 handle_watch (DBusWatch *watch,
835 unsigned int condition,
838 DBusBabysitter *sitter = _dbus_babysitter_ref (data);
843 if (condition & DBUS_WATCH_READABLE)
844 revents |= _DBUS_POLLIN;
845 if (condition & DBUS_WATCH_ERROR)
846 revents |= _DBUS_POLLERR;
847 if (condition & DBUS_WATCH_HANGUP)
848 revents |= _DBUS_POLLHUP;
850 fd = dbus_watch_get_socket (watch);
852 if (fd == sitter->error_pipe_from_child)
853 handle_error_pipe (sitter, revents);
854 else if (fd == sitter->socket_to_babysitter.fd)
855 handle_babysitter_socket (sitter, revents);
857 while (LIVE_CHILDREN (sitter) &&
858 babysitter_iteration (sitter, FALSE))
861 /* fd.o #32992: if the handle_* methods closed their sockets, they previously
862 * didn't always remove the watches. Check that we don't regress. */
863 _dbus_assert (sitter->socket_to_babysitter.fd != -1 || sitter->sitter_watch == NULL);
864 _dbus_assert (sitter->error_pipe_from_child != -1 || sitter->error_watch == NULL);
866 if (_dbus_babysitter_get_child_exited (sitter) &&
867 sitter->finished_cb != NULL)
869 sitter->finished_cb (sitter, sitter->finished_data);
870 sitter->finished_cb = NULL;
873 _dbus_babysitter_unref (sitter);
877 /** Helps remember which end of the pipe is which */
879 /** Helps remember which end of the pipe is which */
883 /* Avoids a danger in re-entrant situations (calling close()
884 * on a file descriptor twice, and another module has
885 * re-opened it since the first close).
887 * This previously claimed to be relevant for threaded situations, but by
888 * trivial inspection, it is not thread-safe. It doesn't actually
889 * matter, since this module is only used in the -util variant of the
890 * library, which is only used in single-threaded situations.
893 close_and_invalidate (int *fd)
901 ret = _dbus_close (*fd, NULL);
915 dbus_bool_t cloexec_done;
917 retval = pipe2 (p, O_CLOEXEC);
918 cloexec_done = retval >= 0;
920 /* Check if kernel seems to be too old to know pipe2(). We assume
921 that if pipe2 is available, O_CLOEXEC is too. */
922 if (retval < 0 && errno == ENOSYS)
928 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
932 dbus_set_error (error,
933 DBUS_ERROR_SPAWN_FAILED,
934 "Failed to create pipe for communicating with child process (%s)",
935 _dbus_strerror (errno));
943 _dbus_fd_set_close_on_exec (p[0]);
944 _dbus_fd_set_close_on_exec (p[1]);
951 do_write (int fd, const void *buf, size_t count)
953 size_t bytes_written;
960 ret = write (fd, ((const char*)buf) + bytes_written, count - bytes_written);
968 _dbus_warn ("Failed to write data to pipe!");
969 exit (1); /* give up, we suck */
973 bytes_written += ret;
975 if (bytes_written < count)
979 static void write_err_and_exit (int fd, int msg) _DBUS_GNUC_NORETURN;
982 write_err_and_exit (int fd, int msg)
986 do_write (fd, &msg, sizeof (msg));
987 do_write (fd, &en, sizeof (en));
993 write_pid (int fd, pid_t pid)
997 do_write (fd, &msg, sizeof (msg));
998 do_write (fd, &pid, sizeof (pid));
1001 static void write_status_and_exit (int fd, int status) _DBUS_GNUC_NORETURN;
1004 write_status_and_exit (int fd, int status)
1006 int msg = CHILD_EXITED;
1008 do_write (fd, &msg, sizeof (msg));
1009 do_write (fd, &status, sizeof (status));
1014 static void do_exec (int child_err_report_fd,
1017 DBusSpawnChildSetupFunc child_setup,
1018 void *user_data) _DBUS_GNUC_NORETURN;
1021 do_exec (int child_err_report_fd,
1024 DBusSpawnChildSetupFunc child_setup,
1027 #ifdef DBUS_ENABLE_EMBEDDED_TESTS
1031 _dbus_verbose_reset ();
1032 _dbus_verbose ("Child process has PID " DBUS_PID_FORMAT "\n",
1036 (* child_setup) (user_data);
1038 #ifdef DBUS_ENABLE_EMBEDDED_TESTS
1039 max_open = sysconf (_SC_OPEN_MAX);
1041 for (i = 3; i < max_open; i++)
1045 if (i == child_err_report_fd)
1048 retval = fcntl (i, F_GETFD);
1050 if (retval != -1 && !(retval & FD_CLOEXEC))
1051 _dbus_warn ("Fd %d did not have the close-on-exec flag set!", i);
1057 _dbus_assert (environ != NULL);
1062 execve (argv[0], argv, envp);
1065 write_err_and_exit (child_err_report_fd,
1070 check_babysit_events (pid_t grandchild_pid,
1079 ret = waitpid (grandchild_pid, &status, WNOHANG);
1080 /* The man page says EINTR can't happen with WNOHANG,
1081 * but there are reports of it (maybe only with valgrind?)
1084 while (ret < 0 && errno == EINTR);
1088 _dbus_verbose ("no child exited\n");
1090 ; /* no child exited */
1094 /* This isn't supposed to happen. */
1095 _dbus_warn ("unexpected waitpid() failure in check_babysit_events(): %s",
1096 _dbus_strerror (errno));
1099 else if (ret == grandchild_pid)
1102 _dbus_verbose ("reaped child pid %ld\n", (long) ret);
1104 write_status_and_exit (parent_pipe, status);
1108 _dbus_warn ("waitpid() reaped pid %d that we've never heard of",
1113 if (revents & _DBUS_POLLIN)
1115 _dbus_verbose ("babysitter got POLLIN from parent pipe\n");
1118 if (revents & (_DBUS_POLLERR | _DBUS_POLLHUP))
1120 /* Parent is gone, so we just exit */
1121 _dbus_verbose ("babysitter got POLLERR or POLLHUP from parent\n");
1126 static int babysit_sigchld_pipe = -1;
1129 babysit_signal_handler (int signo)
1133 if (write (babysit_sigchld_pipe, &b, 1) <= 0)
1138 static void babysit (pid_t grandchild_pid,
1139 int parent_pipe) _DBUS_GNUC_NORETURN;
1142 babysit (pid_t grandchild_pid,
1145 int sigchld_pipe[2];
1147 /* We don't exec, so we keep parent state, such as the pid that
1148 * _dbus_verbose() uses. Reset the pid here.
1150 _dbus_verbose_reset ();
1152 /* I thought SIGCHLD would just wake up the poll, but
1153 * that didn't seem to work, so added this pipe.
1154 * Probably the pipe is more likely to work on busted
1155 * operating systems anyhow.
1157 if (pipe (sigchld_pipe) < 0)
1159 _dbus_warn ("Not enough file descriptors to create pipe in babysitter process");
1163 babysit_sigchld_pipe = sigchld_pipe[WRITE_END];
1165 _dbus_set_signal_handler (SIGCHLD, babysit_signal_handler);
1167 write_pid (parent_pipe, grandchild_pid);
1169 check_babysit_events (grandchild_pid, parent_pipe, 0);
1175 pfds[0].fd = parent_pipe;
1176 pfds[0].events = _DBUS_POLLIN;
1177 pfds[0].revents = 0;
1179 pfds[1].fd = sigchld_pipe[READ_END];
1180 pfds[1].events = _DBUS_POLLIN;
1181 pfds[1].revents = 0;
1183 if (_dbus_poll (pfds, _DBUS_N_ELEMENTS (pfds), -1) < 0 && errno != EINTR)
1185 _dbus_warn ("_dbus_poll() error: %s", strerror (errno));
1189 if (pfds[0].revents != 0)
1191 check_babysit_events (grandchild_pid, parent_pipe, pfds[0].revents);
1193 else if (pfds[1].revents & _DBUS_POLLIN)
1196 if (read (sigchld_pipe[READ_END], &b, 1) == -1)
1200 /* do waitpid check */
1201 check_babysit_events (grandchild_pid, parent_pipe, 0);
1209 * Spawns a new process.
1211 * On Unix platforms, the child_setup function is passed the given
1212 * user_data and is run in the child after fork() but before calling exec().
1213 * This can be used to change uid, resource limits and so on.
1214 * On Windows, this functionality does not fit the multi-processing model
1215 * (Windows does the equivalent of fork() and exec() in a single API call),
1216 * and the child_setup function and its user_data are ignored.
1218 * Also creates a "babysitter" which tracks the status of the
1219 * child process, advising the parent if the child exits.
1220 * If the spawn fails, no babysitter is created.
1221 * If sitter_p is #NULL, no babysitter is kept.
1223 * @param sitter_p return location for babysitter or #NULL
1224 * @param log_name the name under which to log messages about this process being spawned
1225 * @param argv the executable and arguments
1226 * @param env the environment, or #NULL to copy the parent's
1227 * @param child_setup function to call in child pre-exec()
1228 * @param user_data user data for setup function
1229 * @param error error object to be filled in if function fails
1230 * @returns #TRUE on success, #FALSE if error is filled in
1233 _dbus_spawn_async_with_babysitter (DBusBabysitter **sitter_p,
1234 const char *log_name,
1237 DBusSpawnFlags flags,
1238 DBusSpawnChildSetupFunc child_setup,
1242 DBusBabysitter *sitter;
1243 int child_err_report_pipe[2] = { -1, -1 };
1244 DBusSocket babysitter_pipe[2] = { DBUS_SOCKET_INIT, DBUS_SOCKET_INIT };
1251 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1252 _dbus_assert (argv[0] != NULL);
1254 if (sitter_p != NULL)
1259 sitter = _dbus_babysitter_new ();
1262 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1266 sitter->log_name = _dbus_strdup (log_name);
1267 if (sitter->log_name == NULL && log_name != NULL)
1269 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1270 goto cleanup_and_fail;
1273 if (sitter->log_name == NULL)
1274 sitter->log_name = _dbus_strdup (argv[0]);
1276 if (sitter->log_name == NULL)
1278 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1279 goto cleanup_and_fail;
1282 if (!make_pipe (child_err_report_pipe, error))
1283 goto cleanup_and_fail;
1285 if (!_dbus_socketpair (&babysitter_pipe[0], &babysitter_pipe[1], TRUE, error))
1286 goto cleanup_and_fail;
1288 /* Setting up the babysitter is only useful in the parent,
1289 * but we don't want to run out of memory and fail
1290 * after we've already forked, since then we'd leak
1291 * child processes everywhere.
1293 sitter->error_watch = _dbus_watch_new (child_err_report_pipe[READ_END],
1294 DBUS_WATCH_READABLE,
1295 TRUE, handle_watch, sitter, NULL);
1296 if (sitter->error_watch == NULL)
1298 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1299 goto cleanup_and_fail;
1302 if (!_dbus_watch_list_add_watch (sitter->watches, sitter->error_watch))
1304 /* we need to free it early so the destructor won't try to remove it
1305 * without it having been added, which DBusLoop doesn't allow */
1306 _dbus_watch_invalidate (sitter->error_watch);
1307 _dbus_watch_unref (sitter->error_watch);
1308 sitter->error_watch = NULL;
1310 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1311 goto cleanup_and_fail;
1314 sitter->sitter_watch = _dbus_watch_new (babysitter_pipe[0].fd,
1315 DBUS_WATCH_READABLE,
1316 TRUE, handle_watch, sitter, NULL);
1317 if (sitter->sitter_watch == NULL)
1319 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1320 goto cleanup_and_fail;
1323 if (!_dbus_watch_list_add_watch (sitter->watches, sitter->sitter_watch))
1325 /* we need to free it early so the destructor won't try to remove it
1326 * without it having been added, which DBusLoop doesn't allow */
1327 _dbus_watch_invalidate (sitter->sitter_watch);
1328 _dbus_watch_unref (sitter->sitter_watch);
1329 sitter->sitter_watch = NULL;
1331 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1332 goto cleanup_and_fail;
1335 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1338 if (flags & DBUS_SPAWN_REDIRECT_OUTPUT)
1340 /* This may fail, but it's not critical.
1341 * In particular, if we were compiled with journald support but are now
1342 * running on a non-systemd system, this is going to fail, so we
1343 * have to cope gracefully. */
1344 fd_out = sd_journal_stream_fd (sitter->log_name, LOG_INFO, FALSE);
1345 fd_err = sd_journal_stream_fd (sitter->log_name, LOG_WARNING, FALSE);
1353 dbus_set_error (error,
1354 DBUS_ERROR_SPAWN_FORK_FAILED,
1355 "Failed to fork (%s)",
1356 _dbus_strerror (errno));
1357 goto cleanup_and_fail;
1361 /* Immediate child, this is the babysitter process. */
1364 /* Be sure we crash if the parent exits
1365 * and we write to the err_report_pipe
1367 signal (SIGPIPE, SIG_DFL);
1369 /* Close the parent's end of the pipes. */
1370 close_and_invalidate (&child_err_report_pipe[READ_END]);
1371 close_and_invalidate (&babysitter_pipe[0].fd);
1373 /* Create the child that will exec () */
1374 grandchild_pid = fork ();
1376 if (grandchild_pid < 0)
1378 write_err_and_exit (babysitter_pipe[1].fd,
1380 _dbus_assert_not_reached ("Got to code after write_err_and_exit()");
1382 else if (grandchild_pid == 0)
1388 fd = open ("/proc/self/oom_score_adj", O_WRONLY | O_CLOEXEC);
1393 fd = open ("/proc/self/oom_score_adj", O_WRONLY);
1394 _dbus_fd_set_close_on_exec (fd);
1399 if (write (fd, "0", sizeof (char)) < 0)
1400 _dbus_warn ("writing oom_score_adj error: %s", strerror (errno));
1401 _dbus_close (fd, NULL);
1404 /* Go back to ignoring SIGPIPE, since it's evil
1406 signal (SIGPIPE, SIG_IGN);
1408 close_and_invalidate (&babysitter_pipe[1].fd);
1410 /* log to systemd journal if possible */
1412 dup2 (fd_out, STDOUT_FILENO);
1414 dup2 (fd_err, STDERR_FILENO);
1415 close_and_invalidate (&fd_out);
1416 close_and_invalidate (&fd_err);
1418 do_exec (child_err_report_pipe[WRITE_END],
1421 child_setup, user_data);
1422 _dbus_assert_not_reached ("Got to code after exec() - should have exited on error");
1426 close_and_invalidate (&child_err_report_pipe[WRITE_END]);
1428 close_and_invalidate (&fd_out);
1429 close_and_invalidate (&fd_err);
1431 babysit (grandchild_pid, babysitter_pipe[1].fd);
1432 _dbus_assert_not_reached ("Got to code after babysit()");
1437 /* Close the uncared-about ends of the pipes */
1438 close_and_invalidate (&child_err_report_pipe[WRITE_END]);
1439 close_and_invalidate (&babysitter_pipe[1].fd);
1441 close_and_invalidate (&fd_out);
1442 close_and_invalidate (&fd_err);
1445 sitter->socket_to_babysitter = babysitter_pipe[0];
1446 babysitter_pipe[0].fd = -1;
1448 sitter->error_pipe_from_child = child_err_report_pipe[READ_END];
1449 child_err_report_pipe[READ_END] = -1;
1451 sitter->sitter_pid = pid;
1453 if (sitter_p != NULL)
1456 _dbus_babysitter_unref (sitter);
1458 dbus_free_string_array (env);
1460 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1467 _DBUS_ASSERT_ERROR_IS_SET (error);
1469 close_and_invalidate (&child_err_report_pipe[READ_END]);
1470 close_and_invalidate (&child_err_report_pipe[WRITE_END]);
1471 close_and_invalidate (&babysitter_pipe[0].fd);
1472 close_and_invalidate (&babysitter_pipe[1].fd);
1474 close_and_invalidate (&fd_out);
1475 close_and_invalidate (&fd_err);
1479 _dbus_babysitter_unref (sitter);
1485 _dbus_babysitter_set_result_function (DBusBabysitter *sitter,
1486 DBusBabysitterFinishedFunc finished,
1489 sitter->finished_cb = finished;
1490 sitter->finished_data = user_data;
1496 _dbus_babysitter_block_for_child_exit (DBusBabysitter *sitter)
1498 while (LIVE_CHILDREN (sitter))
1499 babysitter_iteration (sitter, TRUE);