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