Spaces:
Sleeping

File size: 1,517 Bytes
a0dea2a
 
8f04220
a0dea2a
b7fd10e
a0dea2a
 
b7fd10e
a0dea2a
 
f0aa03d
a0dea2a
 
 
b7fd10e
 
 
a0dea2a
 
b7fd10e
a0dea2a
 
 
 
 
8f04220
b7fd10e
 
 
8f04220
 
 
b7fd10e
 
a0dea2a
f0aa03d
 
8f04220
274d912
 
 
 
 
 
 
 
 
 
 
a0dea2a
 
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
#!/bin/sh
SERVER="https://mtsky-free-server-docker.hf.space"
LOCAL_CGI="${LOCAL_CGI:-http://192.168.1.1/cgi-bin/api}"
TMPDIR="/tmp/wstunnel"
UCLIENT="uclient-fetch -q -O - -T 10"

mkdir -p "$TMPDIR"
log() { logger -t wstunnel "$1"; }

fetch_poll() {
    $UCLIENT "$SERVER/poll" 2>&1
}

respond() {
    local rid="$1" status="$2" ct="$3" file="$4"
    uclient-fetch -q -O /dev/null -T 10 --post-file="$file" \
        "$SERVER/respond?rid=$rid&status=$status&content_type=$ct" 2>&1
}

cleanup() { rm -f "$TMPDIR"/*; log "stopped"; exit 0; }
trap cleanup INT TERM

log "starting wstunnel client"

while true; do
    resp=$(fetch_poll)
    rc=$?
    if [ "$rc" != "0" ] || [ -z "$resp" ] || [ "$resp" = "{}" ]; then
        [ "$rc" != "0" ] && log "poll rc=$rc"
        continue
    fi

    rid=$(echo "$resp" | sed -n 's/.*"rid":[ ]*"\([^"]*\)".*/\1/p')
    url_enc=$(echo "$resp" | sed -n 's/.*"url_encoded":[ ]*"\([^"]*\)".*/\1/p')

    if [ -n "$rid" ] && [ -n "$url_enc" ]; then
        local_url="${LOCAL_CGI}?url=${url_enc}"
        body_file="$TMPDIR/body-$rid"
        (
            $UCLIENT "$local_url" > "$body_file" 2>&1
            u_rc=$?
            if [ "$u_rc" = "0" ] && [ -s "$body_file" ]; then
                respond "$rid" "200" "text/html" "$body_file" >/dev/null 2>&1
            else
                echo "fetch failed rc=$u_rc" > "$body_file"
                respond "$rid" "502" "text/plain" "$body_file" >/dev/null 2>&1
            fi
            rm -f "$body_file"
        ) &
    fi
done