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