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