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 extern char **environ;
51 * @addtogroup DBusInternalsUtils
56 * I'm pretty sure this whole spawn file could be made simpler,
57 * if you thought about it a bit.
61 * Enumeration for status of a read()
65 READ_STATUS_OK, /**< Read succeeded */
66 READ_STATUS_ERROR, /**< Some kind of error */
67 READ_STATUS_EOF /**< EOF returned */
80 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
82 retval = READ_STATUS_OK;
89 to_read = sizeof (int) * n_ints_in_buf - bytes;
100 if (chunk < 0 && errno == EINTR)
105 dbus_set_error (error,
106 DBUS_ERROR_SPAWN_FAILED,
107 "Failed to read from child pipe (%s)",
108 _dbus_strerror (errno));
110 retval = READ_STATUS_ERROR;
115 retval = READ_STATUS_EOF;
122 *n_ints_read = (int)(bytes / sizeof(int));
135 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
137 retval = READ_STATUS_OK;
144 to_read = sizeof (pid_t) - bytes;
152 ((char*)buf) + bytes,
154 if (chunk < 0 && errno == EINTR)
159 dbus_set_error (error,
160 DBUS_ERROR_SPAWN_FAILED,
161 "Failed to read from child pipe (%s)",
162 _dbus_strerror (errno));
164 retval = READ_STATUS_ERROR;
169 retval = READ_STATUS_EOF;
179 /* The implementation uses an intermediate child between the main process
180 * and the grandchild. The grandchild is our spawned process. The intermediate
181 * child is a babysitter process; it keeps track of when the grandchild
182 * exits/crashes, and reaps the grandchild.
184 * We automatically reap the babysitter process, killing it if necessary,
185 * when the DBusBabysitter's refcount goes to zero.
193 * \- grandchild --> exec --> spawned process
196 * child_err_report_pipe
197 * /-----------<---------<--------------\
200 * main process babysitter grandchild
203 * \-------<->-------/
206 * child_err_report_pipe is genuinely a pipe.
207 * The READ_END (also called error_pipe_from_child) is used in the main
208 * process. The WRITE_END (also called child_err_report_fd) is used in
209 * the grandchild process.
211 * On failure, the grandchild process sends CHILD_EXEC_FAILED + errno.
212 * On success, the pipe just closes (because it's close-on-exec) without
215 * babysitter_pipe is mis-named: it's really a bidirectional socketpair.
216 * The [0] end (also called socket_to_babysitter) is used in the main
217 * process, the [1] end (also called parent_pipe) is used in the babysitter.
219 * If the fork() labelled B in the diagram above fails, the babysitter sends
220 * CHILD_FORK_FAILED + errno.
221 * On success, the babysitter sends CHILD_PID + the grandchild's pid.
222 * On SIGCHLD, the babysitter sends CHILD_EXITED + the exit status.
223 * The main process doesn't explicitly send anything, but when it exits,
224 * the babysitter gets POLLHUP or POLLERR.
227 /* Messages from children to parents */
230 CHILD_EXITED, /* This message is followed by the exit status int */
231 CHILD_FORK_FAILED, /* Followed by errno */
232 CHILD_EXEC_FAILED, /* Followed by errno */
233 CHILD_PID /* Followed by pid_t */
237 * Babysitter implementation details
239 struct DBusBabysitter
241 int refcount; /**< Reference count */
243 char *log_name; /**< the name under which to log messages about this
244 process being spawned */
246 DBusSocket socket_to_babysitter; /**< Connection to the babysitter process */
247 int error_pipe_from_child; /**< Connection to the process that does the exec() */
249 pid_t sitter_pid; /**< PID Of the babysitter */
250 pid_t grandchild_pid; /**< PID of the grandchild */
252 DBusWatchList *watches; /**< Watches */
254 DBusWatch *error_watch; /**< Error pipe watch */
255 DBusWatch *sitter_watch; /**< Sitter pipe watch */
257 DBusBabysitterFinishedFunc finished_cb;
260 int errnum; /**< Error number */
261 int status; /**< Exit status code */
262 unsigned int have_child_status : 1; /**< True if child status has been reaped */
263 unsigned int have_fork_errnum : 1; /**< True if we have an error code from fork() */
264 unsigned int have_exec_errnum : 1; /**< True if we have an error code from exec() */
267 static DBusBabysitter*
268 _dbus_babysitter_new (void)
270 DBusBabysitter *sitter;
272 sitter = dbus_new0 (DBusBabysitter, 1);
276 sitter->refcount = 1;
278 sitter->socket_to_babysitter.fd = -1;
279 sitter->error_pipe_from_child = -1;
281 sitter->sitter_pid = -1;
282 sitter->grandchild_pid = -1;
284 sitter->watches = _dbus_watch_list_new ();
285 if (sitter->watches == NULL)
291 _dbus_babysitter_unref (sitter);
296 * Increment the reference count on the babysitter object.
298 * @param sitter the babysitter
299 * @returns the babysitter
302 _dbus_babysitter_ref (DBusBabysitter *sitter)
304 _dbus_assert (sitter != NULL);
305 _dbus_assert (sitter->refcount > 0);
307 sitter->refcount += 1;
312 static void close_socket_to_babysitter (DBusBabysitter *sitter);
313 static void close_error_pipe_from_child (DBusBabysitter *sitter);
316 * Decrement the reference count on the babysitter object.
317 * When the reference count of the babysitter object reaches
318 * zero, the babysitter is killed and the child that was being
319 * babysat gets emancipated.
321 * @param sitter the babysitter
324 _dbus_babysitter_unref (DBusBabysitter *sitter)
326 _dbus_assert (sitter != NULL);
327 _dbus_assert (sitter->refcount > 0);
329 sitter->refcount -= 1;
330 if (sitter->refcount == 0)
332 /* If we haven't forked other babysitters
333 * since this babysitter and socket were
334 * created then this close will cause the
335 * babysitter to wake up from poll with
336 * a hangup and then the babysitter will
339 close_socket_to_babysitter (sitter);
341 close_error_pipe_from_child (sitter);
343 if (sitter->sitter_pid > 0)
348 /* It's possible the babysitter died on its own above
349 * from the close, or was killed randomly
350 * by some other process, so first try to reap it
352 ret = waitpid (sitter->sitter_pid, &status, WNOHANG);
354 /* If we couldn't reap the child then kill it, and
358 kill (sitter->sitter_pid, SIGKILL);
364 ret = waitpid (sitter->sitter_pid, &status, 0);
366 while (_DBUS_UNLIKELY (ret < 0 && errno == EINTR));
372 _dbus_warn ("Babysitter process not available to be reaped; should not happen\n");
374 _dbus_warn ("Unexpected error %d in waitpid() for babysitter: %s\n",
375 errno, _dbus_strerror (errno));
379 _dbus_verbose ("Reaped %ld, waiting for babysitter %ld\n",
380 (long) ret, (long) sitter->sitter_pid);
382 if (WIFEXITED (sitter->status))
383 _dbus_verbose ("Babysitter exited with status %d\n",
384 WEXITSTATUS (sitter->status));
385 else if (WIFSIGNALED (sitter->status))
386 _dbus_verbose ("Babysitter received signal %d\n",
387 WTERMSIG (sitter->status));
389 _dbus_verbose ("Babysitter exited abnormally\n");
392 sitter->sitter_pid = -1;
396 _dbus_watch_list_free (sitter->watches);
398 dbus_free (sitter->log_name);
405 read_data (DBusBabysitter *sitter,
410 DBusError error = DBUS_ERROR_INIT;
413 r = read_ints (fd, &what, 1, &got, &error);
417 case READ_STATUS_ERROR:
418 _dbus_warn ("Failed to read data from fd %d: %s\n", fd, error.message);
419 dbus_error_free (&error);
422 case READ_STATUS_EOF:
434 case CHILD_FORK_FAILED:
435 case CHILD_EXEC_FAILED:
439 r = read_ints (fd, &arg, 1, &got, &error);
443 case READ_STATUS_ERROR:
444 _dbus_warn ("Failed to read arg from fd %d: %s\n", fd, error.message);
445 dbus_error_free (&error);
447 case READ_STATUS_EOF:
455 if (what == CHILD_EXITED)
457 /* Do not reset sitter->errnum to 0 here. We get here if
458 * the babysitter reports that the grandchild process has
459 * exited, and there are two ways that can happen:
461 * 1. grandchild successfully exec()s the desired process,
462 * but then the desired process exits or is terminated
463 * by a signal. The babysitter observes this and reports
466 * 2. grandchild fails to exec() the desired process,
467 * attempts to report the exec() failure (which
468 * we will receive as CHILD_EXEC_FAILED), and then
469 * exits itself (which will prompt the babysitter to
470 * send CHILD_EXITED). We want the CHILD_EXEC_FAILED
471 * to take precedence (and have its errno logged),
472 * which _dbus_babysitter_set_child_exit_error() does.
474 sitter->have_child_status = TRUE;
475 sitter->status = arg;
476 _dbus_verbose ("recorded child status exited = %d signaled = %d exitstatus = %d termsig = %d\n",
477 WIFEXITED (sitter->status), WIFSIGNALED (sitter->status),
478 WEXITSTATUS (sitter->status), WTERMSIG (sitter->status));
480 else if (what == CHILD_FORK_FAILED)
482 sitter->have_fork_errnum = TRUE;
483 sitter->errnum = arg;
484 _dbus_verbose ("recorded fork errnum %d\n", sitter->errnum);
486 else if (what == CHILD_EXEC_FAILED)
488 sitter->have_exec_errnum = TRUE;
489 sitter->errnum = arg;
490 _dbus_verbose ("recorded exec errnum %d\n", sitter->errnum);
499 r = read_pid (fd, &pid, &error);
503 case READ_STATUS_ERROR:
504 _dbus_warn ("Failed to read PID from fd %d: %s\n", fd, error.message);
505 dbus_error_free (&error);
507 case READ_STATUS_EOF:
513 sitter->grandchild_pid = pid;
515 _dbus_verbose ("recorded grandchild pid %d\n", sitter->grandchild_pid);
519 _dbus_warn ("Unknown message received from babysitter process\n");
528 close_socket_to_babysitter (DBusBabysitter *sitter)
530 _dbus_verbose ("Closing babysitter\n");
532 if (sitter->sitter_watch != NULL)
534 _dbus_assert (sitter->watches != NULL);
535 _dbus_watch_list_remove_watch (sitter->watches, sitter->sitter_watch);
536 _dbus_watch_invalidate (sitter->sitter_watch);
537 _dbus_watch_unref (sitter->sitter_watch);
538 sitter->sitter_watch = NULL;
541 if (sitter->socket_to_babysitter.fd >= 0)
543 _dbus_close_socket (sitter->socket_to_babysitter, NULL);
544 sitter->socket_to_babysitter.fd = -1;
549 close_error_pipe_from_child (DBusBabysitter *sitter)
551 _dbus_verbose ("Closing child error\n");
553 if (sitter->error_watch != NULL)
555 _dbus_assert (sitter->watches != NULL);
556 _dbus_watch_list_remove_watch (sitter->watches, sitter->error_watch);
557 _dbus_watch_invalidate (sitter->error_watch);
558 _dbus_watch_unref (sitter->error_watch);
559 sitter->error_watch = NULL;
562 if (sitter->error_pipe_from_child >= 0)
564 _dbus_close (sitter->error_pipe_from_child, NULL);
565 sitter->error_pipe_from_child = -1;
570 handle_babysitter_socket (DBusBabysitter *sitter,
573 /* Even if we have POLLHUP, we want to keep reading
574 * data until POLLIN goes away; so this function only
575 * looks at HUP/ERR if no IN is set.
577 if (revents & _DBUS_POLLIN)
579 _dbus_verbose ("Reading data from babysitter\n");
580 if (read_data (sitter, sitter->socket_to_babysitter.fd) != READ_STATUS_OK)
581 close_socket_to_babysitter (sitter);
583 else if (revents & (_DBUS_POLLERR | _DBUS_POLLHUP))
585 close_socket_to_babysitter (sitter);
590 handle_error_pipe (DBusBabysitter *sitter,
593 if (revents & _DBUS_POLLIN)
595 _dbus_verbose ("Reading data from child error\n");
596 if (read_data (sitter, sitter->error_pipe_from_child) != READ_STATUS_OK)
597 close_error_pipe_from_child (sitter);
599 else if (revents & (_DBUS_POLLERR | _DBUS_POLLHUP))
601 close_error_pipe_from_child (sitter);
605 /* returns whether there were any poll events handled */
607 babysitter_iteration (DBusBabysitter *sitter,
612 dbus_bool_t descriptors_ready;
614 descriptors_ready = FALSE;
618 if (sitter->error_pipe_from_child >= 0)
620 fds[i].fd = sitter->error_pipe_from_child;
621 fds[i].events = _DBUS_POLLIN;
626 if (sitter->socket_to_babysitter.fd >= 0)
628 fds[i].fd = sitter->socket_to_babysitter.fd;
629 fds[i].events = _DBUS_POLLIN;
640 ret = _dbus_poll (fds, i, 0);
642 while (ret < 0 && errno == EINTR);
644 if (ret == 0 && block)
648 ret = _dbus_poll (fds, i, -1);
650 while (ret < 0 && errno == EINTR);
655 descriptors_ready = TRUE;
660 if (fds[i].fd == sitter->error_pipe_from_child)
661 handle_error_pipe (sitter, fds[i].revents);
662 else if (fds[i].fd == sitter->socket_to_babysitter.fd)
663 handle_babysitter_socket (sitter, fds[i].revents);
668 return descriptors_ready;
672 * Macro returns #TRUE if the babysitter still has live sockets open to the
673 * babysitter child or the grandchild.
675 #define LIVE_CHILDREN(sitter) ((sitter)->socket_to_babysitter.fd >= 0 || (sitter)->error_pipe_from_child >= 0)
678 * Blocks until the babysitter process gives us the PID of the spawned grandchild,
679 * then kills the spawned grandchild.
681 * @param sitter the babysitter object
684 _dbus_babysitter_kill_child (DBusBabysitter *sitter)
686 /* be sure we have the PID of the child */
687 while (LIVE_CHILDREN (sitter) &&
688 sitter->grandchild_pid == -1)
689 babysitter_iteration (sitter, TRUE);
691 _dbus_verbose ("Got child PID %ld for killing\n",
692 (long) sitter->grandchild_pid);
694 if (sitter->grandchild_pid == -1)
695 return; /* child is already dead, or we're so hosed we'll never recover */
697 kill (sitter->grandchild_pid, SIGKILL);
701 * Checks whether the child has exited, without blocking.
703 * @param sitter the babysitter
706 _dbus_babysitter_get_child_exited (DBusBabysitter *sitter)
709 /* Be sure we're up-to-date */
710 while (LIVE_CHILDREN (sitter) &&
711 babysitter_iteration (sitter, FALSE))
714 /* We will have exited the babysitter when the child has exited */
715 return sitter->socket_to_babysitter.fd < 0;
719 * Gets the exit status of the child. We do this so implementation specific
720 * detail is not cluttering up dbus, for example the system launcher code.
721 * This can only be called if the child has exited, i.e. call
722 * _dbus_babysitter_get_child_exited(). It returns FALSE if the child
723 * did not return a status code, e.g. because the child was signaled
724 * or we failed to ever launch the child in the first place.
726 * @param sitter the babysitter
727 * @param status the returned status code
728 * @returns #FALSE on failure
731 _dbus_babysitter_get_child_exit_status (DBusBabysitter *sitter,
734 if (!_dbus_babysitter_get_child_exited (sitter))
735 _dbus_assert_not_reached ("Child has not exited");
737 if (!sitter->have_child_status ||
738 !(WIFEXITED (sitter->status)))
741 *status = WEXITSTATUS (sitter->status);
746 * Sets the #DBusError with an explanation of why the spawned
747 * child process exited (on a signal, or whatever). If
748 * the child process has not exited, does nothing (error
749 * will remain unset).
751 * @param sitter the babysitter
752 * @param error an error to fill in
755 _dbus_babysitter_set_child_exit_error (DBusBabysitter *sitter,
758 if (!_dbus_babysitter_get_child_exited (sitter))
761 /* Note that if exec fails, we will also get a child status
762 * from the babysitter saying the child exited,
763 * so we need to give priority to the exec error
765 if (sitter->have_exec_errnum)
767 dbus_set_error (error, DBUS_ERROR_SPAWN_EXEC_FAILED,
768 "Failed to execute program %s: %s",
769 sitter->log_name, _dbus_strerror (sitter->errnum));
771 else if (sitter->have_fork_errnum)
773 dbus_set_error (error, DBUS_ERROR_NO_MEMORY,
774 "Failed to fork a new process %s: %s",
775 sitter->log_name, _dbus_strerror (sitter->errnum));
777 else if (sitter->have_child_status)
779 if (WIFEXITED (sitter->status))
780 dbus_set_error (error, DBUS_ERROR_SPAWN_CHILD_EXITED,
781 "Process %s exited with status %d",
782 sitter->log_name, WEXITSTATUS (sitter->status));
783 else if (WIFSIGNALED (sitter->status))
784 dbus_set_error (error, DBUS_ERROR_SPAWN_CHILD_SIGNALED,
785 "Process %s received signal %d",
786 sitter->log_name, WTERMSIG (sitter->status));
788 dbus_set_error (error, DBUS_ERROR_FAILED,
789 "Process %s exited abnormally",
794 dbus_set_error (error, DBUS_ERROR_FAILED,
795 "Process %s exited, reason unknown",
801 * Sets watch functions to notify us when the
802 * babysitter object needs to read/write file descriptors.
804 * @param sitter the babysitter
805 * @param add_function function to begin monitoring a new descriptor.
806 * @param remove_function function to stop monitoring a descriptor.
807 * @param toggled_function function to notify when the watch is enabled/disabled
808 * @param data data to pass to add_function and remove_function.
809 * @param free_data_function function to be called to free the data.
810 * @returns #FALSE on failure (no memory)
813 _dbus_babysitter_set_watch_functions (DBusBabysitter *sitter,
814 DBusAddWatchFunction add_function,
815 DBusRemoveWatchFunction remove_function,
816 DBusWatchToggledFunction toggled_function,
818 DBusFreeFunction free_data_function)
820 return _dbus_watch_list_set_functions (sitter->watches,
829 handle_watch (DBusWatch *watch,
830 unsigned int condition,
833 DBusBabysitter *sitter = _dbus_babysitter_ref (data);
838 if (condition & DBUS_WATCH_READABLE)
839 revents |= _DBUS_POLLIN;
840 if (condition & DBUS_WATCH_ERROR)
841 revents |= _DBUS_POLLERR;
842 if (condition & DBUS_WATCH_HANGUP)
843 revents |= _DBUS_POLLHUP;
845 fd = dbus_watch_get_socket (watch);
847 if (fd == sitter->error_pipe_from_child)
848 handle_error_pipe (sitter, revents);
849 else if (fd == sitter->socket_to_babysitter.fd)
850 handle_babysitter_socket (sitter, revents);
852 while (LIVE_CHILDREN (sitter) &&
853 babysitter_iteration (sitter, FALSE))
856 /* fd.o #32992: if the handle_* methods closed their sockets, they previously
857 * didn't always remove the watches. Check that we don't regress. */
858 _dbus_assert (sitter->socket_to_babysitter.fd != -1 || sitter->sitter_watch == NULL);
859 _dbus_assert (sitter->error_pipe_from_child != -1 || sitter->error_watch == NULL);
861 if (_dbus_babysitter_get_child_exited (sitter) &&
862 sitter->finished_cb != NULL)
864 sitter->finished_cb (sitter, sitter->finished_data);
865 sitter->finished_cb = NULL;
868 _dbus_babysitter_unref (sitter);
872 /** Helps remember which end of the pipe is which */
874 /** Helps remember which end of the pipe is which */
878 /* Avoids a danger in re-entrant situations (calling close()
879 * on a file descriptor twice, and another module has
880 * re-opened it since the first close).
882 * This previously claimed to be relevant for threaded situations, but by
883 * trivial inspection, it is not thread-safe. It doesn't actually
884 * matter, since this module is only used in the -util variant of the
885 * library, which is only used in single-threaded situations.
888 close_and_invalidate (int *fd)
896 ret = _dbus_close (*fd, NULL);
910 dbus_bool_t cloexec_done;
912 retval = pipe2 (p, O_CLOEXEC);
913 cloexec_done = retval >= 0;
915 /* Check if kernel seems to be too old to know pipe2(). We assume
916 that if pipe2 is available, O_CLOEXEC is too. */
917 if (retval < 0 && errno == ENOSYS)
923 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
927 dbus_set_error (error,
928 DBUS_ERROR_SPAWN_FAILED,
929 "Failed to create pipe for communicating with child process (%s)",
930 _dbus_strerror (errno));
938 _dbus_fd_set_close_on_exec (p[0]);
939 _dbus_fd_set_close_on_exec (p[1]);
946 do_write (int fd, const void *buf, size_t count)
948 size_t bytes_written;
955 ret = write (fd, ((const char*)buf) + bytes_written, count - bytes_written);
963 _dbus_warn ("Failed to write data to pipe!\n");
964 exit (1); /* give up, we suck */
968 bytes_written += ret;
970 if (bytes_written < count)
975 write_err_and_exit (int fd, int msg)
979 do_write (fd, &msg, sizeof (msg));
980 do_write (fd, &en, sizeof (en));
986 write_pid (int fd, pid_t pid)
990 do_write (fd, &msg, sizeof (msg));
991 do_write (fd, &pid, sizeof (pid));
995 write_status_and_exit (int fd, int status)
997 int msg = CHILD_EXITED;
999 do_write (fd, &msg, sizeof (msg));
1000 do_write (fd, &status, sizeof (status));
1006 do_exec (int child_err_report_fd,
1009 DBusSpawnChildSetupFunc child_setup,
1012 #ifdef DBUS_ENABLE_EMBEDDED_TESTS
1016 _dbus_verbose_reset ();
1017 _dbus_verbose ("Child process has PID " DBUS_PID_FORMAT "\n",
1021 (* child_setup) (user_data);
1023 #ifdef DBUS_ENABLE_EMBEDDED_TESTS
1024 max_open = sysconf (_SC_OPEN_MAX);
1026 for (i = 3; i < max_open; i++)
1030 if (i == child_err_report_fd)
1033 retval = fcntl (i, F_GETFD);
1035 if (retval != -1 && !(retval & FD_CLOEXEC))
1036 _dbus_warn ("Fd %d did not have the close-on-exec flag set!\n", i);
1042 _dbus_assert (environ != NULL);
1047 execve (argv[0], argv, envp);
1050 write_err_and_exit (child_err_report_fd,
1055 check_babysit_events (pid_t grandchild_pid,
1064 ret = waitpid (grandchild_pid, &status, WNOHANG);
1065 /* The man page says EINTR can't happen with WNOHANG,
1066 * but there are reports of it (maybe only with valgrind?)
1069 while (ret < 0 && errno == EINTR);
1073 _dbus_verbose ("no child exited\n");
1075 ; /* no child exited */
1079 /* This isn't supposed to happen. */
1080 _dbus_warn ("unexpected waitpid() failure in check_babysit_events(): %s\n",
1081 _dbus_strerror (errno));
1084 else if (ret == grandchild_pid)
1087 _dbus_verbose ("reaped child pid %ld\n", (long) ret);
1089 write_status_and_exit (parent_pipe, status);
1093 _dbus_warn ("waitpid() reaped pid %d that we've never heard of\n",
1098 if (revents & _DBUS_POLLIN)
1100 _dbus_verbose ("babysitter got POLLIN from parent pipe\n");
1103 if (revents & (_DBUS_POLLERR | _DBUS_POLLHUP))
1105 /* Parent is gone, so we just exit */
1106 _dbus_verbose ("babysitter got POLLERR or POLLHUP from parent\n");
1111 static int babysit_sigchld_pipe = -1;
1114 babysit_signal_handler (int signo)
1118 if (write (babysit_sigchld_pipe, &b, 1) <= 0)
1124 babysit (pid_t grandchild_pid,
1127 int sigchld_pipe[2];
1129 /* We don't exec, so we keep parent state, such as the pid that
1130 * _dbus_verbose() uses. Reset the pid here.
1132 _dbus_verbose_reset ();
1134 /* I thought SIGCHLD would just wake up the poll, but
1135 * that didn't seem to work, so added this pipe.
1136 * Probably the pipe is more likely to work on busted
1137 * operating systems anyhow.
1139 if (pipe (sigchld_pipe) < 0)
1141 _dbus_warn ("Not enough file descriptors to create pipe in babysitter process\n");
1145 babysit_sigchld_pipe = sigchld_pipe[WRITE_END];
1147 _dbus_set_signal_handler (SIGCHLD, babysit_signal_handler);
1149 write_pid (parent_pipe, grandchild_pid);
1151 check_babysit_events (grandchild_pid, parent_pipe, 0);
1157 pfds[0].fd = parent_pipe;
1158 pfds[0].events = _DBUS_POLLIN;
1159 pfds[0].revents = 0;
1161 pfds[1].fd = sigchld_pipe[READ_END];
1162 pfds[1].events = _DBUS_POLLIN;
1163 pfds[1].revents = 0;
1165 if (_dbus_poll (pfds, _DBUS_N_ELEMENTS (pfds), -1) < 0 && errno != EINTR)
1167 _dbus_warn ("_dbus_poll() error: %s\n", strerror (errno));
1171 if (pfds[0].revents != 0)
1173 check_babysit_events (grandchild_pid, parent_pipe, pfds[0].revents);
1175 else if (pfds[1].revents & _DBUS_POLLIN)
1178 if (read (sigchld_pipe[READ_END], &b, 1) == -1)
1182 /* do waitpid check */
1183 check_babysit_events (grandchild_pid, parent_pipe, 0);
1191 * Spawns a new process. The child_setup
1192 * function is passed the given user_data and is run in the child
1193 * just before calling exec().
1195 * Also creates a "babysitter" which tracks the status of the
1196 * child process, advising the parent if the child exits.
1197 * If the spawn fails, no babysitter is created.
1198 * If sitter_p is #NULL, no babysitter is kept.
1200 * @param sitter_p return location for babysitter or #NULL
1201 * @param log_name the name under which to log messages about this process being spawned
1202 * @param argv the executable and arguments
1203 * @param env the environment, or #NULL to copy the parent's
1204 * @param child_setup function to call in child pre-exec()
1205 * @param user_data user data for setup function
1206 * @param error error object to be filled in if function fails
1207 * @returns #TRUE on success, #FALSE if error is filled in
1210 _dbus_spawn_async_with_babysitter (DBusBabysitter **sitter_p,
1211 const char *log_name,
1214 DBusSpawnChildSetupFunc child_setup,
1218 DBusBabysitter *sitter;
1219 int child_err_report_pipe[2] = { -1, -1 };
1220 DBusSocket babysitter_pipe[2] = { DBUS_SOCKET_INIT, DBUS_SOCKET_INIT };
1227 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1228 _dbus_assert (argv[0] != NULL);
1230 if (sitter_p != NULL)
1235 sitter = _dbus_babysitter_new ();
1238 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1242 sitter->log_name = _dbus_strdup (log_name);
1243 if (sitter->log_name == NULL && log_name != NULL)
1245 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1246 goto cleanup_and_fail;
1249 if (sitter->log_name == NULL)
1250 sitter->log_name = _dbus_strdup (argv[0]);
1252 if (sitter->log_name == NULL)
1254 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1255 goto cleanup_and_fail;
1258 if (!make_pipe (child_err_report_pipe, error))
1259 goto cleanup_and_fail;
1261 if (!_dbus_socketpair (&babysitter_pipe[0], &babysitter_pipe[1], TRUE, error))
1262 goto cleanup_and_fail;
1264 /* Setting up the babysitter is only useful in the parent,
1265 * but we don't want to run out of memory and fail
1266 * after we've already forked, since then we'd leak
1267 * child processes everywhere.
1269 sitter->error_watch = _dbus_watch_new (child_err_report_pipe[READ_END],
1270 DBUS_WATCH_READABLE,
1271 TRUE, handle_watch, sitter, NULL);
1272 if (sitter->error_watch == NULL)
1274 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1275 goto cleanup_and_fail;
1278 if (!_dbus_watch_list_add_watch (sitter->watches, sitter->error_watch))
1280 /* we need to free it early so the destructor won't try to remove it
1281 * without it having been added, which DBusLoop doesn't allow */
1282 _dbus_watch_invalidate (sitter->error_watch);
1283 _dbus_watch_unref (sitter->error_watch);
1284 sitter->error_watch = NULL;
1286 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1287 goto cleanup_and_fail;
1290 sitter->sitter_watch = _dbus_watch_new (babysitter_pipe[0].fd,
1291 DBUS_WATCH_READABLE,
1292 TRUE, handle_watch, sitter, NULL);
1293 if (sitter->sitter_watch == NULL)
1295 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1296 goto cleanup_and_fail;
1299 if (!_dbus_watch_list_add_watch (sitter->watches, sitter->sitter_watch))
1301 /* we need to free it early so the destructor won't try to remove it
1302 * without it having been added, which DBusLoop doesn't allow */
1303 _dbus_watch_invalidate (sitter->sitter_watch);
1304 _dbus_watch_unref (sitter->sitter_watch);
1305 sitter->sitter_watch = NULL;
1307 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1308 goto cleanup_and_fail;
1311 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1314 /* This may fail, but it's not critical.
1315 * In particular, if we were compiled with journald support but are now
1316 * running on a non-systemd system, this is going to fail, so we
1317 * have to cope gracefully. */
1318 fd_out = sd_journal_stream_fd (sitter->log_name, LOG_INFO, FALSE);
1319 fd_err = sd_journal_stream_fd (sitter->log_name, LOG_WARNING, FALSE);
1326 dbus_set_error (error,
1327 DBUS_ERROR_SPAWN_FORK_FAILED,
1328 "Failed to fork (%s)",
1329 _dbus_strerror (errno));
1330 goto cleanup_and_fail;
1334 /* Immediate child, this is the babysitter process. */
1337 /* Be sure we crash if the parent exits
1338 * and we write to the err_report_pipe
1340 signal (SIGPIPE, SIG_DFL);
1342 /* Close the parent's end of the pipes. */
1343 close_and_invalidate (&child_err_report_pipe[READ_END]);
1344 close_and_invalidate (&babysitter_pipe[0].fd);
1346 /* Create the child that will exec () */
1347 grandchild_pid = fork ();
1349 if (grandchild_pid < 0)
1351 write_err_and_exit (babysitter_pipe[1].fd,
1353 _dbus_assert_not_reached ("Got to code after write_err_and_exit()");
1355 else if (grandchild_pid == 0)
1357 /* Go back to ignoring SIGPIPE, since it's evil
1359 signal (SIGPIPE, SIG_IGN);
1361 close_and_invalidate (&babysitter_pipe[1].fd);
1363 /* log to systemd journal if possible */
1365 dup2 (fd_out, STDOUT_FILENO);
1367 dup2 (fd_err, STDERR_FILENO);
1368 close_and_invalidate (&fd_out);
1369 close_and_invalidate (&fd_err);
1371 do_exec (child_err_report_pipe[WRITE_END],
1374 child_setup, user_data);
1375 _dbus_assert_not_reached ("Got to code after exec() - should have exited on error");
1379 close_and_invalidate (&child_err_report_pipe[WRITE_END]);
1381 close_and_invalidate (&fd_out);
1382 close_and_invalidate (&fd_err);
1384 babysit (grandchild_pid, babysitter_pipe[1].fd);
1385 _dbus_assert_not_reached ("Got to code after babysit()");
1390 /* Close the uncared-about ends of the pipes */
1391 close_and_invalidate (&child_err_report_pipe[WRITE_END]);
1392 close_and_invalidate (&babysitter_pipe[1].fd);
1394 close_and_invalidate (&fd_out);
1395 close_and_invalidate (&fd_err);
1398 sitter->socket_to_babysitter = babysitter_pipe[0];
1399 babysitter_pipe[0].fd = -1;
1401 sitter->error_pipe_from_child = child_err_report_pipe[READ_END];
1402 child_err_report_pipe[READ_END] = -1;
1404 sitter->sitter_pid = pid;
1406 if (sitter_p != NULL)
1409 _dbus_babysitter_unref (sitter);
1411 dbus_free_string_array (env);
1413 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1420 _DBUS_ASSERT_ERROR_IS_SET (error);
1422 close_and_invalidate (&child_err_report_pipe[READ_END]);
1423 close_and_invalidate (&child_err_report_pipe[WRITE_END]);
1424 close_and_invalidate (&babysitter_pipe[0].fd);
1425 close_and_invalidate (&babysitter_pipe[1].fd);
1427 close_and_invalidate (&fd_out);
1428 close_and_invalidate (&fd_err);
1432 _dbus_babysitter_unref (sitter);
1438 _dbus_babysitter_set_result_function (DBusBabysitter *sitter,
1439 DBusBabysitterFinishedFunc finished,
1442 sitter->finished_cb = finished;
1443 sitter->finished_data = user_data;
1448 #ifdef DBUS_ENABLE_EMBEDDED_TESTS
1451 get_test_exec (const char *exe,
1452 DBusString *scratch_space)
1454 const char *dbus_test_exec;
1456 dbus_test_exec = _dbus_getenv ("DBUS_TEST_EXEC");
1458 if (dbus_test_exec == NULL)
1459 dbus_test_exec = DBUS_TEST_EXEC;
1461 if (!_dbus_string_init (scratch_space))
1464 if (!_dbus_string_append_printf (scratch_space, "%s/%s%s",
1465 dbus_test_exec, exe, DBUS_EXEEXT))
1467 _dbus_string_free (scratch_space);
1471 return _dbus_string_get_data (scratch_space);
1475 _dbus_babysitter_block_for_child_exit (DBusBabysitter *sitter)
1477 while (LIVE_CHILDREN (sitter))
1478 babysitter_iteration (sitter, TRUE);
1482 check_spawn_nonexistent (void *data)
1484 char *argv[4] = { NULL, NULL, NULL, NULL };
1485 DBusBabysitter *sitter = NULL;
1486 DBusError error = DBUS_ERROR_INIT;
1488 /*** Test launching nonexistent binary */
1490 argv[0] = "/this/does/not/exist/32542sdgafgafdg";
1491 if (_dbus_spawn_async_with_babysitter (&sitter, "spawn_nonexistent", argv,
1495 _dbus_babysitter_block_for_child_exit (sitter);
1496 _dbus_babysitter_set_child_exit_error (sitter, &error);
1500 _dbus_babysitter_unref (sitter);
1502 if (!dbus_error_is_set (&error))
1504 _dbus_warn ("Did not get an error launching nonexistent executable\n");
1508 if (!(dbus_error_has_name (&error, DBUS_ERROR_NO_MEMORY) ||
1509 dbus_error_has_name (&error, DBUS_ERROR_SPAWN_EXEC_FAILED)))
1511 _dbus_warn ("Not expecting error when launching nonexistent executable: %s: %s\n",
1512 error.name, error.message);
1513 dbus_error_free (&error);
1517 dbus_error_free (&error);
1523 check_spawn_segfault (void *data)
1525 char *argv[4] = { NULL, NULL, NULL, NULL };
1526 DBusBabysitter *sitter = NULL;
1527 DBusError error = DBUS_ERROR_INIT;
1530 /*** Test launching segfault binary */
1532 argv[0] = get_test_exec ("test-segfault", &argv0);
1534 if (argv[0] == NULL)
1536 /* OOM was simulated, never mind */
1540 if (_dbus_spawn_async_with_babysitter (&sitter, "spawn_segfault", argv,
1544 _dbus_babysitter_block_for_child_exit (sitter);
1545 _dbus_babysitter_set_child_exit_error (sitter, &error);
1548 _dbus_string_free (&argv0);
1551 _dbus_babysitter_unref (sitter);
1553 if (!dbus_error_is_set (&error))
1555 _dbus_warn ("Did not get an error launching segfaulting binary\n");
1559 if (!(dbus_error_has_name (&error, DBUS_ERROR_NO_MEMORY) ||
1560 dbus_error_has_name (&error, DBUS_ERROR_SPAWN_CHILD_SIGNALED)))
1562 _dbus_warn ("Not expecting error when launching segfaulting executable: %s: %s\n",
1563 error.name, error.message);
1564 dbus_error_free (&error);
1568 dbus_error_free (&error);
1574 check_spawn_exit (void *data)
1576 char *argv[4] = { NULL, NULL, NULL, NULL };
1577 DBusBabysitter *sitter = NULL;
1578 DBusError error = DBUS_ERROR_INIT;
1581 /*** Test launching exit failure binary */
1583 argv[0] = get_test_exec ("test-exit", &argv0);
1585 if (argv[0] == NULL)
1587 /* OOM was simulated, never mind */
1591 if (_dbus_spawn_async_with_babysitter (&sitter, "spawn_exit", argv,
1595 _dbus_babysitter_block_for_child_exit (sitter);
1596 _dbus_babysitter_set_child_exit_error (sitter, &error);
1599 _dbus_string_free (&argv0);
1602 _dbus_babysitter_unref (sitter);
1604 if (!dbus_error_is_set (&error))
1606 _dbus_warn ("Did not get an error launching binary that exited with failure code\n");
1610 if (!(dbus_error_has_name (&error, DBUS_ERROR_NO_MEMORY) ||
1611 dbus_error_has_name (&error, DBUS_ERROR_SPAWN_CHILD_EXITED)))
1613 _dbus_warn ("Not expecting error when launching exiting executable: %s: %s\n",
1614 error.name, error.message);
1615 dbus_error_free (&error);
1619 dbus_error_free (&error);
1625 check_spawn_and_kill (void *data)
1627 char *argv[4] = { NULL, NULL, NULL, NULL };
1628 DBusBabysitter *sitter = NULL;
1629 DBusError error = DBUS_ERROR_INIT;
1632 /*** Test launching sleeping binary then killing it */
1634 argv[0] = get_test_exec ("test-sleep-forever", &argv0);
1636 if (argv[0] == NULL)
1638 /* OOM was simulated, never mind */
1642 if (_dbus_spawn_async_with_babysitter (&sitter, "spawn_and_kill", argv,
1646 _dbus_babysitter_kill_child (sitter);
1648 _dbus_babysitter_block_for_child_exit (sitter);
1650 _dbus_babysitter_set_child_exit_error (sitter, &error);
1653 _dbus_string_free (&argv0);
1656 _dbus_babysitter_unref (sitter);
1658 if (!dbus_error_is_set (&error))
1660 _dbus_warn ("Did not get an error after killing spawned binary\n");
1664 if (!(dbus_error_has_name (&error, DBUS_ERROR_NO_MEMORY) ||
1665 dbus_error_has_name (&error, DBUS_ERROR_SPAWN_CHILD_SIGNALED)))
1667 _dbus_warn ("Not expecting error when killing executable: %s: %s\n",
1668 error.name, error.message);
1669 dbus_error_free (&error);
1673 dbus_error_free (&error);
1679 _dbus_spawn_test (const char *test_data_dir)
1681 if (!_dbus_test_oom_handling ("spawn_nonexistent",
1682 check_spawn_nonexistent,
1686 if (!_dbus_test_oom_handling ("spawn_segfault",
1687 check_spawn_segfault,
1691 if (!_dbus_test_oom_handling ("spawn_exit",
1696 if (!_dbus_test_oom_handling ("spawn_and_kill",
1697 check_spawn_and_kill,