Merge branch 'master' of ssh://walters@git.freedesktop.org/git/dbus/dbus
[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       ssize_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       ssize_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 = DBUS_ERROR_INIT;
370   ReadStatus r;
371
372   r = read_ints (fd, &what, 1, &got, &error);
373
374   switch (r)
375     {
376     case READ_STATUS_ERROR:
377       _dbus_warn ("Failed to read data from fd %d: %s\n", fd, error.message);
378       dbus_error_free (&error);
379       return r;
380
381     case READ_STATUS_EOF:
382       return r;
383
384     case READ_STATUS_OK:
385       break;
386     }
387   
388   if (got == 1)
389     {
390       switch (what)
391         {
392         case CHILD_EXITED:
393         case CHILD_FORK_FAILED:
394         case CHILD_EXEC_FAILED:
395           {
396             int arg;
397             
398             r = read_ints (fd, &arg, 1, &got, &error);
399
400             switch (r)
401               {
402               case READ_STATUS_ERROR:
403                 _dbus_warn ("Failed to read arg from fd %d: %s\n", fd, error.message);
404                 dbus_error_free (&error);
405                 return r;
406               case READ_STATUS_EOF:
407                 return r;
408               case READ_STATUS_OK:
409                 break;
410               }
411             
412             if (got == 1)
413               {
414                 if (what == CHILD_EXITED)
415                   {
416                     sitter->have_child_status = TRUE;
417                     sitter->status = arg;
418                     sitter->errnum = 0;
419                     _dbus_verbose ("recorded child status exited = %d signaled = %d exitstatus = %d termsig = %d\n",
420                                    WIFEXITED (sitter->status), WIFSIGNALED (sitter->status),
421                                    WEXITSTATUS (sitter->status), WTERMSIG (sitter->status));
422                   }
423                 else if (what == CHILD_FORK_FAILED)
424                   {
425                     sitter->have_fork_errnum = TRUE;
426                     sitter->errnum = arg;
427                     _dbus_verbose ("recorded fork errnum %d\n", sitter->errnum);
428                   }
429                 else if (what == CHILD_EXEC_FAILED)
430                   {
431                     sitter->have_exec_errnum = TRUE;
432                     sitter->errnum = arg;
433                     _dbus_verbose ("recorded exec errnum %d\n", sitter->errnum);
434                   }
435               }
436           }
437           break;
438         case CHILD_PID:
439           {
440             pid_t pid = -1;
441
442             r = read_pid (fd, &pid, &error);
443             
444             switch (r)
445               {
446               case READ_STATUS_ERROR:
447                 _dbus_warn ("Failed to read PID from fd %d: %s\n", fd, error.message);
448                 dbus_error_free (&error);
449                 return r;
450               case READ_STATUS_EOF:
451                 return r;
452               case READ_STATUS_OK:
453                 break;
454               }
455             
456             sitter->grandchild_pid = pid;
457             
458             _dbus_verbose ("recorded grandchild pid %d\n", sitter->grandchild_pid);
459           }
460           break;
461         default:
462           _dbus_warn ("Unknown message received from babysitter process\n");
463           break;
464         }
465     }
466
467   return r;
468 }
469
470 static void
471 close_socket_to_babysitter (DBusBabysitter *sitter)
472 {
473   _dbus_verbose ("Closing babysitter\n");
474   _dbus_close_socket (sitter->socket_to_babysitter, NULL);
475   sitter->socket_to_babysitter = -1;
476 }
477
478 static void
479 close_error_pipe_from_child (DBusBabysitter *sitter)
480 {
481   _dbus_verbose ("Closing child error\n");
482   _dbus_close_socket (sitter->error_pipe_from_child, NULL);
483   sitter->error_pipe_from_child = -1;
484 }
485
486 static void
487 handle_babysitter_socket (DBusBabysitter *sitter,
488                           int             revents)
489 {
490   /* Even if we have POLLHUP, we want to keep reading
491    * data until POLLIN goes away; so this function only
492    * looks at HUP/ERR if no IN is set.
493    */
494   if (revents & _DBUS_POLLIN)
495     {
496       _dbus_verbose ("Reading data from babysitter\n");
497       if (read_data (sitter, sitter->socket_to_babysitter) != READ_STATUS_OK)
498         close_socket_to_babysitter (sitter);
499     }
500   else if (revents & (_DBUS_POLLERR | _DBUS_POLLHUP))
501     {
502       close_socket_to_babysitter (sitter);
503     }
504 }
505
506 static void
507 handle_error_pipe (DBusBabysitter *sitter,
508                    int             revents)
509 {
510   if (revents & _DBUS_POLLIN)
511     {
512       _dbus_verbose ("Reading data from child error\n");
513       if (read_data (sitter, sitter->error_pipe_from_child) != READ_STATUS_OK)
514         close_error_pipe_from_child (sitter);
515     }
516   else if (revents & (_DBUS_POLLERR | _DBUS_POLLHUP))
517     {
518       close_error_pipe_from_child (sitter);
519     }
520 }
521
522 /* returns whether there were any poll events handled */
523 static dbus_bool_t
524 babysitter_iteration (DBusBabysitter *sitter,
525                       dbus_bool_t     block)
526 {
527   DBusPollFD fds[2];
528   int i;
529   dbus_bool_t descriptors_ready;
530
531   descriptors_ready = FALSE;
532   
533   i = 0;
534
535   if (sitter->error_pipe_from_child >= 0)
536     {
537       fds[i].fd = sitter->error_pipe_from_child;
538       fds[i].events = _DBUS_POLLIN;
539       fds[i].revents = 0;
540       ++i;
541     }
542   
543   if (sitter->socket_to_babysitter >= 0)
544     {
545       fds[i].fd = sitter->socket_to_babysitter;
546       fds[i].events = _DBUS_POLLIN;
547       fds[i].revents = 0;
548       ++i;
549     }
550
551   if (i > 0)
552     {
553       int ret;
554
555       do
556         {
557           ret = _dbus_poll (fds, i, 0);
558         }
559       while (ret < 0 && errno == EINTR);
560
561       if (ret == 0 && block)
562         {
563           do
564             {
565               ret = _dbus_poll (fds, i, -1);
566             }
567           while (ret < 0 && errno == EINTR);
568         }
569
570       if (ret > 0)
571         {
572           descriptors_ready = TRUE;
573           
574           while (i > 0)
575             {
576               --i;
577               if (fds[i].fd == sitter->error_pipe_from_child)
578                 handle_error_pipe (sitter, fds[i].revents);
579               else if (fds[i].fd == sitter->socket_to_babysitter)
580                 handle_babysitter_socket (sitter, fds[i].revents);
581             }
582         }
583     }
584
585   return descriptors_ready;
586 }
587
588 /**
589  * Macro returns #TRUE if the babysitter still has live sockets open to the
590  * babysitter child or the grandchild.
591  */
592 #define LIVE_CHILDREN(sitter) ((sitter)->socket_to_babysitter >= 0 || (sitter)->error_pipe_from_child >= 0)
593
594 /**
595  * Blocks until the babysitter process gives us the PID of the spawned grandchild,
596  * then kills the spawned grandchild.
597  *
598  * @param sitter the babysitter object
599  */
600 void
601 _dbus_babysitter_kill_child (DBusBabysitter *sitter)
602 {
603   /* be sure we have the PID of the child */
604   while (LIVE_CHILDREN (sitter) &&
605          sitter->grandchild_pid == -1)
606     babysitter_iteration (sitter, TRUE);
607
608   _dbus_verbose ("Got child PID %ld for killing\n",
609                  (long) sitter->grandchild_pid);
610   
611   if (sitter->grandchild_pid == -1)
612     return; /* child is already dead, or we're so hosed we'll never recover */
613
614   kill (sitter->grandchild_pid, SIGKILL);
615 }
616
617 /**
618  * Checks whether the child has exited, without blocking.
619  *
620  * @param sitter the babysitter
621  */
622 dbus_bool_t
623 _dbus_babysitter_get_child_exited (DBusBabysitter *sitter)
624 {
625
626   /* Be sure we're up-to-date */
627   while (LIVE_CHILDREN (sitter) &&
628          babysitter_iteration (sitter, FALSE))
629     ;
630
631   /* We will have exited the babysitter when the child has exited */
632   return sitter->socket_to_babysitter < 0;
633 }
634
635 /**
636  * Gets the exit status of the child. We do this so implementation specific
637  * detail is not cluttering up dbus, for example the system launcher code.
638  * This can only be called if the child has exited, i.e. call
639  * _dbus_babysitter_get_child_exited(). It returns FALSE if the child
640  * did not return a status code, e.g. because the child was signaled
641  * or we failed to ever launch the child in the first place.
642  *
643  * @param sitter the babysitter
644  * @param status the returned status code
645  * @returns #FALSE on failure
646  */
647 dbus_bool_t
648 _dbus_babysitter_get_child_exit_status (DBusBabysitter *sitter,
649                                         int            *status)
650 {
651   if (!_dbus_babysitter_get_child_exited (sitter))
652     _dbus_assert_not_reached ("Child has not exited");
653   
654   if (!sitter->have_child_status ||
655       !(WIFEXITED (sitter->status)))
656     return FALSE;
657
658   *status = WEXITSTATUS (sitter->status);
659   return TRUE;
660 }
661
662 /**
663  * Sets the #DBusError with an explanation of why the spawned
664  * child process exited (on a signal, or whatever). If
665  * the child process has not exited, does nothing (error
666  * will remain unset).
667  *
668  * @param sitter the babysitter
669  * @param error an error to fill in
670  */
671 void
672 _dbus_babysitter_set_child_exit_error (DBusBabysitter *sitter,
673                                        DBusError      *error)
674 {
675   if (!_dbus_babysitter_get_child_exited (sitter))
676     return;
677
678   /* Note that if exec fails, we will also get a child status
679    * from the babysitter saying the child exited,
680    * so we need to give priority to the exec error
681    */
682   if (sitter->have_exec_errnum)
683     {
684       dbus_set_error (error, DBUS_ERROR_SPAWN_EXEC_FAILED,
685                       "Failed to execute program %s: %s",
686                       sitter->executable, _dbus_strerror (sitter->errnum));
687     }
688   else if (sitter->have_fork_errnum)
689     {
690       dbus_set_error (error, DBUS_ERROR_NO_MEMORY,
691                       "Failed to fork a new process %s: %s",
692                       sitter->executable, _dbus_strerror (sitter->errnum));
693     }
694   else if (sitter->have_child_status)
695     {
696       if (WIFEXITED (sitter->status))
697         dbus_set_error (error, DBUS_ERROR_SPAWN_CHILD_EXITED,
698                         "Process %s exited with status %d",
699                         sitter->executable, WEXITSTATUS (sitter->status));
700       else if (WIFSIGNALED (sitter->status))
701         dbus_set_error (error, DBUS_ERROR_SPAWN_CHILD_SIGNALED,
702                         "Process %s received signal %d",
703                         sitter->executable, WTERMSIG (sitter->status));
704       else
705         dbus_set_error (error, DBUS_ERROR_FAILED,
706                         "Process %s exited abnormally",
707                         sitter->executable);
708     }
709   else
710     {
711       dbus_set_error (error, DBUS_ERROR_FAILED,
712                       "Process %s exited, reason unknown",
713                       sitter->executable);
714     }
715 }
716
717 /**
718  * Sets watch functions to notify us when the
719  * babysitter object needs to read/write file descriptors.
720  *
721  * @param sitter the babysitter
722  * @param add_function function to begin monitoring a new descriptor.
723  * @param remove_function function to stop monitoring a descriptor.
724  * @param toggled_function function to notify when the watch is enabled/disabled
725  * @param data data to pass to add_function and remove_function.
726  * @param free_data_function function to be called to free the data.
727  * @returns #FALSE on failure (no memory)
728  */
729 dbus_bool_t
730 _dbus_babysitter_set_watch_functions (DBusBabysitter            *sitter,
731                                       DBusAddWatchFunction       add_function,
732                                       DBusRemoveWatchFunction    remove_function,
733                                       DBusWatchToggledFunction   toggled_function,
734                                       void                      *data,
735                                       DBusFreeFunction           free_data_function)
736 {
737   return _dbus_watch_list_set_functions (sitter->watches,
738                                          add_function,
739                                          remove_function,
740                                          toggled_function,
741                                          data,
742                                          free_data_function);
743 }
744
745 static dbus_bool_t
746 handle_watch (DBusWatch       *watch,
747               unsigned int     condition,
748               void            *data)
749 {
750   DBusBabysitter *sitter = data;
751   int revents;
752   int fd;
753   
754   revents = 0;
755   if (condition & DBUS_WATCH_READABLE)
756     revents |= _DBUS_POLLIN;
757   if (condition & DBUS_WATCH_ERROR)
758     revents |= _DBUS_POLLERR;
759   if (condition & DBUS_WATCH_HANGUP)
760     revents |= _DBUS_POLLHUP;
761
762   fd = dbus_watch_get_socket (watch);
763
764   if (fd == sitter->error_pipe_from_child)
765     handle_error_pipe (sitter, revents);
766   else if (fd == sitter->socket_to_babysitter)
767     handle_babysitter_socket (sitter, revents);
768
769   while (LIVE_CHILDREN (sitter) &&
770          babysitter_iteration (sitter, FALSE))
771     ;
772   
773   return TRUE;
774 }
775
776 /** Helps remember which end of the pipe is which */
777 #define READ_END 0
778 /** Helps remember which end of the pipe is which */
779 #define WRITE_END 1
780
781
782 /* Avoids a danger in threaded situations (calling close()
783  * on a file descriptor twice, and another thread has
784  * re-opened it since the first close)
785  */
786 static int
787 close_and_invalidate (int *fd)
788 {
789   int ret;
790
791   if (*fd < 0)
792     return -1;
793   else
794     {
795       ret = _dbus_close_socket (*fd, NULL);
796       *fd = -1;
797     }
798
799   return ret;
800 }
801
802 static dbus_bool_t
803 make_pipe (int         p[2],
804            DBusError  *error)
805 {
806   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
807   
808   if (pipe (p) < 0)
809     {
810       dbus_set_error (error,
811                       DBUS_ERROR_SPAWN_FAILED,
812                       "Failed to create pipe for communicating with child process (%s)",
813                       _dbus_strerror (errno));
814       return FALSE;
815     }
816
817   return TRUE;
818 }
819
820 static void
821 do_write (int fd, const void *buf, size_t count)
822 {
823   size_t bytes_written;
824   int ret;
825   
826   bytes_written = 0;
827   
828  again:
829   
830   ret = write (fd, ((const char*)buf) + bytes_written, count - bytes_written);
831
832   if (ret < 0)
833     {
834       if (errno == EINTR)
835         goto again;
836       else
837         {
838           _dbus_warn ("Failed to write data to pipe!\n");
839           exit (1); /* give up, we suck */
840         }
841     }
842   else
843     bytes_written += ret;
844   
845   if (bytes_written < count)
846     goto again;
847 }
848
849 static void
850 write_err_and_exit (int fd, int msg)
851 {
852   int en = errno;
853
854   do_write (fd, &msg, sizeof (msg));
855   do_write (fd, &en, sizeof (en));
856   
857   exit (1);
858 }
859
860 static void
861 write_pid (int fd, pid_t pid)
862 {
863   int msg = CHILD_PID;
864   
865   do_write (fd, &msg, sizeof (msg));
866   do_write (fd, &pid, sizeof (pid));
867 }
868
869 static void
870 write_status_and_exit (int fd, int status)
871 {
872   int msg = CHILD_EXITED;
873   
874   do_write (fd, &msg, sizeof (msg));
875   do_write (fd, &status, sizeof (status));
876   
877   exit (0);
878 }
879
880 static void
881 do_exec (int                       child_err_report_fd,
882          char                    **argv,
883          char                    **envp,
884          DBusSpawnChildSetupFunc   child_setup,
885          void                     *user_data)
886 {
887 #ifdef DBUS_BUILD_TESTS
888   int i, max_open;
889 #endif
890
891   _dbus_verbose_reset ();
892   _dbus_verbose ("Child process has PID " DBUS_PID_FORMAT "\n",
893                  _dbus_getpid ());
894   
895   if (child_setup)
896     (* child_setup) (user_data);
897
898 #ifdef DBUS_BUILD_TESTS
899   max_open = sysconf (_SC_OPEN_MAX);
900   
901   for (i = 3; i < max_open; i++)
902     {
903       int retval;
904
905       if (i == child_err_report_fd)
906         continue;
907       
908       retval = fcntl (i, F_GETFD);
909
910       if (retval != -1 && !(retval & FD_CLOEXEC))
911         _dbus_warn ("Fd %d did not have the close-on-exec flag set!\n", i);
912     }
913 #endif
914
915   if (envp == NULL)
916     {
917       extern char **environ;
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