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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
26 #include "dbus-launch.h"
38 #include <sys/select.h>
43 extern Display *xdisplay;
46 static char* machine_uuid = NULL;
49 get_machine_uuid (void)
55 save_machine_uuid (const char *uuid_arg)
57 if (strlen (uuid_arg) != 32)
59 fprintf (stderr, "machine ID '%s' looks like it's the wrong length, should be 32 hex digits",
64 machine_uuid = xstrdup (uuid_arg);
67 #define UUID_MAXLEN 40
68 /* Read the machine uuid from file if needed. Returns TRUE if machine_uuid is
69 * set after this function */
71 read_machine_uuid_if_needed (void)
74 char uuid[UUID_MAXLEN];
78 if (machine_uuid != NULL)
81 f = fopen (DBUS_MACHINE_UUID_FILE, "r");
85 if (fgets (uuid, UUID_MAXLEN, f) == NULL)
92 /* rstrip the read uuid */
93 while (len > 31 && isspace(uuid[len - 1]))
100 machine_uuid = xstrdup (uuid);
101 verbose ("UID: %s\n", machine_uuid);
111 verbose (const char *format,
115 static int verbose = TRUE;
116 static int verbose_initted = FALSE;
118 /* things are written a bit oddly here so that
119 * in the non-verbose case we just have the one
120 * conditional and return immediately.
125 if (!verbose_initted)
127 verbose = getenv ("DBUS_VERBOSE") != NULL;
128 verbose_initted = TRUE;
133 fprintf (stderr, "%lu: ", (unsigned long) getpid ());
135 va_start (args, format);
136 vfprintf (stderr, format, args);
143 fprintf (stderr, "dbus-launch [--version] [--help] [--sh-syntax] [--csh-syntax] [--auto-syntax] [--exit-with-session]\n");
150 printf ("D-Bus Message Bus Launcher %s\n"
151 "Copyright (C) 2003 Red Hat, Inc.\n"
152 "This is free software; see the source for copying conditions.\n"
153 "There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n",
159 xstrdup (const char *str)
169 copy = malloc (len + 1);
173 memcpy (copy, str, len + 1);
180 READ_STATUS_OK, /**< Read succeeded */
181 READ_STATUS_ERROR, /**< Some kind of error */
182 READ_STATUS_EOF /**< EOF returned */
193 memset (buf, '\0', maxlen);
194 maxlen -= 1; /* ensure nul term */
196 retval = READ_STATUS_OK;
204 to_read = maxlen - bytes;
212 if (chunk < 0 && errno == EINTR)
217 retval = READ_STATUS_ERROR;
222 retval = READ_STATUS_EOF;
229 if (retval == READ_STATUS_EOF &&
231 retval = READ_STATUS_OK;
234 if (retval != READ_STATUS_ERROR &&
236 buf[bytes-1] == '\n')
249 retval = READ_STATUS_OK;
257 to_read = sizeof (pid_t) - bytes;
263 ((char*)buf) + bytes,
265 if (chunk < 0 && errno == EINTR)
270 retval = READ_STATUS_ERROR;
275 retval = READ_STATUS_EOF;
286 do_write (int fd, const void *buf, size_t count)
288 size_t bytes_written;
295 ret = write (fd, ((const char*)buf) + bytes_written, count - bytes_written);
303 fprintf (stderr, "Failed to write data to pipe! %s\n",
305 exit (1); /* give up, we suck */
309 bytes_written += ret;
311 if (bytes_written < count)
319 do_write (fd, &pid, sizeof (pid));
323 do_waitpid (pid_t pid)
328 ret = waitpid (pid, NULL, 0);
337 static pid_t bus_pid_to_kill = -1;
342 verbose ("Killing message bus and exiting babysitter\n");
343 kill (bus_pid_to_kill, SIGTERM);
345 kill (bus_pid_to_kill, SIGKILL);
349 kill_bus_and_exit (int exitcode)
351 /* in case these point to any NFS mounts, get rid of them immediately */
362 print_variables (const char *bus_address, pid_t bus_pid, long bus_wid,
363 int c_shell_syntax, int bourne_shell_syntax,
368 do_write (1, bus_address, strlen (bus_address) + 1);
369 do_write (1, &bus_pid, sizeof bus_pid);
370 do_write (1, &bus_wid, sizeof bus_wid);
373 else if (c_shell_syntax)
375 printf ("setenv DBUS_SESSION_BUS_ADDRESS '%s';\n", bus_address);
376 printf ("set DBUS_SESSION_BUS_PID=%ld;\n", (long) bus_pid);
378 printf ("set DBUS_SESSION_BUS_WINDOWID=%ld;\n", (long) bus_wid);
381 else if (bourne_shell_syntax)
383 printf ("DBUS_SESSION_BUS_ADDRESS='%s';\n", bus_address);
384 printf ("export DBUS_SESSION_BUS_ADDRESS;\n");
385 printf ("DBUS_SESSION_BUS_PID=%ld;\n", (long) bus_pid);
387 printf ("DBUS_SESSION_BUS_WINDOWID=%ld;\n", (long) bus_wid);
392 printf ("DBUS_SESSION_BUS_ADDRESS=%s\n", bus_address);
393 printf ("DBUS_SESSION_BUS_PID=%ld\n", (long) bus_pid);
395 printf ("DBUS_SESSION_BUS_WINDOWID=%ld\n", (long) bus_wid);
400 static int got_sighup = FALSE;
403 signal_handler (int sig)
418 kill_bus_when_session_ends (void)
424 struct sigaction act;
427 /* install SIGHUP handler */
429 sigemptyset (&empty_mask);
430 act.sa_handler = signal_handler;
431 act.sa_mask = empty_mask;
433 sigaction (SIGHUP, &act, NULL);
434 sigaction (SIGTERM, &act, NULL);
435 sigaction (SIGINT, &act, NULL);
437 #ifdef DBUS_BUILD_X11
439 if (xdisplay != NULL)
441 x_fd = ConnectionNumber (xdisplay);
455 verbose ("stdin isatty(), monitoring it\n");
457 verbose ("stdin was not a TTY, not monitoring it\n");
459 if (tty_fd < 0 && x_fd < 0)
461 fprintf (stderr, "No terminal on standard input and no X display; cannot attach message bus to session lifetime\n");
467 #ifdef DBUS_BUILD_X11
468 /* Dump events on the floor, and let
469 * IO error handler run if we lose
470 * the X connection. It's important to
471 * run this before going into select() since
472 * we might have queued outgoing messages or
483 FD_SET (tty_fd, &read_set);
484 FD_SET (tty_fd, &err_set);
489 FD_SET (x_fd, &read_set);
490 FD_SET (x_fd, &err_set);
493 select (MAX (tty_fd, x_fd) + 1,
494 &read_set, NULL, &err_set, NULL);
498 verbose ("Got SIGHUP, exiting\n");
499 kill_bus_and_exit (0);
502 #ifdef DBUS_BUILD_X11
503 /* Events will be processed before we select again
506 verbose ("X fd condition reading = %d error = %d\n",
507 FD_ISSET (x_fd, &read_set),
508 FD_ISSET (x_fd, &err_set));
513 if (FD_ISSET (tty_fd, &read_set))
518 verbose ("TTY ready for reading\n");
520 bytes_read = read (tty_fd, discard, sizeof (discard));
522 verbose ("Read %d bytes from TTY errno = %d\n",
526 kill_bus_and_exit (0); /* EOF */
527 else if (bytes_read < 0 && errno != EINTR)
529 /* This shouldn't happen I don't think; to avoid
530 * spinning on the fd forever we exit.
532 fprintf (stderr, "dbus-launch: error reading from stdin: %s\n",
534 kill_bus_and_exit (0);
537 else if (FD_ISSET (tty_fd, &err_set))
539 verbose ("TTY has error condition\n");
541 kill_bus_and_exit (0);
548 babysit (int exit_with_session,
550 int read_bus_pid_fd) /* read pid from here */
556 verbose ("babysitting, exit_with_session = %d, child_pid = %ld, read_bus_pid_fd = %d\n",
557 exit_with_session, (long) child_pid, read_bus_pid_fd);
559 /* We chdir ("/") since we are persistent and daemon-like, and fork
560 * again so dbus-launch can reap the parent. However, we don't
561 * setsid() or close fd 0 because the idea is to remain attached
562 * to the tty and the X server in order to kill the message bus
563 * when the session ends.
568 fprintf (stderr, "Could not change to root directory: %s\n",
573 /* Close stdout/stderr so we don't block an "eval" or otherwise
574 * lock up. stdout is still chaining through to dbus-launch
575 * and in turn to the parent shell.
577 dev_null_fd = open ("/dev/null", O_RDWR);
578 if (dev_null_fd >= 0)
580 if (!exit_with_session)
581 dup2 (dev_null_fd, 0);
582 dup2 (dev_null_fd, 1);
583 s = getenv ("DBUS_DEBUG_OUTPUT");
584 if (s == NULL || *s == '\0')
585 dup2 (dev_null_fd, 2);
589 fprintf (stderr, "Failed to open /dev/null: %s\n",
591 /* continue, why not */
598 fprintf (stderr, "fork() failed in babysitter: %s\n",
605 /* Parent reaps pre-fork part of bus daemon, then exits and is
606 * reaped so the babysitter isn't a zombie
609 verbose ("=== Babysitter's intermediate parent continues again\n");
611 if (do_waitpid (child_pid) < 0)
613 /* shouldn't happen */
614 fprintf (stderr, "Failed waitpid() waiting for bus daemon's parent\n");
618 verbose ("Babysitter's intermediate parent exiting\n");
623 /* Child continues */
624 verbose ("=== Babysitter process created\n");
626 verbose ("Reading PID from bus\n");
628 switch (read_pid (read_bus_pid_fd, &bus_pid_to_kill))
632 case READ_STATUS_EOF:
633 fprintf (stderr, "EOF in dbus-launch reading PID from bus daemon\n");
636 case READ_STATUS_ERROR:
637 fprintf (stderr, "Error in dbus-launch reading PID from bus daemon: %s\n",
643 verbose ("Got PID %ld from daemon\n",
644 (long) bus_pid_to_kill);
646 if (exit_with_session)
648 /* Bus is now started and launcher has needed info;
649 * we connect to X display and tty and wait to
650 * kill bus if requested.
653 kill_bus_when_session_ends ();
656 verbose ("Babysitter exiting\n");
662 do_close_stderr (void)
668 /* dbus-launch is a Unix-only program, so we can rely on /dev/null being there.
669 * We're including unistd.h and we're dealing with sh/csh launch sequences...
671 fd = open ("/dev/null", O_RDWR);
674 fprintf (stderr, "Internal error: cannot open /dev/null: %s", strerror (errno));
679 if (dup2 (fd, 2) == -1)
681 /* error; we can't report an error anymore... */
688 pass_info (const char *runprog, const char *bus_address, pid_t bus_pid,
689 long bus_wid, int c_shell_syntax, int bourne_shell_syntax,
691 int argc, char **argv, int remaining_args)
700 envvar = malloc (strlen ("DBUS_SESSION_BUS_ADDRESS=") +
701 strlen (bus_address) + 1);
702 args = malloc (sizeof (char *) * ((argc-remaining_args)+2));
704 if (envvar == NULL || args == NULL)
707 args[0] = xstrdup (runprog);
710 for (i = 1; i <= (argc-remaining_args); i++)
712 size_t len = strlen (argv[remaining_args+i-1])+1;
713 args[i] = malloc (len);
716 strncpy (args[i], argv[remaining_args+i-1], len);
720 strcpy (envvar, "DBUS_SESSION_BUS_ADDRESS=");
721 strcat (envvar, bus_address);
724 execvp (runprog, args);
725 fprintf (stderr, "Couldn't exec %s: %s\n", runprog, strerror (errno));
730 print_variables (bus_address, bus_pid, bus_wid, c_shell_syntax,
731 bourne_shell_syntax, binary_syntax);
733 verbose ("dbus-launch exiting\n");
747 fprintf (stderr, "Out of memory!");
755 main (int argc, char **argv)
757 const char *prev_arg;
759 const char *runprog = NULL;
760 int remaining_args = 0;
761 int exit_with_session;
762 int binary_syntax = FALSE;
763 int c_shell_syntax = FALSE;
764 int bourne_shell_syntax = FALSE;
765 int auto_shell_syntax = FALSE;
766 int autolaunch = FALSE;
767 int requires_arg = FALSE;
768 int close_stderr = FALSE;
771 int bus_pid_to_launcher_pipe[2];
772 int bus_pid_to_babysitter_pipe[2];
773 int bus_address_to_launcher_pipe[2];
776 exit_with_session = FALSE;
783 const char *arg = argv[i];
785 if (strcmp (arg, "--help") == 0 ||
786 strcmp (arg, "-h") == 0 ||
787 strcmp (arg, "-?") == 0)
789 else if (strcmp (arg, "--auto-syntax") == 0)
790 auto_shell_syntax = TRUE;
791 else if (strcmp (arg, "-c") == 0 ||
792 strcmp (arg, "--csh-syntax") == 0)
793 c_shell_syntax = TRUE;
794 else if (strcmp (arg, "-s") == 0 ||
795 strcmp (arg, "--sh-syntax") == 0)
796 bourne_shell_syntax = TRUE;
797 else if (strcmp (arg, "--binary-syntax") == 0)
798 binary_syntax = TRUE;
799 else if (strcmp (arg, "--version") == 0)
801 else if (strcmp (arg, "--exit-with-session") == 0)
802 exit_with_session = TRUE;
803 else if (strcmp (arg, "--close-stderr") == 0)
805 else if (strstr (arg, "--autolaunch=") == arg)
811 fprintf (stderr, "--autolaunch given twice\n");
817 s = strchr (arg, '=');
820 save_machine_uuid (s);
823 strcmp (prev_arg, "--autolaunch") == 0)
827 fprintf (stderr, "--autolaunch given twice\n");
833 save_machine_uuid (arg);
834 requires_arg = FALSE;
836 else if (strcmp (arg, "--autolaunch") == 0)
838 else if (strstr (arg, "--config-file=") == arg)
842 if (config_file != NULL)
844 fprintf (stderr, "--config-file given twice\n");
848 file = strchr (arg, '=');
851 config_file = xstrdup (file);
854 strcmp (prev_arg, "--config-file") == 0)
856 if (config_file != NULL)
858 fprintf (stderr, "--config-file given twice\n");
862 config_file = xstrdup (arg);
863 requires_arg = FALSE;
865 else if (strcmp (arg, "--config-file") == 0)
867 else if (arg[0] == '-')
869 if (strcmp (arg, "--") != 0)
871 fprintf (stderr, "Option `%s' is unknown.\n", arg);
877 remaining_args = i+2;
884 remaining_args = i+1;
894 fprintf (stderr, "Option `%s' requires an argument.\n", prev_arg);
898 if (auto_shell_syntax)
900 if ((shname = getenv ("SHELL")) != NULL)
902 if (!strncmp (shname + strlen (shname) - 3, "csh", 3))
903 c_shell_syntax = TRUE;
905 bourne_shell_syntax = TRUE;
908 bourne_shell_syntax = TRUE;
911 if (exit_with_session)
912 verbose ("--exit-with-session enabled\n");
916 #ifndef DBUS_BUILD_X11
917 fprintf (stderr, "Autolaunch requested, but X11 support not compiled in.\n"
918 "Cannot continue.\n");
925 if (get_machine_uuid () == NULL)
927 fprintf (stderr, "Machine UUID not provided as arg to --autolaunch\n");
931 verbose ("Autolaunch enabled (using X11).\n");
932 if (!exit_with_session)
934 verbose ("--exit-with-session automatically enabled\n");
935 exit_with_session = TRUE;
940 fprintf (stderr, "Autolaunch error: X11 initialization failed.\n");
944 if (!x11_get_address (&address, &pid, &wid))
946 fprintf (stderr, "Autolaunch error: X11 communication error.\n");
952 verbose ("dbus-daemon is already running. Returning existing parameters.\n");
953 pass_info (runprog, address, pid, wid, c_shell_syntax,
954 bourne_shell_syntax, binary_syntax, argc, argv, remaining_args);
958 else if (read_machine_uuid_if_needed())
965 if (pipe (bus_pid_to_launcher_pipe) < 0 ||
966 pipe (bus_address_to_launcher_pipe) < 0 ||
967 pipe (bus_pid_to_babysitter_pipe) < 0)
970 "Failed to create pipe: %s\n",
978 fprintf (stderr, "Failed to fork: %s\n",
986 #define MAX_FD_LEN 64
987 char write_pid_fd_as_string[MAX_FD_LEN];
988 char write_address_fd_as_string[MAX_FD_LEN];
990 #ifdef DBUS_BUILD_X11
997 verbose ("=== Babysitter's intermediate parent created\n");
999 /* Fork once more to create babysitter */
1004 fprintf (stderr, "Failed to fork: %s\n",
1012 verbose ("=== Babysitter's intermediate parent continues\n");
1014 close (bus_pid_to_launcher_pipe[READ_END]);
1015 close (bus_pid_to_launcher_pipe[WRITE_END]);
1016 close (bus_address_to_launcher_pipe[READ_END]);
1017 close (bus_address_to_launcher_pipe[WRITE_END]);
1018 close (bus_pid_to_babysitter_pipe[WRITE_END]);
1020 /* babysit() will fork *again*
1021 * and will also reap the pre-forked bus
1024 babysit (exit_with_session, ret,
1025 bus_pid_to_babysitter_pipe[READ_END]);
1029 verbose ("=== Bus exec process created\n");
1031 /* Now we are the bus process (well, almost;
1032 * dbus-daemon itself forks again)
1034 close (bus_pid_to_launcher_pipe[READ_END]);
1035 close (bus_address_to_launcher_pipe[READ_END]);
1036 close (bus_pid_to_babysitter_pipe[READ_END]);
1037 close (bus_pid_to_babysitter_pipe[WRITE_END]);
1039 sprintf (write_pid_fd_as_string,
1040 "%d", bus_pid_to_launcher_pipe[WRITE_END]);
1042 sprintf (write_address_fd_as_string,
1043 "%d", bus_address_to_launcher_pipe[WRITE_END]);
1045 verbose ("Calling exec()\n");
1047 #ifdef DBUS_BUILD_TESTS
1048 /* exec from testdir */
1049 if (getenv("DBUS_USE_TEST_BINARY") != NULL)
1051 execl (TEST_BUS_BINARY,
1054 "--print-pid", write_pid_fd_as_string,
1055 "--print-address", write_address_fd_as_string,
1056 config_file ? "--config-file" : "--session",
1057 config_file, /* has to be last in this varargs list */
1061 "Failed to execute test message bus daemon %s: %s. Will try again with the system path.\n",
1062 TEST_BUS_BINARY, strerror (errno));
1064 #endif /* DBUS_BUILD_TESTS */
1066 execl (DBUS_DAEMONDIR"/dbus-daemon",
1067 DBUS_DAEMONDIR"/dbus-daemon",
1069 "--print-pid", write_pid_fd_as_string,
1070 "--print-address", write_address_fd_as_string,
1071 config_file ? "--config-file" : "--session",
1072 config_file, /* has to be last in this varargs list */
1076 "Failed to execute message bus daemon %s: %s. Will try again without full path.\n",
1077 DBUS_DAEMONDIR"/dbus-daemon", strerror (errno));
1080 * If it failed, try running without full PATH. Note this is needed
1081 * because the build process builds the run-with-tmp-session-bus.conf
1082 * file and the dbus-daemon will not be in the install location during
1085 execlp ("dbus-daemon",
1088 "--print-pid", write_pid_fd_as_string,
1089 "--print-address", write_address_fd_as_string,
1090 config_file ? "--config-file" : "--session",
1091 config_file, /* has to be last in this varargs list */
1095 "Failed to execute message bus daemon: %s\n",
1102 #define MAX_PID_LEN 64
1104 char bus_address[MAX_ADDR_LEN];
1105 char buf[MAX_PID_LEN];
1111 verbose ("=== Parent dbus-launch continues\n");
1113 close (bus_pid_to_launcher_pipe[WRITE_END]);
1114 close (bus_address_to_launcher_pipe[WRITE_END]);
1115 close (bus_pid_to_babysitter_pipe[READ_END]);
1117 verbose ("Waiting for babysitter's intermediate parent\n");
1119 /* Immediately reap parent of babysitter
1120 * (which was created just for us to reap)
1122 if (do_waitpid (ret) < 0)
1124 fprintf (stderr, "Failed to waitpid() for babysitter intermediate process: %s\n",
1129 verbose ("Reading address from bus\n");
1131 /* Read the pipe data, print, and exit */
1132 switch (read_line (bus_address_to_launcher_pipe[READ_END],
1133 bus_address, MAX_ADDR_LEN))
1135 case READ_STATUS_OK:
1137 case READ_STATUS_EOF:
1138 fprintf (stderr, "EOF in dbus-launch reading address from bus daemon\n");
1141 case READ_STATUS_ERROR:
1142 fprintf (stderr, "Error in dbus-launch reading address from bus daemon: %s\n",
1148 close (bus_address_to_launcher_pipe[READ_END]);
1150 verbose ("Reading PID from daemon\n");
1152 switch (read_line (bus_pid_to_launcher_pipe[READ_END], buf, MAX_PID_LEN))
1154 case READ_STATUS_OK:
1156 case READ_STATUS_EOF:
1157 fprintf (stderr, "EOF reading PID from bus daemon\n");
1160 case READ_STATUS_ERROR:
1161 fprintf (stderr, "Error reading PID from bus daemon: %s\n",
1168 val = strtol (buf, &end, 0);
1169 if (buf == end || end == NULL)
1171 fprintf (stderr, "Failed to parse bus PID \"%s\": %s\n",
1172 buf, strerror (errno));
1178 close (bus_pid_to_launcher_pipe[READ_END]);
1180 #ifdef DBUS_BUILD_X11
1181 if (xdisplay != NULL)
1183 verbose("Saving x11 address\n");
1184 ret2 = x11_save_address (bus_address, bus_pid, &wid);
1185 /* Only get an existing dbus session when autolaunching */
1190 char *address = NULL;
1191 /* another window got added. Return its address */
1192 bus_pid_to_kill = bus_pid;
1193 if (x11_get_address (&address, &bus_pid, &wid)
1196 verbose ("dbus-daemon is already running. Returning existing parameters.\n");
1197 /* Kill the old bus */
1199 pass_info (runprog, address, bus_pid, wid,
1200 c_shell_syntax, bourne_shell_syntax, binary_syntax,
1201 argc, argv, remaining_args);
1206 fprintf (stderr, "Error saving bus information.\n");
1207 bus_pid_to_kill = bus_pid;
1208 kill_bus_and_exit (1);
1214 /* Forward the pid to the babysitter */
1215 write_pid (bus_pid_to_babysitter_pipe[WRITE_END], bus_pid);
1216 close (bus_pid_to_babysitter_pipe[WRITE_END]);
1218 pass_info (runprog, bus_address, bus_pid, wid, c_shell_syntax,
1219 bourne_shell_syntax, binary_syntax, argc, argv, remaining_args);