Spaces:
Sleeping
Sleeping
switch to HTTP long-polling, add router ash script
Browse filesFiles changed (2)
- app.py+43-62
- tunnel_client.shAdded+67
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909113 unmodified lines105106107108109110111112113114115116import aiohttpimport asyncioimport jsonimport osimport sysimport uuidfrom aiohttp import web, WSMsgTypePORT = int(os.environ.get("PORT", 7860))TARGET_ORIGIN = "https://shabakaty.com"clients = {}pending = {}async def ws_handler(request):ws = web.WebSocketResponse(max_msg_size=0)await ws.prepare(request)client_id = id(ws)clients[client_id] = wssys.stderr.write(f"WS client {client_id} connected\n")sys.stderr.flush()try:async for msg in ws:if msg.type == WSMsgType.TEXT:try:data = json.loads(msg.data)if data.get("type") == "response":rid = data.get("rid")if rid and rid in pending:pending[rid]["result"].update(data)pending[rid]["event"].set()except json.JSONDecodeError:passelif msg.type == WSMsgType.ERROR:sys.stderr.write(f"WS error: {ws.exception()}\n")sys.stderr.flush()except asyncio.CancelledError:passfinally:clients.pop(client_id, None)sys.stderr.write(f"WS client {client_id} disconnected\n")sys.stderr.flush()return wsasync def proxy_handler(request):target_url = request.query.get("url")if not target_url:return web.json_response({"error": "missing url param"}, status=400)if not target_url.startswith(("http://", "https://")):target_url = TARGET_ORIGIN.rstrip("/") + "/" + target_url.lstrip("/")if not clients:return web.json_response({"error": "no router connected"}, status=503)rid = str(uuid.uuid4())event = asyncio.Event()result = {}pending[rid] = {"event": event, "result": result}try:ws = next(iter(clients.values()))payload = json.dumps({"type": "request", "rid": rid, "url": target_url})await ws.send_str(payload)try:await asyncio.wait_for(event.wait(), timeout=30)except asyncio.TimeoutError:return web.json_response({"error": "timeout"}, status=504)status = result.get("status", 502)if status != 200:return web.json_response({"error": result.get("body", "upstream error")}, status=status)body = result.get("body", "")ct = result.get("content_type", "text/html")return web.Response(body=body, content_type=ct)finally:pending.pop(rid, None)async def health(request):return web.json_response({"status": "ok", "clients": len(clients), "port": PORT})async def ping_router(request):if not clients:return web.json_response({"error": "no router connected"}, status=503)ws = next(iter(clients.values()))await ws.send_str(json.dumps({"type": "ping"}))return web.json_response({"status": "pong_sent"})async def root(request):return web.json_response({"status": "ok","service": "WebSocket Tunnel Server","clients": len(clients),"port": PORT})13 unmodified linesapp = web.Application(middlewares=[cors_middleware])app.router.add_get("/", root)app.router.add_get("/health", health)app.router.add_get("/ws", ws_handler)app.router.add_get("/cgi-bin/api", proxy_handler)app.router.add_get("/api", proxy_handler)app.router.add_get("/ping", ping_router)if __name__ == "__main__":sys.stderr.write(f"Starting tunnel server on 0.0.0.0:{PORT}\n")sys.stderr.flush()web.run_app(app, host="0.0.0.0", port=PORT, print=lambda *a: None)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707113 unmodified lines85868788899091929394959697import asyncioimport jsonimport osimport sysimport uuidfrom aiohttp import webPORT = int(os.environ.get("PORT", 7860))TARGET_ORIGIN = "https://shabakaty.com"pending = {}async def proxy_handler(request):target_url = request.query.get("url")if not target_url:return web.json_response({"error": "missing url param"}, status=400)if not target_url.startswith(("http://", "https://")):target_url = TARGET_ORIGIN.rstrip("/") + "/" + target_url.lstrip("/")rid = str(uuid.uuid4())event = asyncio.Event()result = {}pending[rid] = {"event": event, "result": result, "url": target_url, "claimed": False}try:await asyncio.wait_for(event.wait(), timeout=30)except asyncio.TimeoutError:return web.json_response({"error": "router timeout"}, status=504)finally:pending.pop(rid, None)status = result.get("status", 502)if status != 200:body = result.get("body", b"upstream error")return web.Response(body=body, status=status, content_type="text/plain")body = result.get("body", b"")ct = result.get("content_type", "text/html")return web.Response(body=body, content_type=ct)async def poll_handler(request):for rid, info in list(pending.items()):if not info["claimed"]:info["claimed"] = Truereturn web.json_response({"rid": rid, "url": info["url"]})return web.json_response({})async def respond_handler(request):rid = request.query.get("rid")if not rid or rid not in pending:return web.json_response({"error": "unknown or expired rid"}, status=400)status = int(request.query.get("status", "200"))content_type = request.query.get("content_type", "text/html")body = await request.read()pending[rid]["result"] = {"status": status,"content_type": content_type,"body": body}pending[rid]["event"].set()return web.json_response({"status": "ok"})async def health(request):return web.json_response({"status": "ok", "pending": len(pending), "port": PORT})async def root(request):return web.json_response({"status": "ok","service": "HTTP Long-Poll Tunnel Server","pending": len(pending),"port": PORT})13 unmodified linesapp = web.Application(middlewares=[cors_middleware])app.router.add_get("/", root)app.router.add_get("/health", health)app.router.add_get("/cgi-bin/api", proxy_handler)app.router.add_get("/api", proxy_handler)app.router.add_get("/poll", poll_handler)app.router.add_post("/respond", respond_handler)app.router.add_get("/respond", respond_handler)if __name__ == "__main__":sys.stderr.write(f"Starting poll-based tunnel server on 0.0.0.0:{PORT}\n")sys.stderr.flush()web.run_app(app, host="0.0.0.0", port=PORT, print=lambda *a: None)
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667#!/bin/sh
# WebSocket Tunnel Client for OpenWRT# Uses HTTP long-polling to relay requests through Hugging Face Space# Server: https://mtsky-free-server-docker.hf.space# Local CGI: http://192.168.1.1/cgi-bin/api
SERVER="https://mtsky-free-server-docker.hf.space"LOCAL_CGI="http://192.168.1.1/cgi-bin/api"TMPDIR="/tmp/wstunnel"POLL_INTERVAL="${POLL_INTERVAL:-1}"WGET_OPTS="-q -O - --timeout=10 --no-check-certificate"WGET_POST_OPTS="-q -O /dev/null --timeout=10 --no-check-certificate"
mkdir -p "$TMPDIR"
log() { logger -t wstunnel "$1"}
fetch_poll() { wget $WGET_OPTS "$SERVER/poll" 2>/dev/null}
respond() { local rid="$1" status="$2" content_type="$3" file="$4" wget $WGET_POST_OPTS \ --post-file="$file" \ "$SERVER/respond?rid=$rid&status=$status&content_type=$content_type" 2>/dev/null}
cleanup() { rm -f "$TMPDIR"/* log "stopped" exit 0}
trap cleanup INT TERM
log "starting wstunnel client"
while true; do if resp=$(fetch_poll); then rid=$(echo "$resp" | sed -n 's/.*"rid":"\([^"]*\)".*/\1/p') url=$(echo "$resp" | sed -n 's/.*"url":"\([^"]*\)".*/\1/p')
if [ -n "$rid" ] && [ -n "$url" ]; then local_url=$(echo "$url" | sed "s|https://shabakaty\.com|$LOCAL_CGI|") log "request $rid: $url -> $local_url"
body_file="$TMPDIR/body-$rid" wget -q -O "$body_file" --timeout=10 --no-check-certificate "$local_url" 2>/dev/null status=$?
if [ "$status" = "0" ] && [ -s "$body_file" ]; then log "response $rid: success" respond "$rid" "200" "text/html" "$body_file" & else log "response $rid: wget failed ($status)" echo "wget failed" > "$body_file" respond "$rid" "502" "text/plain" "$body_file" & fi fi fi
sleep "$POLL_INTERVAL"doneapp.py+43-62
tunnel_client.shAdded+67