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