1 /* -*- mode: C; c-file-style: "gnu" -*- */
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 if (bourne_shell_syntax)
334 printf ("export DBUS_SESSION_BUS_ADDRESS;\n");
335 printf ("DBUS_SESSION_BUS_PID=%ld;\n", (long) bus_pid);
337 printf ("DBUS_SESSION_BUS_WINDOWID=%ld;\n", (long) bus_wid);
342 printf ("DBUS_SESSION_BUS_ADDRESS=%s\n", bus_address);
343 printf ("DBUS_SESSION_BUS_PID=%ld\n", (long) bus_pid);
345 printf ("DBUS_SESSION_BUS_WINDOWID=%ld\n", (long) bus_wid);
350 static int got_sighup = FALSE;
353 signal_handler (int sig)
365 kill_bus_when_session_ends (void)
371 struct sigaction act;
374 /* install SIGHUP handler */
376 sigemptyset (&empty_mask);
377 act.sa_handler = signal_handler;
378 act.sa_mask = empty_mask;
380 sigaction (SIGHUP, &act, NULL);
381 sigaction (SIGTERM, &act, NULL);
383 #ifdef DBUS_BUILD_X11
385 if (xdisplay != NULL)
387 x_fd = ConnectionNumber (xdisplay);
401 verbose ("stdin isatty(), monitoring it\n");
403 verbose ("stdin was not a TTY, not monitoring it\n");
405 if (tty_fd < 0 && x_fd < 0)
407 fprintf (stderr, "No terminal on standard input and no X display; cannot attach message bus to session lifetime\n");
418 FD_SET (tty_fd, &read_set);
419 FD_SET (tty_fd, &err_set);
424 FD_SET (x_fd, &read_set);
425 FD_SET (x_fd, &err_set);
428 select (MAX (tty_fd, x_fd) + 1,
429 &read_set, NULL, &err_set, NULL);
433 verbose ("Got SIGHUP, exiting\n");
434 kill_bus_and_exit (0);
437 #ifdef DBUS_BUILD_X11
438 /* Dump events on the floor, and let
439 * IO error handler run if we lose
443 verbose ("X fd condition reading = %d error = %d\n",
444 FD_ISSET (x_fd, &read_set),
445 FD_ISSET (x_fd, &err_set));
451 if (FD_ISSET (tty_fd, &read_set))
456 verbose ("TTY ready for reading\n");
458 bytes_read = read (tty_fd, discard, sizeof (discard));
460 verbose ("Read %d bytes from TTY errno = %d\n",
464 kill_bus_and_exit (0); /* EOF */
465 else if (bytes_read < 0 && errno != EINTR)
467 /* This shouldn't happen I don't think; to avoid
468 * spinning on the fd forever we exit.
470 fprintf (stderr, "dbus-launch: error reading from stdin: %s\n",
472 kill_bus_and_exit (0);
475 else if (FD_ISSET (tty_fd, &err_set))
477 verbose ("TTY has error condition\n");
479 kill_bus_and_exit (0);
486 babysit (int exit_with_session,
488 int read_bus_pid_fd) /* read pid from here */
494 verbose ("babysitting, exit_with_session = %d, child_pid = %ld, read_bus_pid_fd = %d\n",
495 exit_with_session, (long) child_pid, read_bus_pid_fd);
497 /* We chdir ("/") since we are persistent and daemon-like, and fork
498 * again so dbus-launch can reap the parent. However, we don't
499 * setsid() or close fd 0 because the idea is to remain attached
500 * to the tty and the X server in order to kill the message bus
501 * when the session ends.
506 fprintf (stderr, "Could not change to root directory: %s\n",
511 /* Close stdout/stderr so we don't block an "eval" or otherwise
512 * lock up. stdout is still chaining through to dbus-launch
513 * and in turn to the parent shell.
515 dev_null_fd = open ("/dev/null", O_RDWR);
516 if (dev_null_fd >= 0)
518 if (!exit_with_session)
519 dup2 (dev_null_fd, 0);
520 dup2 (dev_null_fd, 1);
521 s = getenv ("DBUS_DEBUG_OUTPUT");
522 if (s == NULL || *s == '\0')
523 dup2 (dev_null_fd, 2);
527 fprintf (stderr, "Failed to open /dev/null: %s\n",
529 /* continue, why not */
536 fprintf (stderr, "fork() failed in babysitter: %s\n",
543 /* Parent reaps pre-fork part of bus daemon, then exits and is
544 * reaped so the babysitter isn't a zombie
547 verbose ("=== Babysitter's intermediate parent continues again\n");
549 if (do_waitpid (child_pid) < 0)
551 /* shouldn't happen */
552 fprintf (stderr, "Failed waitpid() waiting for bus daemon's parent\n");
556 verbose ("Babysitter's intermediate parent exiting\n");
561 /* Child continues */
562 verbose ("=== Babysitter process created\n");
564 verbose ("Reading PID from bus\n");
566 switch (read_pid (read_bus_pid_fd, &bus_pid_to_kill))
570 case READ_STATUS_EOF:
571 fprintf (stderr, "EOF in dbus-launch reading PID from bus daemon\n");
574 case READ_STATUS_ERROR:
575 fprintf (stderr, "Error in dbus-launch reading PID from bus daemon: %s\n",
581 verbose ("Got PID %ld from daemon\n",
582 (long) bus_pid_to_kill);
584 if (exit_with_session)
586 /* Bus is now started and launcher has needed info;
587 * we connect to X display and tty and wait to
588 * kill bus if requested.
591 kill_bus_when_session_ends ();
594 verbose ("Babysitter exiting\n");
599 static void do_close_stderr (void)
603 /* dbus-launch is a Unix-only program, so we can rely on /dev/null being there.
604 * We're including unistd.h and we're dealing with sh/csh launch sequences...
606 int fd = open ("/dev/null", O_RDWR);
609 fprintf (stderr, "Internal error: cannot open /dev/null: %s", strerror (errno));
614 if (dup2 (fd, 2) == -1)
615 // error; we can't report an error anymore...
624 main (int argc, char **argv)
626 const char *prev_arg;
628 const char *runprog = NULL;
629 int remaining_args = 0;
630 int exit_with_session;
631 int binary_syntax = FALSE;
632 int c_shell_syntax = FALSE;
633 int bourne_shell_syntax = FALSE;
634 int auto_shell_syntax = FALSE;
635 int autolaunch = FALSE;
636 int requires_arg = FALSE;
637 int close_stderr = FALSE;
640 int bus_pid_to_launcher_pipe[2];
641 int bus_pid_to_babysitter_pipe[2];
642 int bus_address_to_launcher_pipe[2];
645 exit_with_session = FALSE;
652 const char *arg = argv[i];
654 if (strcmp (arg, "--help") == 0 ||
655 strcmp (arg, "-h") == 0 ||
656 strcmp (arg, "-?") == 0)
658 else if (strcmp (arg, "--auto-syntax") == 0)
659 auto_shell_syntax = TRUE;
660 else if (strcmp (arg, "-c") == 0 ||
661 strcmp (arg, "--csh-syntax") == 0)
662 c_shell_syntax = TRUE;
663 else if (strcmp (arg, "-s") == 0 ||
664 strcmp (arg, "--sh-syntax") == 0)
665 bourne_shell_syntax = TRUE;
666 else if (strcmp (arg, "--binary-syntax") == 0)
667 binary_syntax = TRUE;
668 else if (strcmp (arg, "--version") == 0)
670 else if (strcmp (arg, "--exit-with-session") == 0)
671 exit_with_session = TRUE;
672 else if (strcmp (arg, "--close-stderr") == 0)
674 else if (strstr (arg, "--autolaunch=") == arg)
680 fprintf (stderr, "--autolaunch given twice\n");
686 s = strchr (arg, '=');
689 save_machine_uuid (s);
692 strcmp (prev_arg, "--autolaunch") == 0)
696 fprintf (stderr, "--autolaunch given twice\n");
702 save_machine_uuid (arg);
703 requires_arg = FALSE;
705 else if (strcmp (arg, "--autolaunch") == 0)
707 else if (strstr (arg, "--config-file=") == arg)
711 if (config_file != NULL)
713 fprintf (stderr, "--config-file given twice\n");
717 file = strchr (arg, '=');
720 config_file = xstrdup (file);
723 strcmp (prev_arg, "--config-file") == 0)
725 if (config_file != NULL)
727 fprintf (stderr, "--config-file given twice\n");
731 config_file = xstrdup (arg);
732 requires_arg = FALSE;
734 else if (strcmp (arg, "--config-file") == 0)
736 else if (arg[0] == '-')
738 if (strcmp (arg, "--") != 0)
740 fprintf (stderr, "Option `%s' is unknown.\n", arg);
746 remaining_args = i+2;
753 remaining_args = i+1;
763 fprintf (stderr, "Option `%s' requires an argument.\n", prev_arg);
767 if (auto_shell_syntax)
769 if ((shname = getenv ("SHELL")) != NULL)
771 if (!strncmp (shname + strlen (shname) - 3, "csh", 3))
772 c_shell_syntax = TRUE;
774 bourne_shell_syntax = TRUE;
777 bourne_shell_syntax = TRUE;
780 if (exit_with_session)
781 verbose ("--exit-with-session enabled\n");
785 #ifndef DBUS_BUILD_X11
786 fprintf (stderr, "Autolaunch requested, but X11 support not compiled in.\n"
787 "Cannot continue.\n");
794 if (get_machine_uuid () == NULL)
796 fprintf (stderr, "Machine UUID not provided as arg to --autolaunch\n");
800 /* FIXME right now autolaunch always does print_variables(), but it should really
801 * exec the child program instead if a child program was specified. For now
802 * we just exit if this conflict arises.
806 fprintf (stderr, "Currently --autolaunch does not support running a program\n");
810 verbose ("Autolaunch enabled (using X11).\n");
811 if (!exit_with_session)
813 verbose ("--exit-with-session automatically enabled\n");
814 exit_with_session = TRUE;
819 fprintf (stderr, "Autolaunch error: X11 initialization failed.\n");
823 if (!x11_get_address (&address, &pid, &wid))
825 fprintf (stderr, "Autolaunch error: X11 communication error.\n");
831 verbose ("dbus-daemon is already running. Returning existing parameters.\n");
832 print_variables (address, pid, wid, c_shell_syntax,
833 bourne_shell_syntax, binary_syntax);
839 if (pipe (bus_pid_to_launcher_pipe) < 0 ||
840 pipe (bus_address_to_launcher_pipe) < 0 ||
841 pipe (bus_pid_to_babysitter_pipe) < 0)
844 "Failed to create pipe: %s\n",
852 fprintf (stderr, "Failed to fork: %s\n",
860 #define MAX_FD_LEN 64
861 char write_pid_fd_as_string[MAX_FD_LEN];
862 char write_address_fd_as_string[MAX_FD_LEN];
867 verbose ("=== Babysitter's intermediate parent created\n");
869 /* Fork once more to create babysitter */
874 fprintf (stderr, "Failed to fork: %s\n",
882 verbose ("=== Babysitter's intermediate parent continues\n");
884 close (bus_pid_to_launcher_pipe[READ_END]);
885 close (bus_pid_to_launcher_pipe[WRITE_END]);
886 close (bus_address_to_launcher_pipe[READ_END]);
887 close (bus_address_to_launcher_pipe[WRITE_END]);
888 close (bus_pid_to_babysitter_pipe[WRITE_END]);
890 /* babysit() will fork *again*
891 * and will also reap the pre-forked bus
894 babysit (exit_with_session, ret,
895 bus_pid_to_babysitter_pipe[READ_END]);
899 verbose ("=== Bus exec process created\n");
901 /* Now we are the bus process (well, almost;
902 * dbus-daemon itself forks again)
904 close (bus_pid_to_launcher_pipe[READ_END]);
905 close (bus_address_to_launcher_pipe[READ_END]);
906 close (bus_pid_to_babysitter_pipe[READ_END]);
907 close (bus_pid_to_babysitter_pipe[WRITE_END]);
909 sprintf (write_pid_fd_as_string,
910 "%d", bus_pid_to_launcher_pipe[WRITE_END]);
912 sprintf (write_address_fd_as_string,
913 "%d", bus_address_to_launcher_pipe[WRITE_END]);
915 verbose ("Calling exec()\n");
917 #ifdef DBUS_BUILD_TESTS
918 /* exec from testdir */
919 if (getenv("DBUS_USE_TEST_BINARY") != NULL)
921 execl (TEST_BUS_BINARY,
924 "--print-pid", write_pid_fd_as_string,
925 "--print-address", write_address_fd_as_string,
926 config_file ? "--config-file" : "--session",
927 config_file, /* has to be last in this varargs list */
931 "Failed to execute test message bus daemon %s: %s. Will try again with the system path.\n",
932 TEST_BUS_BINARY, strerror (errno));
934 #endif /* DBUS_BUILD_TESTS */
936 execl (DBUS_DAEMONDIR"/dbus-daemon",
937 DBUS_DAEMONDIR"/dbus-daemon",
939 "--print-pid", write_pid_fd_as_string,
940 "--print-address", write_address_fd_as_string,
941 config_file ? "--config-file" : "--session",
942 config_file, /* has to be last in this varargs list */
946 "Failed to execute message bus daemon %s: %s. Will try again without full path.\n",
947 DBUS_DAEMONDIR"/dbus-daemon", strerror (errno));
950 * If it failed, try running without full PATH. Note this is needed
951 * because the build process builds the run-with-tmp-session-bus.conf
952 * file and the dbus-daemon will not be in the install location during
955 execlp ("dbus-daemon",
958 "--print-pid", write_pid_fd_as_string,
959 "--print-address", write_address_fd_as_string,
960 config_file ? "--config-file" : "--session",
961 config_file, /* has to be last in this varargs list */
965 "Failed to execute message bus daemon: %s\n",
972 #define MAX_PID_LEN 64
974 char bus_address[MAX_ADDR_LEN];
975 char buf[MAX_PID_LEN];
981 verbose ("=== Parent dbus-launch continues\n");
983 close (bus_pid_to_launcher_pipe[WRITE_END]);
984 close (bus_address_to_launcher_pipe[WRITE_END]);
985 close (bus_pid_to_babysitter_pipe[READ_END]);
987 verbose ("Waiting for babysitter's intermediate parent\n");
989 /* Immediately reap parent of babysitter
990 * (which was created just for us to reap)
992 if (do_waitpid (ret) < 0)
994 fprintf (stderr, "Failed to waitpid() for babysitter intermediate process: %s\n",
999 verbose ("Reading address from bus\n");
1001 /* Read the pipe data, print, and exit */
1002 switch (read_line (bus_address_to_launcher_pipe[READ_END],
1003 bus_address, MAX_ADDR_LEN))
1005 case READ_STATUS_OK:
1007 case READ_STATUS_EOF:
1008 fprintf (stderr, "EOF in dbus-launch reading address from bus daemon\n");
1011 case READ_STATUS_ERROR:
1012 fprintf (stderr, "Error in dbus-launch reading address from bus daemon: %s\n",
1018 close (bus_address_to_launcher_pipe[READ_END]);
1020 verbose ("Reading PID from daemon\n");
1022 switch (read_line (bus_pid_to_launcher_pipe[READ_END], buf, MAX_PID_LEN))
1024 case READ_STATUS_OK:
1026 case READ_STATUS_EOF:
1027 fprintf (stderr, "EOF reading PID from bus daemon\n");
1030 case READ_STATUS_ERROR:
1031 fprintf (stderr, "Error reading PID from bus daemon: %s\n",
1038 val = strtol (buf, &end, 0);
1039 if (buf == end || end == NULL)
1041 fprintf (stderr, "Failed to parse bus PID \"%s\": %s\n",
1042 buf, strerror (errno));
1048 close (bus_pid_to_launcher_pipe[READ_END]);
1050 #ifdef DBUS_BUILD_X11
1051 /* FIXME the runprog == NULL is broken - we need to launch the runprog with the existing bus,
1052 * instead of just doing print_variables() if there's an existing bus.
1054 if (xdisplay != NULL && runprog == NULL)
1056 ret2 = x11_save_address (bus_address, bus_pid, &wid);
1059 /* another window got added. Return its address */
1064 if (x11_get_address (&address, &pid, &wid) && address != NULL)
1066 verbose ("dbus-daemon is already running. Returning existing parameters.\n");
1067 print_variables (address, pid, wid, c_shell_syntax,
1068 bourne_shell_syntax, binary_syntax);
1071 bus_pid_to_kill = bus_pid;
1072 kill_bus_and_exit (0);
1075 /* if failed, fall through */
1079 fprintf (stderr, "Error saving bus information.\n");
1080 bus_pid_to_kill = bus_pid;
1081 kill_bus_and_exit (1);
1086 /* Forward the pid to the babysitter */
1087 write_pid (bus_pid_to_babysitter_pipe[WRITE_END], bus_pid);
1088 close (bus_pid_to_babysitter_pipe[WRITE_END]);
1095 envvar = malloc (strlen ("DBUS_SESSION_BUS_ADDRESS=") + strlen (bus_address) + 1);
1096 args = malloc (sizeof (char *) * ((argc-remaining_args)+2));
1098 if (envvar == NULL || args == NULL)
1101 args[0] = xstrdup (runprog);
1104 for (i = 1; i <= (argc-remaining_args); i++)
1106 size_t len = strlen (argv[remaining_args+i-1])+1;
1107 args[i] = malloc (len);
1110 strncpy (args[i], argv[remaining_args+i-1], len);
1114 strcpy (envvar, "DBUS_SESSION_BUS_ADDRESS=");
1115 strcat (envvar, bus_address);
1118 execvp (runprog, args);
1119 fprintf (stderr, "Couldn't exec %s: %s\n", runprog, strerror (errno));
1124 print_variables (bus_address, bus_pid, wid, c_shell_syntax,
1125 bourne_shell_syntax, binary_syntax);
1128 verbose ("dbus-launch exiting\n");
1140 fprintf (stderr, "Out of memory!");