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