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");
466 FD_SET (tty_fd, &read_set);
467 FD_SET (tty_fd, &err_set);
472 FD_SET (x_fd, &read_set);
473 FD_SET (x_fd, &err_set);
476 select (MAX (tty_fd, x_fd) + 1,
477 &read_set, NULL, &err_set, NULL);
481 verbose ("Got SIGHUP, exiting\n");
482 kill_bus_and_exit (0);
485 #ifdef DBUS_BUILD_X11
486 /* Dump events on the floor, and let
487 * IO error handler run if we lose
491 verbose ("X fd condition reading = %d error = %d\n",
492 FD_ISSET (x_fd, &read_set),
493 FD_ISSET (x_fd, &err_set));
499 if (FD_ISSET (tty_fd, &read_set))
504 verbose ("TTY ready for reading\n");
506 bytes_read = read (tty_fd, discard, sizeof (discard));
508 verbose ("Read %d bytes from TTY errno = %d\n",
512 kill_bus_and_exit (0); /* EOF */
513 else if (bytes_read < 0 && errno != EINTR)
515 /* This shouldn't happen I don't think; to avoid
516 * spinning on the fd forever we exit.
518 fprintf (stderr, "dbus-launch: error reading from stdin: %s\n",
520 kill_bus_and_exit (0);
523 else if (FD_ISSET (tty_fd, &err_set))
525 verbose ("TTY has error condition\n");
527 kill_bus_and_exit (0);
534 babysit (int exit_with_session,
536 int read_bus_pid_fd) /* read pid from here */
542 verbose ("babysitting, exit_with_session = %d, child_pid = %ld, read_bus_pid_fd = %d\n",
543 exit_with_session, (long) child_pid, read_bus_pid_fd);
545 /* We chdir ("/") since we are persistent and daemon-like, and fork
546 * again so dbus-launch can reap the parent. However, we don't
547 * setsid() or close fd 0 because the idea is to remain attached
548 * to the tty and the X server in order to kill the message bus
549 * when the session ends.
554 fprintf (stderr, "Could not change to root directory: %s\n",
559 /* Close stdout/stderr so we don't block an "eval" or otherwise
560 * lock up. stdout is still chaining through to dbus-launch
561 * and in turn to the parent shell.
563 dev_null_fd = open ("/dev/null", O_RDWR);
564 if (dev_null_fd >= 0)
566 if (!exit_with_session)
567 dup2 (dev_null_fd, 0);
568 dup2 (dev_null_fd, 1);
569 s = getenv ("DBUS_DEBUG_OUTPUT");
570 if (s == NULL || *s == '\0')
571 dup2 (dev_null_fd, 2);
575 fprintf (stderr, "Failed to open /dev/null: %s\n",
577 /* continue, why not */
584 fprintf (stderr, "fork() failed in babysitter: %s\n",
591 /* Parent reaps pre-fork part of bus daemon, then exits and is
592 * reaped so the babysitter isn't a zombie
595 verbose ("=== Babysitter's intermediate parent continues again\n");
597 if (do_waitpid (child_pid) < 0)
599 /* shouldn't happen */
600 fprintf (stderr, "Failed waitpid() waiting for bus daemon's parent\n");
604 verbose ("Babysitter's intermediate parent exiting\n");
609 /* Child continues */
610 verbose ("=== Babysitter process created\n");
612 verbose ("Reading PID from bus\n");
614 switch (read_pid (read_bus_pid_fd, &bus_pid_to_kill))
618 case READ_STATUS_EOF:
619 fprintf (stderr, "EOF in dbus-launch reading PID from bus daemon\n");
622 case READ_STATUS_ERROR:
623 fprintf (stderr, "Error in dbus-launch reading PID from bus daemon: %s\n",
629 verbose ("Got PID %ld from daemon\n",
630 (long) bus_pid_to_kill);
632 if (exit_with_session)
634 /* Bus is now started and launcher has needed info;
635 * we connect to X display and tty and wait to
636 * kill bus if requested.
639 kill_bus_when_session_ends ();
642 verbose ("Babysitter exiting\n");
648 do_close_stderr (void)
654 /* dbus-launch is a Unix-only program, so we can rely on /dev/null being there.
655 * We're including unistd.h and we're dealing with sh/csh launch sequences...
657 fd = open ("/dev/null", O_RDWR);
660 fprintf (stderr, "Internal error: cannot open /dev/null: %s", strerror (errno));
665 if (dup2 (fd, 2) == -1)
667 /* error; we can't report an error anymore... */
674 pass_info (const char *runprog, const char *bus_address, pid_t bus_pid,
675 long bus_wid, int c_shell_syntax, int bourne_shell_syntax,
677 int argc, char **argv, int remaining_args)
685 envvar = malloc (strlen ("DBUS_SESSION_BUS_ADDRESS=") +
686 strlen (bus_address) + 1);
687 args = malloc (sizeof (char *) * ((argc-remaining_args)+2));
689 if (envvar == NULL || args == NULL)
692 args[0] = xstrdup (runprog);
695 for (i = 1; i <= (argc-remaining_args); i++)
697 size_t len = strlen (argv[remaining_args+i-1])+1;
698 args[i] = malloc (len);
701 strncpy (args[i], argv[remaining_args+i-1], len);
705 strcpy (envvar, "DBUS_SESSION_BUS_ADDRESS=");
706 strcat (envvar, bus_address);
709 execvp (runprog, args);
710 fprintf (stderr, "Couldn't exec %s: %s\n", runprog, strerror (errno));
715 print_variables (bus_address, bus_pid, bus_wid, c_shell_syntax,
716 bourne_shell_syntax, binary_syntax);
718 verbose ("dbus-launch exiting\n");
726 fprintf (stderr, "Out of memory!");
734 main (int argc, char **argv)
736 const char *prev_arg;
738 const char *runprog = NULL;
739 int remaining_args = 0;
740 int exit_with_session;
741 int binary_syntax = FALSE;
742 int c_shell_syntax = FALSE;
743 int bourne_shell_syntax = FALSE;
744 int auto_shell_syntax = FALSE;
745 int autolaunch = FALSE;
746 int requires_arg = FALSE;
747 int close_stderr = FALSE;
750 int bus_pid_to_launcher_pipe[2];
751 int bus_pid_to_babysitter_pipe[2];
752 int bus_address_to_launcher_pipe[2];
755 exit_with_session = FALSE;
762 const char *arg = argv[i];
764 if (strcmp (arg, "--help") == 0 ||
765 strcmp (arg, "-h") == 0 ||
766 strcmp (arg, "-?") == 0)
768 else if (strcmp (arg, "--auto-syntax") == 0)
769 auto_shell_syntax = TRUE;
770 else if (strcmp (arg, "-c") == 0 ||
771 strcmp (arg, "--csh-syntax") == 0)
772 c_shell_syntax = TRUE;
773 else if (strcmp (arg, "-s") == 0 ||
774 strcmp (arg, "--sh-syntax") == 0)
775 bourne_shell_syntax = TRUE;
776 else if (strcmp (arg, "--binary-syntax") == 0)
777 binary_syntax = TRUE;
778 else if (strcmp (arg, "--version") == 0)
780 else if (strcmp (arg, "--exit-with-session") == 0)
781 exit_with_session = TRUE;
782 else if (strcmp (arg, "--close-stderr") == 0)
784 else if (strstr (arg, "--autolaunch=") == arg)
790 fprintf (stderr, "--autolaunch given twice\n");
796 s = strchr (arg, '=');
799 save_machine_uuid (s);
802 strcmp (prev_arg, "--autolaunch") == 0)
806 fprintf (stderr, "--autolaunch given twice\n");
812 save_machine_uuid (arg);
813 requires_arg = FALSE;
815 else if (strcmp (arg, "--autolaunch") == 0)
817 else if (strstr (arg, "--config-file=") == arg)
821 if (config_file != NULL)
823 fprintf (stderr, "--config-file given twice\n");
827 file = strchr (arg, '=');
830 config_file = xstrdup (file);
833 strcmp (prev_arg, "--config-file") == 0)
835 if (config_file != NULL)
837 fprintf (stderr, "--config-file given twice\n");
841 config_file = xstrdup (arg);
842 requires_arg = FALSE;
844 else if (strcmp (arg, "--config-file") == 0)
846 else if (arg[0] == '-')
848 if (strcmp (arg, "--") != 0)
850 fprintf (stderr, "Option `%s' is unknown.\n", arg);
856 remaining_args = i+2;
863 remaining_args = i+1;
873 fprintf (stderr, "Option `%s' requires an argument.\n", prev_arg);
877 if (auto_shell_syntax)
879 if ((shname = getenv ("SHELL")) != NULL)
881 if (!strncmp (shname + strlen (shname) - 3, "csh", 3))
882 c_shell_syntax = TRUE;
884 bourne_shell_syntax = TRUE;
887 bourne_shell_syntax = TRUE;
890 if (exit_with_session)
891 verbose ("--exit-with-session enabled\n");
895 #ifndef DBUS_BUILD_X11
896 fprintf (stderr, "Autolaunch requested, but X11 support not compiled in.\n"
897 "Cannot continue.\n");
904 if (get_machine_uuid () == NULL)
906 fprintf (stderr, "Machine UUID not provided as arg to --autolaunch\n");
910 verbose ("Autolaunch enabled (using X11).\n");
911 if (!exit_with_session)
913 verbose ("--exit-with-session automatically enabled\n");
914 exit_with_session = TRUE;
919 fprintf (stderr, "Autolaunch error: X11 initialization failed.\n");
923 if (!x11_get_address (&address, &pid, &wid))
925 fprintf (stderr, "Autolaunch error: X11 communication error.\n");
931 verbose ("dbus-daemon is already running. Returning existing parameters.\n");
932 pass_info (runprog, address, pid, wid, c_shell_syntax,
933 bourne_shell_syntax, binary_syntax, argc, argv, remaining_args);
937 else if (read_machine_uuid_if_needed())
944 if (pipe (bus_pid_to_launcher_pipe) < 0 ||
945 pipe (bus_address_to_launcher_pipe) < 0 ||
946 pipe (bus_pid_to_babysitter_pipe) < 0)
949 "Failed to create pipe: %s\n",
957 fprintf (stderr, "Failed to fork: %s\n",
965 #define MAX_FD_LEN 64
966 char write_pid_fd_as_string[MAX_FD_LEN];
967 char write_address_fd_as_string[MAX_FD_LEN];
972 verbose ("=== Babysitter's intermediate parent created\n");
974 /* Fork once more to create babysitter */
979 fprintf (stderr, "Failed to fork: %s\n",
987 verbose ("=== Babysitter's intermediate parent continues\n");
989 close (bus_pid_to_launcher_pipe[READ_END]);
990 close (bus_pid_to_launcher_pipe[WRITE_END]);
991 close (bus_address_to_launcher_pipe[READ_END]);
992 close (bus_address_to_launcher_pipe[WRITE_END]);
993 close (bus_pid_to_babysitter_pipe[WRITE_END]);
995 /* babysit() will fork *again*
996 * and will also reap the pre-forked bus
999 babysit (exit_with_session, ret,
1000 bus_pid_to_babysitter_pipe[READ_END]);
1004 verbose ("=== Bus exec process created\n");
1006 /* Now we are the bus process (well, almost;
1007 * dbus-daemon itself forks again)
1009 close (bus_pid_to_launcher_pipe[READ_END]);
1010 close (bus_address_to_launcher_pipe[READ_END]);
1011 close (bus_pid_to_babysitter_pipe[READ_END]);
1012 close (bus_pid_to_babysitter_pipe[WRITE_END]);
1014 sprintf (write_pid_fd_as_string,
1015 "%d", bus_pid_to_launcher_pipe[WRITE_END]);
1017 sprintf (write_address_fd_as_string,
1018 "%d", bus_address_to_launcher_pipe[WRITE_END]);
1020 verbose ("Calling exec()\n");
1022 #ifdef DBUS_BUILD_TESTS
1023 /* exec from testdir */
1024 if (getenv("DBUS_USE_TEST_BINARY") != NULL)
1026 execl (TEST_BUS_BINARY,
1029 "--print-pid", write_pid_fd_as_string,
1030 "--print-address", write_address_fd_as_string,
1031 config_file ? "--config-file" : "--session",
1032 config_file, /* has to be last in this varargs list */
1036 "Failed to execute test message bus daemon %s: %s. Will try again with the system path.\n",
1037 TEST_BUS_BINARY, strerror (errno));
1039 #endif /* DBUS_BUILD_TESTS */
1041 execl (DBUS_DAEMONDIR"/dbus-daemon",
1042 DBUS_DAEMONDIR"/dbus-daemon",
1044 "--print-pid", write_pid_fd_as_string,
1045 "--print-address", write_address_fd_as_string,
1046 config_file ? "--config-file" : "--session",
1047 config_file, /* has to be last in this varargs list */
1051 "Failed to execute message bus daemon %s: %s. Will try again without full path.\n",
1052 DBUS_DAEMONDIR"/dbus-daemon", strerror (errno));
1055 * If it failed, try running without full PATH. Note this is needed
1056 * because the build process builds the run-with-tmp-session-bus.conf
1057 * file and the dbus-daemon will not be in the install location during
1060 execlp ("dbus-daemon",
1063 "--print-pid", write_pid_fd_as_string,
1064 "--print-address", write_address_fd_as_string,
1065 config_file ? "--config-file" : "--session",
1066 config_file, /* has to be last in this varargs list */
1070 "Failed to execute message bus daemon: %s\n",
1077 #define MAX_PID_LEN 64
1079 char bus_address[MAX_ADDR_LEN];
1080 char buf[MAX_PID_LEN];
1086 verbose ("=== Parent dbus-launch continues\n");
1088 close (bus_pid_to_launcher_pipe[WRITE_END]);
1089 close (bus_address_to_launcher_pipe[WRITE_END]);
1090 close (bus_pid_to_babysitter_pipe[READ_END]);
1092 verbose ("Waiting for babysitter's intermediate parent\n");
1094 /* Immediately reap parent of babysitter
1095 * (which was created just for us to reap)
1097 if (do_waitpid (ret) < 0)
1099 fprintf (stderr, "Failed to waitpid() for babysitter intermediate process: %s\n",
1104 verbose ("Reading address from bus\n");
1106 /* Read the pipe data, print, and exit */
1107 switch (read_line (bus_address_to_launcher_pipe[READ_END],
1108 bus_address, MAX_ADDR_LEN))
1110 case READ_STATUS_OK:
1112 case READ_STATUS_EOF:
1113 fprintf (stderr, "EOF in dbus-launch reading address from bus daemon\n");
1116 case READ_STATUS_ERROR:
1117 fprintf (stderr, "Error in dbus-launch reading address from bus daemon: %s\n",
1123 close (bus_address_to_launcher_pipe[READ_END]);
1125 verbose ("Reading PID from daemon\n");
1127 switch (read_line (bus_pid_to_launcher_pipe[READ_END], buf, MAX_PID_LEN))
1129 case READ_STATUS_OK:
1131 case READ_STATUS_EOF:
1132 fprintf (stderr, "EOF reading PID from bus daemon\n");
1135 case READ_STATUS_ERROR:
1136 fprintf (stderr, "Error reading PID from bus daemon: %s\n",
1143 val = strtol (buf, &end, 0);
1144 if (buf == end || end == NULL)
1146 fprintf (stderr, "Failed to parse bus PID \"%s\": %s\n",
1147 buf, strerror (errno));
1153 close (bus_pid_to_launcher_pipe[READ_END]);
1155 #ifdef DBUS_BUILD_X11
1156 if (xdisplay != NULL)
1158 verbose("Saving x11 address\n");
1159 ret2 = x11_save_address (bus_address, bus_pid, &wid);
1160 /* Only get an existing dbus session when autolaunching */
1165 char *address = NULL;
1166 /* another window got added. Return its address */
1167 bus_pid_to_kill = bus_pid;
1168 if (x11_get_address (&address, &bus_pid, &wid)
1171 verbose ("dbus-daemon is already running. Returning existing parameters.\n");
1172 /* Kill the old bus */
1174 pass_info (runprog, address, bus_pid, wid,
1175 c_shell_syntax, bourne_shell_syntax, binary_syntax,
1176 argc, argv, remaining_args);
1181 fprintf (stderr, "Error saving bus information.\n");
1182 bus_pid_to_kill = bus_pid;
1183 kill_bus_and_exit (1);
1189 /* Forward the pid to the babysitter */
1190 write_pid (bus_pid_to_babysitter_pipe[WRITE_END], bus_pid);
1191 close (bus_pid_to_babysitter_pipe[WRITE_END]);
1193 pass_info (runprog, bus_address, bus_pid, wid, c_shell_syntax,
1194 bourne_shell_syntax, binary_syntax, argc, argv, remaining_args);