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