Always remove, invalidate and free watches before closing watched sockets
[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 static void close_socket_to_babysitter  (DBusBabysitter *sitter);
261 static void close_error_pipe_from_child (DBusBabysitter *sitter);
262
263 /**
264  * Decrement the reference count on the babysitter object.
265  * When the reference count of the babysitter object reaches
266  * zero, the babysitter is killed and the child that was being
267  * babysat gets emancipated.
268  *
269  * @param sitter the babysitter
270  */
271 void
272 _dbus_babysitter_unref (DBusBabysitter *sitter)
273 {
274   _dbus_assert (sitter != NULL);
275   _dbus_assert (sitter->refcount > 0);
276   
277   sitter->refcount -= 1;
278   if (sitter->refcount == 0)
279     {
280       /* If we haven't forked other babysitters
281        * since this babysitter and socket were
282        * created then this close will cause the
283        * babysitter to wake up from poll with
284        * a hangup and then the babysitter will
285        * quit itself.
286        */
287       close_socket_to_babysitter (sitter);
288
289       close_error_pipe_from_child (sitter);
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->watches)
341         _dbus_watch_list_free (sitter->watches);
342
343       dbus_free (sitter->executable);
344       
345       dbus_free (sitter);
346     }
347 }
348
349 static ReadStatus
350 read_data (DBusBabysitter *sitter,
351            int             fd)
352 {
353   int what;
354   int got;
355   DBusError error = DBUS_ERROR_INIT;
356   ReadStatus r;
357
358   r = read_ints (fd, &what, 1, &got, &error);
359
360   switch (r)
361     {
362     case READ_STATUS_ERROR:
363       _dbus_warn ("Failed to read data from fd %d: %s\n", fd, error.message);
364       dbus_error_free (&error);
365       return r;
366
367     case READ_STATUS_EOF:
368       return r;
369
370     case READ_STATUS_OK:
371       break;
372     }
373   
374   if (got == 1)
375     {
376       switch (what)
377         {
378         case CHILD_EXITED:
379         case CHILD_FORK_FAILED:
380         case CHILD_EXEC_FAILED:
381           {
382             int arg;
383             
384             r = read_ints (fd, &arg, 1, &got, &error);
385
386             switch (r)
387               {
388               case READ_STATUS_ERROR:
389                 _dbus_warn ("Failed to read arg from fd %d: %s\n", fd, error.message);
390                 dbus_error_free (&error);
391                 return r;
392               case READ_STATUS_EOF:
393                 return r;
394               case READ_STATUS_OK:
395                 break;
396               }
397             
398             if (got == 1)
399               {
400                 if (what == CHILD_EXITED)
401                   {
402                     sitter->have_child_status = TRUE;
403                     sitter->status = arg;
404                     sitter->errnum = 0;
405                     _dbus_verbose ("recorded child status exited = %d signaled = %d exitstatus = %d termsig = %d\n",
406                                    WIFEXITED (sitter->status), WIFSIGNALED (sitter->status),
407                                    WEXITSTATUS (sitter->status), WTERMSIG (sitter->status));
408                   }
409                 else if (what == CHILD_FORK_FAILED)
410                   {
411                     sitter->have_fork_errnum = TRUE;
412                     sitter->errnum = arg;
413                     _dbus_verbose ("recorded fork errnum %d\n", sitter->errnum);
414                   }
415                 else if (what == CHILD_EXEC_FAILED)
416                   {
417                     sitter->have_exec_errnum = TRUE;
418                     sitter->errnum = arg;
419                     _dbus_verbose ("recorded exec errnum %d\n", sitter->errnum);
420                   }
421               }
422           }
423           break;
424         case CHILD_PID:
425           {
426             pid_t pid = -1;
427
428             r = read_pid (fd, &pid, &error);
429             
430             switch (r)
431               {
432               case READ_STATUS_ERROR:
433                 _dbus_warn ("Failed to read PID from fd %d: %s\n", fd, error.message);
434                 dbus_error_free (&error);
435                 return r;
436               case READ_STATUS_EOF:
437                 return r;
438               case READ_STATUS_OK:
439                 break;
440               }
441             
442             sitter->grandchild_pid = pid;
443             
444             _dbus_verbose ("recorded grandchild pid %d\n", sitter->grandchild_pid);
445           }
446           break;
447         default:
448           _dbus_warn ("Unknown message received from babysitter process\n");
449           break;
450         }
451     }
452
453   return r;
454 }
455
456 static void
457 close_socket_to_babysitter (DBusBabysitter *sitter)
458 {
459   _dbus_verbose ("Closing babysitter\n");
460
461   if (sitter->sitter_watch != NULL)
462     {
463       _dbus_assert (sitter->watches != NULL);
464       _dbus_watch_list_remove_watch (sitter->watches,  sitter->sitter_watch);
465       _dbus_watch_invalidate (sitter->sitter_watch);
466       _dbus_watch_unref (sitter->sitter_watch);
467       sitter->sitter_watch = NULL;
468     }
469
470   if (sitter->socket_to_babysitter >= 0)
471     {
472       _dbus_close_socket (sitter->socket_to_babysitter, NULL);
473       sitter->socket_to_babysitter = -1;
474     }
475 }
476
477 static void
478 close_error_pipe_from_child (DBusBabysitter *sitter)
479 {
480   _dbus_verbose ("Closing child error\n");
481
482   if (sitter->error_watch != NULL)
483     {
484       _dbus_assert (sitter->watches != NULL);
485       _dbus_watch_list_remove_watch (sitter->watches,  sitter->error_watch);
486       _dbus_watch_invalidate (sitter->error_watch);
487       _dbus_watch_unref (sitter->error_watch);
488       sitter->error_watch = NULL;
489     }
490
491   if (sitter->error_pipe_from_child >= 0)
492     {
493       _dbus_close_socket (sitter->error_pipe_from_child, NULL);
494       sitter->error_pipe_from_child = -1;
495     }
496 }
497
498 static void
499 handle_babysitter_socket (DBusBabysitter *sitter,
500                           int             revents)
501 {
502   /* Even if we have POLLHUP, we want to keep reading
503    * data until POLLIN goes away; so this function only
504    * looks at HUP/ERR if no IN is set.
505    */
506   if (revents & _DBUS_POLLIN)
507     {
508       _dbus_verbose ("Reading data from babysitter\n");
509       if (read_data (sitter, sitter->socket_to_babysitter) != READ_STATUS_OK)
510         close_socket_to_babysitter (sitter);
511     }
512   else if (revents & (_DBUS_POLLERR | _DBUS_POLLHUP))
513     {
514       close_socket_to_babysitter (sitter);
515     }
516 }
517
518 static void
519 handle_error_pipe (DBusBabysitter *sitter,
520                    int             revents)
521 {
522   if (revents & _DBUS_POLLIN)
523     {
524       _dbus_verbose ("Reading data from child error\n");
525       if (read_data (sitter, sitter->error_pipe_from_child) != READ_STATUS_OK)
526         close_error_pipe_from_child (sitter);
527     }
528   else if (revents & (_DBUS_POLLERR | _DBUS_POLLHUP))
529     {
530       close_error_pipe_from_child (sitter);
531     }
532 }
533
534 /* returns whether there were any poll events handled */
535 static dbus_bool_t
536 babysitter_iteration (DBusBabysitter *sitter,
537                       dbus_bool_t     block)
538 {
539   DBusPollFD fds[2];
540   int i;
541   dbus_bool_t descriptors_ready;
542
543   descriptors_ready = FALSE;
544   
545   i = 0;
546
547   if (sitter->error_pipe_from_child >= 0)
548     {
549       fds[i].fd = sitter->error_pipe_from_child;
550       fds[i].events = _DBUS_POLLIN;
551       fds[i].revents = 0;
552       ++i;
553     }
554   
555   if (sitter->socket_to_babysitter >= 0)
556     {
557       fds[i].fd = sitter->socket_to_babysitter;
558       fds[i].events = _DBUS_POLLIN;
559       fds[i].revents = 0;
560       ++i;
561     }
562
563   if (i > 0)
564     {
565       int ret;
566
567       do
568         {
569           ret = _dbus_poll (fds, i, 0);
570         }
571       while (ret < 0 && errno == EINTR);
572
573       if (ret == 0 && block)
574         {
575           do
576             {
577               ret = _dbus_poll (fds, i, -1);
578             }
579           while (ret < 0 && errno == EINTR);
580         }
581
582       if (ret > 0)
583         {
584           descriptors_ready = TRUE;
585           
586           while (i > 0)
587             {
588               --i;
589               if (fds[i].fd == sitter->error_pipe_from_child)
590                 handle_error_pipe (sitter, fds[i].revents);
591               else if (fds[i].fd == sitter->socket_to_babysitter)
592                 handle_babysitter_socket (sitter, fds[i].revents);
593             }
594         }
595     }
596
597   return descriptors_ready;
598 }
599
600 /**
601  * Macro returns #TRUE if the babysitter still has live sockets open to the
602  * babysitter child or the grandchild.
603  */
604 #define LIVE_CHILDREN(sitter) ((sitter)->socket_to_babysitter >= 0 || (sitter)->error_pipe_from_child >= 0)
605
606 /**
607  * Blocks until the babysitter process gives us the PID of the spawned grandchild,
608  * then kills the spawned grandchild.
609  *
610  * @param sitter the babysitter object
611  */
612 void
613 _dbus_babysitter_kill_child (DBusBabysitter *sitter)
614 {
615   /* be sure we have the PID of the child */
616   while (LIVE_CHILDREN (sitter) &&
617          sitter->grandchild_pid == -1)
618     babysitter_iteration (sitter, TRUE);
619
620   _dbus_verbose ("Got child PID %ld for killing\n",
621                  (long) sitter->grandchild_pid);
622   
623   if (sitter->grandchild_pid == -1)
624     return; /* child is already dead, or we're so hosed we'll never recover */
625
626   kill (sitter->grandchild_pid, SIGKILL);
627 }
628
629 /**
630  * Checks whether the child has exited, without blocking.
631  *
632  * @param sitter the babysitter
633  */
634 dbus_bool_t
635 _dbus_babysitter_get_child_exited (DBusBabysitter *sitter)
636 {
637
638   /* Be sure we're up-to-date */
639   while (LIVE_CHILDREN (sitter) &&
640          babysitter_iteration (sitter, FALSE))
641     ;
642
643   /* We will have exited the babysitter when the child has exited */
644   return sitter->socket_to_babysitter < 0;
645 }
646
647 /**
648  * Gets the exit status of the child. We do this so implementation specific
649  * detail is not cluttering up dbus, for example the system launcher code.
650  * This can only be called if the child has exited, i.e. call
651  * _dbus_babysitter_get_child_exited(). It returns FALSE if the child
652  * did not return a status code, e.g. because the child was signaled
653  * or we failed to ever launch the child in the first place.
654  *
655  * @param sitter the babysitter
656  * @param status the returned status code
657  * @returns #FALSE on failure
658  */
659 dbus_bool_t
660 _dbus_babysitter_get_child_exit_status (DBusBabysitter *sitter,
661                                         int            *status)
662 {
663   if (!_dbus_babysitter_get_child_exited (sitter))
664     _dbus_assert_not_reached ("Child has not exited");
665   
666   if (!sitter->have_child_status ||
667       !(WIFEXITED (sitter->status)))
668     return FALSE;
669
670   *status = WEXITSTATUS (sitter->status);
671   return TRUE;
672 }
673
674 /**
675  * Sets the #DBusError with an explanation of why the spawned
676  * child process exited (on a signal, or whatever). If
677  * the child process has not exited, does nothing (error
678  * will remain unset).
679  *
680  * @param sitter the babysitter
681  * @param error an error to fill in
682  */
683 void
684 _dbus_babysitter_set_child_exit_error (DBusBabysitter *sitter,
685                                        DBusError      *error)
686 {
687   if (!_dbus_babysitter_get_child_exited (sitter))
688     return;
689
690   /* Note that if exec fails, we will also get a child status
691    * from the babysitter saying the child exited,
692    * so we need to give priority to the exec error
693    */
694   if (sitter->have_exec_errnum)
695     {
696       dbus_set_error (error, DBUS_ERROR_SPAWN_EXEC_FAILED,
697                       "Failed to execute program %s: %s",
698                       sitter->executable, _dbus_strerror (sitter->errnum));
699     }
700   else if (sitter->have_fork_errnum)
701     {
702       dbus_set_error (error, DBUS_ERROR_NO_MEMORY,
703                       "Failed to fork a new process %s: %s",
704                       sitter->executable, _dbus_strerror (sitter->errnum));
705     }
706   else if (sitter->have_child_status)
707     {
708       if (WIFEXITED (sitter->status))
709         dbus_set_error (error, DBUS_ERROR_SPAWN_CHILD_EXITED,
710                         "Process %s exited with status %d",
711                         sitter->executable, WEXITSTATUS (sitter->status));
712       else if (WIFSIGNALED (sitter->status))
713         dbus_set_error (error, DBUS_ERROR_SPAWN_CHILD_SIGNALED,
714                         "Process %s received signal %d",
715                         sitter->executable, WTERMSIG (sitter->status));
716       else
717         dbus_set_error (error, DBUS_ERROR_FAILED,
718                         "Process %s exited abnormally",
719                         sitter->executable);
720     }
721   else
722     {
723       dbus_set_error (error, DBUS_ERROR_FAILED,
724                       "Process %s exited, reason unknown",
725                       sitter->executable);
726     }
727 }
728
729 /**
730  * Sets watch functions to notify us when the
731  * babysitter object needs to read/write file descriptors.
732  *
733  * @param sitter the babysitter
734  * @param add_function function to begin monitoring a new descriptor.
735  * @param remove_function function to stop monitoring a descriptor.
736  * @param toggled_function function to notify when the watch is enabled/disabled
737  * @param data data to pass to add_function and remove_function.
738  * @param free_data_function function to be called to free the data.
739  * @returns #FALSE on failure (no memory)
740  */
741 dbus_bool_t
742 _dbus_babysitter_set_watch_functions (DBusBabysitter            *sitter,
743                                       DBusAddWatchFunction       add_function,
744                                       DBusRemoveWatchFunction    remove_function,
745                                       DBusWatchToggledFunction   toggled_function,
746                                       void                      *data,
747                                       DBusFreeFunction           free_data_function)
748 {
749   return _dbus_watch_list_set_functions (sitter->watches,
750                                          add_function,
751                                          remove_function,
752                                          toggled_function,
753                                          data,
754                                          free_data_function);
755 }
756
757 static dbus_bool_t
758 handle_watch (DBusWatch       *watch,
759               unsigned int     condition,
760               void            *data)
761 {
762   DBusBabysitter *sitter = _dbus_babysitter_ref (data);
763   int revents;
764   int fd;
765   
766   revents = 0;
767   if (condition & DBUS_WATCH_READABLE)
768     revents |= _DBUS_POLLIN;
769   if (condition & DBUS_WATCH_ERROR)
770     revents |= _DBUS_POLLERR;
771   if (condition & DBUS_WATCH_HANGUP)
772     revents |= _DBUS_POLLHUP;
773
774   fd = dbus_watch_get_socket (watch);
775
776   if (fd == sitter->error_pipe_from_child)
777     handle_error_pipe (sitter, revents);
778   else if (fd == sitter->socket_to_babysitter)
779     handle_babysitter_socket (sitter, revents);
780
781   while (LIVE_CHILDREN (sitter) &&
782          babysitter_iteration (sitter, FALSE))
783     ;
784
785   /* fd.o #32992: if the handle_* methods closed their sockets, they previously
786    * didn't always remove the watches. Check that we don't regress. */
787   _dbus_assert (sitter->socket_to_babysitter != -1 || sitter->sitter_watch == NULL);
788   _dbus_assert (sitter->error_pipe_from_child != -1 || sitter->error_watch == NULL);
789
790   _dbus_babysitter_unref (sitter);
791   return TRUE;
792 }
793
794 /** Helps remember which end of the pipe is which */
795 #define READ_END 0
796 /** Helps remember which end of the pipe is which */
797 #define WRITE_END 1
798
799
800 /* Avoids a danger in threaded situations (calling close()
801  * on a file descriptor twice, and another thread has
802  * re-opened it since the first close)
803  */
804 static int
805 close_and_invalidate (int *fd)
806 {
807   int ret;
808
809   if (*fd < 0)
810     return -1;
811   else
812     {
813       ret = _dbus_close_socket (*fd, NULL);
814       *fd = -1;
815     }
816
817   return ret;
818 }
819
820 static dbus_bool_t
821 make_pipe (int         p[2],
822            DBusError  *error)
823 {
824   int retval;
825
826 #ifdef HAVE_PIPE2
827   dbus_bool_t cloexec_done;
828
829   retval = pipe2 (p, O_CLOEXEC);
830   cloexec_done = retval >= 0;
831
832   /* Check if kernel seems to be too old to know pipe2(). We assume
833      that if pipe2 is available, O_CLOEXEC is too.  */
834   if (retval < 0 && errno == ENOSYS)
835 #endif
836     {
837       retval = pipe(p);
838     }
839
840   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
841
842   if (retval < 0)
843     {
844       dbus_set_error (error,
845                       DBUS_ERROR_SPAWN_FAILED,
846                       "Failed to create pipe for communicating with child process (%s)",
847                       _dbus_strerror (errno));
848       return FALSE;
849     }
850
851 #ifdef HAVE_PIPE2
852   if (!cloexec_done)
853 #endif
854     {
855       _dbus_fd_set_close_on_exec (p[0]);
856       _dbus_fd_set_close_on_exec (p[1]);
857     }
858
859   return TRUE;
860 }
861
862 static void
863 do_write (int fd, const void *buf, size_t count)
864 {
865   size_t bytes_written;
866   int ret;
867   
868   bytes_written = 0;
869   
870  again:
871   
872   ret = write (fd, ((const char*)buf) + bytes_written, count - bytes_written);
873
874   if (ret < 0)
875     {
876       if (errno == EINTR)
877         goto again;
878       else
879         {
880           _dbus_warn ("Failed to write data to pipe!\n");
881           exit (1); /* give up, we suck */
882         }
883     }
884   else
885     bytes_written += ret;
886   
887   if (bytes_written < count)
888     goto again;
889 }
890
891 static void
892 write_err_and_exit (int fd, int msg)
893 {
894   int en = errno;
895
896   do_write (fd, &msg, sizeof (msg));
897   do_write (fd, &en, sizeof (en));
898   
899   exit (1);
900 }
901
902 static void
903 write_pid (int fd, pid_t pid)
904 {
905   int msg = CHILD_PID;
906   
907   do_write (fd, &msg, sizeof (msg));
908   do_write (fd, &pid, sizeof (pid));
909 }
910
911 static void
912 write_status_and_exit (int fd, int status)
913 {
914   int msg = CHILD_EXITED;
915   
916   do_write (fd, &msg, sizeof (msg));
917   do_write (fd, &status, sizeof (status));
918   
919   exit (0);
920 }
921
922 static void
923 do_exec (int                       child_err_report_fd,
924          char                    **argv,
925          char                    **envp,
926          DBusSpawnChildSetupFunc   child_setup,
927          void                     *user_data)
928 {
929 #ifdef DBUS_BUILD_TESTS
930   int i, max_open;
931 #endif
932
933   _dbus_verbose_reset ();
934   _dbus_verbose ("Child process has PID " DBUS_PID_FORMAT "\n",
935                  _dbus_getpid ());
936   
937   if (child_setup)
938     (* child_setup) (user_data);
939
940 #ifdef DBUS_BUILD_TESTS
941   max_open = sysconf (_SC_OPEN_MAX);
942   
943   for (i = 3; i < max_open; i++)
944     {
945       int retval;
946
947       if (i == child_err_report_fd)
948         continue;
949       
950       retval = fcntl (i, F_GETFD);
951
952       if (retval != -1 && !(retval & FD_CLOEXEC))
953         _dbus_warn ("Fd %d did not have the close-on-exec flag set!\n", i);
954     }
955 #endif
956
957   if (envp == NULL)
958     {
959       _dbus_assert (environ != NULL);
960
961       envp = environ;
962     }
963   
964   execve (argv[0], argv, envp);
965   
966   /* Exec failed */
967   write_err_and_exit (child_err_report_fd,
968                       CHILD_EXEC_FAILED);
969 }
970
971 static void
972 check_babysit_events (pid_t grandchild_pid,
973                       int   parent_pipe,
974                       int   revents)
975 {
976   pid_t ret;
977   int status;
978   
979   do
980     {
981       ret = waitpid (grandchild_pid, &status, WNOHANG);
982       /* The man page says EINTR can't happen with WNOHANG,
983        * but there are reports of it (maybe only with valgrind?)
984        */
985     }
986   while (ret < 0 && errno == EINTR);
987
988   if (ret == 0)
989     {
990       _dbus_verbose ("no child exited\n");
991       
992       ; /* no child exited */
993     }
994   else if (ret < 0)
995     {
996       /* This isn't supposed to happen. */
997       _dbus_warn ("unexpected waitpid() failure in check_babysit_events(): %s\n",
998                   _dbus_strerror (errno));
999       exit (1);
1000     }
1001   else if (ret == grandchild_pid)
1002     {
1003       /* Child exited */
1004       _dbus_verbose ("reaped child pid %ld\n", (long) ret);
1005       
1006       write_status_and_exit (parent_pipe, status);
1007     }
1008   else
1009     {
1010       _dbus_warn ("waitpid() reaped pid %d that we've never heard of\n",
1011                   (int) ret);
1012       exit (1);
1013     }
1014
1015   if (revents & _DBUS_POLLIN)
1016     {
1017       _dbus_verbose ("babysitter got POLLIN from parent pipe\n");
1018     }
1019
1020   if (revents & (_DBUS_POLLERR | _DBUS_POLLHUP))
1021     {
1022       /* Parent is gone, so we just exit */
1023       _dbus_verbose ("babysitter got POLLERR or POLLHUP from parent\n");
1024       exit (0);
1025     }
1026 }
1027
1028 static int babysit_sigchld_pipe = -1;
1029
1030 static void
1031 babysit_signal_handler (int signo)
1032 {
1033   char b = '\0';
1034  again:
1035   if (write (babysit_sigchld_pipe, &b, 1) <= 0) 
1036     if (errno == EINTR)
1037       goto again;
1038 }
1039
1040 static void
1041 babysit (pid_t grandchild_pid,
1042          int   parent_pipe)
1043 {
1044   int sigchld_pipe[2];
1045
1046   /* We don't exec, so we keep parent state, such as the pid that
1047    * _dbus_verbose() uses. Reset the pid here.
1048    */
1049   _dbus_verbose_reset ();
1050   
1051   /* I thought SIGCHLD would just wake up the poll, but
1052    * that didn't seem to work, so added this pipe.
1053    * Probably the pipe is more likely to work on busted
1054    * operating systems anyhow.
1055    */
1056   if (pipe (sigchld_pipe) < 0)
1057     {
1058       _dbus_warn ("Not enough file descriptors to create pipe in babysitter process\n");
1059       exit (1);
1060     }
1061
1062   babysit_sigchld_pipe = sigchld_pipe[WRITE_END];
1063
1064   _dbus_set_signal_handler (SIGCHLD, babysit_signal_handler);
1065   
1066   write_pid (parent_pipe, grandchild_pid);
1067
1068   check_babysit_events (grandchild_pid, parent_pipe, 0);
1069
1070   while (TRUE)
1071     {
1072       DBusPollFD pfds[2];
1073       
1074       pfds[0].fd = parent_pipe;
1075       pfds[0].events = _DBUS_POLLIN;
1076       pfds[0].revents = 0;
1077
1078       pfds[1].fd = sigchld_pipe[READ_END];
1079       pfds[1].events = _DBUS_POLLIN;
1080       pfds[1].revents = 0;
1081       
1082       if (_dbus_poll (pfds, _DBUS_N_ELEMENTS (pfds), -1) < 0 && errno != EINTR)
1083         {
1084           _dbus_warn ("_dbus_poll() error: %s\n", strerror (errno));
1085           exit (1);
1086         }
1087
1088       if (pfds[0].revents != 0)
1089         {
1090           check_babysit_events (grandchild_pid, parent_pipe, pfds[0].revents);
1091         }
1092       else if (pfds[1].revents & _DBUS_POLLIN)
1093         {
1094           char b;
1095           if (read (sigchld_pipe[READ_END], &b, 1) == -1)
1096             /* ignore */;
1097           /* do waitpid check */
1098           check_babysit_events (grandchild_pid, parent_pipe, 0);
1099         }
1100     }
1101   
1102   exit (1);
1103 }
1104
1105 /**
1106  * Spawns a new process. The executable name and argv[0]
1107  * are the same, both are provided in argv[0]. The child_setup
1108  * function is passed the given user_data and is run in the child
1109  * just before calling exec().
1110  *
1111  * Also creates a "babysitter" which tracks the status of the
1112  * child process, advising the parent if the child exits.
1113  * If the spawn fails, no babysitter is created.
1114  * If sitter_p is #NULL, no babysitter is kept.
1115  *
1116  * @param sitter_p return location for babysitter or #NULL
1117  * @param argv the executable and arguments
1118  * @param env the environment (not used on unix yet)
1119  * @param child_setup function to call in child pre-exec()
1120  * @param user_data user data for setup function
1121  * @param error error object to be filled in if function fails
1122  * @returns #TRUE on success, #FALSE if error is filled in
1123  */
1124 dbus_bool_t
1125 _dbus_spawn_async_with_babysitter (DBusBabysitter          **sitter_p,
1126                                    char                    **argv,
1127                                    char                    **env,
1128                                    DBusSpawnChildSetupFunc   child_setup,
1129                                    void                     *user_data,
1130                                    DBusError                *error)
1131 {
1132   DBusBabysitter *sitter;
1133   int child_err_report_pipe[2] = { -1, -1 };
1134   int babysitter_pipe[2] = { -1, -1 };
1135   pid_t pid;
1136   
1137   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1138
1139   if (sitter_p != NULL)
1140     *sitter_p = NULL;
1141
1142   sitter = NULL;
1143
1144   sitter = _dbus_babysitter_new ();
1145   if (sitter == NULL)
1146     {
1147       dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1148       return FALSE;
1149     }
1150
1151   sitter->executable = _dbus_strdup (argv[0]);
1152   if (sitter->executable == NULL)
1153     {
1154       dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1155       goto cleanup_and_fail;
1156     }
1157   
1158   if (!make_pipe (child_err_report_pipe, error))
1159     goto cleanup_and_fail;
1160
1161   if (!_dbus_full_duplex_pipe (&babysitter_pipe[0], &babysitter_pipe[1], TRUE, error))
1162     goto cleanup_and_fail;
1163
1164   /* Setting up the babysitter is only useful in the parent,
1165    * but we don't want to run out of memory and fail
1166    * after we've already forked, since then we'd leak
1167    * child processes everywhere.
1168    */
1169   sitter->error_watch = _dbus_watch_new (child_err_report_pipe[READ_END],
1170                                          DBUS_WATCH_READABLE,
1171                                          TRUE, handle_watch, sitter, NULL);
1172   if (sitter->error_watch == NULL)
1173     {
1174       dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1175       goto cleanup_and_fail;
1176     }
1177         
1178   if (!_dbus_watch_list_add_watch (sitter->watches,  sitter->error_watch))
1179     {
1180       /* we need to free it early so the destructor won't try to remove it
1181        * without it having been added, which DBusLoop doesn't allow */
1182       _dbus_watch_invalidate (sitter->error_watch);
1183       _dbus_watch_unref (sitter->error_watch);
1184       sitter->error_watch = NULL;
1185
1186       dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1187       goto cleanup_and_fail;
1188     }
1189       
1190   sitter->sitter_watch = _dbus_watch_new (babysitter_pipe[0],
1191                                           DBUS_WATCH_READABLE,
1192                                           TRUE, handle_watch, sitter, NULL);
1193   if (sitter->sitter_watch == NULL)
1194     {
1195       dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1196       goto cleanup_and_fail;
1197     }
1198       
1199   if (!_dbus_watch_list_add_watch (sitter->watches,  sitter->sitter_watch))
1200     {
1201       /* we need to free it early so the destructor won't try to remove it
1202        * without it having been added, which DBusLoop doesn't allow */
1203       _dbus_watch_invalidate (sitter->sitter_watch);
1204       _dbus_watch_unref (sitter->sitter_watch);
1205       sitter->sitter_watch = NULL;
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