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