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