Reuse D-Bus sessions across login sessions

d-bussession

I access a machine through multiple login sessions. The sessions' lifetimes may or may not overlap. In my case, these login sessions are currently always over SSH, but I would prefer to handle local sessions too.

I sometimes need D-Bus in these sessions, and I want to share the same D-Bus session across these login sessions, in order to use GVFS.

What is the recommended way to do this? I don't want to break any use of D-Bus that I may not be aware of. I've considered using

export $(dbus-launch --autolaunch $(cat /var/lib/dbus/machine-id))

but (as of Ubuntu 12.04) this doesn't seem right:

  • this requires an X session, but my SSH sessions may or may not be forwarding an X display, and even the ones that are don't have the same $DISPLAY;
  • if no X display is available, dbus-launch complains that “Autolaunch error: X11 initialization failed.” and doesn't start a daemon;
  • the dbus-launch man page states that “The --autolaunch option is considered an internal implementation detail (…). There's no real reason to use it outside of the libdbus implementation anyhow.”

Does dbus-launch or another tool in the D-Bus suite support automatically detecting a running dbus-daemon and connecting to it? The necessary information is in ~/.dbus/session-bus/$(cat /var/lib/dbus/machine-id)-${DISPLAY#*:} if D-Bus is started with an X connection, but doesn't seem to be stored anywhere if no X connection is available.

Should I cobble my own D-Bus session file? If I do, should I use a file in the ~/.dbus/session-bus directory? Is the path /var/lib/dbus/machine-id reliable and portable?

Best Answer

DBus makes sharing the settings for the dbus daemon a little tricky.

For my setup, the settings from dbus-launch --sh-syntax are saved in a file that is source by the .bash_rc. The downside of this is that, after every reboot, that process is performed manually.

However, it should be very simple to check for an existing DBus daemon. Let's say the settings file is at $HOME/.dbus_settings:

need_start=1

if [ -r "$HOME/.dbus_settings" ]
then
    . "$HOME/.dbus_settings"
fi

if [ -n "$DBUS_SESSION_BUS_PID" ]
then
    if kill -0 "$DBUS_SESSION_BUS_PID" 2>/dev/null
    then
        need_start=0  # Found one
    fi
fi

if [ "$need_start" -ne 0 ]
then
    dbus-launch --sh-syntax >"$HOME/.dbus_settings"
    . "$HOME/.dbus_settings"
fi

Without the --autolaunch option, I don't believe an X windows connection is needed.

Related Question