Merge branch 'master' of git+ssh://johnp@git.freedesktop.org/git/dbus/dbus
[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 #ifdef DBUS_BUILD_X11
462       /* Dump events on the floor, and let
463        * IO error handler run if we lose
464        * the X connection. It's important to
465        * run this before going into select() since
466        * we might have queued outgoing messages or
467        * events.
468        */
469       x11_handle_event ();
470 #endif
471       
472       FD_ZERO (&read_set);
473       FD_ZERO (&err_set);
474
475       if (tty_fd >= 0)
476         {
477           FD_SET (tty_fd, &read_set);
478           FD_SET (tty_fd, &err_set);
479         }
480
481       if (x_fd >= 0)
482         {
483           FD_SET (x_fd, &read_set);
484           FD_SET (x_fd, &err_set);
485         }
486
487       select (MAX (tty_fd, x_fd) + 1,
488               &read_set, NULL, &err_set, NULL);
489
490       if (got_sighup)
491         {
492           verbose ("Got SIGHUP, exiting\n");
493           kill_bus_and_exit (0);
494         }
495       
496 #ifdef DBUS_BUILD_X11
497       /* Events will be processed before we select again
498        */
499       if (x_fd >= 0)
500         verbose ("X fd condition reading = %d error = %d\n",
501                  FD_ISSET (x_fd, &read_set),
502                  FD_ISSET (x_fd, &err_set));
503 #endif
504
505       if (tty_fd >= 0)
506         {
507           if (FD_ISSET (tty_fd, &read_set))
508             {
509               int bytes_read;
510               char discard[512];
511
512               verbose ("TTY ready for reading\n");
513               
514               bytes_read = read (tty_fd, discard, sizeof (discard));
515
516               verbose ("Read %d bytes from TTY errno = %d\n",
517                        bytes_read, errno);
518               
519               if (bytes_read == 0)
520                 kill_bus_and_exit (0); /* EOF */
521               else if (bytes_read < 0 && errno != EINTR)
522                 {
523                   /* This shouldn't happen I don't think; to avoid
524                    * spinning on the fd forever we exit.
525                    */
526                   fprintf (stderr, "dbus-launch: error reading from stdin: %s\n",
527                            strerror (errno));
528                   kill_bus_and_exit (0);
529                 }
530             }
531           else if (FD_ISSET (tty_fd, &err_set))
532             {
533               verbose ("TTY has error condition\n");
534               
535               kill_bus_and_exit (0);
536             }
537         }
538     }
539 }
540
541 static void
542 babysit (int   exit_with_session,
543          pid_t child_pid,
544          int   read_bus_pid_fd)  /* read pid from here */
545 {
546   int ret;
547   int dev_null_fd;
548   const char *s;
549
550   verbose ("babysitting, exit_with_session = %d, child_pid = %ld, read_bus_pid_fd = %d\n",
551            exit_with_session, (long) child_pid, read_bus_pid_fd);
552   
553   /* We chdir ("/") since we are persistent and daemon-like, and fork
554    * again so dbus-launch can reap the parent.  However, we don't
555    * setsid() or close fd 0 because the idea is to remain attached
556    * to the tty and the X server in order to kill the message bus
557    * when the session ends.
558    */
559
560   if (chdir ("/") < 0)
561     {
562       fprintf (stderr, "Could not change to root directory: %s\n",
563                strerror (errno));
564       exit (1);
565     }
566
567   /* Close stdout/stderr so we don't block an "eval" or otherwise
568    * lock up. stdout is still chaining through to dbus-launch
569    * and in turn to the parent shell.
570    */
571   dev_null_fd = open ("/dev/null", O_RDWR);
572   if (dev_null_fd >= 0)
573     {
574       if (!exit_with_session)
575         dup2 (dev_null_fd, 0);
576       dup2 (dev_null_fd, 1);
577       s = getenv ("DBUS_DEBUG_OUTPUT");
578       if (s == NULL || *s == '\0')
579         dup2 (dev_null_fd, 2);
580     }
581   else
582     {
583       fprintf (stderr, "Failed to open /dev/null: %s\n",
584                strerror (errno));
585       /* continue, why not */
586     }
587   
588   ret = fork ();
589
590   if (ret < 0)
591     {
592       fprintf (stderr, "fork() failed in babysitter: %s\n",
593                strerror (errno));
594       exit (1);
595     }
596
597   if (ret > 0)
598     {
599       /* Parent reaps pre-fork part of bus daemon, then exits and is
600        * reaped so the babysitter isn't a zombie
601        */
602
603       verbose ("=== Babysitter's intermediate parent continues again\n");
604       
605       if (do_waitpid (child_pid) < 0)
606         {
607           /* shouldn't happen */
608           fprintf (stderr, "Failed waitpid() waiting for bus daemon's parent\n");
609           exit (1);
610         }
611
612       verbose ("Babysitter's intermediate parent exiting\n");
613       
614       exit (0);
615     }
616
617   /* Child continues */
618   verbose ("=== Babysitter process created\n");
619
620   verbose ("Reading PID from bus\n");
621       
622   switch (read_pid (read_bus_pid_fd, &bus_pid_to_kill))
623     {
624     case READ_STATUS_OK:
625       break;
626     case READ_STATUS_EOF:
627       fprintf (stderr, "EOF in dbus-launch reading PID from bus daemon\n");
628       exit (1);
629       break;
630     case READ_STATUS_ERROR:
631       fprintf (stderr, "Error in dbus-launch reading PID from bus daemon: %s\n",
632                strerror (errno));
633       exit (1);
634       break;
635     }
636
637   verbose ("Got PID %ld from daemon\n",
638            (long) bus_pid_to_kill);
639   
640   if (exit_with_session)
641     {
642       /* Bus is now started and launcher has needed info;
643        * we connect to X display and tty and wait to
644        * kill bus if requested.
645        */
646       
647       kill_bus_when_session_ends ();
648     }
649
650   verbose ("Babysitter exiting\n");
651   
652   exit (0);
653 }
654
655 static void
656 do_close_stderr (void)
657 {
658   int fd;
659
660   fflush (stderr);
661
662   /* dbus-launch is a Unix-only program, so we can rely on /dev/null being there.
663    * We're including unistd.h and we're dealing with sh/csh launch sequences...
664    */
665   fd = open ("/dev/null", O_RDWR);
666   if (fd == -1)
667     {
668       fprintf (stderr, "Internal error: cannot open /dev/null: %s", strerror (errno));
669       exit (1);
670     }
671
672   close (2);
673   if (dup2 (fd, 2) == -1)
674     {
675       /* error; we can't report an error anymore... */
676       exit (1);
677     }
678   close (fd);
679 }
680
681 static void
682 pass_info (const char *runprog, const char *bus_address, pid_t bus_pid,
683            long bus_wid, int c_shell_syntax, int bourne_shell_syntax,
684            int binary_syntax,
685            int argc, char **argv, int remaining_args)
686 {
687   if (runprog)
688     {
689       char *envvar;
690       char **args;
691       int i;
692
693       envvar = malloc (strlen ("DBUS_SESSION_BUS_ADDRESS=") +
694           strlen (bus_address) + 1);
695       args = malloc (sizeof (char *) * ((argc-remaining_args)+2));
696
697       if (envvar == NULL || args == NULL)
698         goto oom;
699
700      args[0] = xstrdup (runprog);
701       if (!args[0])
702         goto oom;
703      for (i = 1; i <= (argc-remaining_args); i++)
704       {
705         size_t len = strlen (argv[remaining_args+i-1])+1;
706         args[i] = malloc (len);
707         if (!args[i])
708           goto oom;
709         strncpy (args[i], argv[remaining_args+i-1], len);
710        }
711      args[i] = NULL;
712
713      strcpy (envvar, "DBUS_SESSION_BUS_ADDRESS=");
714      strcat (envvar, bus_address);
715      putenv (envvar);
716
717      execvp (runprog, args);
718      fprintf (stderr, "Couldn't exec %s: %s\n", runprog, strerror (errno));
719      exit (1);
720     }
721    else
722     {
723       print_variables (bus_address, bus_pid, bus_wid, c_shell_syntax,
724          bourne_shell_syntax, binary_syntax);
725     }
726   verbose ("dbus-launch exiting\n");
727
728   fflush (stdout);
729   fflush (stderr);
730   close (1);
731   close (2);
732   exit (0);
733 oom:
734   fprintf (stderr, "Out of memory!");
735   exit (1);
736 }
737
738 #define READ_END  0
739 #define WRITE_END 1
740
741 int
742 main (int argc, char **argv)
743 {
744   const char *prev_arg;
745   const char *shname;
746   const char *runprog = NULL;
747   int remaining_args = 0;
748   int exit_with_session;
749   int binary_syntax = FALSE;
750   int c_shell_syntax = FALSE;
751   int bourne_shell_syntax = FALSE;
752   int auto_shell_syntax = FALSE;
753   int autolaunch = FALSE;
754   int requires_arg = FALSE;
755   int close_stderr = FALSE;
756   int i;
757   int ret;
758   int bus_pid_to_launcher_pipe[2];
759   int bus_pid_to_babysitter_pipe[2];
760   int bus_address_to_launcher_pipe[2];
761   char *config_file;
762   
763   exit_with_session = FALSE;
764   config_file = NULL;
765   
766   prev_arg = NULL;
767   i = 1;
768   while (i < argc)
769     {
770       const char *arg = argv[i];
771  
772       if (strcmp (arg, "--help") == 0 ||
773           strcmp (arg, "-h") == 0 ||
774           strcmp (arg, "-?") == 0)
775         usage (0);
776       else if (strcmp (arg, "--auto-syntax") == 0)
777         auto_shell_syntax = TRUE;
778       else if (strcmp (arg, "-c") == 0 ||
779                strcmp (arg, "--csh-syntax") == 0)
780         c_shell_syntax = TRUE;
781       else if (strcmp (arg, "-s") == 0 ||
782                strcmp (arg, "--sh-syntax") == 0)
783         bourne_shell_syntax = TRUE;
784       else if (strcmp (arg, "--binary-syntax") == 0)
785         binary_syntax = TRUE;
786       else if (strcmp (arg, "--version") == 0)
787         version ();
788       else if (strcmp (arg, "--exit-with-session") == 0)
789         exit_with_session = TRUE;
790       else if (strcmp (arg, "--close-stderr") == 0)
791         close_stderr = TRUE;
792       else if (strstr (arg, "--autolaunch=") == arg)
793         {
794           const char *s;
795
796           if (autolaunch)
797             {
798               fprintf (stderr, "--autolaunch given twice\n");
799               exit (1);
800             }
801           
802           autolaunch = TRUE;
803
804           s = strchr (arg, '=');
805           ++s;
806
807           save_machine_uuid (s);
808         }
809       else if (prev_arg &&
810                strcmp (prev_arg, "--autolaunch") == 0)
811         {
812           if (autolaunch)
813             {
814               fprintf (stderr, "--autolaunch given twice\n");
815               exit (1);
816             }
817           
818           autolaunch = TRUE;
819
820           save_machine_uuid (arg);
821           requires_arg = FALSE;
822         }
823       else if (strcmp (arg, "--autolaunch") == 0)
824         requires_arg = TRUE;
825       else if (strstr (arg, "--config-file=") == arg)
826         {
827           const char *file;
828
829           if (config_file != NULL)
830             {
831               fprintf (stderr, "--config-file given twice\n");
832               exit (1);
833             }
834           
835           file = strchr (arg, '=');
836           ++file;
837
838           config_file = xstrdup (file);
839         }
840       else if (prev_arg &&
841                strcmp (prev_arg, "--config-file") == 0)
842         {
843           if (config_file != NULL)
844             {
845               fprintf (stderr, "--config-file given twice\n");
846               exit (1);
847             }
848
849           config_file = xstrdup (arg);
850           requires_arg = FALSE;
851         }
852       else if (strcmp (arg, "--config-file") == 0)
853         requires_arg = TRUE;
854       else if (arg[0] == '-')
855         {
856           if (strcmp (arg, "--") != 0)
857             {
858               fprintf (stderr, "Option `%s' is unknown.\n", arg);
859               exit (1);
860             }
861           else
862             {
863               runprog = argv[i+1];
864               remaining_args = i+2;
865               break;
866             }
867         }
868       else
869         {
870           runprog = arg;
871           remaining_args = i+1;
872           break;
873         }
874       
875       prev_arg = arg;
876       
877       ++i;
878     }
879   if (requires_arg)
880     {
881       fprintf (stderr, "Option `%s' requires an argument.\n", prev_arg);
882       exit (1);
883     }
884
885   if (auto_shell_syntax)
886     {
887       if ((shname = getenv ("SHELL")) != NULL)
888        {
889          if (!strncmp (shname + strlen (shname) - 3, "csh", 3))
890            c_shell_syntax = TRUE;
891          else
892            bourne_shell_syntax = TRUE;
893        }
894       else
895        bourne_shell_syntax = TRUE;
896     }  
897
898   if (exit_with_session)
899     verbose ("--exit-with-session enabled\n");
900
901   if (autolaunch)
902     {      
903 #ifndef DBUS_BUILD_X11
904       fprintf (stderr, "Autolaunch requested, but X11 support not compiled in.\n"
905                "Cannot continue.\n");
906       exit (1);
907 #else
908       char *address;
909       pid_t pid;
910       long wid;
911       
912       if (get_machine_uuid () == NULL)
913         {
914           fprintf (stderr, "Machine UUID not provided as arg to --autolaunch\n");
915           exit (1);
916         }
917
918       verbose ("Autolaunch enabled (using X11).\n");
919       if (!exit_with_session)
920         {
921           verbose ("--exit-with-session automatically enabled\n");
922           exit_with_session = TRUE;
923         }
924
925       if (!x11_init ())
926         {
927           fprintf (stderr, "Autolaunch error: X11 initialization failed.\n");
928           exit (1);
929         }
930
931       if (!x11_get_address (&address, &pid, &wid))
932         {
933           fprintf (stderr, "Autolaunch error: X11 communication error.\n");
934           exit (1);
935         }
936
937       if (address != NULL)
938         {
939           verbose ("dbus-daemon is already running. Returning existing parameters.\n");
940           pass_info (runprog, address, pid, wid, c_shell_syntax,
941                            bourne_shell_syntax, binary_syntax, argc, argv, remaining_args);
942           exit (0);
943         }
944     }
945    else if (read_machine_uuid_if_needed())
946     {
947       x11_init();
948 #endif
949     }
950
951
952   if (pipe (bus_pid_to_launcher_pipe) < 0 ||
953       pipe (bus_address_to_launcher_pipe) < 0 ||
954       pipe (bus_pid_to_babysitter_pipe) < 0)
955     {
956       fprintf (stderr,
957                "Failed to create pipe: %s\n",
958                strerror (errno));
959       exit (1);
960     }
961
962   ret = fork ();
963   if (ret < 0)
964     {
965       fprintf (stderr, "Failed to fork: %s\n",
966                strerror (errno));
967       exit (1);
968     }
969
970   if (ret == 0)
971     {
972       /* Child */
973 #define MAX_FD_LEN 64
974       char write_pid_fd_as_string[MAX_FD_LEN];
975       char write_address_fd_as_string[MAX_FD_LEN];
976
977 #ifdef DBUS_BUILD_X11
978       xdisplay = NULL;
979 #endif
980
981       if (close_stderr)
982         do_close_stderr ();
983
984       verbose ("=== Babysitter's intermediate parent created\n");
985
986       /* Fork once more to create babysitter */
987       
988       ret = fork ();
989       if (ret < 0)
990         {
991           fprintf (stderr, "Failed to fork: %s\n",
992                    strerror (errno));
993           exit (1);
994         }
995       
996       if (ret > 0)
997         {
998           /* In babysitter */
999           verbose ("=== Babysitter's intermediate parent continues\n");
1000           
1001           close (bus_pid_to_launcher_pipe[READ_END]);
1002           close (bus_pid_to_launcher_pipe[WRITE_END]);
1003           close (bus_address_to_launcher_pipe[READ_END]);
1004           close (bus_address_to_launcher_pipe[WRITE_END]);
1005           close (bus_pid_to_babysitter_pipe[WRITE_END]);
1006
1007           /* babysit() will fork *again*
1008            * and will also reap the pre-forked bus
1009            * daemon
1010            */
1011           babysit (exit_with_session, ret,
1012                    bus_pid_to_babysitter_pipe[READ_END]);
1013           exit (0);
1014         }
1015
1016       verbose ("=== Bus exec process created\n");
1017       
1018       /* Now we are the bus process (well, almost;
1019        * dbus-daemon itself forks again)
1020        */
1021       close (bus_pid_to_launcher_pipe[READ_END]);
1022       close (bus_address_to_launcher_pipe[READ_END]);
1023       close (bus_pid_to_babysitter_pipe[READ_END]);
1024       close (bus_pid_to_babysitter_pipe[WRITE_END]);
1025
1026       sprintf (write_pid_fd_as_string,
1027                "%d", bus_pid_to_launcher_pipe[WRITE_END]);
1028
1029       sprintf (write_address_fd_as_string,
1030                "%d", bus_address_to_launcher_pipe[WRITE_END]);
1031
1032       verbose ("Calling exec()\n");
1033  
1034 #ifdef DBUS_BUILD_TESTS 
1035       /* exec from testdir */
1036       if (getenv("DBUS_USE_TEST_BINARY") != NULL)
1037         {
1038           execl (TEST_BUS_BINARY,
1039                  TEST_BUS_BINARY,
1040                  "--fork",
1041                  "--print-pid", write_pid_fd_as_string,
1042                  "--print-address", write_address_fd_as_string,
1043                  config_file ? "--config-file" : "--session",
1044                  config_file, /* has to be last in this varargs list */
1045                  NULL); 
1046
1047           fprintf (stderr,
1048                    "Failed to execute test message bus daemon %s: %s. Will try again with the system path.\n",
1049                    TEST_BUS_BINARY, strerror (errno));
1050         }
1051  #endif /* DBUS_BUILD_TESTS */
1052
1053       execl (DBUS_DAEMONDIR"/dbus-daemon",
1054              DBUS_DAEMONDIR"/dbus-daemon",
1055              "--fork",
1056              "--print-pid", write_pid_fd_as_string,
1057              "--print-address", write_address_fd_as_string,
1058              config_file ? "--config-file" : "--session",
1059              config_file, /* has to be last in this varargs list */
1060              NULL);
1061
1062       fprintf (stderr,
1063                "Failed to execute message bus daemon %s: %s.  Will try again without full path.\n",
1064                DBUS_DAEMONDIR"/dbus-daemon", strerror (errno));
1065       
1066       /*
1067        * If it failed, try running without full PATH.  Note this is needed
1068        * because the build process builds the run-with-tmp-session-bus.conf
1069        * file and the dbus-daemon will not be in the install location during
1070        * build time.
1071        */
1072       execlp ("dbus-daemon",
1073               "dbus-daemon",
1074               "--fork",
1075               "--print-pid", write_pid_fd_as_string,
1076               "--print-address", write_address_fd_as_string,
1077               config_file ? "--config-file" : "--session",
1078               config_file, /* has to be last in this varargs list */
1079               NULL);
1080
1081       fprintf (stderr,
1082                "Failed to execute message bus daemon: %s\n",
1083                strerror (errno));
1084       exit (1);
1085     }
1086   else
1087     {
1088       /* Parent */
1089 #define MAX_PID_LEN 64
1090       pid_t bus_pid;  
1091       char bus_address[MAX_ADDR_LEN];
1092       char buf[MAX_PID_LEN];
1093       char *end;
1094       long wid = 0;
1095       long val;
1096       int ret2;
1097
1098       verbose ("=== Parent dbus-launch continues\n");
1099       
1100       close (bus_pid_to_launcher_pipe[WRITE_END]);
1101       close (bus_address_to_launcher_pipe[WRITE_END]);
1102       close (bus_pid_to_babysitter_pipe[READ_END]);
1103
1104       verbose ("Waiting for babysitter's intermediate parent\n");
1105       
1106       /* Immediately reap parent of babysitter
1107        * (which was created just for us to reap)
1108        */
1109       if (do_waitpid (ret) < 0)
1110         {
1111           fprintf (stderr, "Failed to waitpid() for babysitter intermediate process: %s\n",
1112                    strerror (errno));
1113           exit (1);
1114         }
1115
1116       verbose ("Reading address from bus\n");
1117       
1118       /* Read the pipe data, print, and exit */
1119       switch (read_line (bus_address_to_launcher_pipe[READ_END],
1120                          bus_address, MAX_ADDR_LEN))
1121         {
1122         case READ_STATUS_OK:
1123           break;
1124         case READ_STATUS_EOF:
1125           fprintf (stderr, "EOF in dbus-launch reading address from bus daemon\n");
1126           exit (1);
1127           break;
1128         case READ_STATUS_ERROR:
1129           fprintf (stderr, "Error in dbus-launch reading address from bus daemon: %s\n",
1130                    strerror (errno));
1131           exit (1);
1132           break;
1133         }
1134         
1135       close (bus_address_to_launcher_pipe[READ_END]);
1136
1137       verbose ("Reading PID from daemon\n");
1138       /* Now read data */
1139       switch (read_line (bus_pid_to_launcher_pipe[READ_END], buf, MAX_PID_LEN))
1140         {
1141         case READ_STATUS_OK:
1142           break;
1143         case READ_STATUS_EOF:
1144           fprintf (stderr, "EOF reading PID from bus daemon\n");
1145           exit (1);
1146           break;
1147         case READ_STATUS_ERROR:
1148           fprintf (stderr, "Error reading PID from bus daemon: %s\n",
1149                    strerror (errno));
1150           exit (1);
1151           break;
1152         }
1153
1154       end = NULL;
1155       val = strtol (buf, &end, 0);
1156       if (buf == end || end == NULL)
1157         {
1158           fprintf (stderr, "Failed to parse bus PID \"%s\": %s\n",
1159                    buf, strerror (errno));
1160           exit (1);
1161         }
1162
1163       bus_pid = val;
1164
1165       close (bus_pid_to_launcher_pipe[READ_END]);
1166
1167 #ifdef DBUS_BUILD_X11
1168       if (xdisplay != NULL)
1169         {
1170           verbose("Saving x11 address\n");
1171           ret2 = x11_save_address (bus_address, bus_pid, &wid);
1172           /* Only get an existing dbus session when autolaunching */
1173           if (autolaunch)
1174             {
1175               if (ret2 == 0)
1176                 {
1177                   char *address = NULL;
1178                   /* another window got added. Return its address */
1179                   bus_pid_to_kill = bus_pid;
1180                   if (x11_get_address (&address, &bus_pid, &wid)
1181                        && address != NULL)
1182                     {
1183                       verbose ("dbus-daemon is already running. Returning existing parameters.\n");
1184                       /* Kill the old bus */
1185                       kill_bus();
1186                       pass_info (runprog, address, bus_pid, wid,
1187                          c_shell_syntax, bourne_shell_syntax, binary_syntax,
1188                          argc, argv, remaining_args);
1189                     }
1190                   }
1191               if (ret2 < 0)
1192                 {
1193                   fprintf (stderr, "Error saving bus information.\n");
1194                   bus_pid_to_kill = bus_pid;
1195                   kill_bus_and_exit (1);
1196                 }
1197             }
1198         }
1199 #endif
1200
1201       /* Forward the pid to the babysitter */
1202       write_pid (bus_pid_to_babysitter_pipe[WRITE_END], bus_pid);
1203       close (bus_pid_to_babysitter_pipe[WRITE_END]);
1204
1205        pass_info (runprog, bus_address, bus_pid, wid, c_shell_syntax,
1206               bourne_shell_syntax, binary_syntax, argc, argv, remaining_args);
1207     }
1208
1209   return 0;
1210 }