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