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