Skip to content

Commit

Permalink
Implement a more robust remote connection detection (who)
Browse files Browse the repository at this point in the history
First, we switch from `who am i` to `who -m` because this is the POSIX
way and macOS supports it as well.

Second, if the above fails, we fall back to using just `who` and grep
the line that represents our TTY. This works e.g. with busybox systems.

Finally, we use (extremely) simplified regular expressions for detecting
IPv4, IPv6 and hostname. This is a best-effort attempt at detecting the
remote connections when SSH_CONNECTION is not set.
  • Loading branch information
mafredri committed May 6, 2018
1 parent 75aaf3b commit 1283d83
Showing 1 changed file with 18 additions and 2 deletions.
20 changes: 18 additions & 2 deletions pure.zsh
Original file line number Diff line number Diff line change
Expand Up @@ -484,10 +484,26 @@ prompt_pure_state_setup() {
if [[ -z $ssh_connection ]] && (( $+commands[who] )); then
# When changing user on a remote system, the $SSH_CONNECTION
# environment variable can be lost, attempt detection via who.
# Ignore local X sessions displayed as (:1).
if who am i | grep -v '(:[0-9]*)$' | grep -q '(.*)$' &>/dev/null; then
local who_out
who_out=$(who -m 2>/dev/null)
if (( $? )); then
# Who am I not supported, fallback to plain who.
who_out=$(who 2>/dev/null | grep ${TTY#/dev/})
fi

local reIPv6='([a-f0-9:]+:+)+[a-f0-9]+' # Simplified, but matches loopback as well (::1).
local reIPv4='([0-9]{1,3}\.){3}[0-9]+' # Simplified, allows invalid ranges.
# Here we assume two non-consecutive periods represents a
# hostname. This matches foo.bar.baz, but not foo.bar.
local reHostname='([.][^. ]+){2}'

# Usually the remote address is surrounded by parenthesis, but
# not on all systems (e.g. busybox).
local -H MATCH MBEGIN MEND
if [[ $who_out =~ "\(?($reIPv4|$reIPv6|$reHostname)\)?\$" ]]; then
ssh_connection=true
fi
unset MATCH MBEGIN MEND
fi

# show username@host if logged in through SSH
Expand Down

0 comments on commit 1283d83

Please sign in to comment.