Skip to content

Commit abcb115

Browse files
committedFeb 15, 2015
Export some env vars, proxy D-Bus session bus
Export all current env vars (except $HOME as that could contain /root), but it could possibly include $DISPLAY and $DBUS_SESSION_BUS_ADDRESS. DBUS_SESSION_BUS_ADDRESS is set to a named Unix socket address when an abstract socket is found. This ensures that the net namespace will also be able to connect to the D-Bus session bus.
1 parent 28ec640 commit abcb115

File tree

2 files changed

+54
-2
lines changed

2 files changed

+54
-2
lines changed
 

‎env.sh

+47
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
2+
# Tries to find the D-Bus session bus address, listening on a Unix domain socket
3+
# as needed.
4+
dbus_addr() {
5+
local user home x_display dbus_file abstract_path
6+
user=${SUDO_USER:-$(id -u)}
7+
8+
# Only start socat if not running as root.
9+
if [[ $user == root ]]; then
10+
return
11+
fi
12+
13+
# Find dbus session bus path
14+
home=$(getent passwd "$user" | cut -d: -f6)
15+
x_display=${DISPLAY:-:0}
16+
x_display=${x_display#*:}
17+
x_display=${x_display%.*}
18+
dbus_file="$home/.dbus/session-bus/$(cat /etc/machine-id)-${x_display}"
19+
20+
env_re='^DBUS_SESSION_BUS_ADDRESS=unix:abstract=\K/tmp/dbus-[a-zA-Z0-9]+'
21+
22+
abstract_path=
23+
if [ -z "${DBUS_SESSION_BUS_ADDRESS:-}" ] && [ -e "$dbus_file" ]; then
24+
abstract_path=$(grep -Po -m1 "$env_re" "$dbus_file") || :
25+
fi
26+
if [ -z "${abstract_path}" ]; then
27+
abstract_path=$(env | grep -Po -m1 "$env_re") || :
28+
fi
29+
30+
# Hurrah! Found a Unix domain socket!
31+
if [ -n "${abstract_path}" ]; then
32+
# If the dbus session bus address is found, try to listen on a named
33+
# Unix domain socket (if not already). This ensures that it is visible
34+
# in the net namespace.
35+
if ! [ -e "${abstract_path}" ]; then
36+
sudo -u "$user" \
37+
socat UNIX-LISTEN:$abstract_path,fork \
38+
ABSTRACT-CONNECT:$abstract_path >&2 &
39+
fi
40+
export DBUS_SESSION_BUS_ADDRESS=unix:path=$abstract_path
41+
fi
42+
}
43+
44+
# Only try to find the dbus session address when running outside the netns.
45+
# If inside the netns, the parent could be determined, and then a swap using
46+
# /proc/xxx/ns/net could be done, but that is ugly.
47+
[ -n "$(ip netns identify)" ] || dbus_addr

‎netns

+7-2
Original file line numberDiff line numberDiff line change
@@ -146,9 +146,14 @@ exec)
146146
if [ -n "${SUDO_USER:-}" ]; then
147147
# If no command is given, enter the shell
148148
[ $# -gt 0 ] || set -- -s
149-
# Change user back
150-
set -- sudo -u "$SUDO_USER" "$@"
149+
# Change user back, preserving environment (except HOME)
150+
set -- sudo -EH -u "$SUDO_USER" "$@"
151151
fi
152+
153+
# Set environment variables from a separate file (if existent)
154+
envfile=$(dirname "$0")/env.sh
155+
[ ! -e "$envfile" ] || . "$envfile"
156+
152157
exec nsenter --net=$ns_file "$@"
153158
;;
154159
*)

0 commit comments

Comments
 (0)