1 /* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*- */
2 /* dbus-launch.c dbus-launch utility
4 * Copyright (C) 2003, 2006 Red Hat, Inc.
5 * Copyright (C) 2006 Thiago Macieira <thiago@kde.org>
7 * Licensed under the Academic Free License version 2.1
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.
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.
19 * You should have received a copy of the GNU General Public License
20 * along with this program; if not, write to the Free Software
21 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
24 #include "dbus-launch.h"
35 #include <sys/select.h>
40 extern Display *xdisplay;
43 static char* machine_uuid = NULL;
46 get_machine_uuid (void)
52 save_machine_uuid (const char *uuid_arg)
54 if (strlen (uuid_arg) != 32)
56 fprintf (stderr, "machine ID '%s' looks like it's the wrong length, should be 32 hex digits",
61 machine_uuid = xstrdup (uuid_arg);
65 verbose (const char *format,
69 static int verbose = TRUE;
70 static int verbose_initted = FALSE;
72 /* things are written a bit oddly here so that
73 * in the non-verbose case we just have the one
74 * conditional and return immediately.
81 verbose = getenv ("DBUS_VERBOSE") != NULL;
82 verbose_initted = TRUE;
87 fprintf (stderr, "%lu: ", (unsigned long) getpid ());
89 va_start (args, format);
90 vfprintf (stderr, format, args);
97 fprintf (stderr, "dbus-launch [--version] [--help] [--sh-syntax] [--csh-syntax] [--auto-syntax] [--exit-with-session]\n");
104 printf ("D-Bus Message Bus Launcher %s\n"
105 "Copyright (C) 2003 Red Hat, Inc.\n"
106 "This is free software; see the source for copying conditions.\n"
107 "There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n",
113 xstrdup (const char *str)
123 copy = malloc (len + 1);
127 memcpy (copy, str, len + 1);
134 READ_STATUS_OK, /**< Read succeeded */
135 READ_STATUS_ERROR, /**< Some kind of error */
136 READ_STATUS_EOF /**< EOF returned */
147 memset (buf, '\0', maxlen);
148 maxlen -= 1; /* ensure nul term */
150 retval = READ_STATUS_OK;
158 to_read = maxlen - bytes;
166 if (chunk < 0 && errno == EINTR)
171 retval = READ_STATUS_ERROR;
176 retval = READ_STATUS_EOF;
183 if (retval == READ_STATUS_EOF &&
185 retval = READ_STATUS_OK;
188 if (retval != READ_STATUS_ERROR &&
190 buf[bytes-1] == '\n')
203 retval = READ_STATUS_OK;
211 to_read = sizeof (pid_t) - bytes;
217 ((char*)buf) + bytes,
219 if (chunk < 0 && errno == EINTR)
224 retval = READ_STATUS_ERROR;
229 retval = READ_STATUS_EOF;
240 do_write (int fd, const void *buf, size_t count)
242 size_t bytes_written;
249 ret = write (fd, ((const char*)buf) + bytes_written, count - bytes_written);
257 fprintf (stderr, "Failed to write data to pipe! %s\n",
259 exit (1); /* give up, we suck */
263 bytes_written += ret;
265 if (bytes_written < count)
273 do_write (fd, &pid, sizeof (pid));
277 do_waitpid (pid_t pid)
282 ret = waitpid (pid, NULL, 0);
291 static pid_t bus_pid_to_kill = -1;
294 kill_bus_and_exit (int exitcode)
296 verbose ("Killing message bus and exiting babysitter\n");
298 /* in case these point to any NFS mounts, get rid of them immediately */
303 kill (bus_pid_to_kill, SIGTERM);
305 kill (bus_pid_to_kill, SIGKILL);
311 print_variables (const char *bus_address, pid_t bus_pid, long bus_wid,
312 int c_shell_syntax, int bourne_shell_syntax,
317 write (1, bus_address, strlen (bus_address) + 1);
318 write (1, &bus_pid, sizeof bus_pid);
319 write (1, &bus_wid, sizeof bus_wid);
322 else if (c_shell_syntax)
324 printf ("setenv DBUS_SESSION_BUS_ADDRESS '%s';\n", bus_address);
325 printf ("set DBUS_SESSION_BUS_PID=%ld;\n", (long) bus_pid);
327 printf ("set DBUS_SESSION_BUS_WINDOWID=%ld;\n", (long) bus_wid);
330 else if (bourne_shell_syntax)
332 printf ("DBUS_SESSION_BUS_ADDRESS='%s';\n", bus_address);
333 printf ("export DBUS_SESSION_BUS_ADDRESS;\n");
334 printf ("DBUS_SESSION_BUS_PID=%ld;\n", (long) bus_pid);
336 printf ("DBUS_SESSION_BUS_WINDOWID=%ld;\n", (long) bus_wid);
341 printf ("DBUS_SESSION_BUS_ADDRESS=%s\n", bus_address);
342 printf ("DBUS_SESSION_BUS_PID=%ld\n", (long) bus_pid);
344 printf ("DBUS_SESSION_BUS_WINDOWID=%ld\n", (long) bus_wid);
349 static int got_sighup = FALSE;
352 signal_handler (int sig)
364 kill_bus_when_session_ends (void)
370 struct sigaction act;
373 /* install SIGHUP handler */
375 sigemptyset (&empty_mask);
376 act.sa_handler = signal_handler;
377 act.sa_mask = empty_mask;
379 sigaction (SIGHUP, &act, NULL);
380 sigaction (SIGTERM, &act, NULL);
382 #ifdef DBUS_BUILD_X11
384 if (xdisplay != NULL)
386 x_fd = ConnectionNumber (xdisplay);
400 verbose ("stdin isatty(), monitoring it\n");
402 verbose ("stdin was not a TTY, not monitoring it\n");
404 if (tty_fd < 0 && x_fd < 0)
406 fprintf (stderr, "No terminal on standard input and no X display; cannot attach message bus to session lifetime\n");
417 FD_SET (tty_fd, &read_set);
418 FD_SET (tty_fd, &err_set);
423 FD_SET (x_fd, &read_set);
424 FD_SET (x_fd, &err_set);
427 select (MAX (tty_fd, x_fd) + 1,
428 &read_set, NULL, &err_set, NULL);
432 verbose ("Got SIGHUP, exiting\n");
433 kill_bus_and_exit (0);
436 #ifdef DBUS_BUILD_X11
437 /* Dump events on the floor, and let
438 * IO error handler run if we lose
442 verbose ("X fd condition reading = %d error = %d\n",
443 FD_ISSET (x_fd, &read_set),
444 FD_ISSET (x_fd, &err_set));
450 if (FD_ISSET (tty_fd, &read_set))
455 verbose ("TTY ready for reading\n");
457 bytes_read = read (tty_fd, discard, sizeof (discard));
459 verbose ("Read %d bytes from TTY errno = %d\n",
463 kill_bus_and_exit (0); /* EOF */
464 else if (bytes_read < 0 && errno != EINTR)
466 /* This shouldn't happen I don't think; to avoid
467 * spinning on the fd forever we exit.
469 fprintf (stderr, "dbus-launch: error reading from stdin: %s\n",
471 kill_bus_and_exit (0);
474 else if (FD_ISSET (tty_fd, &err_set))
476 verbose ("TTY has error condition\n");
478 kill_bus_and_exit (0);
485 babysit (int exit_with_session,
487 int read_bus_pid_fd) /* read pid from here */
493 verbose ("babysitting, exit_with_session = %d, child_pid = %ld, read_bus_pid_fd = %d\n",
494 exit_with_session, (long) child_pid, read_bus_pid_fd);
496 /* We chdir ("/") since we are persistent and daemon-like, and fork
497 * again so dbus-launch can reap the parent. However, we don't
498 * setsid() or close fd 0 because the idea is to remain attached
499 * to the tty and the X server in order to kill the message bus
500 * when the session ends.
505 fprintf (stderr, "Could not change to root directory: %s\n",
510 /* Close stdout/stderr so we don't block an "eval" or otherwise
511 * lock up. stdout is still chaining through to dbus-launch
512 * and in turn to the parent shell.
514 dev_null_fd = open ("/dev/null", O_RDWR);
515 if (dev_null_fd >= 0)
517 if (!exit_with_session)
518 dup2 (dev_null_fd, 0);
519 dup2 (dev_null_fd, 1);
520 s = getenv ("DBUS_DEBUG_OUTPUT");
521 if (s == NULL || *s == '\0')
522 dup2 (dev_null_fd, 2);
526 fprintf (stderr, "Failed to open /dev/null: %s\n",
528 /* continue, why not */
535 fprintf (stderr, "fork() failed in babysitter: %s\n",
542 /* Parent reaps pre-fork part of bus daemon, then exits and is
543 * reaped so the babysitter isn't a zombie
546 verbose ("=== Babysitter's intermediate parent continues again\n");
548 if (do_waitpid (child_pid) < 0)
550 /* shouldn't happen */
551 fprintf (stderr, "Failed waitpid() waiting for bus daemon's parent\n");
555 verbose ("Babysitter's intermediate parent exiting\n");
560 /* Child continues */
561 verbose ("=== Babysitter process created\n");
563 verbose ("Reading PID from bus\n");
565 switch (read_pid (read_bus_pid_fd, &bus_pid_to_kill))
569 case READ_STATUS_EOF:
570 fprintf (stderr, "EOF in dbus-launch reading PID from bus daemon\n");
573 case READ_STATUS_ERROR:
574 fprintf (stderr, "Error in dbus-launch reading PID from bus daemon: %s\n",
580 verbose ("Got PID %ld from daemon\n",
581 (long) bus_pid_to_kill);
583 if (exit_with_session)
585 /* Bus is now started and launcher has needed info;
586 * we connect to X display and tty and wait to
587 * kill bus if requested.
590 kill_bus_when_session_ends ();
593 verbose ("Babysitter exiting\n");
599 do_close_stderr (void)
605 /* dbus-launch is a Unix-only program, so we can rely on /dev/null being there.
606 * We're including unistd.h and we're dealing with sh/csh launch sequences...
608 fd = open ("/dev/null", O_RDWR);
611 fprintf (stderr, "Internal error: cannot open /dev/null: %s", strerror (errno));
616 if (dup2 (fd, 2) == -1)
617 // error; we can't report an error anymore...
626 main (int argc, char **argv)
628 const char *prev_arg;
630 const char *runprog = NULL;
631 int remaining_args = 0;
632 int exit_with_session;
633 int binary_syntax = FALSE;
634 int c_shell_syntax = FALSE;
635 int bourne_shell_syntax = FALSE;
636 int auto_shell_syntax = FALSE;
637 int autolaunch = FALSE;
638 int requires_arg = FALSE;
639 int close_stderr = FALSE;
642 int bus_pid_to_launcher_pipe[2];
643 int bus_pid_to_babysitter_pipe[2];
644 int bus_address_to_launcher_pipe[2];
647 exit_with_session = FALSE;
654 const char *arg = argv[i];
656 if (strcmp (arg, "--help") == 0 ||
657 strcmp (arg, "-h") == 0 ||
658 strcmp (arg, "-?") == 0)
660 else if (strcmp (arg, "--auto-syntax") == 0)
661 auto_shell_syntax = TRUE;
662 else if (strcmp (arg, "-c") == 0 ||
663 strcmp (arg, "--csh-syntax") == 0)
664 c_shell_syntax = TRUE;
665 else if (strcmp (arg, "-s") == 0 ||
666 strcmp (arg, "--sh-syntax") == 0)
667 bourne_shell_syntax = TRUE;
668 else if (strcmp (arg, "--binary-syntax") == 0)
669 binary_syntax = TRUE;
670 else if (strcmp (arg, "--version") == 0)
672 else if (strcmp (arg, "--exit-with-session") == 0)
673 exit_with_session = TRUE;
674 else if (strcmp (arg, "--close-stderr") == 0)
676 else if (strstr (arg, "--autolaunch=") == arg)
682 fprintf (stderr, "--autolaunch given twice\n");
688 s = strchr (arg, '=');
691 save_machine_uuid (s);
694 strcmp (prev_arg, "--autolaunch") == 0)
698 fprintf (stderr, "--autolaunch given twice\n");
704 save_machine_uuid (arg);
705 requires_arg = FALSE;
707 else if (strcmp (arg, "--autolaunch") == 0)
709 else if (strstr (arg, "--config-file=") == arg)
713 if (config_file != NULL)
715 fprintf (stderr, "--config-file given twice\n");
719 file = strchr (arg, '=');
722 config_file = xstrdup (file);
725 strcmp (prev_arg, "--config-file") == 0)
727 if (config_file != NULL)
729 fprintf (stderr, "--config-file given twice\n");
733 config_file = xstrdup (arg);
734 requires_arg = FALSE;
736 else if (strcmp (arg, "--config-file") == 0)
738 else if (arg[0] == '-')
740 if (strcmp (arg, "--") != 0)
742 fprintf (stderr, "Option `%s' is unknown.\n", arg);
748 remaining_args = i+2;
755 remaining_args = i+1;
765 fprintf (stderr, "Option `%s' requires an argument.\n", prev_arg);
769 if (auto_shell_syntax)
771 if ((shname = getenv ("SHELL")) != NULL)
773 if (!strncmp (shname + strlen (shname) - 3, "csh", 3))
774 c_shell_syntax = TRUE;
776 bourne_shell_syntax = TRUE;
779 bourne_shell_syntax = TRUE;
782 if (exit_with_session)
783 verbose ("--exit-with-session enabled\n");
787 #ifndef DBUS_BUILD_X11
788 fprintf (stderr, "Autolaunch requested, but X11 support not compiled in.\n"
789 "Cannot continue.\n");
796 if (get_machine_uuid () == NULL)
798 fprintf (stderr, "Machine UUID not provided as arg to --autolaunch\n");
802 /* FIXME right now autolaunch always does print_variables(), but it should really
803 * exec the child program instead if a child program was specified. For now
804 * we just exit if this conflict arises.
808 fprintf (stderr, "Currently --autolaunch does not support running a program\n");
812 verbose ("Autolaunch enabled (using X11).\n");
813 if (!exit_with_session)
815 verbose ("--exit-with-session automatically enabled\n");
816 exit_with_session = TRUE;
821 fprintf (stderr, "Autolaunch error: X11 initialization failed.\n");
825 if (!x11_get_address (&address, &pid, &wid))
827 fprintf (stderr, "Autolaunch error: X11 communication error.\n");
833 verbose ("dbus-daemon is already running. Returning existing parameters.\n");
834 print_variables (address, pid, wid, c_shell_syntax,
835 bourne_shell_syntax, binary_syntax);
841 if (pipe (bus_pid_to_launcher_pipe) < 0 ||
842 pipe (bus_address_to_launcher_pipe) < 0 ||
843 pipe (bus_pid_to_babysitter_pipe) < 0)
846 "Failed to create pipe: %s\n",
854 fprintf (stderr, "Failed to fork: %s\n",
862 #define MAX_FD_LEN 64
863 char write_pid_fd_as_string[MAX_FD_LEN];
864 char write_address_fd_as_string[MAX_FD_LEN];
869 verbose ("=== Babysitter's intermediate parent created\n");
871 /* Fork once more to create babysitter */
876 fprintf (stderr, "Failed to fork: %s\n",
884 verbose ("=== Babysitter's intermediate parent continues\n");
886 close (bus_pid_to_launcher_pipe[READ_END]);
887 close (bus_pid_to_launcher_pipe[WRITE_END]);
888 close (bus_address_to_launcher_pipe[READ_END]);
889 close (bus_address_to_launcher_pipe[WRITE_END]);
890 close (bus_pid_to_babysitter_pipe[WRITE_END]);
892 /* babysit() will fork *again*
893 * and will also reap the pre-forked bus
896 babysit (exit_with_session, ret,
897 bus_pid_to_babysitter_pipe[READ_END]);
901 verbose ("=== Bus exec process created\n");
903 /* Now we are the bus process (well, almost;
904 * dbus-daemon itself forks again)
906 close (bus_pid_to_launcher_pipe[READ_END]);
907 close (bus_address_to_launcher_pipe[READ_END]);
908 close (bus_pid_to_babysitter_pipe[READ_END]);
909 close (bus_pid_to_babysitter_pipe[WRITE_END]);
911 sprintf (write_pid_fd_as_string,
912 "%d", bus_pid_to_launcher_pipe[WRITE_END]);
914 sprintf (write_address_fd_as_string,
915 "%d", bus_address_to_launcher_pipe[WRITE_END]);
917 verbose ("Calling exec()\n");
919 #ifdef DBUS_BUILD_TESTS
920 /* exec from testdir */
921 if (getenv("DBUS_USE_TEST_BINARY") != NULL)
923 execl (TEST_BUS_BINARY,
926 "--print-pid", write_pid_fd_as_string,
927 "--print-address", write_address_fd_as_string,
928 config_file ? "--config-file" : "--session",
929 config_file, /* has to be last in this varargs list */
933 "Failed to execute test message bus daemon %s: %s. Will try again with the system path.\n",
934 TEST_BUS_BINARY, strerror (errno));
936 #endif /* DBUS_BUILD_TESTS */
938 execl (DBUS_DAEMONDIR"/dbus-daemon",
939 DBUS_DAEMONDIR"/dbus-daemon",
941 "--print-pid", write_pid_fd_as_string,
942 "--print-address", write_address_fd_as_string,
943 config_file ? "--config-file" : "--session",
944 config_file, /* has to be last in this varargs list */
948 "Failed to execute message bus daemon %s: %s. Will try again without full path.\n",
949 DBUS_DAEMONDIR"/dbus-daemon", strerror (errno));
952 * If it failed, try running without full PATH. Note this is needed
953 * because the build process builds the run-with-tmp-session-bus.conf
954 * file and the dbus-daemon will not be in the install location during
957 execlp ("dbus-daemon",
960 "--print-pid", write_pid_fd_as_string,
961 "--print-address", write_address_fd_as_string,
962 config_file ? "--config-file" : "--session",
963 config_file, /* has to be last in this varargs list */
967 "Failed to execute message bus daemon: %s\n",
974 #define MAX_PID_LEN 64
976 char bus_address[MAX_ADDR_LEN];
977 char buf[MAX_PID_LEN];
983 verbose ("=== Parent dbus-launch continues\n");
985 close (bus_pid_to_launcher_pipe[WRITE_END]);
986 close (bus_address_to_launcher_pipe[WRITE_END]);
987 close (bus_pid_to_babysitter_pipe[READ_END]);
989 verbose ("Waiting for babysitter's intermediate parent\n");
991 /* Immediately reap parent of babysitter
992 * (which was created just for us to reap)
994 if (do_waitpid (ret) < 0)
996 fprintf (stderr, "Failed to waitpid() for babysitter intermediate process: %s\n",
1001 verbose ("Reading address from bus\n");
1003 /* Read the pipe data, print, and exit */
1004 switch (read_line (bus_address_to_launcher_pipe[READ_END],
1005 bus_address, MAX_ADDR_LEN))
1007 case READ_STATUS_OK:
1009 case READ_STATUS_EOF:
1010 fprintf (stderr, "EOF in dbus-launch reading address from bus daemon\n");
1013 case READ_STATUS_ERROR:
1014 fprintf (stderr, "Error in dbus-launch reading address from bus daemon: %s\n",
1020 close (bus_address_to_launcher_pipe[READ_END]);
1022 verbose ("Reading PID from daemon\n");
1024 switch (read_line (bus_pid_to_launcher_pipe[READ_END], buf, MAX_PID_LEN))
1026 case READ_STATUS_OK:
1028 case READ_STATUS_EOF:
1029 fprintf (stderr, "EOF reading PID from bus daemon\n");
1032 case READ_STATUS_ERROR:
1033 fprintf (stderr, "Error reading PID from bus daemon: %s\n",
1040 val = strtol (buf, &end, 0);
1041 if (buf == end || end == NULL)
1043 fprintf (stderr, "Failed to parse bus PID \"%s\": %s\n",
1044 buf, strerror (errno));
1050 close (bus_pid_to_launcher_pipe[READ_END]);
1052 #ifdef DBUS_BUILD_X11
1053 /* FIXME the runprog == NULL is broken - we need to launch the runprog with the existing bus,
1054 * instead of just doing print_variables() if there's an existing bus.
1056 if (xdisplay != NULL && runprog == NULL)
1058 ret2 = x11_save_address (bus_address, bus_pid, &wid);
1061 /* another window got added. Return its address */
1066 if (x11_get_address (&address, &pid, &wid) && address != NULL)
1068 verbose ("dbus-daemon is already running. Returning existing parameters.\n");
1069 print_variables (address, pid, wid, c_shell_syntax,
1070 bourne_shell_syntax, binary_syntax);
1073 bus_pid_to_kill = bus_pid;
1074 kill_bus_and_exit (0);
1077 /* if failed, fall through */
1081 fprintf (stderr, "Error saving bus information.\n");
1082 bus_pid_to_kill = bus_pid;
1083 kill_bus_and_exit (1);
1088 /* Forward the pid to the babysitter */
1089 write_pid (bus_pid_to_babysitter_pipe[WRITE_END], bus_pid);
1090 close (bus_pid_to_babysitter_pipe[WRITE_END]);
1097 envvar = malloc (strlen ("DBUS_SESSION_BUS_ADDRESS=") + strlen (bus_address) + 1);
1098 args = malloc (sizeof (char *) * ((argc-remaining_args)+2));
1100 if (envvar == NULL || args == NULL)
1103 args[0] = xstrdup (runprog);
1106 for (i = 1; i <= (argc-remaining_args); i++)
1108 size_t len = strlen (argv[remaining_args+i-1])+1;
1109 args[i] = malloc (len);
1112 strncpy (args[i], argv[remaining_args+i-1], len);
1116 strcpy (envvar, "DBUS_SESSION_BUS_ADDRESS=");
1117 strcat (envvar, bus_address);
1120 execvp (runprog, args);
1121 fprintf (stderr, "Couldn't exec %s: %s\n", runprog, strerror (errno));
1126 print_variables (bus_address, bus_pid, wid, c_shell_syntax,
1127 bourne_shell_syntax, binary_syntax);
1130 verbose ("dbus-launch exiting\n");
1142 fprintf (stderr, "Out of memory!");