1 /* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*- */
2 /* dbus-spawn.c Wrapper around fork/exec
3 *
4 * Copyright (C) 2002, 2003, 2004 Red Hat, Inc.
5 * Copyright (C) 2003 CodeFactory AB
6 *
7 * Licensed under the Academic Free License version 2.1
8 *
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.
13 *
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.
18 *
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
22 *
23 */
24
25 #include <config.h>
26
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"
32
33 #include <unistd.h>
34 #include <fcntl.h>
35 #include <signal.h>
36 #include <sys/wait.h>
37 #include <stdlib.h>
38 #ifdef HAVE_ERRNO_H
39 #include <errno.h>
40 #endif
41
42 extern char **environ;
43
44 /**
45 * @addtogroup DBusInternalsUtils
46 * @{
47 */
48
49 /*
50 * I'm pretty sure this whole spawn file could be made simpler,
51 * if you thought about it a bit.
52 */
53
54 /**
55 * Enumeration for status of a read()
56 */
57 typedef enum
58 {
59 READ_STATUS_OK, /**< Read succeeded */
60 READ_STATUS_ERROR, /**< Some kind of error */
61 READ_STATUS_EOF /**< EOF returned */
62 } ReadStatus;
63
64 static ReadStatus
read_ints(int fd,int * buf,int n_ints_in_buf,int * n_ints_read,DBusError * error)65 read_ints (int fd,
66 int *buf,
67 int n_ints_in_buf,
68 int *n_ints_read,
69 DBusError *error)
70 {
71 size_t bytes = 0;
72 ReadStatus retval;
73
74 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
75
76 retval = READ_STATUS_OK;
77
78 while (TRUE)
79 {
80 ssize_t chunk;
81 size_t to_read;
82
83 to_read = sizeof (int) * n_ints_in_buf - bytes;
84
85 if (to_read == 0)
86 break;
87
88 again:
89
90 chunk = read (fd,
91 ((char*)buf) + bytes,
92 to_read);
93
94 if (chunk < 0 && errno == EINTR)
95 goto again;
96
97 if (chunk < 0)
98 {
99 dbus_set_error (error,
100 DBUS_ERROR_SPAWN_FAILED,
101 "Failed to read from child pipe (%s)",
102 _dbus_strerror (errno));
103
104 retval = READ_STATUS_ERROR;
105 break;
106 }
107 else if (chunk == 0)
108 {
109 retval = READ_STATUS_EOF;
110 break; /* EOF */
111 }
112 else /* chunk > 0 */
113 bytes += chunk;
114 }
115
116 *n_ints_read = (int)(bytes / sizeof(int));
117
118 return retval;
119 }
120
121 static ReadStatus
read_pid(int fd,pid_t * buf,DBusError * error)122 read_pid (int fd,
123 pid_t *buf,
124 DBusError *error)
125 {
126 size_t bytes = 0;
127 ReadStatus retval;
128
129 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
130
131 retval = READ_STATUS_OK;
132
133 while (TRUE)
134 {
135 ssize_t chunk;
136 size_t to_read;
137
138 to_read = sizeof (pid_t) - bytes;
139
140 if (to_read == 0)
141 break;
142
143 again:
144
145 chunk = read (fd,
146 ((char*)buf) + bytes,
147 to_read);
148 if (chunk < 0 && errno == EINTR)
149 goto again;
150
151 if (chunk < 0)
152 {
153 dbus_set_error (error,
154 DBUS_ERROR_SPAWN_FAILED,
155 "Failed to read from child pipe (%s)",
156 _dbus_strerror (errno));
157
158 retval = READ_STATUS_ERROR;
159 break;
160 }
161 else if (chunk == 0)
162 {
163 retval = READ_STATUS_EOF;
164 break; /* EOF */
165 }
166 else /* chunk > 0 */
167 bytes += chunk;
168 }
169
170 return retval;
171 }
172
173 /* The implementation uses an intermediate child between the main process
174 * and the grandchild. The grandchild is our spawned process. The intermediate
175 * child is a babysitter process; it keeps track of when the grandchild
176 * exits/crashes, and reaps the grandchild.
177 */
178
179 /* Messages from children to parents */
180 enum
181 {
182 CHILD_EXITED, /* This message is followed by the exit status int */
183 CHILD_FORK_FAILED, /* Followed by errno */
184 CHILD_EXEC_FAILED, /* Followed by errno */
185 CHILD_PID /* Followed by pid_t */
186 };
187
188 /**
189 * Babysitter implementation details
190 */
191 struct DBusBabysitter
192 {
193 int refcount; /**< Reference count */
194
195 char *executable; /**< executable name to use in error messages */
196
197 int socket_to_babysitter; /**< Connection to the babysitter process */
198 int error_pipe_from_child; /**< Connection to the process that does the exec() */
199
200 pid_t sitter_pid; /**< PID Of the babysitter */
201 pid_t grandchild_pid; /**< PID of the grandchild */
202
203 DBusWatchList *watches; /**< Watches */
204
205 DBusWatch *error_watch; /**< Error pipe watch */
206 DBusWatch *sitter_watch; /**< Sitter pipe watch */
207
208 int errnum; /**< Error number */
209 int status; /**< Exit status code */
210 unsigned int have_child_status : 1; /**< True if child status has been reaped */
211 unsigned int have_fork_errnum : 1; /**< True if we have an error code from fork() */
212 unsigned int have_exec_errnum : 1; /**< True if we have an error code from exec() */
213 };
214
215 static DBusBabysitter*
_dbus_babysitter_new(void)216 _dbus_babysitter_new (void)
217 {
218 DBusBabysitter *sitter;
219
220 sitter = dbus_new0 (DBusBabysitter, 1);
221 if (sitter == NULL)
222 return NULL;
223
224 sitter->refcount = 1;
225
226 sitter->socket_to_babysitter = -1;
227 sitter->error_pipe_from_child = -1;
228
229 sitter->sitter_pid = -1;
230 sitter->grandchild_pid = -1;
231
232 sitter->watches = _dbus_watch_list_new ();
233 if (sitter->watches == NULL)
234 goto failed;
235
236 return sitter;
237
238 failed:
239 _dbus_babysitter_unref (sitter);
240 return NULL;
241 }
242
243 /**
244 * Increment the reference count on the babysitter object.
245 *
246 * @param sitter the babysitter
247 * @returns the babysitter
248 */
249 DBusBabysitter *
_dbus_babysitter_ref(DBusBabysitter * sitter)250 _dbus_babysitter_ref (DBusBabysitter *sitter)
251 {
252 _dbus_assert (sitter != NULL);
253 _dbus_assert (sitter->refcount > 0);
254
255 sitter->refcount += 1;
256
257 return sitter;
258 }
259
260 /**
261 * Decrement the reference count on the babysitter object.
262 * When the reference count of the babysitter object reaches
263 * zero, the babysitter is killed and the child that was being
264 * babysat gets emancipated.
265 *
266 * @param sitter the babysitter
267 */
268 void
_dbus_babysitter_unref(DBusBabysitter * sitter)269 _dbus_babysitter_unref (DBusBabysitter *sitter)
270 {
271 _dbus_assert (sitter != NULL);
272 _dbus_assert (sitter->refcount > 0);
273
274 sitter->refcount -= 1;
275 if (sitter->refcount == 0)
276 {
277 if (sitter->socket_to_babysitter >= 0)
278 {
279 /* If we haven't forked other babysitters
280 * since this babysitter and socket were
281 * created then this close will cause the
282 * babysitter to wake up from poll with
283 * a hangup and then the babysitter will
284 * quit itself.
285 */
286 _dbus_close_socket (sitter->socket_to_babysitter, NULL);
287 sitter->socket_to_babysitter = -1;
288 }
289
290 if (sitter->error_pipe_from_child >= 0)
291 {
292 _dbus_close_socket (sitter->error_pipe_from_child, NULL);
293 sitter->error_pipe_from_child = -1;
294 }
295
296 if (sitter->sitter_pid > 0)
297 {
298 int status;
299 int ret;
300
301 /* It's possible the babysitter died on its own above
302 * from the close, or was killed randomly
303 * by some other process, so first try to reap it
304 */
305 ret = waitpid (sitter->sitter_pid, &status, WNOHANG);
306
307 /* If we couldn't reap the child then kill it, and
308 * try again
309 */
310 if (ret == 0)
311 kill (sitter->sitter_pid, SIGKILL);
312
313 again:
314 if (ret == 0)
315 ret = waitpid (sitter->sitter_pid, &status, 0);
316
317 if (ret < 0)
318 {
319 if (errno == EINTR)
320 goto again;
321 else if (errno == ECHILD)
322 _dbus_warn ("Babysitter process not available to be reaped; should not happen\n");
323 else
324 _dbus_warn ("Unexpected error %d in waitpid() for babysitter: %s\n",
325 errno, _dbus_strerror (errno));
326 }
327 else
328 {
329 _dbus_verbose ("Reaped %ld, waiting for babysitter %ld\n",
330 (long) ret, (long) sitter->sitter_pid);
331
332 if (WIFEXITED (sitter->status))
333 _dbus_verbose ("Babysitter exited with status %d\n",
334 WEXITSTATUS (sitter->status));
335 else if (WIFSIGNALED (sitter->status))
336 _dbus_verbose ("Babysitter received signal %d\n",
337 WTERMSIG (sitter->status));
338 else
339 _dbus_verbose ("Babysitter exited abnormally\n");
340 }
341
342 sitter->sitter_pid = -1;
343 }
344
345 if (sitter->error_watch)
346 {
347 _dbus_watch_invalidate (sitter->error_watch);
348 _dbus_watch_unref (sitter->error_watch);
349 sitter->error_watch = NULL;
350 }
351
352 if (sitter->sitter_watch)
353 {
354 _dbus_watch_invalidate (sitter->sitter_watch);
355 _dbus_watch_unref (sitter->sitter_watch);
356 sitter->sitter_watch = NULL;
357 }
358
359 if (sitter->watches)
360 _dbus_watch_list_free (sitter->watches);
361
362 dbus_free (sitter->executable);
363
364 dbus_free (sitter);
365 }
366 }
367
368 static ReadStatus
read_data(DBusBabysitter * sitter,int fd)369 read_data (DBusBabysitter *sitter,
370 int fd)
371 {
372 int what;
373 int got;
374 DBusError error = DBUS_ERROR_INIT;
375 ReadStatus r;
376
377 r = read_ints (fd, &what, 1, &got, &error);
378
379 switch (r)
380 {
381 case READ_STATUS_ERROR:
382 _dbus_warn ("Failed to read data from fd %d: %s\n", fd, error.message);
383 dbus_error_free (&error);
384 return r;
385
386 case READ_STATUS_EOF:
387 return r;
388
389 case READ_STATUS_OK:
390 break;
391 }
392
393 if (got == 1)
394 {
395 switch (what)
396 {
397 case CHILD_EXITED:
398 case CHILD_FORK_FAILED:
399 case CHILD_EXEC_FAILED:
400 {
401 int arg;
402
403 r = read_ints (fd, &arg, 1, &got, &error);
404
405 switch (r)
406 {
407 case READ_STATUS_ERROR:
408 _dbus_warn ("Failed to read arg from fd %d: %s\n", fd, error.message);
409 dbus_error_free (&error);
410 return r;
411 case READ_STATUS_EOF:
412 return r;
413 case READ_STATUS_OK:
414 break;
415 }
416
417 if (got == 1)
418 {
419 if (what == CHILD_EXITED)
420 {
421 sitter->have_child_status = TRUE;
422 sitter->status = arg;
423 sitter->errnum = 0;
424 _dbus_verbose ("recorded child status exited = %d signaled = %d exitstatus = %d termsig = %d\n",
425 WIFEXITED (sitter->status), WIFSIGNALED (sitter->status),
426 WEXITSTATUS (sitter->status), WTERMSIG (sitter->status));
427 }
428 else if (what == CHILD_FORK_FAILED)
429 {
430 sitter->have_fork_errnum = TRUE;
431 sitter->errnum = arg;
432 _dbus_verbose ("recorded fork errnum %d\n", sitter->errnum);
433 }
434 else if (what == CHILD_EXEC_FAILED)
435 {
436 sitter->have_exec_errnum = TRUE;
437 sitter->errnum = arg;
438 _dbus_verbose ("recorded exec errnum %d\n", sitter->errnum);
439 }
440 }
441 }
442 break;
443 case CHILD_PID:
444 {
445 pid_t pid = -1;
446
447 r = read_pid (fd, &pid, &error);
448
449 switch (r)
450 {
451 case READ_STATUS_ERROR:
452 _dbus_warn ("Failed to read PID from fd %d: %s\n", fd, error.message);
453 dbus_error_free (&error);
454 return r;
455 case READ_STATUS_EOF:
456 return r;
457 case READ_STATUS_OK:
458 break;
459 }
460
461 sitter->grandchild_pid = pid;
462
463 _dbus_verbose ("recorded grandchild pid %d\n", sitter->grandchild_pid);
464 }
465 break;
466 default:
467 _dbus_warn ("Unknown message received from babysitter process\n");
468 break;
469 }
470 }
471
472 return r;
473 }
474
475 static void
close_socket_to_babysitter(DBusBabysitter * sitter)476 close_socket_to_babysitter (DBusBabysitter *sitter)
477 {
478 _dbus_verbose ("Closing babysitter\n");
479 _dbus_close_socket (sitter->socket_to_babysitter, NULL);
480 sitter->socket_to_babysitter = -1;
481 }
482
483 static void
close_error_pipe_from_child(DBusBabysitter * sitter)484 close_error_pipe_from_child (DBusBabysitter *sitter)
485 {
486 _dbus_verbose ("Closing child error\n");
487 _dbus_close_socket (sitter->error_pipe_from_child, NULL);
488 sitter->error_pipe_from_child = -1;
489 }
490
491 static void
handle_babysitter_socket(DBusBabysitter * sitter,int revents)492 handle_babysitter_socket (DBusBabysitter *sitter,
493 int revents)
494 {
495 /* Even if we have POLLHUP, we want to keep reading
496 * data until POLLIN goes away; so this function only
497 * looks at HUP/ERR if no IN is set.
498 */
499 if (revents & _DBUS_POLLIN)
500 {
501 _dbus_verbose ("Reading data from babysitter\n");
502 if (read_data (sitter, sitter->socket_to_babysitter) != READ_STATUS_OK)
503 close_socket_to_babysitter (sitter);
504 }
505 else if (revents & (_DBUS_POLLERR | _DBUS_POLLHUP))
506 {
507 close_socket_to_babysitter (sitter);
508 }
509 }
510
511 static void
handle_error_pipe(DBusBabysitter * sitter,int revents)512 handle_error_pipe (DBusBabysitter *sitter,
513 int revents)
514 {
515 if (revents & _DBUS_POLLIN)
516 {
517 _dbus_verbose ("Reading data from child error\n");
518 if (read_data (sitter, sitter->error_pipe_from_child) != READ_STATUS_OK)
519 close_error_pipe_from_child (sitter);
520 }
521 else if (revents & (_DBUS_POLLERR | _DBUS_POLLHUP))
522 {
523 close_error_pipe_from_child (sitter);
524 }
525 }
526
527 /* returns whether there were any poll events handled */
528 static dbus_bool_t
babysitter_iteration(DBusBabysitter * sitter,dbus_bool_t block)529 babysitter_iteration (DBusBabysitter *sitter,
530 dbus_bool_t block)
531 {
532 DBusPollFD fds[2];
533 int i;
534 dbus_bool_t descriptors_ready;
535
536 descriptors_ready = FALSE;
537
538 i = 0;
539
540 if (sitter->error_pipe_from_child >= 0)
541 {
542 fds[i].fd = sitter->error_pipe_from_child;
543 fds[i].events = _DBUS_POLLIN;
544 fds[i].revents = 0;
545 ++i;
546 }
547
548 if (sitter->socket_to_babysitter >= 0)
549 {
550 fds[i].fd = sitter->socket_to_babysitter;
551 fds[i].events = _DBUS_POLLIN;
552 fds[i].revents = 0;
553 ++i;
554 }
555
556 if (i > 0)
557 {
558 int ret;
559
560 do
561 {
562 ret = _dbus_poll (fds, i, 0);
563 }
564 while (ret < 0 && errno == EINTR);
565
566 if (ret == 0 && block)
567 {
568 do
569 {
570 ret = _dbus_poll (fds, i, -1);
571 }
572 while (ret < 0 && errno == EINTR);
573 }
574
575 if (ret > 0)
576 {
577 descriptors_ready = TRUE;
578
579 while (i > 0)
580 {
581 --i;
582 if (fds[i].fd == sitter->error_pipe_from_child)
583 handle_error_pipe (sitter, fds[i].revents);
584 else if (fds[i].fd == sitter->socket_to_babysitter)
585 handle_babysitter_socket (sitter, fds[i].revents);
586 }
587 }
588 }
589
590 return descriptors_ready;
591 }
592
593 /**
594 * Macro returns #TRUE if the babysitter still has live sockets open to the
595 * babysitter child or the grandchild.
596 */
597 #define LIVE_CHILDREN(sitter) ((sitter)->socket_to_babysitter >= 0 || (sitter)->error_pipe_from_child >= 0)
598
599 /**
600 * Blocks until the babysitter process gives us the PID of the spawned grandchild,
601 * then kills the spawned grandchild.
602 *
603 * @param sitter the babysitter object
604 */
605 void
_dbus_babysitter_kill_child(DBusBabysitter * sitter)606 _dbus_babysitter_kill_child (DBusBabysitter *sitter)
607 {
608 /* be sure we have the PID of the child */
609 while (LIVE_CHILDREN (sitter) &&
610 sitter->grandchild_pid == -1)
611 babysitter_iteration (sitter, TRUE);
612
613 _dbus_verbose ("Got child PID %ld for killing\n",
614 (long) sitter->grandchild_pid);
615
616 if (sitter->grandchild_pid == -1)
617 return; /* child is already dead, or we're so hosed we'll never recover */
618
619 kill (sitter->grandchild_pid, SIGKILL);
620 }
621
622 /**
623 * Checks whether the child has exited, without blocking.
624 *
625 * @param sitter the babysitter
626 */
627 dbus_bool_t
_dbus_babysitter_get_child_exited(DBusBabysitter * sitter)628 _dbus_babysitter_get_child_exited (DBusBabysitter *sitter)
629 {
630
631 /* Be sure we're up-to-date */
632 while (LIVE_CHILDREN (sitter) &&
633 babysitter_iteration (sitter, FALSE))
634 ;
635
636 /* We will have exited the babysitter when the child has exited */
637 return sitter->socket_to_babysitter < 0;
638 }
639
640 /**
641 * Gets the exit status of the child. We do this so implementation specific
642 * detail is not cluttering up dbus, for example the system launcher code.
643 * This can only be called if the child has exited, i.e. call
644 * _dbus_babysitter_get_child_exited(). It returns FALSE if the child
645 * did not return a status code, e.g. because the child was signaled
646 * or we failed to ever launch the child in the first place.
647 *
648 * @param sitter the babysitter
649 * @param status the returned status code
650 * @returns #FALSE on failure
651 */
652 dbus_bool_t
_dbus_babysitter_get_child_exit_status(DBusBabysitter * sitter,int * status)653 _dbus_babysitter_get_child_exit_status (DBusBabysitter *sitter,
654 int *status)
655 {
656 if (!_dbus_babysitter_get_child_exited (sitter))
657 _dbus_assert_not_reached ("Child has not exited");
658
659 if (!sitter->have_child_status ||
660 !(WIFEXITED (sitter->status)))
661 return FALSE;
662
663 *status = WEXITSTATUS (sitter->status);
664 return TRUE;
665 }
666
667 /**
668 * Sets the #DBusError with an explanation of why the spawned
669 * child process exited (on a signal, or whatever). If
670 * the child process has not exited, does nothing (error
671 * will remain unset).
672 *
673 * @param sitter the babysitter
674 * @param error an error to fill in
675 */
676 void
_dbus_babysitter_set_child_exit_error(DBusBabysitter * sitter,DBusError * error)677 _dbus_babysitter_set_child_exit_error (DBusBabysitter *sitter,
678 DBusError *error)
679 {
680 if (!_dbus_babysitter_get_child_exited (sitter))
681 return;
682
683 /* Note that if exec fails, we will also get a child status
684 * from the babysitter saying the child exited,
685 * so we need to give priority to the exec error
686 */
687 if (sitter->have_exec_errnum)
688 {
689 dbus_set_error (error, DBUS_ERROR_SPAWN_EXEC_FAILED,
690 "Failed to execute program %s: %s",
691 sitter->executable, _dbus_strerror (sitter->errnum));
692 }
693 else if (sitter->have_fork_errnum)
694 {
695 dbus_set_error (error, DBUS_ERROR_NO_MEMORY,
696 "Failed to fork a new process %s: %s",
697 sitter->executable, _dbus_strerror (sitter->errnum));
698 }
699 else if (sitter->have_child_status)
700 {
701 if (WIFEXITED (sitter->status))
702 dbus_set_error (error, DBUS_ERROR_SPAWN_CHILD_EXITED,
703 "Process %s exited with status %d",
704 sitter->executable, WEXITSTATUS (sitter->status));
705 else if (WIFSIGNALED (sitter->status))
706 dbus_set_error (error, DBUS_ERROR_SPAWN_CHILD_SIGNALED,
707 "Process %s received signal %d",
708 sitter->executable, WTERMSIG (sitter->status));
709 else
710 dbus_set_error (error, DBUS_ERROR_FAILED,
711 "Process %s exited abnormally",
712 sitter->executable);
713 }
714 else
715 {
716 dbus_set_error (error, DBUS_ERROR_FAILED,
717 "Process %s exited, reason unknown",
718 sitter->executable);
719 }
720 }
721
722 /**
723 * Sets watch functions to notify us when the
724 * babysitter object needs to read/write file descriptors.
725 *
726 * @param sitter the babysitter
727 * @param add_function function to begin monitoring a new descriptor.
728 * @param remove_function function to stop monitoring a descriptor.
729 * @param toggled_function function to notify when the watch is enabled/disabled
730 * @param data data to pass to add_function and remove_function.
731 * @param free_data_function function to be called to free the data.
732 * @returns #FALSE on failure (no memory)
733 */
734 dbus_bool_t
_dbus_babysitter_set_watch_functions(DBusBabysitter * sitter,DBusAddWatchFunction add_function,DBusRemoveWatchFunction remove_function,DBusWatchToggledFunction toggled_function,void * data,DBusFreeFunction free_data_function)735 _dbus_babysitter_set_watch_functions (DBusBabysitter *sitter,
736 DBusAddWatchFunction add_function,
737 DBusRemoveWatchFunction remove_function,
738 DBusWatchToggledFunction toggled_function,
739 void *data,
740 DBusFreeFunction free_data_function)
741 {
742 return _dbus_watch_list_set_functions (sitter->watches,
743 add_function,
744 remove_function,
745 toggled_function,
746 data,
747 free_data_function);
748 }
749
750 static dbus_bool_t
handle_watch(DBusWatch * watch,unsigned int condition,void * data)751 handle_watch (DBusWatch *watch,
752 unsigned int condition,
753 void *data)
754 {
755 DBusBabysitter *sitter = data;
756 int revents;
757 int fd;
758
759 revents = 0;
760 if (condition & DBUS_WATCH_READABLE)
761 revents |= _DBUS_POLLIN;
762 if (condition & DBUS_WATCH_ERROR)
763 revents |= _DBUS_POLLERR;
764 if (condition & DBUS_WATCH_HANGUP)
765 revents |= _DBUS_POLLHUP;
766
767 fd = dbus_watch_get_socket (watch);
768
769 if (fd == sitter->error_pipe_from_child)
770 handle_error_pipe (sitter, revents);
771 else if (fd == sitter->socket_to_babysitter)
772 handle_babysitter_socket (sitter, revents);
773
774 while (LIVE_CHILDREN (sitter) &&
775 babysitter_iteration (sitter, FALSE))
776 ;
777
778 return TRUE;
779 }
780
781 /** Helps remember which end of the pipe is which */
782 #define READ_END 0
783 /** Helps remember which end of the pipe is which */
784 #define WRITE_END 1
785
786
787 /* Avoids a danger in threaded situations (calling close()
788 * on a file descriptor twice, and another thread has
789 * re-opened it since the first close)
790 */
791 static int
close_and_invalidate(int * fd)792 close_and_invalidate (int *fd)
793 {
794 int ret;
795
796 if (*fd < 0)
797 return -1;
798 else
799 {
800 ret = _dbus_close_socket (*fd, NULL);
801 *fd = -1;
802 }
803
804 return ret;
805 }
806
807 static dbus_bool_t
make_pipe(int p[2],DBusError * error)808 make_pipe (int p[2],
809 DBusError *error)
810 {
811 int retval;
812
813 #ifdef HAVE_PIPE2
814 dbus_bool_t cloexec_done;
815
816 retval = pipe2 (p, O_CLOEXEC);
817 cloexec_done = retval >= 0;
818
819 /* Check if kernel seems to be too old to know pipe2(). We assume
820 that if pipe2 is available, O_CLOEXEC is too. */
821 if (retval < 0 && errno == ENOSYS)
822 #endif
823 {
824 retval = pipe(p);
825 }
826
827 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
828
829 if (retval < 0)
830 {
831 dbus_set_error (error,
832 DBUS_ERROR_SPAWN_FAILED,
833 "Failed to create pipe for communicating with child process (%s)",
834 _dbus_strerror (errno));
835 return FALSE;
836 }
837
838 #ifdef HAVE_PIPE2
839 if (!cloexec_done)
840 #endif
841 {
842 _dbus_fd_set_close_on_exec (p[0]);
843 _dbus_fd_set_close_on_exec (p[1]);
844 }
845
846 return TRUE;
847 }
848
849 static void
do_write(int fd,const void * buf,size_t count)850 do_write (int fd, const void *buf, size_t count)
851 {
852 size_t bytes_written;
853 int ret;
854
855 bytes_written = 0;
856
857 again:
858
859 ret = write (fd, ((const char*)buf) + bytes_written, count - bytes_written);
860
861 if (ret < 0)
862 {
863 if (errno == EINTR)
864 goto again;
865 else
866 {
867 _dbus_warn ("Failed to write data to pipe!\n");
868 exit (1); /* give up, we suck */
869 }
870 }
871 else
872 bytes_written += ret;
873
874 if (bytes_written < count)
875 goto again;
876 }
877
878 static void
write_err_and_exit(int fd,int msg)879 write_err_and_exit (int fd, int msg)
880 {
881 int en = errno;
882
883 do_write (fd, &msg, sizeof (msg));
884 do_write (fd, &en, sizeof (en));
885
886 exit (1);
887 }
888
889 static void
write_pid(int fd,pid_t pid)890 write_pid (int fd, pid_t pid)
891 {
892 int msg = CHILD_PID;
893
894 do_write (fd, &msg, sizeof (msg));
895 do_write (fd, &pid, sizeof (pid));
896 }
897
898 static void
write_status_and_exit(int fd,int status)899 write_status_and_exit (int fd, int status)
900 {
901 int msg = CHILD_EXITED;
902
903 do_write (fd, &msg, sizeof (msg));
904 do_write (fd, &status, sizeof (status));
905
906 exit (0);
907 }
908
909 static void
do_exec(int child_err_report_fd,char ** argv,char ** envp,DBusSpawnChildSetupFunc child_setup,void * user_data)910 do_exec (int child_err_report_fd,
911 char **argv,
912 char **envp,
913 DBusSpawnChildSetupFunc child_setup,
914 void *user_data)
915 {
916 #ifdef DBUS_BUILD_TESTS
917 int i, max_open;
918 #endif
919
920 _dbus_verbose_reset ();
921 _dbus_verbose ("Child process has PID " DBUS_PID_FORMAT "\n",
922 _dbus_getpid ());
923
924 if (child_setup)
925 (* child_setup) (user_data);
926
927 #ifdef DBUS_BUILD_TESTS
928 max_open = sysconf (_SC_OPEN_MAX);
929
930 for (i = 3; i < max_open; i++)
931 {
932 int retval;
933
934 if (i == child_err_report_fd)
935 continue;
936
937 retval = fcntl (i, F_GETFD);
938
939 if (retval != -1 && !(retval & FD_CLOEXEC))
940 _dbus_warn ("Fd %d did not have the close-on-exec flag set!\n", i);
941 }
942 #endif
943
944 if (envp == NULL)
945 {
946 _dbus_assert (environ != NULL);
947
948 envp = environ;
949 }
950
951 execve (argv[0], argv, envp);
952
953 /* Exec failed */
954 write_err_and_exit (child_err_report_fd,
955 CHILD_EXEC_FAILED);
956 }
957
958 static void
check_babysit_events(pid_t grandchild_pid,int parent_pipe,int revents)959 check_babysit_events (pid_t grandchild_pid,
960 int parent_pipe,
961 int revents)
962 {
963 pid_t ret;
964 int status;
965
966 do
967 {
968 ret = waitpid (grandchild_pid, &status, WNOHANG);
969 /* The man page says EINTR can't happen with WNOHANG,
970 * but there are reports of it (maybe only with valgrind?)
971 */
972 }
973 while (ret < 0 && errno == EINTR);
974
975 if (ret == 0)
976 {
977 _dbus_verbose ("no child exited\n");
978
979 ; /* no child exited */
980 }
981 else if (ret < 0)
982 {
983 /* This isn't supposed to happen. */
984 _dbus_warn ("unexpected waitpid() failure in check_babysit_events(): %s\n",
985 _dbus_strerror (errno));
986 exit (1);
987 }
988 else if (ret == grandchild_pid)
989 {
990 /* Child exited */
991 _dbus_verbose ("reaped child pid %ld\n", (long) ret);
992
993 write_status_and_exit (parent_pipe, status);
994 }
995 else
996 {
997 _dbus_warn ("waitpid() reaped pid %d that we've never heard of\n",
998 (int) ret);
999 exit (1);
1000 }
1001
1002 if (revents & _DBUS_POLLIN)
1003 {
1004 _dbus_verbose ("babysitter got POLLIN from parent pipe\n");
1005 }
1006
1007 if (revents & (_DBUS_POLLERR | _DBUS_POLLHUP))
1008 {
1009 /* Parent is gone, so we just exit */
1010 _dbus_verbose ("babysitter got POLLERR or POLLHUP from parent\n");
1011 exit (0);
1012 }
1013 }
1014
1015 static int babysit_sigchld_pipe = -1;
1016
1017 static void
babysit_signal_handler(int signo)1018 babysit_signal_handler (int signo)
1019 {
1020 char b = '\0';
1021 again:
1022 if (write (babysit_sigchld_pipe, &b, 1) <= 0)
1023 if (errno == EINTR)
1024 goto again;
1025 }
1026
1027 static void
babysit(pid_t grandchild_pid,int parent_pipe)1028 babysit (pid_t grandchild_pid,
1029 int parent_pipe)
1030 {
1031 int sigchld_pipe[2];
1032
1033 /* We don't exec, so we keep parent state, such as the pid that
1034 * _dbus_verbose() uses. Reset the pid here.
1035 */
1036 _dbus_verbose_reset ();
1037
1038 /* I thought SIGCHLD would just wake up the poll, but
1039 * that didn't seem to work, so added this pipe.
1040 * Probably the pipe is more likely to work on busted
1041 * operating systems anyhow.
1042 */
1043 if (pipe (sigchld_pipe) < 0)
1044 {
1045 _dbus_warn ("Not enough file descriptors to create pipe in babysitter process\n");
1046 exit (1);
1047 }
1048
1049 babysit_sigchld_pipe = sigchld_pipe[WRITE_END];
1050
1051 _dbus_set_signal_handler (SIGCHLD, babysit_signal_handler);
1052
1053 write_pid (parent_pipe, grandchild_pid);
1054
1055 check_babysit_events (grandchild_pid, parent_pipe, 0);
1056
1057 while (TRUE)
1058 {
1059 DBusPollFD pfds[2];
1060
1061 pfds[0].fd = parent_pipe;
1062 pfds[0].events = _DBUS_POLLIN;
1063 pfds[0].revents = 0;
1064
1065 pfds[1].fd = sigchld_pipe[READ_END];
1066 pfds[1].events = _DBUS_POLLIN;
1067 pfds[1].revents = 0;
1068
1069 if (_dbus_poll (pfds, _DBUS_N_ELEMENTS (pfds), -1) < 0 && errno != EINTR)
1070 {
1071 _dbus_warn ("_dbus_poll() error: %s\n", strerror (errno));
1072 exit (1);
1073 }
1074
1075 if (pfds[0].revents != 0)
1076 {
1077 check_babysit_events (grandchild_pid, parent_pipe, pfds[0].revents);
1078 }
1079 else if (pfds[1].revents & _DBUS_POLLIN)
1080 {
1081 char b;
1082 if (read (sigchld_pipe[READ_END], &b, 1) == -1)
1083 /* ignore */;
1084 /* do waitpid check */
1085 check_babysit_events (grandchild_pid, parent_pipe, 0);
1086 }
1087 }
1088
1089 exit (1);
1090 }
1091
1092 /**
1093 * Spawns a new process. The executable name and argv[0]
1094 * are the same, both are provided in argv[0]. The child_setup
1095 * function is passed the given user_data and is run in the child
1096 * just before calling exec().
1097 *
1098 * Also creates a "babysitter" which tracks the status of the
1099 * child process, advising the parent if the child exits.
1100 * If the spawn fails, no babysitter is created.
1101 * If sitter_p is #NULL, no babysitter is kept.
1102 *
1103 * @param sitter_p return location for babysitter or #NULL
1104 * @param argv the executable and arguments
1105 * @param env the environment (not used on unix yet)
1106 * @param child_setup function to call in child pre-exec()
1107 * @param user_data user data for setup function
1108 * @param error error object to be filled in if function fails
1109 * @returns #TRUE on success, #FALSE if error is filled in
1110 */
1111 dbus_bool_t
_dbus_spawn_async_with_babysitter(DBusBabysitter ** sitter_p,char ** argv,char ** env,DBusSpawnChildSetupFunc child_setup,void * user_data,DBusError * error)1112 _dbus_spawn_async_with_babysitter (DBusBabysitter **sitter_p,
1113 char **argv,
1114 char **env,
1115 DBusSpawnChildSetupFunc child_setup,
1116 void *user_data,
1117 DBusError *error)
1118 {
1119 DBusBabysitter *sitter;
1120 int child_err_report_pipe[2] = { -1, -1 };
1121 int babysitter_pipe[2] = { -1, -1 };
1122 pid_t pid;
1123
1124 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1125
1126 if (sitter_p != NULL)
1127 *sitter_p = NULL;
1128
1129 sitter = NULL;
1130
1131 sitter = _dbus_babysitter_new ();
1132 if (sitter == NULL)
1133 {
1134 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1135 return FALSE;
1136 }
1137
1138 sitter->executable = _dbus_strdup (argv[0]);
1139 if (sitter->executable == NULL)
1140 {
1141 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1142 goto cleanup_and_fail;
1143 }
1144
1145 if (!make_pipe (child_err_report_pipe, error))
1146 goto cleanup_and_fail;
1147
1148 if (!_dbus_full_duplex_pipe (&babysitter_pipe[0], &babysitter_pipe[1], TRUE, error))
1149 goto cleanup_and_fail;
1150
1151 /* Setting up the babysitter is only useful in the parent,
1152 * but we don't want to run out of memory and fail
1153 * after we've already forked, since then we'd leak
1154 * child processes everywhere.
1155 */
1156 sitter->error_watch = _dbus_watch_new (child_err_report_pipe[READ_END],
1157 DBUS_WATCH_READABLE,
1158 TRUE, handle_watch, sitter, NULL);
1159 if (sitter->error_watch == NULL)
1160 {
1161 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1162 goto cleanup_and_fail;
1163 }
1164
1165 if (!_dbus_watch_list_add_watch (sitter->watches, sitter->error_watch))
1166 {
1167 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1168 goto cleanup_and_fail;
1169 }
1170
1171 sitter->sitter_watch = _dbus_watch_new (babysitter_pipe[0],
1172 DBUS_WATCH_READABLE,
1173 TRUE, handle_watch, sitter, NULL);
1174 if (sitter->sitter_watch == NULL)
1175 {
1176 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1177 goto cleanup_and_fail;
1178 }
1179
1180 if (!_dbus_watch_list_add_watch (sitter->watches, sitter->sitter_watch))
1181 {
1182 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1183 goto cleanup_and_fail;
1184 }
1185
1186 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1187
1188 pid = fork ();
1189
1190 if (pid < 0)
1191 {
1192 dbus_set_error (error,
1193 DBUS_ERROR_SPAWN_FORK_FAILED,
1194 "Failed to fork (%s)",
1195 _dbus_strerror (errno));
1196 goto cleanup_and_fail;
1197 }
1198 else if (pid == 0)
1199 {
1200 /* Immediate child, this is the babysitter process. */
1201 int grandchild_pid;
1202
1203 /* Be sure we crash if the parent exits
1204 * and we write to the err_report_pipe
1205 */
1206 signal (SIGPIPE, SIG_DFL);
1207
1208 /* Close the parent's end of the pipes. */
1209 close_and_invalidate (&child_err_report_pipe[READ_END]);
1210 close_and_invalidate (&babysitter_pipe[0]);
1211
1212 /* Create the child that will exec () */
1213 grandchild_pid = fork ();
1214
1215 if (grandchild_pid < 0)
1216 {
1217 write_err_and_exit (babysitter_pipe[1],
1218 CHILD_FORK_FAILED);
1219 _dbus_assert_not_reached ("Got to code after write_err_and_exit()");
1220 }
1221 else if (grandchild_pid == 0)
1222 {
1223 do_exec (child_err_report_pipe[WRITE_END],
1224 argv,
1225 env,
1226 child_setup, user_data);
1227 _dbus_assert_not_reached ("Got to code after exec() - should have exited on error");
1228 }
1229 else
1230 {
1231 babysit (grandchild_pid, babysitter_pipe[1]);
1232 _dbus_assert_not_reached ("Got to code after babysit()");
1233 }
1234 }
1235 else
1236 {
1237 /* Close the uncared-about ends of the pipes */
1238 close_and_invalidate (&child_err_report_pipe[WRITE_END]);
1239 close_and_invalidate (&babysitter_pipe[1]);
1240
1241 sitter->socket_to_babysitter = babysitter_pipe[0];
1242 babysitter_pipe[0] = -1;
1243
1244 sitter->error_pipe_from_child = child_err_report_pipe[READ_END];
1245 child_err_report_pipe[READ_END] = -1;
1246
1247 sitter->sitter_pid = pid;
1248
1249 if (sitter_p != NULL)
1250 *sitter_p = sitter;
1251 else
1252 _dbus_babysitter_unref (sitter);
1253
1254 dbus_free_string_array (env);
1255
1256 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1257
1258 return TRUE;
1259 }
1260
1261 cleanup_and_fail:
1262
1263 _DBUS_ASSERT_ERROR_IS_SET (error);
1264
1265 close_and_invalidate (&child_err_report_pipe[READ_END]);
1266 close_and_invalidate (&child_err_report_pipe[WRITE_END]);
1267 close_and_invalidate (&babysitter_pipe[0]);
1268 close_and_invalidate (&babysitter_pipe[1]);
1269
1270 if (sitter != NULL)
1271 _dbus_babysitter_unref (sitter);
1272
1273 return FALSE;
1274 }
1275
1276 /** @} */
1277
1278 #ifdef DBUS_BUILD_TESTS
1279
1280 static void
_dbus_babysitter_block_for_child_exit(DBusBabysitter * sitter)1281 _dbus_babysitter_block_for_child_exit (DBusBabysitter *sitter)
1282 {
1283 while (LIVE_CHILDREN (sitter))
1284 babysitter_iteration (sitter, TRUE);
1285 }
1286
1287 static dbus_bool_t
check_spawn_nonexistent(void * data)1288 check_spawn_nonexistent (void *data)
1289 {
1290 char *argv[4] = { NULL, NULL, NULL, NULL };
1291 DBusBabysitter *sitter = NULL;
1292 DBusError error = DBUS_ERROR_INIT;
1293
1294 /*** Test launching nonexistent binary */
1295
1296 argv[0] = "/this/does/not/exist/32542sdgafgafdg";
1297 if (_dbus_spawn_async_with_babysitter (&sitter, argv,
1298 NULL, NULL, NULL,
1299 &error))
1300 {
1301 _dbus_babysitter_block_for_child_exit (sitter);
1302 _dbus_babysitter_set_child_exit_error (sitter, &error);
1303 }
1304
1305 if (sitter)
1306 _dbus_babysitter_unref (sitter);
1307
1308 if (!dbus_error_is_set (&error))
1309 {
1310 _dbus_warn ("Did not get an error launching nonexistent executable\n");
1311 return FALSE;
1312 }
1313
1314 if (!(dbus_error_has_name (&error, DBUS_ERROR_NO_MEMORY) ||
1315 dbus_error_has_name (&error, DBUS_ERROR_SPAWN_EXEC_FAILED)))
1316 {
1317 _dbus_warn ("Not expecting error when launching nonexistent executable: %s: %s\n",
1318 error.name, error.message);
1319 dbus_error_free (&error);
1320 return FALSE;
1321 }
1322
1323 dbus_error_free (&error);
1324
1325 return TRUE;
1326 }
1327
1328 static dbus_bool_t
check_spawn_segfault(void * data)1329 check_spawn_segfault (void *data)
1330 {
1331 char *argv[4] = { NULL, NULL, NULL, NULL };
1332 DBusBabysitter *sitter = NULL;
1333 DBusError error = DBUS_ERROR_INIT;
1334
1335 /*** Test launching segfault binary */
1336
1337 argv[0] = TEST_SEGFAULT_BINARY;
1338 if (_dbus_spawn_async_with_babysitter (&sitter, argv,
1339 NULL, NULL, NULL,
1340 &error))
1341 {
1342 _dbus_babysitter_block_for_child_exit (sitter);
1343 _dbus_babysitter_set_child_exit_error (sitter, &error);
1344 }
1345
1346 if (sitter)
1347 _dbus_babysitter_unref (sitter);
1348
1349 if (!dbus_error_is_set (&error))
1350 {
1351 _dbus_warn ("Did not get an error launching segfaulting binary\n");
1352 return FALSE;
1353 }
1354
1355 if (!(dbus_error_has_name (&error, DBUS_ERROR_NO_MEMORY) ||
1356 dbus_error_has_name (&error, DBUS_ERROR_SPAWN_CHILD_SIGNALED)))
1357 {
1358 _dbus_warn ("Not expecting error when launching segfaulting executable: %s: %s\n",
1359 error.name, error.message);
1360 dbus_error_free (&error);
1361 return FALSE;
1362 }
1363
1364 dbus_error_free (&error);
1365
1366 return TRUE;
1367 }
1368
1369 static dbus_bool_t
check_spawn_exit(void * data)1370 check_spawn_exit (void *data)
1371 {
1372 char *argv[4] = { NULL, NULL, NULL, NULL };
1373 DBusBabysitter *sitter = NULL;
1374 DBusError error = DBUS_ERROR_INIT;
1375
1376 /*** Test launching exit failure binary */
1377
1378 argv[0] = TEST_EXIT_BINARY;
1379 if (_dbus_spawn_async_with_babysitter (&sitter, argv,
1380 NULL, NULL, NULL,
1381 &error))
1382 {
1383 _dbus_babysitter_block_for_child_exit (sitter);
1384 _dbus_babysitter_set_child_exit_error (sitter, &error);
1385 }
1386
1387 if (sitter)
1388 _dbus_babysitter_unref (sitter);
1389
1390 if (!dbus_error_is_set (&error))
1391 {
1392 _dbus_warn ("Did not get an error launching binary that exited with failure code\n");
1393 return FALSE;
1394 }
1395
1396 if (!(dbus_error_has_name (&error, DBUS_ERROR_NO_MEMORY) ||
1397 dbus_error_has_name (&error, DBUS_ERROR_SPAWN_CHILD_EXITED)))
1398 {
1399 _dbus_warn ("Not expecting error when launching exiting executable: %s: %s\n",
1400 error.name, error.message);
1401 dbus_error_free (&error);
1402 return FALSE;
1403 }
1404
1405 dbus_error_free (&error);
1406
1407 return TRUE;
1408 }
1409
1410 static dbus_bool_t
check_spawn_and_kill(void * data)1411 check_spawn_and_kill (void *data)
1412 {
1413 char *argv[4] = { NULL, NULL, NULL, NULL };
1414 DBusBabysitter *sitter = NULL;
1415 DBusError error = DBUS_ERROR_INIT;
1416
1417 /*** Test launching sleeping binary then killing it */
1418
1419 argv[0] = TEST_SLEEP_FOREVER_BINARY;
1420 if (_dbus_spawn_async_with_babysitter (&sitter, argv,
1421 NULL, NULL, NULL,
1422 &error))
1423 {
1424 _dbus_babysitter_kill_child (sitter);
1425
1426 _dbus_babysitter_block_for_child_exit (sitter);
1427
1428 _dbus_babysitter_set_child_exit_error (sitter, &error);
1429 }
1430
1431 if (sitter)
1432 _dbus_babysitter_unref (sitter);
1433
1434 if (!dbus_error_is_set (&error))
1435 {
1436 _dbus_warn ("Did not get an error after killing spawned binary\n");
1437 return FALSE;
1438 }
1439
1440 if (!(dbus_error_has_name (&error, DBUS_ERROR_NO_MEMORY) ||
1441 dbus_error_has_name (&error, DBUS_ERROR_SPAWN_CHILD_SIGNALED)))
1442 {
1443 _dbus_warn ("Not expecting error when killing executable: %s: %s\n",
1444 error.name, error.message);
1445 dbus_error_free (&error);
1446 return FALSE;
1447 }
1448
1449 dbus_error_free (&error);
1450
1451 return TRUE;
1452 }
1453
1454 dbus_bool_t
_dbus_spawn_test(const char * test_data_dir)1455 _dbus_spawn_test (const char *test_data_dir)
1456 {
1457 if (!_dbus_test_oom_handling ("spawn_nonexistent",
1458 check_spawn_nonexistent,
1459 NULL))
1460 return FALSE;
1461
1462 if (!_dbus_test_oom_handling ("spawn_segfault",
1463 check_spawn_segfault,
1464 NULL))
1465 return FALSE;
1466
1467 if (!_dbus_test_oom_handling ("spawn_exit",
1468 check_spawn_exit,
1469 NULL))
1470 return FALSE;
1471
1472 if (!_dbus_test_oom_handling ("spawn_and_kill",
1473 check_spawn_and_kill,
1474 NULL))
1475 return FALSE;
1476
1477 return TRUE;
1478 }
1479 #endif
1480