summaryrefslogtreecommitdiff
path: root/dot/local/bin/xvnc
blob: 3265a380d31eff9751d4cd948b38c572326b81e4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
#!/bin/bash
set -e
set -o pipefail

# x11vnc option '-noxrecord' added as workaround for crashing bug
# See https://github.com/LibVNC/x11vnc/issues/61
#
# The option is not be needed with latest x11vnc from source, but we don't rely
# on the remote side being up to date.

ssh()
{
    command ssh "$@" 2>&1 | sed 's/^/REMOTE> /'
}

direct_connection()
{
    port=$((5900 + ${local_display#*:}))
    ssh -o ControlPath=none -n \
        -L $port:localhost:$port \
        ${remote_port:+-p $remote_port} \
        "$remote_host" \
        "x11vnc -noxrecord -nopw -ncache -ncache_cr -localhost -display ${remote_display}" &
    pid=$!
    sleep 1 # surrender race
    if [ "$NOTIGER" ]
    then
        xtightvncviewer -encodings "copyrect tight zrle hextile" localhost:0
    else
        xtigervncviewer localhost:0
    fi
    kill $pid
}

atexit()
{
    [ "$DEBUG" ] || exec 2>/dev/null || true
    set +e
    set -- "$X11VNC" "$SSH"
    ps hu "$@"
    kill "$@"
    rm -rf "$OUR_TMP"
}

share_display()
{
    if [ "$DEBUG" ]
    then
        set -x
    fi

    port=5500
    OUR_TMP=$(mktemp -d) || exit
    local_socket_file=$OUR_TMP/x11vnc.socket
    ssh_control=$OUR_TMP/ssh.socket

    x11vnc -noxrecord -q -nopw -ncache -ncache_cr -display "${local_display}" -unixsock "$local_socket_file" -rfbport 0 &
    X11VNC=$!
    trap atexit EXIT

    rando=$(tr -dc A-Za-z0-9 < /dev/urandom | head -c15) && [ "$rando" ]
    remote_socket_file=/tmp/xtigervncviewer.$rando.socket

    ssh -n \
        -o ControlPath=none \
        -o ExitOnForwardFailure=yes \
        -R "$remote_socket_file:$local_socket_file" \
        ${remote_port:+ -p "$remote_port" } \
        "$remote_host" \
        "${DEBUG:+ set -x; } trap 'rm -f $remote_socket_file' EXIT; DISPLAY=$remote_display xtigervncviewer $remote_socket_file" &
    SSH=$!
    wait -n
}

if [ "$1" = -r ]
then
    shift
    cmd=share_display
elif [ "$1" = -d ]
then
    shift
    cmd=direct_connection
else
    cmd=direct_connection
fi

remote_host=${1:-blackboard}

case "$remote_host" in
    *:*) remote_port=${remote_host##*:}
         remote_host=${remote_host%:*}
         ;;
    *) remote_port=
       ;;
esac
remote_display=${2:-:0}
local_display=${3:-:0}

$cmd