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"
36 #include <sys/select.h>
41 extern Display *xdisplay;
44 static char* machine_uuid = NULL;
47 get_machine_uuid (void)
53 save_machine_uuid (const char *uuid_arg)
55 if (strlen (uuid_arg) != 32)
57 fprintf (stderr, "machine ID '%s' looks like it's the wrong length, should be 32 hex digits",
62 machine_uuid = xstrdup (uuid_arg);
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 */
69 read_machine_uuid_if_needed (void)
72 char uuid[UUID_MAXLEN];
76 if (machine_uuid != NULL)
79 f = fopen (DBUS_MACHINE_UUID_FILE, "r");
83 if (fgets (uuid, UUID_MAXLEN, f) == NULL)
90 /* rstrip the read uuid */
91 while (len > 31 && isspace(uuid[len - 1]))
98 machine_uuid = xstrdup (uuid);
99 verbose ("UID: %s\n", machine_uuid);
109 verbose (const char *format,
113 static int verbose = TRUE;
114 static int verbose_initted = FALSE;
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.
123 if (!verbose_initted)
125 verbose = getenv ("DBUS_VERBOSE") != NULL;
126 verbose_initted = TRUE;
131 fprintf (stderr, "%lu: ", (unsigned long) getpid ());
133 va_start (args, format);
134 vfprintf (stderr, format, args);
141 fprintf (stderr, "dbus-launch [--version] [--help] [--sh-syntax] [--csh-syntax] [--auto-syntax] [--exit-with-session]\n");
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",
157 xstrdup (const char *str)
167 copy = malloc (len + 1);
171 memcpy (copy, str, len + 1);
178 READ_STATUS_OK, /**< Read succeeded */
179 READ_STATUS_ERROR, /**< Some kind of error */
180 READ_STATUS_EOF /**< EOF returned */
191 memset (buf, '\0', maxlen);
192 maxlen -= 1; /* ensure nul term */
194 retval = READ_STATUS_OK;
202 to_read = maxlen - bytes;
210 if (chunk < 0 && errno == EINTR)
215 retval = READ_STATUS_ERROR;
220 retval = READ_STATUS_EOF;
227 if (retval == READ_STATUS_EOF &&
229 retval = READ_STATUS_OK;
232 if (retval != READ_STATUS_ERROR &&
234 buf[bytes-1] == '\n')
247 retval = READ_STATUS_OK;
255 to_read = sizeof (pid_t) - bytes;
261 ((char*)buf) + bytes,
263 if (chunk < 0 && errno == EINTR)
268 retval = READ_STATUS_ERROR;
273 retval = READ_STATUS_EOF;
284 do_write (int fd, const void *buf, size_t count)
286 size_t bytes_written;
293 ret = write (fd, ((const char*)buf) + bytes_written, count - bytes_written);
301 fprintf (stderr, "Failed to write data to pipe! %s\n",
303 exit (1); /* give up, we suck */
307 bytes_written += ret;
309 if (bytes_written < count)
317 do_write (fd, &pid, sizeof (pid));
321 do_waitpid (pid_t pid)
326 ret = waitpid (pid, NULL, 0);
335 static pid_t bus_pid_to_kill = -1;
340 verbose ("Killing message bus and exiting babysitter\n");
341 kill (bus_pid_to_kill, SIGTERM);
343 kill (bus_pid_to_kill, SIGKILL);
347 kill_bus_and_exit (int exitcode)
349 /* in case these point to any NFS mounts, get rid of them immediately */
360 print_variables (const char *bus_address, pid_t bus_pid, long bus_wid,
361 int c_shell_syntax, int bourne_shell_syntax,
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);
371 else if (c_shell_syntax)
373 printf ("setenv DBUS_SESSION_BUS_ADDRESS '%s';\n", bus_address);
374 printf ("set DBUS_SESSION_BUS_PID=%ld;\n", (long) bus_pid);
376 printf ("set DBUS_SESSION_BUS_WINDOWID=%ld;\n", (long) bus_wid);
379 else if (bourne_shell_syntax)
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);
385 printf ("DBUS_SESSION_BUS_WINDOWID=%ld;\n", (long) bus_wid);
390 printf ("DBUS_SESSION_BUS_ADDRESS=%s\n", bus_address);
391 printf ("DBUS_SESSION_BUS_PID=%ld\n", (long) bus_pid);
393 printf ("DBUS_SESSION_BUS_WINDOWID=%ld\n", (long) bus_wid);
398 static int got_sighup = FALSE;
401 signal_handler (int sig)
413 kill_bus_when_session_ends (void)
419 struct sigaction act;
422 /* install SIGHUP handler */
424 sigemptyset (&empty_mask);
425 act.sa_handler = signal_handler;
426 act.sa_mask = empty_mask;
428 sigaction (SIGHUP, &act, NULL);
429 sigaction (SIGTERM, &act, NULL);
431 #ifdef DBUS_BUILD_X11
433 if (xdisplay != NULL)
435 x_fd = ConnectionNumber (xdisplay);
449 verbose ("stdin isatty(), monitoring it\n");
451 verbose ("stdin was not a TTY, not monitoring it\n");
453 if (tty_fd < 0 && x_fd < 0)
455 fprintf (stderr, "No terminal on standard input and no X display; cannot attach message bus to session lifetime\n");
461 #ifdef DBUS_BUILD_X11
462 /* Dump events on the floor, and let
463 * IO error handler run if we lose
464 * the X connection. It's important to
465 * run this before going into select() since
466 * we might have queued outgoing messages or
477 FD_SET (tty_fd, &read_set);
478 FD_SET (tty_fd, &err_set);
483 FD_SET (x_fd, &read_set);
484 FD_SET (x_fd, &err_set);
487 select (MAX (tty_fd, x_fd) + 1,
488 &read_set, NULL, &err_set, NULL);
492 verbose ("Got SIGHUP, exiting\n");
493 kill_bus_and_exit (0);
496 #ifdef DBUS_BUILD_X11
497 /* Events will be processed before we select again
500 verbose ("X fd condition reading = %d error = %d\n",
501 FD_ISSET (x_fd, &read_set),
502 FD_ISSET (x_fd, &err_set));
507 if (FD_ISSET (tty_fd, &read_set))
512 verbose ("TTY ready for reading\n");
514 bytes_read = read (tty_fd, discard, sizeof (discard));
516 verbose ("Read %d bytes from TTY errno = %d\n",
520 kill_bus_and_exit (0); /* EOF */
521 else if (bytes_read < 0 && errno != EINTR)
523 /* This shouldn't happen I don't think; to avoid
524 * spinning on the fd forever we exit.
526 fprintf (stderr, "dbus-launch: error reading from stdin: %s\n",
528 kill_bus_and_exit (0);
531 else if (FD_ISSET (tty_fd, &err_set))
533 verbose ("TTY has error condition\n");
535 kill_bus_and_exit (0);
542 babysit (int exit_with_session,
544 int read_bus_pid_fd) /* read pid from here */
550 verbose ("babysitting, exit_with_session = %d, child_pid = %ld, read_bus_pid_fd = %d\n",
551 exit_with_session, (long) child_pid, read_bus_pid_fd);
553 /* We chdir ("/") since we are persistent and daemon-like, and fork
554 * again so dbus-launch can reap the parent. However, we don't
555 * setsid() or close fd 0 because the idea is to remain attached
556 * to the tty and the X server in order to kill the message bus
557 * when the session ends.
562 fprintf (stderr, "Could not change to root directory: %s\n",
567 /* Close stdout/stderr so we don't block an "eval" or otherwise
568 * lock up. stdout is still chaining through to dbus-launch
569 * and in turn to the parent shell.
571 dev_null_fd = open ("/dev/null", O_RDWR);
572 if (dev_null_fd >= 0)
574 if (!exit_with_session)
575 dup2 (dev_null_fd, 0);
576 dup2 (dev_null_fd, 1);
577 s = getenv ("DBUS_DEBUG_OUTPUT");
578 if (s == NULL || *s == '\0')
579 dup2 (dev_null_fd, 2);
583 fprintf (stderr, "Failed to open /dev/null: %s\n",
585 /* continue, why not */
592 fprintf (stderr, "fork() failed in babysitter: %s\n",
599 /* Parent reaps pre-fork part of bus daemon, then exits and is
600 * reaped so the babysitter isn't a zombie
603 verbose ("=== Babysitter's intermediate parent continues again\n");
605 if (do_waitpid (child_pid) < 0)
607 /* shouldn't happen */
608 fprintf (stderr, "Failed waitpid() waiting for bus daemon's parent\n");
612 verbose ("Babysitter's intermediate parent exiting\n");
617 /* Child continues */
618 verbose ("=== Babysitter process created\n");
620 verbose ("Reading PID from bus\n");
622 switch (read_pid (read_bus_pid_fd, &bus_pid_to_kill))
626 case READ_STATUS_EOF:
627 fprintf (stderr, "EOF in dbus-launch reading PID from bus daemon\n");
630 case READ_STATUS_ERROR:
631 fprintf (stderr, "Error in dbus-launch reading PID from bus daemon: %s\n",
637 verbose ("Got PID %ld from daemon\n",
638 (long) bus_pid_to_kill);
640 if (exit_with_session)
642 /* Bus is now started and launcher has needed info;
643 * we connect to X display and tty and wait to
644 * kill bus if requested.
647 kill_bus_when_session_ends ();
650 verbose ("Babysitter exiting\n");
656 do_close_stderr (void)
662 /* dbus-launch is a Unix-only program, so we can rely on /dev/null being there.
663 * We're including unistd.h and we're dealing with sh/csh launch sequences...
665 fd = open ("/dev/null", O_RDWR);
668 fprintf (stderr, "Internal error: cannot open /dev/null: %s", strerror (errno));
673 if (dup2 (fd, 2) == -1)
675 /* error; we can't report an error anymore... */
682 pass_info (const char *runprog, const char *bus_address, pid_t bus_pid,
683 long bus_wid, int c_shell_syntax, int bourne_shell_syntax,
685 int argc, char **argv, int remaining_args)
693 envvar = malloc (strlen ("DBUS_SESSION_BUS_ADDRESS=") +
694 strlen (bus_address) + 1);
695 args = malloc (sizeof (char *) * ((argc-remaining_args)+2));
697 if (envvar == NULL || args == NULL)
700 args[0] = xstrdup (runprog);
703 for (i = 1; i <= (argc-remaining_args); i++)
705 size_t len = strlen (argv[remaining_args+i-1])+1;
706 args[i] = malloc (len);
709 strncpy (args[i], argv[remaining_args+i-1], len);
713 strcpy (envvar, "DBUS_SESSION_BUS_ADDRESS=");
714 strcat (envvar, bus_address);
717 execvp (runprog, args);
718 fprintf (stderr, "Couldn't exec %s: %s\n", runprog, strerror (errno));
723 print_variables (bus_address, bus_pid, bus_wid, c_shell_syntax,
724 bourne_shell_syntax, binary_syntax);
726 verbose ("dbus-launch exiting\n");
734 fprintf (stderr, "Out of memory!");
742 main (int argc, char **argv)
744 const char *prev_arg;
746 const char *runprog = NULL;
747 int remaining_args = 0;
748 int exit_with_session;
749 int binary_syntax = FALSE;
750 int c_shell_syntax = FALSE;
751 int bourne_shell_syntax = FALSE;
752 int auto_shell_syntax = FALSE;
753 int autolaunch = FALSE;
754 int requires_arg = FALSE;
755 int close_stderr = FALSE;
758 int bus_pid_to_launcher_pipe[2];
759 int bus_pid_to_babysitter_pipe[2];
760 int bus_address_to_launcher_pipe[2];
763 exit_with_session = FALSE;
770 const char *arg = argv[i];
772 if (strcmp (arg, "--help") == 0 ||
773 strcmp (arg, "-h") == 0 ||
774 strcmp (arg, "-?") == 0)
776 else if (strcmp (arg, "--auto-syntax") == 0)
777 auto_shell_syntax = TRUE;
778 else if (strcmp (arg, "-c") == 0 ||
779 strcmp (arg, "--csh-syntax") == 0)
780 c_shell_syntax = TRUE;
781 else if (strcmp (arg, "-s") == 0 ||
782 strcmp (arg, "--sh-syntax") == 0)
783 bourne_shell_syntax = TRUE;
784 else if (strcmp (arg, "--binary-syntax") == 0)
785 binary_syntax = TRUE;
786 else if (strcmp (arg, "--version") == 0)
788 else if (strcmp (arg, "--exit-with-session") == 0)
789 exit_with_session = TRUE;
790 else if (strcmp (arg, "--close-stderr") == 0)
792 else if (strstr (arg, "--autolaunch=") == arg)
798 fprintf (stderr, "--autolaunch given twice\n");
804 s = strchr (arg, '=');
807 save_machine_uuid (s);
810 strcmp (prev_arg, "--autolaunch") == 0)
814 fprintf (stderr, "--autolaunch given twice\n");
820 save_machine_uuid (arg);
821 requires_arg = FALSE;
823 else if (strcmp (arg, "--autolaunch") == 0)
825 else if (strstr (arg, "--config-file=") == arg)
829 if (config_file != NULL)
831 fprintf (stderr, "--config-file given twice\n");
835 file = strchr (arg, '=');
838 config_file = xstrdup (file);
841 strcmp (prev_arg, "--config-file") == 0)
843 if (config_file != NULL)
845 fprintf (stderr, "--config-file given twice\n");
849 config_file = xstrdup (arg);
850 requires_arg = FALSE;
852 else if (strcmp (arg, "--config-file") == 0)
854 else if (arg[0] == '-')
856 if (strcmp (arg, "--") != 0)
858 fprintf (stderr, "Option `%s' is unknown.\n", arg);
864 remaining_args = i+2;
871 remaining_args = i+1;
881 fprintf (stderr, "Option `%s' requires an argument.\n", prev_arg);
885 if (auto_shell_syntax)
887 if ((shname = getenv ("SHELL")) != NULL)
889 if (!strncmp (shname + strlen (shname) - 3, "csh", 3))
890 c_shell_syntax = TRUE;
892 bourne_shell_syntax = TRUE;
895 bourne_shell_syntax = TRUE;
898 if (exit_with_session)
899 verbose ("--exit-with-session enabled\n");
903 #ifndef DBUS_BUILD_X11
904 fprintf (stderr, "Autolaunch requested, but X11 support not compiled in.\n"
905 "Cannot continue.\n");
912 if (get_machine_uuid () == NULL)
914 fprintf (stderr, "Machine UUID not provided as arg to --autolaunch\n");
918 verbose ("Autolaunch enabled (using X11).\n");
919 if (!exit_with_session)
921 verbose ("--exit-with-session automatically enabled\n");
922 exit_with_session = TRUE;
927 fprintf (stderr, "Autolaunch error: X11 initialization failed.\n");
931 if (!x11_get_address (&address, &pid, &wid))
933 fprintf (stderr, "Autolaunch error: X11 communication error.\n");
939 verbose ("dbus-daemon is already running. Returning existing parameters.\n");
940 pass_info (runprog, address, pid, wid, c_shell_syntax,
941 bourne_shell_syntax, binary_syntax, argc, argv, remaining_args);
945 else if (read_machine_uuid_if_needed())
952 if (pipe (bus_pid_to_launcher_pipe) < 0 ||
953 pipe (bus_address_to_launcher_pipe) < 0 ||
954 pipe (bus_pid_to_babysitter_pipe) < 0)
957 "Failed to create pipe: %s\n",
965 fprintf (stderr, "Failed to fork: %s\n",
973 #define MAX_FD_LEN 64
974 char write_pid_fd_as_string[MAX_FD_LEN];
975 char write_address_fd_as_string[MAX_FD_LEN];
977 #ifdef DBUS_BUILD_X11
984 verbose ("=== Babysitter's intermediate parent created\n");
986 /* Fork once more to create babysitter */
991 fprintf (stderr, "Failed to fork: %s\n",
999 verbose ("=== Babysitter's intermediate parent continues\n");
1001 close (bus_pid_to_launcher_pipe[READ_END]);
1002 close (bus_pid_to_launcher_pipe[WRITE_END]);
1003 close (bus_address_to_launcher_pipe[READ_END]);
1004 close (bus_address_to_launcher_pipe[WRITE_END]);
1005 close (bus_pid_to_babysitter_pipe[WRITE_END]);
1007 /* babysit() will fork *again*
1008 * and will also reap the pre-forked bus
1011 babysit (exit_with_session, ret,
1012 bus_pid_to_babysitter_pipe[READ_END]);
1016 verbose ("=== Bus exec process created\n");
1018 /* Now we are the bus process (well, almost;
1019 * dbus-daemon itself forks again)
1021 close (bus_pid_to_launcher_pipe[READ_END]);
1022 close (bus_address_to_launcher_pipe[READ_END]);
1023 close (bus_pid_to_babysitter_pipe[READ_END]);
1024 close (bus_pid_to_babysitter_pipe[WRITE_END]);
1026 sprintf (write_pid_fd_as_string,
1027 "%d", bus_pid_to_launcher_pipe[WRITE_END]);
1029 sprintf (write_address_fd_as_string,
1030 "%d", bus_address_to_launcher_pipe[WRITE_END]);
1032 verbose ("Calling exec()\n");
1034 #ifdef DBUS_BUILD_TESTS
1035 /* exec from testdir */
1036 if (getenv("DBUS_USE_TEST_BINARY") != NULL)
1038 execl (TEST_BUS_BINARY,
1041 "--print-pid", write_pid_fd_as_string,
1042 "--print-address", write_address_fd_as_string,
1043 config_file ? "--config-file" : "--session",
1044 config_file, /* has to be last in this varargs list */
1048 "Failed to execute test message bus daemon %s: %s. Will try again with the system path.\n",
1049 TEST_BUS_BINARY, strerror (errno));
1051 #endif /* DBUS_BUILD_TESTS */
1053 execl (DBUS_DAEMONDIR"/dbus-daemon",
1054 DBUS_DAEMONDIR"/dbus-daemon",
1056 "--print-pid", write_pid_fd_as_string,
1057 "--print-address", write_address_fd_as_string,
1058 config_file ? "--config-file" : "--session",
1059 config_file, /* has to be last in this varargs list */
1063 "Failed to execute message bus daemon %s: %s. Will try again without full path.\n",
1064 DBUS_DAEMONDIR"/dbus-daemon", strerror (errno));
1067 * If it failed, try running without full PATH. Note this is needed
1068 * because the build process builds the run-with-tmp-session-bus.conf
1069 * file and the dbus-daemon will not be in the install location during
1072 execlp ("dbus-daemon",
1075 "--print-pid", write_pid_fd_as_string,
1076 "--print-address", write_address_fd_as_string,
1077 config_file ? "--config-file" : "--session",
1078 config_file, /* has to be last in this varargs list */
1082 "Failed to execute message bus daemon: %s\n",
1089 #define MAX_PID_LEN 64
1091 char bus_address[MAX_ADDR_LEN];
1092 char buf[MAX_PID_LEN];
1098 verbose ("=== Parent dbus-launch continues\n");
1100 close (bus_pid_to_launcher_pipe[WRITE_END]);
1101 close (bus_address_to_launcher_pipe[WRITE_END]);
1102 close (bus_pid_to_babysitter_pipe[READ_END]);
1104 verbose ("Waiting for babysitter's intermediate parent\n");
1106 /* Immediately reap parent of babysitter
1107 * (which was created just for us to reap)
1109 if (do_waitpid (ret) < 0)
1111 fprintf (stderr, "Failed to waitpid() for babysitter intermediate process: %s\n",
1116 verbose ("Reading address from bus\n");
1118 /* Read the pipe data, print, and exit */
1119 switch (read_line (bus_address_to_launcher_pipe[READ_END],
1120 bus_address, MAX_ADDR_LEN))
1122 case READ_STATUS_OK:
1124 case READ_STATUS_EOF:
1125 fprintf (stderr, "EOF in dbus-launch reading address from bus daemon\n");
1128 case READ_STATUS_ERROR:
1129 fprintf (stderr, "Error in dbus-launch reading address from bus daemon: %s\n",
1135 close (bus_address_to_launcher_pipe[READ_END]);
1137 verbose ("Reading PID from daemon\n");
1139 switch (read_line (bus_pid_to_launcher_pipe[READ_END], buf, MAX_PID_LEN))
1141 case READ_STATUS_OK:
1143 case READ_STATUS_EOF:
1144 fprintf (stderr, "EOF reading PID from bus daemon\n");
1147 case READ_STATUS_ERROR:
1148 fprintf (stderr, "Error reading PID from bus daemon: %s\n",
1155 val = strtol (buf, &end, 0);
1156 if (buf == end || end == NULL)
1158 fprintf (stderr, "Failed to parse bus PID \"%s\": %s\n",
1159 buf, strerror (errno));
1165 close (bus_pid_to_launcher_pipe[READ_END]);
1167 #ifdef DBUS_BUILD_X11
1168 if (xdisplay != NULL)
1170 verbose("Saving x11 address\n");
1171 ret2 = x11_save_address (bus_address, bus_pid, &wid);
1172 /* Only get an existing dbus session when autolaunching */
1177 char *address = NULL;
1178 /* another window got added. Return its address */
1179 bus_pid_to_kill = bus_pid;
1180 if (x11_get_address (&address, &bus_pid, &wid)
1183 verbose ("dbus-daemon is already running. Returning existing parameters.\n");
1184 /* Kill the old bus */
1186 pass_info (runprog, address, bus_pid, wid,
1187 c_shell_syntax, bourne_shell_syntax, binary_syntax,
1188 argc, argv, remaining_args);
1193 fprintf (stderr, "Error saving bus information.\n");
1194 bus_pid_to_kill = bus_pid;
1195 kill_bus_and_exit (1);
1201 /* Forward the pid to the babysitter */
1202 write_pid (bus_pid_to_babysitter_pipe[WRITE_END], bus_pid);
1203 close (bus_pid_to_babysitter_pipe[WRITE_END]);
1205 pass_info (runprog, bus_address, bus_pid, wid, c_shell_syntax,
1206 bourne_shell_syntax, binary_syntax, argc, argv, remaining_args);