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