Merge branch 'dbus-1.2'
[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       size_t chunk;
81       ssize_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       size_t chunk;    
136       ssize_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   return TRUE;
779 }
780
781 /** Helps remember which end of the pipe is which */
782 #define READ_END 0
783 /** Helps remember which end of the pipe is which */
784 #define WRITE_END 1
785
786
787 /* Avoids a danger in threaded situations (calling close()
788  * on a file descriptor twice, and another thread has
789  * re-opened it since the first close)
790  */
791 static int
792 close_and_invalidate (int *fd)
793 {
794   int ret;
795
796   if (*fd < 0)
797     return -1;
798   else
799     {
800       ret = _dbus_close_socket (*fd, NULL);
801       *fd = -1;
802     }
803
804   return ret;
805 }
806
807 static dbus_bool_t
808 make_pipe (int         p[2],
809            DBusError  *error)
810 {
811   int retval;
812
813 #ifdef HAVE_PIPE2
814   dbus_bool_t cloexec_done;
815
816   retval = pipe2 (p, O_CLOEXEC);
817   cloexec_done = retval >= 0;
818
819   /* Check if kernel seems to be too old to know pipe2(). We assume
820      that if pipe2 is available, O_CLOEXEC is too.  */
821   if (retval < 0 && errno == ENOSYS)
822 #endif
823     {
824       retval = pipe(p);
825     }
826
827   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
828
829   if (retval < 0)
830     {
831       dbus_set_error (error,
832                       DBUS_ERROR_SPAWN_FAILED,
833                       "Failed to create pipe for communicating with child process (%s)",
834                       _dbus_strerror (errno));
835       return FALSE;
836     }
837
838 #ifdef HAVE_PIPE2
839   if (!cloexec_done)
840 #endif
841     {
842       _dbus_fd_set_close_on_exec (p[0]);
843       _dbus_fd_set_close_on_exec (p[1]);
844     }
845
846   return TRUE;
847 }
848
849 static void
850 do_write (int fd, const void *buf, size_t count)
851 {
852   size_t bytes_written;
853   int ret;
854   
855   bytes_written = 0;
856   
857  again:
858   
859   ret = write (fd, ((const char*)buf) + bytes_written, count - bytes_written);
860
861   if (ret < 0)
862     {
863       if (errno == EINTR)
864         goto again;
865       else
866         {
867           _dbus_warn ("Failed to write data to pipe!\n");
868           exit (1); /* give up, we suck */
869         }
870     }
871   else
872     bytes_written += ret;
873   
874   if (bytes_written < count)
875     goto again;
876 }
877
878 static void
879 write_err_and_exit (int fd, int msg)
880 {
881   int en = errno;
882
883   do_write (fd, &msg, sizeof (msg));
884   do_write (fd, &en, sizeof (en));
885   
886   exit (1);
887 }
888
889 static void
890 write_pid (int fd, pid_t pid)
891 {
892   int msg = CHILD_PID;
893   
894   do_write (fd, &msg, sizeof (msg));
895   do_write (fd, &pid, sizeof (pid));
896 }
897
898 static void
899 write_status_and_exit (int fd, int status)
900 {
901   int msg = CHILD_EXITED;
902   
903   do_write (fd, &msg, sizeof (msg));
904   do_write (fd, &status, sizeof (status));
905   
906   exit (0);
907 }
908
909 static void
910 do_exec (int                       child_err_report_fd,
911          char                    **argv,
912          char                    **envp,
913          DBusSpawnChildSetupFunc   child_setup,
914          void                     *user_data)
915 {
916 #ifdef DBUS_BUILD_TESTS
917   int i, max_open;
918 #endif
919
920   _dbus_verbose_reset ();
921   _dbus_verbose ("Child process has PID " DBUS_PID_FORMAT "\n",
922                  _dbus_getpid ());
923   
924   if (child_setup)
925     (* child_setup) (user_data);
926
927 #ifdef DBUS_BUILD_TESTS
928   max_open = sysconf (_SC_OPEN_MAX);
929   
930   for (i = 3; i < max_open; i++)
931     {
932       int retval;
933
934       if (i == child_err_report_fd)
935         continue;
936       
937       retval = fcntl (i, F_GETFD);
938
939       if (retval != -1 && !(retval & FD_CLOEXEC))
940         _dbus_warn ("Fd %d did not have the close-on-exec flag set!\n", i);
941     }
942 #endif
943
944   if (envp == NULL)
945     {
946       _dbus_assert (environ != NULL);
947
948       envp = environ;
949     }
950   
951   execve (argv[0], argv, envp);
952   
953   /* Exec failed */
954   write_err_and_exit (child_err_report_fd,
955                       CHILD_EXEC_FAILED);
956 }
957
958 static void
959 check_babysit_events (pid_t grandchild_pid,
960                       int   parent_pipe,
961                       int   revents)
962 {
963   pid_t ret;
964   int status;
965   
966   do
967     {
968       ret = waitpid (grandchild_pid, &status, WNOHANG);
969       /* The man page says EINTR can't happen with WNOHANG,
970        * but there are reports of it (maybe only with valgrind?)
971        */
972     }
973   while (ret < 0 && errno == EINTR);
974
975   if (ret == 0)
976     {
977       _dbus_verbose ("no child exited\n");
978       
979       ; /* no child exited */
980     }
981   else if (ret < 0)
982     {
983       /* This isn't supposed to happen. */
984       _dbus_warn ("unexpected waitpid() failure in check_babysit_events(): %s\n",
985                   _dbus_strerror (errno));
986       exit (1);
987     }
988   else if (ret == grandchild_pid)
989     {
990       /* Child exited */
991       _dbus_verbose ("reaped child pid %ld\n", (long) ret);
992       
993       write_status_and_exit (parent_pipe, status);
994     }
995   else
996     {
997       _dbus_warn ("waitpid() reaped pid %d that we've never heard of\n",
998                   (int) ret);
999       exit (1);
1000     }
1001
1002   if (revents & _DBUS_POLLIN)
1003     {
1004       _dbus_verbose ("babysitter got POLLIN from parent pipe\n");
1005     }
1006
1007   if (revents & (_DBUS_POLLERR | _DBUS_POLLHUP))
1008     {
1009       /* Parent is gone, so we just exit */
1010       _dbus_verbose ("babysitter got POLLERR or POLLHUP from parent\n");
1011       exit (0);
1012     }
1013 }
1014
1015 static int babysit_sigchld_pipe = -1;
1016
1017 static void
1018 babysit_signal_handler (int signo)
1019 {
1020   char b = '\0';
1021  again:
1022   if (write (babysit_sigchld_pipe, &b, 1) <= 0) 
1023     if (errno == EINTR)
1024       goto again;
1025 }
1026
1027 static void
1028 babysit (pid_t grandchild_pid,
1029          int   parent_pipe)
1030 {
1031   int sigchld_pipe[2];
1032
1033   /* We don't exec, so we keep parent state, such as the pid that
1034    * _dbus_verbose() uses. Reset the pid here.
1035    */
1036   _dbus_verbose_reset ();
1037   
1038   /* I thought SIGCHLD would just wake up the poll, but
1039    * that didn't seem to work, so added this pipe.
1040    * Probably the pipe is more likely to work on busted
1041    * operating systems anyhow.
1042    */
1043   if (pipe (sigchld_pipe) < 0)
1044     {
1045       _dbus_warn ("Not enough file descriptors to create pipe in babysitter process\n");
1046       exit (1);
1047     }
1048
1049   babysit_sigchld_pipe = sigchld_pipe[WRITE_END];
1050
1051   _dbus_set_signal_handler (SIGCHLD, babysit_signal_handler);
1052   
1053   write_pid (parent_pipe, grandchild_pid);
1054
1055   check_babysit_events (grandchild_pid, parent_pipe, 0);
1056
1057   while (TRUE)
1058     {
1059       DBusPollFD pfds[2];
1060       
1061       pfds[0].fd = parent_pipe;
1062       pfds[0].events = _DBUS_POLLIN;
1063       pfds[0].revents = 0;
1064
1065       pfds[1].fd = sigchld_pipe[READ_END];
1066       pfds[1].events = _DBUS_POLLIN;
1067       pfds[1].revents = 0;
1068       
1069       if (_dbus_poll (pfds, _DBUS_N_ELEMENTS (pfds), -1) < 0 && errno != EINTR)
1070         {
1071           _dbus_warn ("_dbus_poll() error: %s\n", strerror (errno));
1072           exit (1);
1073         }
1074
1075       if (pfds[0].revents != 0)
1076         {
1077           check_babysit_events (grandchild_pid, parent_pipe, pfds[0].revents);
1078         }
1079       else if (pfds[1].revents & _DBUS_POLLIN)
1080         {
1081           char b;
1082           read (sigchld_pipe[READ_END], &b, 1);
1083           /* do waitpid check */
1084           check_babysit_events (grandchild_pid, parent_pipe, 0);
1085         }
1086     }
1087   
1088   exit (1);
1089 }
1090
1091 /**
1092  * Spawns a new process. The executable name and argv[0]
1093  * are the same, both are provided in argv[0]. The child_setup
1094  * function is passed the given user_data and is run in the child
1095  * just before calling exec().
1096  *
1097  * Also creates a "babysitter" which tracks the status of the
1098  * child process, advising the parent if the child exits.
1099  * If the spawn fails, no babysitter is created.
1100  * If sitter_p is #NULL, no babysitter is kept.
1101  *
1102  * @param sitter_p return location for babysitter or #NULL
1103  * @param argv the executable and arguments
1104  * @param env the environment (not used on unix yet)
1105  * @param child_setup function to call in child pre-exec()
1106  * @param user_data user data for setup function
1107  * @param error error object to be filled in if function fails
1108  * @returns #TRUE on success, #FALSE if error is filled in
1109  */
1110 dbus_bool_t
1111 _dbus_spawn_async_with_babysitter (DBusBabysitter          **sitter_p,
1112                                    char                    **argv,
1113                                    char                    **env,
1114                                    DBusSpawnChildSetupFunc   child_setup,
1115                                    void                     *user_data,
1116                                    DBusError                *error)
1117 {
1118   DBusBabysitter *sitter;
1119   int child_err_report_pipe[2] = { -1, -1 };
1120   int babysitter_pipe[2] = { -1, -1 };
1121   pid_t pid;
1122   
1123   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1124
1125   if (sitter_p != NULL)
1126     *sitter_p = NULL;
1127
1128   sitter = NULL;
1129
1130   sitter = _dbus_babysitter_new ();
1131   if (sitter == NULL)
1132     {
1133       dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1134       return FALSE;
1135     }
1136
1137   sitter->executable = _dbus_strdup (argv[0]);
1138   if (sitter->executable == NULL)
1139     {
1140       dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1141       goto cleanup_and_fail;
1142     }
1143   
1144   if (!make_pipe (child_err_report_pipe, error))
1145     goto cleanup_and_fail;
1146
1147   if (!_dbus_full_duplex_pipe (&babysitter_pipe[0], &babysitter_pipe[1], TRUE, error))
1148     goto cleanup_and_fail;
1149
1150   /* Setting up the babysitter is only useful in the parent,
1151    * but we don't want to run out of memory and fail
1152    * after we've already forked, since then we'd leak
1153    * child processes everywhere.
1154    */
1155   sitter->error_watch = _dbus_watch_new (child_err_report_pipe[READ_END],
1156                                          DBUS_WATCH_READABLE,
1157                                          TRUE, handle_watch, sitter, NULL);
1158   if (sitter->error_watch == NULL)
1159     {
1160       dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1161       goto cleanup_and_fail;
1162     }
1163         
1164   if (!_dbus_watch_list_add_watch (sitter->watches,  sitter->error_watch))
1165     {
1166       dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1167       goto cleanup_and_fail;
1168     }
1169       
1170   sitter->sitter_watch = _dbus_watch_new (babysitter_pipe[0],
1171                                           DBUS_WATCH_READABLE,
1172                                           TRUE, handle_watch, sitter, NULL);
1173   if (sitter->sitter_watch == NULL)
1174     {
1175       dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1176       goto cleanup_and_fail;
1177     }
1178       
1179   if (!_dbus_watch_list_add_watch (sitter->watches,  sitter->sitter_watch))
1180     {
1181       dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1182       goto cleanup_and_fail;
1183     }
1184
1185   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1186   
1187   pid = fork ();
1188   
1189   if (pid < 0)
1190     {
1191       dbus_set_error (error,
1192                       DBUS_ERROR_SPAWN_FORK_FAILED,
1193                       "Failed to fork (%s)",
1194                       _dbus_strerror (errno));
1195       goto cleanup_and_fail;
1196     }
1197   else if (pid == 0)
1198     {
1199       /* Immediate child, this is the babysitter process. */
1200       int grandchild_pid;
1201       
1202       /* Be sure we crash if the parent exits
1203        * and we write to the err_report_pipe
1204        */
1205       signal (SIGPIPE, SIG_DFL);
1206
1207       /* Close the parent's end of the pipes. */
1208       close_and_invalidate (&child_err_report_pipe[READ_END]);
1209       close_and_invalidate (&babysitter_pipe[0]);
1210       
1211       /* Create the child that will exec () */
1212       grandchild_pid = fork ();
1213       
1214       if (grandchild_pid < 0)
1215         {
1216           write_err_and_exit (babysitter_pipe[1],
1217                               CHILD_FORK_FAILED);
1218           _dbus_assert_not_reached ("Got to code after write_err_and_exit()");
1219         }
1220       else if (grandchild_pid == 0)
1221         {
1222           do_exec (child_err_report_pipe[WRITE_END],
1223                    argv,
1224                    env,
1225                    child_setup, user_data);
1226           _dbus_assert_not_reached ("Got to code after exec() - should have exited on error");
1227         }
1228       else
1229         {
1230           babysit (grandchild_pid, babysitter_pipe[1]);
1231           _dbus_assert_not_reached ("Got to code after babysit()");
1232         }
1233     }
1234   else
1235     {      
1236       /* Close the uncared-about ends of the pipes */
1237       close_and_invalidate (&child_err_report_pipe[WRITE_END]);
1238       close_and_invalidate (&babysitter_pipe[1]);
1239
1240       sitter->socket_to_babysitter = babysitter_pipe[0];
1241       babysitter_pipe[0] = -1;
1242       
1243       sitter->error_pipe_from_child = child_err_report_pipe[READ_END];
1244       child_err_report_pipe[READ_END] = -1;
1245
1246       sitter->sitter_pid = pid;
1247
1248       if (sitter_p != NULL)
1249         *sitter_p = sitter;
1250       else
1251         _dbus_babysitter_unref (sitter);
1252
1253       dbus_free_string_array (env);
1254
1255       _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1256       
1257       return TRUE;
1258     }
1259
1260  cleanup_and_fail:
1261
1262   _DBUS_ASSERT_ERROR_IS_SET (error);
1263   
1264   close_and_invalidate (&child_err_report_pipe[READ_END]);
1265   close_and_invalidate (&child_err_report_pipe[WRITE_END]);
1266   close_and_invalidate (&babysitter_pipe[0]);
1267   close_and_invalidate (&babysitter_pipe[1]);
1268
1269   if (sitter != NULL)
1270     _dbus_babysitter_unref (sitter);
1271   
1272   return FALSE;
1273 }
1274
1275 /** @} */
1276
1277 #ifdef DBUS_BUILD_TESTS
1278
1279 static void
1280 _dbus_babysitter_block_for_child_exit (DBusBabysitter *sitter)
1281 {
1282   while (LIVE_CHILDREN (sitter))
1283     babysitter_iteration (sitter, TRUE);
1284 }
1285
1286 static dbus_bool_t
1287 check_spawn_nonexistent (void *data)
1288 {
1289   char *argv[4] = { NULL, NULL, NULL, NULL };
1290   DBusBabysitter *sitter = NULL;
1291   DBusError error = DBUS_ERROR_INIT;
1292
1293   /*** Test launching nonexistent binary */
1294   
1295   argv[0] = "/this/does/not/exist/32542sdgafgafdg";
1296   if (_dbus_spawn_async_with_babysitter (&sitter, argv,
1297                                          NULL, NULL, NULL,
1298                                          &error))
1299     {
1300       _dbus_babysitter_block_for_child_exit (sitter);
1301       _dbus_babysitter_set_child_exit_error (sitter, &error);
1302     }
1303
1304   if (sitter)
1305     _dbus_babysitter_unref (sitter);
1306
1307   if (!dbus_error_is_set (&error))
1308     {
1309       _dbus_warn ("Did not get an error launching nonexistent executable\n");
1310       return FALSE;
1311     }
1312
1313   if (!(dbus_error_has_name (&error, DBUS_ERROR_NO_MEMORY) ||
1314         dbus_error_has_name (&error, DBUS_ERROR_SPAWN_EXEC_FAILED)))
1315     {
1316       _dbus_warn ("Not expecting error when launching nonexistent executable: %s: %s\n",
1317                   error.name, error.message);
1318       dbus_error_free (&error);
1319       return FALSE;
1320     }
1321
1322   dbus_error_free (&error);
1323   
1324   return TRUE;
1325 }
1326
1327 static dbus_bool_t
1328 check_spawn_segfault (void *data)
1329 {
1330   char *argv[4] = { NULL, NULL, NULL, NULL };
1331   DBusBabysitter *sitter = NULL;
1332   DBusError error = DBUS_ERROR_INIT;
1333
1334   /*** Test launching segfault binary */
1335   
1336   argv[0] = TEST_SEGFAULT_BINARY;
1337   if (_dbus_spawn_async_with_babysitter (&sitter, argv,
1338                                          NULL, NULL, NULL,
1339                                          &error))
1340     {
1341       _dbus_babysitter_block_for_child_exit (sitter);
1342       _dbus_babysitter_set_child_exit_error (sitter, &error);
1343     }
1344
1345   if (sitter)
1346     _dbus_babysitter_unref (sitter);
1347
1348   if (!dbus_error_is_set (&error))
1349     {
1350       _dbus_warn ("Did not get an error launching segfaulting binary\n");
1351       return FALSE;
1352     }
1353
1354   if (!(dbus_error_has_name (&error, DBUS_ERROR_NO_MEMORY) ||
1355         dbus_error_has_name (&error, DBUS_ERROR_SPAWN_CHILD_SIGNALED)))
1356     {
1357       _dbus_warn ("Not expecting error when launching segfaulting executable: %s: %s\n",
1358                   error.name, error.message);
1359       dbus_error_free (&error);
1360       return FALSE;
1361     }
1362
1363   dbus_error_free (&error);
1364   
1365   return TRUE;
1366 }
1367
1368 static dbus_bool_t
1369 check_spawn_exit (void *data)
1370 {
1371   char *argv[4] = { NULL, NULL, NULL, NULL };
1372   DBusBabysitter *sitter = NULL;
1373   DBusError error = DBUS_ERROR_INIT;
1374
1375   /*** Test launching exit failure binary */
1376   
1377   argv[0] = TEST_EXIT_BINARY;
1378   if (_dbus_spawn_async_with_babysitter (&sitter, argv,
1379                                          NULL, NULL, NULL,
1380                                          &error))
1381     {
1382       _dbus_babysitter_block_for_child_exit (sitter);
1383       _dbus_babysitter_set_child_exit_error (sitter, &error);
1384     }
1385
1386   if (sitter)
1387     _dbus_babysitter_unref (sitter);
1388
1389   if (!dbus_error_is_set (&error))
1390     {
1391       _dbus_warn ("Did not get an error launching binary that exited with failure code\n");
1392       return FALSE;
1393     }
1394
1395   if (!(dbus_error_has_name (&error, DBUS_ERROR_NO_MEMORY) ||
1396         dbus_error_has_name (&error, DBUS_ERROR_SPAWN_CHILD_EXITED)))
1397     {
1398       _dbus_warn ("Not expecting error when launching exiting executable: %s: %s\n",
1399                   error.name, error.message);
1400       dbus_error_free (&error);
1401       return FALSE;
1402     }
1403
1404   dbus_error_free (&error);
1405   
1406   return TRUE;
1407 }
1408
1409 static dbus_bool_t
1410 check_spawn_and_kill (void *data)
1411 {
1412   char *argv[4] = { NULL, NULL, NULL, NULL };
1413   DBusBabysitter *sitter = NULL;
1414   DBusError error = DBUS_ERROR_INIT;
1415
1416   /*** Test launching sleeping binary then killing it */
1417
1418   argv[0] = TEST_SLEEP_FOREVER_BINARY;
1419   if (_dbus_spawn_async_with_babysitter (&sitter, argv,
1420                                          NULL, NULL, NULL,
1421                                          &error))
1422     {
1423       _dbus_babysitter_kill_child (sitter);
1424       
1425       _dbus_babysitter_block_for_child_exit (sitter);
1426       
1427       _dbus_babysitter_set_child_exit_error (sitter, &error);
1428     }
1429
1430   if (sitter)
1431     _dbus_babysitter_unref (sitter);
1432
1433   if (!dbus_error_is_set (&error))
1434     {
1435       _dbus_warn ("Did not get an error after killing spawned binary\n");
1436       return FALSE;
1437     }
1438
1439   if (!(dbus_error_has_name (&error, DBUS_ERROR_NO_MEMORY) ||
1440         dbus_error_has_name (&error, DBUS_ERROR_SPAWN_CHILD_SIGNALED)))
1441     {
1442       _dbus_warn ("Not expecting error when killing executable: %s: %s\n",
1443                   error.name, error.message);
1444       dbus_error_free (&error);
1445       return FALSE;
1446     }
1447
1448   dbus_error_free (&error);
1449   
1450   return TRUE;
1451 }
1452
1453 dbus_bool_t
1454 _dbus_spawn_test (const char *test_data_dir)
1455 {
1456   if (!_dbus_test_oom_handling ("spawn_nonexistent",
1457                                 check_spawn_nonexistent,
1458                                 NULL))
1459     return FALSE;
1460
1461   if (!_dbus_test_oom_handling ("spawn_segfault",
1462                                 check_spawn_segfault,
1463                                 NULL))
1464     return FALSE;
1465
1466   if (!_dbus_test_oom_handling ("spawn_exit",
1467                                 check_spawn_exit,
1468                                 NULL))
1469     return FALSE;
1470
1471   if (!_dbus_test_oom_handling ("spawn_and_kill",
1472                                 check_spawn_and_kill,
1473                                 NULL))
1474     return FALSE;
1475   
1476   return TRUE;
1477 }
1478 #endif