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