* configure.in: add DBUS_BINDIR as a #define to C source code.
[platform/upstream/dbus.git] / tools / dbus-launch.c
1 /* -*- mode: C; c-file-style: "gnu" -*- */
2 /* dbus-launch.c  dbus-launch utility
3  *
4  * Copyright (C) 2003 Red Hat, Inc.
5  *
6  * Licensed under the Academic Free License version 2.1
7  * 
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 2 of the License, or
11  * (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  * 
18  * You should have received a copy of the GNU General Public License
19  * along with this program; if not, write to the Free Software
20  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
21  *
22  */
23 #include "dbus-launch.h"
24 #include <stdlib.h>
25 #include <unistd.h>
26 #include <fcntl.h>
27 #include <signal.h>
28 #include <sys/wait.h>
29 #include <errno.h>
30 #include <stdio.h>
31 #include <string.h>
32 #include <signal.h>
33 #include <stdarg.h>
34 #include <sys/select.h>
35 #include <time.h>
36
37 #ifdef DBUS_BUILD_X11
38 #include <X11/Xlib.h>
39 extern Display *xdisplay;
40 #endif
41
42 void
43 verbose (const char *format,
44          ...)
45 {
46   va_list args;
47   static int verbose = TRUE;
48   static int verbose_initted = FALSE;
49   
50   /* things are written a bit oddly here so that
51    * in the non-verbose case we just have the one
52    * conditional and return immediately.
53    */
54   if (!verbose)
55     return;
56   
57   if (!verbose_initted)
58     {
59       verbose = getenv ("DBUS_VERBOSE") != NULL;
60       verbose_initted = TRUE;
61       if (!verbose)
62         return;
63     }
64
65   fprintf (stderr, "%lu: ", (unsigned long) getpid ());
66   
67   va_start (args, format);
68   vfprintf (stderr, format, args);
69   va_end (args);
70 }
71
72 static void
73 usage (int ecode)
74 {
75   fprintf (stderr, "dbus-launch [--version] [--help] [--sh-syntax] [--csh-syntax] [--auto-syntax] [--exit-with-session]\n");
76   exit (ecode);
77 }
78
79 static void
80 version (void)
81 {
82   printf ("D-Bus Message Bus Launcher %s\n"
83           "Copyright (C) 2003 Red Hat, Inc.\n"
84           "This is free software; see the source for copying conditions.\n"
85           "There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n",
86           VERSION);
87   exit (0);
88 }
89
90 char *
91 xstrdup (const char *str)
92 {
93   int len;
94   char *copy;
95   
96   if (str == NULL)
97     return NULL;
98   
99   len = strlen (str);
100
101   copy = malloc (len + 1);
102   if (copy == NULL)
103     return NULL;
104
105   memcpy (copy, str, len + 1);
106   
107   return copy;
108 }
109
110 typedef enum
111 {
112   READ_STATUS_OK,    /**< Read succeeded */
113   READ_STATUS_ERROR, /**< Some kind of error */
114   READ_STATUS_EOF    /**< EOF returned */
115 } ReadStatus;
116
117 static ReadStatus
118 read_line (int        fd,
119            char      *buf,
120            size_t     maxlen)
121 {
122   size_t bytes = 0;
123   ReadStatus retval;
124
125   memset (buf, '\0', maxlen);
126   maxlen -= 1; /* ensure nul term */
127   
128   retval = READ_STATUS_OK;
129   
130   while (TRUE)
131     {
132       ssize_t chunk;    
133       size_t to_read;
134       
135     again:
136       to_read = maxlen - bytes;
137
138       if (to_read == 0)
139         break;
140       
141       chunk = read (fd,
142                     buf + bytes,
143                     to_read);
144       if (chunk < 0 && errno == EINTR)
145         goto again;
146           
147       if (chunk < 0)
148         {
149           retval = READ_STATUS_ERROR;
150           break;
151         }
152       else if (chunk == 0)
153         {
154           retval = READ_STATUS_EOF;
155           break; /* EOF */
156         }
157       else /* chunk > 0 */
158         bytes += chunk;
159     }
160
161   if (retval == READ_STATUS_EOF &&
162       bytes > 0)
163     retval = READ_STATUS_OK;
164   
165   /* whack newline */
166   if (retval != READ_STATUS_ERROR &&
167       bytes > 0 &&
168       buf[bytes-1] == '\n')
169     buf[bytes-1] = '\0';
170   
171   return retval;
172 }
173
174 static ReadStatus
175 read_pid (int        fd,
176           pid_t     *buf)
177 {
178   size_t bytes = 0;
179   ReadStatus retval;
180
181   retval = READ_STATUS_OK;
182   
183   while (TRUE)
184     {
185       ssize_t chunk;    
186       size_t to_read;
187       
188     again:
189       to_read = sizeof (pid_t) - bytes;
190
191       if (to_read == 0)
192         break;
193       
194       chunk = read (fd,
195                     ((char*)buf) + bytes,
196                     to_read);
197       if (chunk < 0 && errno == EINTR)
198         goto again;
199           
200       if (chunk < 0)
201         {
202           retval = READ_STATUS_ERROR;
203           break;
204         }
205       else if (chunk == 0)
206         {
207           retval = READ_STATUS_EOF;
208           break; /* EOF */
209         }
210       else /* chunk > 0 */
211         bytes += chunk;
212     }
213
214   return retval;
215 }
216
217 static void
218 do_write (int fd, const void *buf, size_t count)
219 {
220   size_t bytes_written;
221   int ret;
222   
223   bytes_written = 0;
224   
225  again:
226   
227   ret = write (fd, ((const char*)buf) + bytes_written, count - bytes_written);
228
229   if (ret < 0)
230     {
231       if (errno == EINTR)
232         goto again;
233       else
234         {
235           fprintf (stderr, "Failed to write data to pipe! %s\n",
236                    strerror (errno));
237           exit (1); /* give up, we suck */
238         }
239     }
240   else
241     bytes_written += ret;
242   
243   if (bytes_written < count)
244     goto again;
245 }
246
247 static void
248 write_pid (int   fd,
249            pid_t pid)
250 {
251   do_write (fd, &pid, sizeof (pid));
252 }
253
254 static int
255 do_waitpid (pid_t pid)
256 {
257   int ret;
258   
259  again:
260   ret = waitpid (pid, NULL, 0);
261
262   if (ret < 0 &&
263       errno == EINTR)
264     goto again;
265
266   return ret;
267 }
268
269 static pid_t bus_pid_to_kill = -1;
270
271 void
272 kill_bus_and_exit (int exitcode)
273 {
274   verbose ("Killing message bus and exiting babysitter\n");
275   
276   /* in case these point to any NFS mounts, get rid of them immediately */
277   close (0);
278   close (1);
279   close (2);
280
281   kill (bus_pid_to_kill, SIGTERM);
282   sleep (3);
283   kill (bus_pid_to_kill, SIGKILL);
284
285   exit (exitcode);
286 }
287
288 static void
289 print_variables (const char *bus_address, pid_t bus_pid, long bus_wid,
290                  int c_shell_syntax, int bourne_shell_syntax,
291                  int binary_syntax)
292 {
293   if (binary_syntax)
294     {
295       write (1, bus_address, strlen (bus_address) + 1);
296       write (1, &bus_pid, sizeof bus_pid);
297       write (1, &bus_wid, sizeof bus_wid);
298       return;
299     }
300   else if (c_shell_syntax)
301     {
302       printf ("setenv DBUS_SESSION_BUS_ADDRESS '%s';\n", bus_address);  
303       printf ("set DBUS_SESSION_BUS_PID=%ld;\n", (long) bus_pid);
304       if (bus_wid)
305         printf ("set DBUS_SESSION_BUS_WINDOWID=%ld;\n", (long) bus_wid);
306     }
307   else
308     {
309       printf ("DBUS_SESSION_BUS_ADDRESS='%s';\n", bus_address);
310       if (bourne_shell_syntax)
311         printf ("export DBUS_SESSION_BUS_ADDRESS;\n");
312       printf ("DBUS_SESSION_BUS_PID=%ld;\n", (long) bus_pid);
313       if (bus_wid)
314         printf ("DBUS_SESSION_BUS_WINDOWID=%ld;\n", (long) bus_wid);
315     }
316 }
317
318 static int got_sighup = FALSE;
319
320 static void
321 signal_handler (int sig)
322 {
323   switch (sig)
324     {
325     case SIGHUP:
326     case SIGTERM:
327       got_sighup = TRUE;
328       break;
329     }
330 }
331
332 static void
333 kill_bus_when_session_ends (void)
334 {
335   int tty_fd;
336   int x_fd;
337   fd_set read_set;
338   fd_set err_set;
339   struct sigaction act;
340   sigset_t empty_mask;
341   
342   /* install SIGHUP handler */
343   got_sighup = FALSE;
344   sigemptyset (&empty_mask);
345   act.sa_handler = signal_handler;
346   act.sa_mask    = empty_mask;
347   act.sa_flags   = 0;
348   sigaction (SIGHUP,  &act, NULL);
349   sigaction (SIGTERM,  &act, NULL);
350   
351 #ifdef DBUS_BUILD_X11
352   x11_init();
353   if (xdisplay != NULL)
354     {
355       x_fd = ConnectionNumber (xdisplay);
356     }
357   else
358     x_fd = -1;
359 #else
360   x_fd = -1;
361 #endif
362
363   if (isatty (0))
364     tty_fd = 0;
365   else
366     tty_fd = -1;
367
368   if (tty_fd >= 0)
369     verbose ("stdin isatty(), monitoring it\n");
370   else
371     verbose ("stdin was not a TTY, not monitoring it\n");  
372   
373   if (tty_fd < 0 && x_fd < 0)
374     {
375       fprintf (stderr, "No terminal on standard input and no X display; cannot attach message bus to session lifetime\n");
376       exit (1);
377     }
378   
379   while (TRUE)
380     {
381       FD_ZERO (&read_set);
382       FD_ZERO (&err_set);
383
384       if (tty_fd >= 0)
385         {
386           FD_SET (tty_fd, &read_set);
387           FD_SET (tty_fd, &err_set);
388         }
389
390       if (x_fd >= 0)
391         {
392           FD_SET (x_fd, &read_set);
393           FD_SET (x_fd, &err_set);
394         }
395       
396       select (MAX (tty_fd, x_fd) + 1,
397               &read_set, NULL, &err_set, NULL);
398
399       if (got_sighup)
400         {
401           verbose ("Got SIGHUP, exiting\n");
402           kill_bus_and_exit (0);
403         }
404       
405 #ifdef DBUS_BUILD_X11
406       /* Dump events on the floor, and let
407        * IO error handler run if we lose
408        * the X connection
409        */
410       if (x_fd >= 0)
411         verbose ("X fd condition reading = %d error = %d\n",
412                  FD_ISSET (x_fd, &read_set),
413                  FD_ISSET (x_fd, &err_set));
414       x11_handle_event ();
415 #endif
416
417       if (tty_fd >= 0)
418         {
419           if (FD_ISSET (tty_fd, &read_set))
420             {
421               int bytes_read;
422               char discard[512];
423
424               verbose ("TTY ready for reading\n");
425               
426               bytes_read = read (tty_fd, discard, sizeof (discard));
427
428               verbose ("Read %d bytes from TTY errno = %d\n",
429                        bytes_read, errno);
430               
431               if (bytes_read == 0)
432                 kill_bus_and_exit (0); /* EOF */
433               else if (bytes_read < 0 && errno != EINTR)
434                 {
435                   /* This shouldn't happen I don't think; to avoid
436                    * spinning on the fd forever we exit.
437                    */
438                   fprintf (stderr, "dbus-launch: error reading from stdin: %s\n",
439                            strerror (errno));
440                   kill_bus_and_exit (0);
441                 }
442             }
443           else if (FD_ISSET (tty_fd, &err_set))
444             {
445               verbose ("TTY has error condition\n");
446               
447               kill_bus_and_exit (0);
448             }
449         }
450     }
451 }
452
453 static void
454 babysit (int   exit_with_session,
455          pid_t child_pid,
456          int   read_bus_pid_fd)  /* read pid from here */
457 {
458   int ret;
459   int dev_null_fd;
460   const char *s;
461
462   verbose ("babysitting, exit_with_session = %d, child_pid = %ld, read_bus_pid_fd = %d\n",
463            exit_with_session, (long) child_pid, read_bus_pid_fd);
464   
465   /* We chdir ("/") since we are persistent and daemon-like, and fork
466    * again so dbus-launch can reap the parent.  However, we don't
467    * setsid() or close fd 0 because the idea is to remain attached
468    * to the tty and the X server in order to kill the message bus
469    * when the session ends.
470    */
471
472   if (chdir ("/") < 0)
473     {
474       fprintf (stderr, "Could not change to root directory: %s\n",
475                strerror (errno));
476       exit (1);
477     }
478
479   /* Close stdout/stderr so we don't block an "eval" or otherwise
480    * lock up. stdout is still chaining through to dbus-launch
481    * and in turn to the parent shell.
482    */
483   dev_null_fd = open ("/dev/null", O_RDWR);
484   if (dev_null_fd >= 0)
485     {
486       if (!exit_with_session)
487         dup2 (dev_null_fd, 0);
488       dup2 (dev_null_fd, 1);
489       s = getenv ("DBUS_DEBUG_OUTPUT");
490       if (s == NULL || *s == '\0')
491         dup2 (dev_null_fd, 2);
492     }
493   else
494     {
495       fprintf (stderr, "Failed to open /dev/null: %s\n",
496                strerror (errno));
497       /* continue, why not */
498     }
499   
500   ret = fork ();
501
502   if (ret < 0)
503     {
504       fprintf (stderr, "fork() failed in babysitter: %s\n",
505                strerror (errno));
506       exit (1);
507     }
508
509   if (ret > 0)
510     {
511       /* Parent reaps pre-fork part of bus daemon, then exits and is
512        * reaped so the babysitter isn't a zombie
513        */
514
515       verbose ("=== Babysitter's intermediate parent continues again\n");
516       
517       if (do_waitpid (child_pid) < 0)
518         {
519           /* shouldn't happen */
520           fprintf (stderr, "Failed waitpid() waiting for bus daemon's parent\n");
521           exit (1);
522         }
523
524       verbose ("Babysitter's intermediate parent exiting\n");
525       
526       exit (0);
527     }
528
529   /* Child continues */
530   verbose ("=== Babysitter process created\n");
531
532   verbose ("Reading PID from bus\n");
533       
534   switch (read_pid (read_bus_pid_fd, &bus_pid_to_kill))
535     {
536     case READ_STATUS_OK:
537       break;
538     case READ_STATUS_EOF:
539       fprintf (stderr, "EOF in dbus-launch reading PID from bus daemon\n");
540       exit (1);
541       break;
542     case READ_STATUS_ERROR:
543       fprintf (stderr, "Error in dbus-launch reading PID from bus daemon: %s\n",
544                strerror (errno));
545       exit (1);
546       break;
547     }
548
549   verbose ("Got PID %ld from daemon\n",
550            (long) bus_pid_to_kill);
551   
552   if (exit_with_session)
553     {
554       /* Bus is now started and launcher has needed info;
555        * we connect to X display and tty and wait to
556        * kill bus if requested.
557        */
558       
559       kill_bus_when_session_ends ();
560     }
561
562   verbose ("Babysitter exiting\n");
563   
564   exit (0);
565 }
566
567 #define READ_END  0
568 #define WRITE_END 1
569
570 int
571 main (int argc, char **argv)
572 {
573   const char *prev_arg;
574   const char *shname;
575   const char *runprog = NULL;
576   int remaining_args = 0;
577   int exit_with_session;
578   int binary_syntax = FALSE;
579   int c_shell_syntax = FALSE;
580   int bourne_shell_syntax = FALSE;
581   int auto_shell_syntax = FALSE;
582   int autolaunch = FALSE;
583   int i;  
584   int ret;
585   int bus_pid_to_launcher_pipe[2];
586   int bus_pid_to_babysitter_pipe[2];
587   int bus_address_to_launcher_pipe[2];
588   char *config_file;
589   
590   exit_with_session = FALSE;
591   config_file = NULL;
592   
593   prev_arg = NULL;
594   i = 1;
595   while (i < argc)
596     {
597       const char *arg = argv[i];
598       
599       if (strcmp (arg, "--help") == 0 ||
600           strcmp (arg, "-h") == 0 ||
601           strcmp (arg, "-?") == 0)
602         usage (0);
603       else if (strcmp (arg, "--auto-syntax") == 0)
604         auto_shell_syntax = TRUE;
605       else if (strcmp (arg, "-c") == 0 ||
606                strcmp (arg, "--csh-syntax") == 0)
607         c_shell_syntax = TRUE;
608       else if (strcmp (arg, "-s") == 0 ||
609                strcmp (arg, "--sh-syntax") == 0)
610         bourne_shell_syntax = TRUE;
611       else if (strcmp (arg, "--binary-syntax") == 0)
612         binary_syntax = TRUE;
613       else if (strcmp (arg, "--version") == 0)
614         version ();
615       else if (strcmp (arg, "--exit-with-session") == 0)
616         exit_with_session = TRUE;
617       else if (strcmp (arg, "--autolaunch") == 0)
618         autolaunch = TRUE;
619       else if (strstr (arg, "--config-file=") == arg)
620         {
621           const char *file;
622
623           if (config_file != NULL)
624             {
625               fprintf (stderr, "--config-file given twice\n");
626               exit (1);
627             }
628           
629           file = strchr (arg, '=');
630           ++file;
631
632           config_file = xstrdup (file);
633         }
634       else if (prev_arg &&
635                strcmp (prev_arg, "--config-file") == 0)
636         {
637           if (config_file != NULL)
638             {
639               fprintf (stderr, "--config-file given twice\n");
640               exit (1);
641             }
642
643           config_file = xstrdup (arg);
644         }
645       else if (strcmp (arg, "--config-file") == 0)
646         ; /* wait for next arg */
647       else
648         {
649           runprog = arg;
650           remaining_args = i+1;
651           break;
652         }
653       
654       prev_arg = arg;
655       
656       ++i;
657     }
658
659   if (auto_shell_syntax)
660     {
661       if ((shname = getenv ("SHELL")) != NULL)
662        {
663          if (!strncmp (shname + strlen (shname) - 3, "csh", 3))
664            c_shell_syntax = TRUE;
665          else
666            bourne_shell_syntax = TRUE;
667        }
668       else
669        bourne_shell_syntax = TRUE;
670     }  
671
672   if (exit_with_session)
673     verbose ("--exit-with-session enabled\n");
674
675   if (autolaunch)
676     {
677 #ifndef DBUS_BUILD_X11
678       fprintf (stderr, "Autolaunch requested, but X11 support not compiled in.\n"
679                "Cannot continue.\n");
680       exit (1);
681 #else
682       char *address;
683       pid_t pid;
684       long wid;
685
686       verbose ("Autolaunch enabled (using X11).\n");
687       if (!exit_with_session)
688         {
689           verbose ("--exit-with-session automatically enabled\n");
690           exit_with_session = TRUE;
691         }
692
693       if (!x11_init ())
694         {
695           fprintf (stderr, "Autolaunch error: X11 initialization failed.\n");
696           exit (1);
697         }
698
699       if (!x11_get_address (&address, &pid, &wid))
700         {
701           fprintf (stderr, "Autolaunch error: X11 communication error.\n");
702           exit (1);
703         }
704
705       if (address != NULL)
706         {
707           verbose ("dbus-daemon is already running. Returning existing parameters.\n");
708           print_variables (address, pid, wid, c_shell_syntax,
709                            bourne_shell_syntax, binary_syntax);
710           exit (0);
711         }
712 #endif
713     }
714
715   if (pipe (bus_pid_to_launcher_pipe) < 0 ||
716       pipe (bus_address_to_launcher_pipe) < 0 ||
717       pipe (bus_pid_to_babysitter_pipe) < 0)
718     {
719       fprintf (stderr,
720                "Failed to create pipe: %s\n",
721                strerror (errno));
722       exit (1);
723     }
724
725   ret = fork ();
726   if (ret < 0)
727     {
728       fprintf (stderr, "Failed to fork: %s\n",
729                strerror (errno));
730       exit (1);
731     }
732
733   if (ret == 0)
734     {
735       /* Child */
736 #define MAX_FD_LEN 64
737       char write_pid_fd_as_string[MAX_FD_LEN];
738       char write_address_fd_as_string[MAX_FD_LEN];
739
740       verbose ("=== Babysitter's intermediate parent created\n");
741
742       /* Fork once more to create babysitter */
743       
744       ret = fork ();
745       if (ret < 0)
746         {
747           fprintf (stderr, "Failed to fork: %s\n",
748                    strerror (errno));
749           exit (1);
750         }
751       
752       if (ret > 0)
753         {
754           /* In babysitter */
755           verbose ("=== Babysitter's intermediate parent continues\n");
756           
757           close (bus_pid_to_launcher_pipe[READ_END]);
758           close (bus_pid_to_launcher_pipe[WRITE_END]);
759           close (bus_address_to_launcher_pipe[READ_END]);
760           close (bus_address_to_launcher_pipe[WRITE_END]);
761           close (bus_pid_to_babysitter_pipe[WRITE_END]);
762           
763           /* babysit() will fork *again*
764            * and will also reap the pre-forked bus
765            * daemon
766            */
767           babysit (exit_with_session, ret,
768                    bus_pid_to_babysitter_pipe[READ_END]);
769           exit (0);
770         }
771
772       verbose ("=== Bus exec process created\n");
773       
774       /* Now we are the bus process (well, almost;
775        * dbus-daemon itself forks again)
776        */
777       close (bus_pid_to_launcher_pipe[READ_END]);
778       close (bus_address_to_launcher_pipe[READ_END]);
779       close (bus_pid_to_babysitter_pipe[READ_END]);
780       close (bus_pid_to_babysitter_pipe[WRITE_END]);
781
782       sprintf (write_pid_fd_as_string,
783                "%d", bus_pid_to_launcher_pipe[WRITE_END]);
784
785       sprintf (write_address_fd_as_string,
786                "%d", bus_address_to_launcher_pipe[WRITE_END]);
787
788       verbose ("Calling exec()\n");
789       
790       execl (DBUS_DAEMONDIR"/dbus-daemon",
791              DBUS_DAEMONDIR"/dbus-daemon",
792              "--fork",
793              "--print-pid", write_pid_fd_as_string,
794              "--print-address", write_address_fd_as_string,
795              config_file ? "--config-file" : "--session",
796              config_file, /* has to be last in this varargs list */
797              NULL);
798
799       fprintf (stderr,
800                "Failed to execute message bus daemon %s: %s.  Will try again without full path.\n",
801                DBUS_DAEMONDIR"/dbus-daemon", strerror (errno));
802
803       /*
804        * If it failed, try running without full PATH.  Note this is needed
805        * because the build process builds the run-with-tmp-session-bus.conf
806        * file and the dbus-daemon will not be in the install location during
807        * build time.
808        */
809       execlp ("dbus-daemon",
810               "dbus-daemon",
811               "--fork",
812               "--print-pid", write_pid_fd_as_string,
813               "--print-address", write_address_fd_as_string,
814               config_file ? "--config-file" : "--session",
815               config_file, /* has to be last in this varargs list */
816               NULL);
817
818       fprintf (stderr,
819                "Failed to execute message bus daemon: %s\n",
820                strerror (errno));
821       exit (1);
822     }
823   else
824     {
825       /* Parent */
826 #define MAX_PID_LEN 64
827       pid_t bus_pid;  
828       char bus_address[MAX_ADDR_LEN];
829       char buf[MAX_PID_LEN];
830       char *end;
831       long wid = 0;
832       long val;
833       int ret2;
834
835       verbose ("=== Parent dbus-launch continues\n");
836       
837       close (bus_pid_to_launcher_pipe[WRITE_END]);
838       close (bus_address_to_launcher_pipe[WRITE_END]);
839       close (bus_pid_to_babysitter_pipe[READ_END]);
840
841       verbose ("Waiting for babysitter's intermediate parent\n");
842       
843       /* Immediately reap parent of babysitter
844        * (which was created just for us to reap)
845        */
846       if (do_waitpid (ret) < 0)
847         {
848           fprintf (stderr, "Failed to waitpid() for babysitter intermediate process: %s\n",
849                    strerror (errno));
850           exit (1);
851         }
852
853       verbose ("Reading address from bus\n");
854       
855       /* Read the pipe data, print, and exit */
856       switch (read_line (bus_address_to_launcher_pipe[READ_END],
857                          bus_address, MAX_ADDR_LEN))
858         {
859         case READ_STATUS_OK:
860           break;
861         case READ_STATUS_EOF:
862           fprintf (stderr, "EOF in dbus-launch reading address from bus daemon\n");
863           exit (1);
864           break;
865         case READ_STATUS_ERROR:
866           fprintf (stderr, "Error in dbus-launch reading address from bus daemon: %s\n",
867                    strerror (errno));
868           exit (1);
869           break;
870         }
871         
872       close (bus_address_to_launcher_pipe[READ_END]);
873
874       verbose ("Reading PID from daemon\n");
875       /* Now read data */
876       switch (read_line (bus_pid_to_launcher_pipe[READ_END], buf, MAX_PID_LEN))
877         {
878         case READ_STATUS_OK:
879           break;
880         case READ_STATUS_EOF:
881           fprintf (stderr, "EOF reading PID from bus daemon\n");
882           exit (1);
883           break;
884         case READ_STATUS_ERROR:
885           fprintf (stderr, "Error reading PID from bus daemon: %s\n",
886                    strerror (errno));
887           exit (1);
888           break;
889         }
890
891       end = NULL;
892       val = strtol (buf, &end, 0);
893       if (buf == end || end == NULL)
894         {
895           fprintf (stderr, "Failed to parse bus PID \"%s\": %s\n",
896                    buf, strerror (errno));
897           exit (1);
898         }
899
900       bus_pid = val;
901
902       close (bus_pid_to_launcher_pipe[READ_END]);
903
904 #ifdef DBUS_BUILD_X11
905       ret2 = x11_save_address (bus_address, bus_pid, &wid);
906       if (ret2 == 0)
907         {
908           /* another window got added. Return its address */
909           char *address;
910           pid_t pid;
911           long wid;
912
913           if (x11_get_address (&address, &pid, &wid) && address != NULL)
914             {
915               verbose ("dbus-daemon is already running. Returning existing parameters.\n");
916               print_variables (address, pid, wid, c_shell_syntax,
917                                bourne_shell_syntax, binary_syntax);
918               free (address);
919
920               bus_pid_to_kill = bus_pid;
921               kill_bus_and_exit (0);
922             }
923
924           /* if failed, fall through */
925         }
926       if (ret2 <= 0)
927         {
928           fprintf (stderr, "Error saving bus information.\n");
929           bus_pid_to_kill = bus_pid;
930           kill_bus_and_exit (1);
931         }
932 #endif
933
934       /* Forward the pid to the babysitter */
935       write_pid (bus_pid_to_babysitter_pipe[WRITE_END], bus_pid);
936       close (bus_pid_to_babysitter_pipe[WRITE_END]);
937
938       if (runprog)
939         {
940           char *envvar;
941           char **args;
942
943           envvar = malloc (strlen ("DBUS_SESSION_BUS_ADDRESS=") + strlen (bus_address) + 1);
944           args = malloc (sizeof (char *) * ((argc-remaining_args)+2));
945
946           if (envvar == NULL || args == NULL)
947             goto oom;
948
949           args[0] = xstrdup (runprog);
950           if (!args[0])
951             goto oom;
952           for (i = 1; i <= (argc-remaining_args); i++)
953             {
954               size_t len = strlen (argv[remaining_args+i-1])+1;
955               args[i] = malloc (len);
956               if (!args[i])
957                 goto oom;
958               strncpy (args[i], argv[remaining_args+i-1], len);
959             }
960           args[i] = NULL;
961
962           strcpy (envvar, "DBUS_SESSION_BUS_ADDRESS=");
963           strcat (envvar, bus_address);
964           putenv (envvar);
965
966           execvp (runprog, args);
967           fprintf (stderr, "Couldn't exec %s: %s\n", runprog, strerror (errno));
968           exit (1);
969         }
970       else
971         {
972           print_variables (bus_address, bus_pid, wid, c_shell_syntax,
973                            bourne_shell_syntax, binary_syntax);
974         }
975           
976       verbose ("dbus-launch exiting\n");
977
978       fflush (stdout);
979       fflush (stderr);
980       close (1);
981       close (2);
982       
983       exit (0);
984     } 
985   
986   return 0;
987  oom:
988   fprintf (stderr, "Out of memory!");
989   exit (1);
990 }