dbus-spawn.c

00001 /* -*- mode: C; c-file-style: "gnu" -*- */
00002 /* dbus-spawn.c Wrapper around fork/exec
00003  * 
00004  * Copyright (C) 2002, 2003, 2004  Red Hat, Inc.
00005  * Copyright (C) 2003 CodeFactory AB
00006  *
00007  * Licensed under the Academic Free License version 2.1
00008  * 
00009  * This program is free software; you can redistribute it and/or modify
00010  * it under the terms of the GNU General Public License as published by
00011  * the Free Software Foundation; either version 2 of the License, or
00012  * (at your option) any later version.
00013  *
00014  * This program is distributed in the hope that it will be useful,
00015  * but WITHOUT ANY WARRANTY; without even the implied warranty of
00016  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
00017  * GNU General Public License for more details.
00018  * 
00019  * You should have received a copy of the GNU General Public License
00020  * along with this program; if not, write to the Free Software
00021  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
00022  *
00023  */
00024 #include "dbus-spawn.h"
00025 #include "dbus-sysdeps.h"
00026 #include "dbus-internals.h"
00027 #include "dbus-test.h"
00028 #include "dbus-protocol.h"
00029 
00030 #include <unistd.h>
00031 #include <fcntl.h>
00032 #include <signal.h>
00033 #include <sys/wait.h>
00034 #include <errno.h>
00035 #include <stdlib.h>
00036 
00042 /*
00043  * I'm pretty sure this whole spawn file could be made simpler,
00044  * if you thought about it a bit.
00045  */
00046 
00050 typedef enum
00051 {
00052   READ_STATUS_OK,    
00053   READ_STATUS_ERROR, 
00054   READ_STATUS_EOF    
00055 } ReadStatus;
00056 
00057 static ReadStatus
00058 read_ints (int        fd,
00059            int       *buf,
00060            int        n_ints_in_buf,
00061            int       *n_ints_read,
00062            DBusError *error)
00063 {
00064   size_t bytes = 0;    
00065   ReadStatus retval;
00066   
00067   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
00068 
00069   retval = READ_STATUS_OK;
00070   
00071   while (TRUE)
00072     {
00073       size_t chunk;
00074       size_t to_read;
00075 
00076       to_read = sizeof (int) * n_ints_in_buf - bytes;
00077 
00078       if (to_read == 0)
00079         break;
00080 
00081     again:
00082       
00083       chunk = read (fd,
00084                     ((char*)buf) + bytes,
00085                     to_read);
00086       
00087       if (chunk < 0 && errno == EINTR)
00088         goto again;
00089           
00090       if (chunk < 0)
00091         {
00092           dbus_set_error (error,
00093                           DBUS_ERROR_SPAWN_FAILED,
00094                           "Failed to read from child pipe (%s)",
00095                           _dbus_strerror (errno));
00096 
00097           retval = READ_STATUS_ERROR;
00098           break;
00099         }
00100       else if (chunk == 0)
00101         {
00102           retval = READ_STATUS_EOF;
00103           break; /* EOF */
00104         }
00105       else /* chunk > 0 */
00106         bytes += chunk;
00107     }
00108 
00109   *n_ints_read = (int)(bytes / sizeof(int));
00110 
00111   return retval;
00112 }
00113 
00114 static ReadStatus
00115 read_pid (int        fd,
00116           pid_t     *buf,
00117           DBusError *error)
00118 {
00119   size_t bytes = 0;    
00120   ReadStatus retval;
00121   
00122   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
00123 
00124   retval = READ_STATUS_OK;
00125   
00126   while (TRUE)
00127     {
00128       size_t chunk;    
00129       size_t to_read;
00130       
00131       to_read = sizeof (pid_t) - bytes;
00132 
00133       if (to_read == 0)
00134         break;
00135 
00136     again:
00137       
00138       chunk = read (fd,
00139                     ((char*)buf) + bytes,
00140                     to_read);
00141       if (chunk < 0 && errno == EINTR)
00142         goto again;
00143           
00144       if (chunk < 0)
00145         {
00146           dbus_set_error (error,
00147                           DBUS_ERROR_SPAWN_FAILED,
00148                           "Failed to read from child pipe (%s)",
00149                           _dbus_strerror (errno));
00150 
00151           retval = READ_STATUS_ERROR;
00152           break;
00153         }
00154       else if (chunk == 0)
00155         {
00156           retval = READ_STATUS_EOF;
00157           break; /* EOF */
00158         }
00159       else /* chunk > 0 */
00160         bytes += chunk;
00161     }
00162 
00163   return retval;
00164 }
00165 
00166 /* The implementation uses an intermediate child between the main process
00167  * and the grandchild. The grandchild is our spawned process. The intermediate
00168  * child is a babysitter process; it keeps track of when the grandchild
00169  * exits/crashes, and reaps the grandchild.
00170  */
00171 
00172 /* Messages from children to parents */
00173 enum
00174 {
00175   CHILD_EXITED,            /* This message is followed by the exit status int */
00176   CHILD_FORK_FAILED,       /* Followed by errno */
00177   CHILD_EXEC_FAILED,       /* Followed by errno */
00178   CHILD_PID                /* Followed by pid_t */
00179 };
00180 
00184 struct DBusBabysitter
00185 {
00186   int refcount; 
00188   char *executable; 
00190   int socket_to_babysitter; 
00191   int error_pipe_from_child; 
00193   pid_t sitter_pid;  
00194   pid_t grandchild_pid; 
00196   DBusWatchList *watches; 
00198   DBusWatch *error_watch; 
00199   DBusWatch *sitter_watch; 
00201   int errnum; 
00202   int status; 
00203   unsigned int have_child_status : 1; 
00204   unsigned int have_fork_errnum : 1; 
00205   unsigned int have_exec_errnum : 1; 
00206 };
00207 
00208 static DBusBabysitter*
00209 _dbus_babysitter_new (void)
00210 {
00211   DBusBabysitter *sitter;
00212 
00213   sitter = dbus_new0 (DBusBabysitter, 1);
00214   if (sitter == NULL)
00215     return NULL;
00216 
00217   sitter->refcount = 1;
00218 
00219   sitter->socket_to_babysitter = -1;
00220   sitter->error_pipe_from_child = -1;
00221   
00222   sitter->sitter_pid = -1;
00223   sitter->grandchild_pid = -1;
00224 
00225   sitter->watches = _dbus_watch_list_new ();
00226   if (sitter->watches == NULL)
00227     goto failed;
00228   
00229   return sitter;
00230 
00231  failed:
00232   _dbus_babysitter_unref (sitter);
00233   return NULL;
00234 }
00235 
00242 DBusBabysitter *
00243 _dbus_babysitter_ref (DBusBabysitter *sitter)
00244 {
00245   _dbus_assert (sitter != NULL);
00246   _dbus_assert (sitter->refcount > 0);
00247   
00248   sitter->refcount += 1;
00249 
00250   return sitter;
00251 }
00252 
00261 void
00262 _dbus_babysitter_unref (DBusBabysitter *sitter)
00263 {
00264   _dbus_assert (sitter != NULL);
00265   _dbus_assert (sitter->refcount > 0);
00266   
00267   sitter->refcount -= 1;
00268   if (sitter->refcount == 0)
00269     {      
00270       if (sitter->socket_to_babysitter >= 0)
00271         {
00272           /* If we haven't forked other babysitters
00273            * since this babysitter and socket were
00274            * created then this close will cause the
00275            * babysitter to wake up from poll with
00276            * a hangup and then the babysitter will
00277            * quit itself.
00278            */
00279           _dbus_close_socket (sitter->socket_to_babysitter, NULL);
00280           sitter->socket_to_babysitter = -1;
00281         }
00282 
00283       if (sitter->error_pipe_from_child >= 0)
00284         {
00285           _dbus_close_socket (sitter->error_pipe_from_child, NULL);
00286           sitter->error_pipe_from_child = -1;
00287         }
00288 
00289       if (sitter->sitter_pid > 0)
00290         {
00291           int status;
00292           int ret;
00293 
00294           /* It's possible the babysitter died on its own above 
00295            * from the close, or was killed randomly
00296            * by some other process, so first try to reap it
00297            */
00298           ret = waitpid (sitter->sitter_pid, &status, WNOHANG);
00299 
00300           /* If we couldn't reap the child then kill it, and
00301            * try again
00302            */
00303           if (ret == 0)
00304             kill (sitter->sitter_pid, SIGKILL);
00305 
00306         again:
00307           if (ret == 0)
00308             ret = waitpid (sitter->sitter_pid, &status, 0);
00309 
00310           if (ret < 0)
00311             {
00312               if (errno == EINTR)
00313                 goto again;
00314               else if (errno == ECHILD)
00315                 _dbus_warn ("Babysitter process not available to be reaped; should not happen\n");
00316               else
00317                 _dbus_warn ("Unexpected error %d in waitpid() for babysitter: %s\n",
00318                             errno, _dbus_strerror (errno));
00319             }
00320           else
00321             {
00322               _dbus_verbose ("Reaped %ld, waiting for babysitter %ld\n",
00323                              (long) ret, (long) sitter->sitter_pid);
00324               
00325               if (WIFEXITED (sitter->status))
00326                 _dbus_verbose ("Babysitter exited with status %d\n",
00327                                WEXITSTATUS (sitter->status));
00328               else if (WIFSIGNALED (sitter->status))
00329                 _dbus_verbose ("Babysitter received signal %d\n",
00330                                WTERMSIG (sitter->status));
00331               else
00332                 _dbus_verbose ("Babysitter exited abnormally\n");
00333             }
00334 
00335           sitter->sitter_pid = -1;
00336         }
00337       
00338       if (sitter->error_watch)
00339         {
00340           _dbus_watch_invalidate (sitter->error_watch);
00341           _dbus_watch_unref (sitter->error_watch);
00342           sitter->error_watch = NULL;
00343         }
00344 
00345       if (sitter->sitter_watch)
00346         {
00347           _dbus_watch_invalidate (sitter->sitter_watch);
00348           _dbus_watch_unref (sitter->sitter_watch);
00349           sitter->sitter_watch = NULL;
00350         }
00351       
00352       if (sitter->watches)
00353         _dbus_watch_list_free (sitter->watches);
00354 
00355       dbus_free (sitter->executable);
00356       
00357       dbus_free (sitter);
00358     }
00359 }
00360 
00361 static ReadStatus
00362 read_data (DBusBabysitter *sitter,
00363            int             fd)
00364 {
00365   int what;
00366   int got;
00367   DBusError error;
00368   ReadStatus r;
00369   
00370   dbus_error_init (&error);
00371   
00372   r = read_ints (fd, &what, 1, &got, &error);
00373 
00374   switch (r)
00375     {
00376     case READ_STATUS_ERROR:
00377       _dbus_warn ("Failed to read data from fd %d: %s\n", fd, error.message);
00378       dbus_error_free (&error);
00379       return r;
00380 
00381     case READ_STATUS_EOF:
00382       return r;
00383 
00384     case READ_STATUS_OK:
00385       break;
00386     }
00387   
00388   if (got == 1)
00389     {
00390       switch (what)
00391         {
00392         case CHILD_EXITED:
00393         case CHILD_FORK_FAILED:
00394         case CHILD_EXEC_FAILED:
00395           {
00396             int arg;
00397             
00398             r = read_ints (fd, &arg, 1, &got, &error);
00399 
00400             switch (r)
00401               {
00402               case READ_STATUS_ERROR:
00403                 _dbus_warn ("Failed to read arg from fd %d: %s\n", fd, error.message);
00404                 dbus_error_free (&error);
00405                 return r;
00406               case READ_STATUS_EOF:
00407                 return r;
00408               case READ_STATUS_OK:
00409                 break;
00410               }
00411             
00412             if (got == 1)
00413               {
00414                 if (what == CHILD_EXITED)
00415                   {
00416                     sitter->have_child_status = TRUE;
00417                     sitter->status = arg;
00418                     _dbus_verbose ("recorded child status exited = %d signaled = %d exitstatus = %d termsig = %d\n",
00419                                    WIFEXITED (sitter->status), WIFSIGNALED (sitter->status),
00420                                    WEXITSTATUS (sitter->status), WTERMSIG (sitter->status));
00421                   }
00422                 else if (what == CHILD_FORK_FAILED)
00423                   {
00424                     sitter->have_fork_errnum = TRUE;
00425                     sitter->errnum = arg;
00426                     _dbus_verbose ("recorded fork errnum %d\n", sitter->errnum);
00427                   }
00428                 else if (what == CHILD_EXEC_FAILED)
00429                   {
00430                     sitter->have_exec_errnum = TRUE;
00431                     sitter->errnum = arg;
00432                     _dbus_verbose ("recorded exec errnum %d\n", sitter->errnum);
00433                   }
00434               }
00435           }
00436           break;
00437         case CHILD_PID:
00438           {
00439             pid_t pid = -1;
00440 
00441             r = read_pid (fd, &pid, &error);
00442             
00443             switch (r)
00444               {
00445               case READ_STATUS_ERROR:
00446                 _dbus_warn ("Failed to read PID from fd %d: %s\n", fd, error.message);
00447                 dbus_error_free (&error);
00448                 return r;
00449               case READ_STATUS_EOF:
00450                 return r;
00451               case READ_STATUS_OK:
00452                 break;
00453               }
00454             
00455             sitter->grandchild_pid = pid;
00456             
00457             _dbus_verbose ("recorded grandchild pid %d\n", sitter->grandchild_pid);
00458           }
00459           break;
00460         default:
00461           _dbus_warn ("Unknown message received from babysitter process\n");
00462           break;
00463         }
00464     }
00465 
00466   return r;
00467 }
00468 
00469 static void
00470 close_socket_to_babysitter (DBusBabysitter *sitter)
00471 {
00472   _dbus_verbose ("Closing babysitter\n");
00473   _dbus_close_socket (sitter->socket_to_babysitter, NULL);
00474   sitter->socket_to_babysitter = -1;
00475 }
00476 
00477 static void
00478 close_error_pipe_from_child (DBusBabysitter *sitter)
00479 {
00480   _dbus_verbose ("Closing child error\n");
00481   _dbus_close_socket (sitter->error_pipe_from_child, NULL);
00482   sitter->error_pipe_from_child = -1;
00483 }
00484 
00485 static void
00486 handle_babysitter_socket (DBusBabysitter *sitter,
00487                           int             revents)
00488 {
00489   /* Even if we have POLLHUP, we want to keep reading
00490    * data until POLLIN goes away; so this function only
00491    * looks at HUP/ERR if no IN is set.
00492    */
00493   if (revents & _DBUS_POLLIN)
00494     {
00495       _dbus_verbose ("Reading data from babysitter\n");
00496       if (read_data (sitter, sitter->socket_to_babysitter) != READ_STATUS_OK)
00497         close_socket_to_babysitter (sitter);
00498     }
00499   else if (revents & (_DBUS_POLLERR | _DBUS_POLLHUP))
00500     {
00501       close_socket_to_babysitter (sitter);
00502     }
00503 }
00504 
00505 static void
00506 handle_error_pipe (DBusBabysitter *sitter,
00507                    int             revents)
00508 {
00509   if (revents & _DBUS_POLLIN)
00510     {
00511       _dbus_verbose ("Reading data from child error\n");
00512       if (read_data (sitter, sitter->error_pipe_from_child) != READ_STATUS_OK)
00513         close_error_pipe_from_child (sitter);
00514     }
00515   else if (revents & (_DBUS_POLLERR | _DBUS_POLLHUP))
00516     {
00517       close_error_pipe_from_child (sitter);
00518     }
00519 }
00520 
00521 /* returns whether there were any poll events handled */
00522 static dbus_bool_t
00523 babysitter_iteration (DBusBabysitter *sitter,
00524                       dbus_bool_t     block)
00525 {
00526   DBusPollFD fds[2];
00527   int i;
00528   dbus_bool_t descriptors_ready;
00529 
00530   descriptors_ready = FALSE;
00531   
00532   i = 0;
00533 
00534   if (sitter->error_pipe_from_child >= 0)
00535     {
00536       fds[i].fd = sitter->error_pipe_from_child;
00537       fds[i].events = _DBUS_POLLIN;
00538       fds[i].revents = 0;
00539       ++i;
00540     }
00541   
00542   if (sitter->socket_to_babysitter >= 0)
00543     {
00544       fds[i].fd = sitter->socket_to_babysitter;
00545       fds[i].events = _DBUS_POLLIN;
00546       fds[i].revents = 0;
00547       ++i;
00548     }
00549 
00550   if (i > 0)
00551     {
00552       int ret;
00553 
00554       ret = _dbus_poll (fds, i, 0);
00555       if (ret == 0 && block)
00556         ret = _dbus_poll (fds, i, -1);
00557       
00558       if (ret > 0)
00559         {
00560           descriptors_ready = TRUE;
00561           
00562           while (i > 0)
00563             {
00564               --i;
00565               if (fds[i].fd == sitter->error_pipe_from_child)
00566                 handle_error_pipe (sitter, fds[i].revents);
00567               else if (fds[i].fd == sitter->socket_to_babysitter)
00568                 handle_babysitter_socket (sitter, fds[i].revents);
00569             }
00570         }
00571     }
00572 
00573   return descriptors_ready;
00574 }
00575 
00580 #define LIVE_CHILDREN(sitter) ((sitter)->socket_to_babysitter >= 0 || (sitter)->error_pipe_from_child >= 0)
00581 
00588 void
00589 _dbus_babysitter_kill_child (DBusBabysitter *sitter)
00590 {
00591   /* be sure we have the PID of the child */
00592   while (LIVE_CHILDREN (sitter) &&
00593          sitter->grandchild_pid == -1)
00594     babysitter_iteration (sitter, TRUE);
00595 
00596   _dbus_verbose ("Got child PID %ld for killing\n",
00597                  (long) sitter->grandchild_pid);
00598   
00599   if (sitter->grandchild_pid == -1)
00600     return; /* child is already dead, or we're so hosed we'll never recover */
00601 
00602   kill (sitter->grandchild_pid, SIGKILL);
00603 }
00604 
00610 dbus_bool_t
00611 _dbus_babysitter_get_child_exited (DBusBabysitter *sitter)
00612 {
00613 
00614   /* Be sure we're up-to-date */
00615   while (LIVE_CHILDREN (sitter) &&
00616          babysitter_iteration (sitter, FALSE))
00617     ;
00618 
00619   /* We will have exited the babysitter when the child has exited */
00620   return sitter->socket_to_babysitter < 0;
00621 }
00622 
00632 void
00633 _dbus_babysitter_set_child_exit_error (DBusBabysitter *sitter,
00634                                        DBusError      *error)
00635 {
00636   if (!_dbus_babysitter_get_child_exited (sitter))
00637     return;
00638 
00639   /* Note that if exec fails, we will also get a child status
00640    * from the babysitter saying the child exited,
00641    * so we need to give priority to the exec error
00642    */
00643   if (sitter->have_exec_errnum)
00644     {
00645       dbus_set_error (error, DBUS_ERROR_SPAWN_EXEC_FAILED,
00646                       "Failed to execute program %s: %s",
00647                       sitter->executable, _dbus_strerror (sitter->errnum));
00648     }
00649   else if (sitter->have_fork_errnum)
00650     {
00651       dbus_set_error (error, DBUS_ERROR_NO_MEMORY,
00652                       "Failed to fork a new process %s: %s",
00653                       sitter->executable, _dbus_strerror (sitter->errnum));
00654     }
00655   else if (sitter->have_child_status)
00656     {
00657       if (WIFEXITED (sitter->status))
00658         dbus_set_error (error, DBUS_ERROR_SPAWN_CHILD_EXITED,
00659                         "Process %s exited with status %d",
00660                         sitter->executable, WEXITSTATUS (sitter->status));
00661       else if (WIFSIGNALED (sitter->status))
00662         dbus_set_error (error, DBUS_ERROR_SPAWN_CHILD_SIGNALED,
00663                         "Process %s received signal %d",
00664                         sitter->executable, WTERMSIG (sitter->status));
00665       else
00666         dbus_set_error (error, DBUS_ERROR_FAILED,
00667                         "Process %s exited abnormally",
00668                         sitter->executable);
00669     }
00670   else
00671     {
00672       dbus_set_error (error, DBUS_ERROR_FAILED,
00673                       "Process %s exited, reason unknown",
00674                       sitter->executable);
00675     }
00676 }
00677 
00690 dbus_bool_t
00691 _dbus_babysitter_set_watch_functions (DBusBabysitter            *sitter,
00692                                       DBusAddWatchFunction       add_function,
00693                                       DBusRemoveWatchFunction    remove_function,
00694                                       DBusWatchToggledFunction   toggled_function,
00695                                       void                      *data,
00696                                       DBusFreeFunction           free_data_function)
00697 {
00698   return _dbus_watch_list_set_functions (sitter->watches,
00699                                          add_function,
00700                                          remove_function,
00701                                          toggled_function,
00702                                          data,
00703                                          free_data_function);
00704 }
00705 
00706 static dbus_bool_t
00707 handle_watch (DBusWatch       *watch,
00708               unsigned int     condition,
00709               void            *data)
00710 {
00711   DBusBabysitter *sitter = data;
00712   int revents;
00713   int fd;
00714   
00715   revents = 0;
00716   if (condition & DBUS_WATCH_READABLE)
00717     revents |= _DBUS_POLLIN;
00718   if (condition & DBUS_WATCH_ERROR)
00719     revents |= _DBUS_POLLERR;
00720   if (condition & DBUS_WATCH_HANGUP)
00721     revents |= _DBUS_POLLHUP;
00722 
00723   fd = dbus_watch_get_fd (watch);
00724 
00725   if (fd == sitter->error_pipe_from_child)
00726     handle_error_pipe (sitter, revents);
00727   else if (fd == sitter->socket_to_babysitter)
00728     handle_babysitter_socket (sitter, revents);
00729 
00730   while (LIVE_CHILDREN (sitter) &&
00731          babysitter_iteration (sitter, FALSE))
00732     ;
00733   
00734   return TRUE;
00735 }
00736 
00738 #define READ_END 0
00739 
00740 #define WRITE_END 1
00741 
00742 
00743 /* Avoids a danger in threaded situations (calling close()
00744  * on a file descriptor twice, and another thread has
00745  * re-opened it since the first close)
00746  */
00747 static int
00748 close_and_invalidate (int *fd)
00749 {
00750   int ret;
00751 
00752   if (*fd < 0)
00753     return -1;
00754   else
00755     {
00756       ret = _dbus_close_socket (*fd, NULL);
00757       *fd = -1;
00758     }
00759 
00760   return ret;
00761 }
00762 
00763 static dbus_bool_t
00764 make_pipe (int         p[2],
00765            DBusError  *error)
00766 {
00767   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
00768   
00769   if (pipe (p) < 0)
00770     {
00771       dbus_set_error (error,
00772                       DBUS_ERROR_SPAWN_FAILED,
00773                       "Failed to create pipe for communicating with child process (%s)",
00774                       _dbus_strerror (errno));
00775       return FALSE;
00776     }
00777 
00778   return TRUE;
00779 }
00780 
00781 static void
00782 do_write (int fd, const void *buf, size_t count)
00783 {
00784   size_t bytes_written;
00785   int ret;
00786   
00787   bytes_written = 0;
00788   
00789  again:
00790   
00791   ret = write (fd, ((const char*)buf) + bytes_written, count - bytes_written);
00792 
00793   if (ret < 0)
00794     {
00795       if (errno == EINTR)
00796         goto again;
00797       else
00798         {
00799           _dbus_warn ("Failed to write data to pipe!\n");
00800           exit (1); /* give up, we suck */
00801         }
00802     }
00803   else
00804     bytes_written += ret;
00805   
00806   if (bytes_written < count)
00807     goto again;
00808 }
00809 
00810 static void
00811 write_err_and_exit (int fd, int msg)
00812 {
00813   int en = errno;
00814 
00815   do_write (fd, &msg, sizeof (msg));
00816   do_write (fd, &en, sizeof (en));
00817   
00818   exit (1);
00819 }
00820 
00821 static void
00822 write_pid (int fd, pid_t pid)
00823 {
00824   int msg = CHILD_PID;
00825   
00826   do_write (fd, &msg, sizeof (msg));
00827   do_write (fd, &pid, sizeof (pid));
00828 }
00829 
00830 static void
00831 write_status_and_exit (int fd, int status)
00832 {
00833   int msg = CHILD_EXITED;
00834   
00835   do_write (fd, &msg, sizeof (msg));
00836   do_write (fd, &status, sizeof (status));
00837   
00838   exit (0);
00839 }
00840 
00841 static void
00842 do_exec (int                       child_err_report_fd,
00843          char                    **argv,
00844          DBusSpawnChildSetupFunc   child_setup,
00845          void                     *user_data)
00846 {
00847 #ifdef DBUS_BUILD_TESTS
00848   int i, max_open;
00849 #endif
00850   /* Change oom protection to off to prevent inheritance from dbus server */
00851   int oom = open ("/proc/self/oom_adj", O_WRONLY|O_SYNC);
00852   if (oom >= 0)
00853    {
00854      write (oom, "0", sizeof (char));
00855      _dbus_close (oom, NULL);
00856    }
00857 
00858   _dbus_verbose_reset ();
00859   _dbus_verbose ("Child process has PID %lu\n",
00860                  _dbus_getpid ());
00861   
00862   if (child_setup)
00863     (* child_setup) (user_data);
00864 
00865 #ifdef DBUS_BUILD_TESTS
00866   max_open = sysconf (_SC_OPEN_MAX);
00867   
00868   for (i = 3; i < max_open; i++)
00869     {
00870       int retval;
00871 
00872       if (i == child_err_report_fd)
00873         continue;
00874       
00875       retval = fcntl (i, F_GETFD);
00876 
00877       if (retval != -1 && !(retval & FD_CLOEXEC))
00878         _dbus_warn ("Fd %d did not have the close-on-exec flag set!\n", i);
00879     }
00880 #endif
00881   
00882   execv (argv[0], argv);
00883   
00884   /* Exec failed */
00885   write_err_and_exit (child_err_report_fd,
00886                       CHILD_EXEC_FAILED);
00887 }
00888 
00889 static void
00890 check_babysit_events (pid_t grandchild_pid,
00891                       int   parent_pipe,
00892                       int   revents)
00893 {
00894   pid_t ret;
00895   int status;
00896   
00897   do
00898     {
00899       ret = waitpid (grandchild_pid, &status, WNOHANG);
00900       /* The man page says EINTR can't happen with WNOHANG,
00901        * but there are reports of it (maybe only with valgrind?)
00902        */
00903     }
00904   while (ret < 0 && errno == EINTR);
00905 
00906   if (ret == 0)
00907     {
00908       _dbus_verbose ("no child exited\n");
00909       
00910       ; /* no child exited */
00911     }
00912   else if (ret < 0)
00913     {
00914       /* This isn't supposed to happen. */
00915       _dbus_warn ("unexpected waitpid() failure in check_babysit_events(): %s\n",
00916                   _dbus_strerror (errno));
00917       exit (1);
00918     }
00919   else if (ret == grandchild_pid)
00920     {
00921       /* Child exited */
00922       _dbus_verbose ("reaped child pid %ld\n", (long) ret);
00923       
00924       write_status_and_exit (parent_pipe, status);
00925     }
00926   else
00927     {
00928       _dbus_warn ("waitpid() reaped pid %d that we've never heard of\n",
00929                   (int) ret);
00930       exit (1);
00931     }
00932 
00933   if (revents & _DBUS_POLLIN)
00934     {
00935       _dbus_verbose ("babysitter got POLLIN from parent pipe\n");
00936     }
00937 
00938   if (revents & (_DBUS_POLLERR | _DBUS_POLLHUP))
00939     {
00940       /* Parent is gone, so we just exit */
00941       _dbus_verbose ("babysitter got POLLERR or POLLHUP from parent\n");
00942       exit (0);
00943     }
00944 }
00945 
00946 static int babysit_sigchld_pipe = -1;
00947 
00948 static void
00949 babysit_signal_handler (int signo)
00950 {
00951   char b = '\0';
00952  again:
00953   write (babysit_sigchld_pipe, &b, 1);
00954   if (errno == EINTR)
00955     goto again;
00956 }
00957 
00958 static void
00959 babysit (pid_t grandchild_pid,
00960          int   parent_pipe)
00961 {
00962   int sigchld_pipe[2];
00963 
00964   /* We don't exec, so we keep parent state, such as the pid that
00965    * _dbus_verbose() uses. Reset the pid here.
00966    */
00967   _dbus_verbose_reset ();
00968   
00969   /* I thought SIGCHLD would just wake up the poll, but
00970    * that didn't seem to work, so added this pipe.
00971    * Probably the pipe is more likely to work on busted
00972    * operating systems anyhow.
00973    */
00974   if (pipe (sigchld_pipe) < 0)
00975     {
00976       _dbus_warn ("Not enough file descriptors to create pipe in babysitter process\n");
00977       exit (1);
00978     }
00979 
00980   babysit_sigchld_pipe = sigchld_pipe[WRITE_END];
00981 
00982   _dbus_set_signal_handler (SIGCHLD, babysit_signal_handler);
00983   
00984   write_pid (parent_pipe, grandchild_pid);
00985 
00986   check_babysit_events (grandchild_pid, parent_pipe, 0);
00987 
00988   while (TRUE)
00989     {
00990       DBusPollFD pfds[2];
00991       
00992       pfds[0].fd = parent_pipe;
00993       pfds[0].events = _DBUS_POLLIN;
00994       pfds[0].revents = 0;
00995 
00996       pfds[1].fd = sigchld_pipe[READ_END];
00997       pfds[1].events = _DBUS_POLLIN;
00998       pfds[1].revents = 0;
00999       
01000       _dbus_poll (pfds, _DBUS_N_ELEMENTS (pfds), -1);
01001 
01002       if (pfds[0].revents != 0)
01003         {
01004           check_babysit_events (grandchild_pid, parent_pipe, pfds[0].revents);
01005         }
01006       else if (pfds[1].revents & _DBUS_POLLIN)
01007         {
01008           char b;
01009           read (sigchld_pipe[READ_END], &b, 1);
01010           /* do waitpid check */
01011           check_babysit_events (grandchild_pid, parent_pipe, 0);
01012         }
01013     }
01014   
01015   exit (1);
01016 }
01017 
01036 dbus_bool_t
01037 _dbus_spawn_async_with_babysitter (DBusBabysitter          **sitter_p,
01038                                    char                    **argv,
01039                                    DBusSpawnChildSetupFunc   child_setup,
01040                                    void                     *user_data,
01041                                    DBusError                *error)
01042 {
01043   DBusBabysitter *sitter;
01044   int child_err_report_pipe[2] = { -1, -1 };
01045   int babysitter_pipe[2] = { -1, -1 };
01046   pid_t pid;
01047   
01048   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
01049 
01050   *sitter_p = NULL;
01051   sitter = NULL;
01052 
01053   sitter = _dbus_babysitter_new ();
01054   if (sitter == NULL)
01055     {
01056       dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
01057       return FALSE;
01058     }
01059 
01060   sitter->executable = _dbus_strdup (argv[0]);
01061   if (sitter->executable == NULL)
01062     {
01063       dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
01064       goto cleanup_and_fail;
01065     }
01066   
01067   if (!make_pipe (child_err_report_pipe, error))
01068     goto cleanup_and_fail;
01069 
01070   _dbus_fd_set_close_on_exec (child_err_report_pipe[READ_END]);
01071   _dbus_fd_set_close_on_exec (child_err_report_pipe[WRITE_END]);
01072 
01073   if (!_dbus_full_duplex_pipe (&babysitter_pipe[0], &babysitter_pipe[1], TRUE, error))
01074     goto cleanup_and_fail;
01075 
01076   _dbus_fd_set_close_on_exec (babysitter_pipe[0]);
01077   _dbus_fd_set_close_on_exec (babysitter_pipe[1]);
01078 
01079   /* Setting up the babysitter is only useful in the parent,
01080    * but we don't want to run out of memory and fail
01081    * after we've already forked, since then we'd leak
01082    * child processes everywhere.
01083    */
01084   sitter->error_watch = _dbus_watch_new (child_err_report_pipe[READ_END],
01085                                          DBUS_WATCH_READABLE,
01086                                          TRUE, handle_watch, sitter, NULL);
01087   if (sitter->error_watch == NULL)
01088     {
01089       dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
01090       goto cleanup_and_fail;
01091     }
01092         
01093   if (!_dbus_watch_list_add_watch (sitter->watches,  sitter->error_watch))
01094     {
01095       dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
01096       goto cleanup_and_fail;
01097     }
01098       
01099   sitter->sitter_watch = _dbus_watch_new (babysitter_pipe[0],
01100                                           DBUS_WATCH_READABLE,
01101                                           TRUE, handle_watch, sitter, NULL);
01102   if (sitter->sitter_watch == NULL)
01103     {
01104       dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
01105       goto cleanup_and_fail;
01106     }
01107       
01108   if (!_dbus_watch_list_add_watch (sitter->watches,  sitter->sitter_watch))
01109     {
01110       dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
01111       goto cleanup_and_fail;
01112     }
01113 
01114   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
01115   
01116   pid = fork ();
01117   
01118   if (pid < 0)
01119     {
01120       dbus_set_error (error,
01121                       DBUS_ERROR_SPAWN_FORK_FAILED,
01122                       "Failed to fork (%s)",
01123                       _dbus_strerror (errno));
01124       goto cleanup_and_fail;
01125     }
01126   else if (pid == 0)
01127     {
01128       /* Immediate child, this is the babysitter process. */
01129       int grandchild_pid;
01130       
01131       /* Be sure we crash if the parent exits
01132        * and we write to the err_report_pipe
01133        */
01134       signal (SIGPIPE, SIG_DFL);
01135 
01136       /* Close the parent's end of the pipes. */
01137       close_and_invalidate (&child_err_report_pipe[READ_END]);
01138       close_and_invalidate (&babysitter_pipe[0]);
01139       
01140       /* Create the child that will exec () */
01141       grandchild_pid = fork ();
01142       
01143       if (grandchild_pid < 0)
01144         {
01145           write_err_and_exit (babysitter_pipe[1],
01146                               CHILD_FORK_FAILED);
01147           _dbus_assert_not_reached ("Got to code after write_err_and_exit()");
01148         }
01149       else if (grandchild_pid == 0)
01150         {
01151           int p;
01152           /* put the child into a new session and process group, so that
01153            * killpg() can be used safely */
01154           if (setsid () == -1)
01155             _dbus_warn ("setsid() failed: %s\n", _dbus_strerror (errno));
01156           errno = 0;
01157           p = getpriority(PRIO_PROCESS, 0);
01158           if (!errno && p < 0) {
01159             setpriority(PRIO_PROCESS, 0, 0);
01160           }
01161           do_exec (child_err_report_pipe[WRITE_END],
01162                    argv,
01163                    child_setup, user_data);
01164           _dbus_assert_not_reached ("Got to code after exec() - should have exited on error");
01165         }
01166       else
01167         {
01168           babysit (grandchild_pid, babysitter_pipe[1]);
01169           _dbus_assert_not_reached ("Got to code after babysit()");
01170         }
01171     }
01172   else
01173     {      
01174       /* Close the uncared-about ends of the pipes */
01175       close_and_invalidate (&child_err_report_pipe[WRITE_END]);
01176       close_and_invalidate (&babysitter_pipe[1]);
01177 
01178       sitter->socket_to_babysitter = babysitter_pipe[0];
01179       babysitter_pipe[0] = -1;
01180       
01181       sitter->error_pipe_from_child = child_err_report_pipe[READ_END];
01182       child_err_report_pipe[READ_END] = -1;
01183 
01184       sitter->sitter_pid = pid;
01185 
01186       if (sitter_p != NULL)
01187         *sitter_p = sitter;
01188       else
01189         _dbus_babysitter_unref (sitter);
01190 
01191       _DBUS_ASSERT_ERROR_IS_CLEAR (error);
01192       
01193       return TRUE;
01194     }
01195 
01196  cleanup_and_fail:
01197 
01198   _DBUS_ASSERT_ERROR_IS_SET (error);
01199   
01200   close_and_invalidate (&child_err_report_pipe[READ_END]);
01201   close_and_invalidate (&child_err_report_pipe[WRITE_END]);
01202   close_and_invalidate (&babysitter_pipe[0]);
01203   close_and_invalidate (&babysitter_pipe[1]);
01204 
01205   if (sitter != NULL)
01206     _dbus_babysitter_unref (sitter);
01207   
01208   return FALSE;
01209 }
01210 
01213 #ifdef DBUS_BUILD_TESTS
01214 
01215 static void
01216 _dbus_babysitter_block_for_child_exit (DBusBabysitter *sitter)
01217 {
01218   while (LIVE_CHILDREN (sitter))
01219     babysitter_iteration (sitter, TRUE);
01220 }
01221 
01222 static dbus_bool_t
01223 check_spawn_nonexistent (void *data)
01224 {
01225   char *argv[4] = { NULL, NULL, NULL, NULL };
01226   DBusBabysitter *sitter;
01227   DBusError error;
01228   
01229   sitter = NULL;
01230   
01231   dbus_error_init (&error);
01232 
01233   /*** Test launching nonexistent binary */
01234   
01235   argv[0] = "/this/does/not/exist/32542sdgafgafdg";
01236   if (_dbus_spawn_async_with_babysitter (&sitter, argv,
01237                                          NULL, NULL,
01238                                          &error))
01239     {
01240       _dbus_babysitter_block_for_child_exit (sitter);
01241       _dbus_babysitter_set_child_exit_error (sitter, &error);
01242     }
01243 
01244   if (sitter)
01245     _dbus_babysitter_unref (sitter);
01246 
01247   if (!dbus_error_is_set (&error))
01248     {
01249       _dbus_warn ("Did not get an error launching nonexistent executable\n");
01250       return FALSE;
01251     }
01252 
01253   if (!(dbus_error_has_name (&error, DBUS_ERROR_NO_MEMORY) ||
01254         dbus_error_has_name (&error, DBUS_ERROR_SPAWN_EXEC_FAILED)))
01255     {
01256       _dbus_warn ("Not expecting error when launching nonexistent executable: %s: %s\n",
01257                   error.name, error.message);
01258       dbus_error_free (&error);
01259       return FALSE;
01260     }
01261 
01262   dbus_error_free (&error);
01263   
01264   return TRUE;
01265 }
01266 
01267 static dbus_bool_t
01268 check_spawn_segfault (void *data)
01269 {
01270   char *argv[4] = { NULL, NULL, NULL, NULL };
01271   DBusBabysitter *sitter;
01272   DBusError error;
01273   
01274   sitter = NULL;
01275   
01276   dbus_error_init (&error);
01277 
01278   /*** Test launching segfault binary */
01279   
01280   argv[0] = TEST_SEGFAULT_BINARY;
01281   if (_dbus_spawn_async_with_babysitter (&sitter, argv,
01282                                          NULL, NULL,
01283                                          &error))
01284     {
01285       _dbus_babysitter_block_for_child_exit (sitter);
01286       _dbus_babysitter_set_child_exit_error (sitter, &error);
01287     }
01288 
01289   if (sitter)
01290     _dbus_babysitter_unref (sitter);
01291 
01292   if (!dbus_error_is_set (&error))
01293     {
01294       _dbus_warn ("Did not get an error launching segfaulting binary\n");
01295       return FALSE;
01296     }
01297 
01298   if (!(dbus_error_has_name (&error, DBUS_ERROR_NO_MEMORY) ||
01299         dbus_error_has_name (&error, DBUS_ERROR_SPAWN_CHILD_SIGNALED)))
01300     {
01301       _dbus_warn ("Not expecting error when launching segfaulting executable: %s: %s\n",
01302                   error.name, error.message);
01303       dbus_error_free (&error);
01304       return FALSE;
01305     }
01306 
01307   dbus_error_free (&error);
01308   
01309   return TRUE;
01310 }
01311 
01312 static dbus_bool_t
01313 check_spawn_exit (void *data)
01314 {
01315   char *argv[4] = { NULL, NULL, NULL, NULL };
01316   DBusBabysitter *sitter;
01317   DBusError error;
01318   
01319   sitter = NULL;
01320   
01321   dbus_error_init (&error);
01322 
01323   /*** Test launching exit failure binary */
01324   
01325   argv[0] = TEST_EXIT_BINARY;
01326   if (_dbus_spawn_async_with_babysitter (&sitter, argv,
01327                                          NULL, NULL,
01328                                          &error))
01329     {
01330       _dbus_babysitter_block_for_child_exit (sitter);
01331       _dbus_babysitter_set_child_exit_error (sitter, &error);
01332     }
01333 
01334   if (sitter)
01335     _dbus_babysitter_unref (sitter);
01336 
01337   if (!dbus_error_is_set (&error))
01338     {
01339       _dbus_warn ("Did not get an error launching binary that exited with failure code\n");
01340       return FALSE;
01341     }
01342 
01343   if (!(dbus_error_has_name (&error, DBUS_ERROR_NO_MEMORY) ||
01344         dbus_error_has_name (&error, DBUS_ERROR_SPAWN_CHILD_EXITED)))
01345     {
01346       _dbus_warn ("Not expecting error when launching exiting executable: %s: %s\n",
01347                   error.name, error.message);
01348       dbus_error_free (&error);
01349       return FALSE;
01350     }
01351 
01352   dbus_error_free (&error);
01353   
01354   return TRUE;
01355 }
01356 
01357 static dbus_bool_t
01358 check_spawn_and_kill (void *data)
01359 {
01360   char *argv[4] = { NULL, NULL, NULL, NULL };
01361   DBusBabysitter *sitter;
01362   DBusError error;
01363   
01364   sitter = NULL;
01365   
01366   dbus_error_init (&error);
01367 
01368   /*** Test launching sleeping binary then killing it */
01369 
01370   argv[0] = TEST_SLEEP_FOREVER_BINARY;
01371   if (_dbus_spawn_async_with_babysitter (&sitter, argv,
01372                                          NULL, NULL,
01373                                          &error))
01374     {
01375       _dbus_babysitter_kill_child (sitter);
01376       
01377       _dbus_babysitter_block_for_child_exit (sitter);
01378       
01379       _dbus_babysitter_set_child_exit_error (sitter, &error);
01380     }
01381 
01382   if (sitter)
01383     _dbus_babysitter_unref (sitter);
01384 
01385   if (!dbus_error_is_set (&error))
01386     {
01387       _dbus_warn ("Did not get an error after killing spawned binary\n");
01388       return FALSE;
01389     }
01390 
01391   if (!(dbus_error_has_name (&error, DBUS_ERROR_NO_MEMORY) ||
01392         dbus_error_has_name (&error, DBUS_ERROR_SPAWN_CHILD_SIGNALED)))
01393     {
01394       _dbus_warn ("Not expecting error when killing executable: %s: %s\n",
01395                   error.name, error.message);
01396       dbus_error_free (&error);
01397       return FALSE;
01398     }
01399 
01400   dbus_error_free (&error);
01401   
01402   return TRUE;
01403 }
01404 
01405 dbus_bool_t
01406 _dbus_spawn_test (const char *test_data_dir)
01407 {
01408   if (!_dbus_test_oom_handling ("spawn_nonexistent",
01409                                 check_spawn_nonexistent,
01410                                 NULL))
01411     return FALSE;
01412 
01413   if (!_dbus_test_oom_handling ("spawn_segfault",
01414                                 check_spawn_segfault,
01415                                 NULL))
01416     return FALSE;
01417 
01418   if (!_dbus_test_oom_handling ("spawn_exit",
01419                                 check_spawn_exit,
01420                                 NULL))
01421     return FALSE;
01422 
01423   if (!_dbus_test_oom_handling ("spawn_and_kill",
01424                                 check_spawn_and_kill,
01425                                 NULL))
01426     return FALSE;
01427   
01428   return TRUE;
01429 }
01430 #endif

Generated on Fri Sep 21 18:12:13 2007 for D-Bus by  doxygen 1.5.1