Spaces:
Sleeping

free-server-docker / tunnel_client.py
mtsky12d's picture
full WebSocket tunnel server with aiohttp
6d783c9
Raw History Blame Contribute Delete
3.01 kB
#!/usr/bin/env python3
"""WebSocket tunnel client for OpenWRT router.
Connects to HF Space tunnel server, forwards CGI requests from server
to local shabakaty.com via wget."""
import asyncio
import json
import os
import subprocess
import sys
import time
SERVER_URL = os.environ.get("SERVER_URL", "wss://mtsky-free-server-docker.hf.space/ws")
LOCAL_CGI = os.environ.get("LOCAL_CGI", "http://192.168.1.1/cgi-bin/api")
RECONNECT_DELAY = int(os.environ.get("RECONNECT_DELAY", "5"))
async def run_wget(url):
"""Execute wget to fetch URL from router's perspective."""
try:
proc = await asyncio.create_subprocess_shell(
f'wget -q -O - --timeout=10 "{url}" 2>/dev/null',
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE
)
stdout, stderr = await asyncio.wait_for(proc.communicate(), timeout=15)
if proc.returncode != 0:
return {"status": 502, "body": f"wget failed: {stderr.decode(errors='replace')[:200]}", "content_type": "text/plain"}
body = stdout.decode(errors="replace")
return {"status": 200, "body": body, "content_type": "text/html"}
except asyncio.TimeoutError:
return {"status": 504, "body": "wget timeout", "content_type": "text/plain"}
except Exception as e:
return {"status": 502, "body": str(e)[:200], "content_type": "text/plain"}
async def connect():
import aiohttp
while True:
try:
async with aiohttp.ClientSession() as session:
async with session.ws_connect(SERVER_URL, heartbeat=30) as ws:
sys.stderr.write(f"Connected to {SERVER_URL}\n")
sys.stderr.flush()
async for msg in ws:
if msg.type == aiohttp.WSMsgType.TEXT:
data = json.loads(msg.data)
if data.get("type") == "ping":
await ws.send_str(json.dumps({"type": "pong"}))
continue
if data.get("type") == "request":
rid = data.get("rid")
target = data.get("url", "")
sys.stderr.write(f"Request {rid}: {target}\n")
sys.stderr.flush()
local_url = target.replace("https://shabakaty.com", LOCAL_CGI)
result = await run_wget(local_url)
result["type"] = "response"
result["rid"] = rid
await ws.send_str(json.dumps(result))
except Exception as e:
sys.stderr.write(f"Connection error: {e}\n")
sys.stderr.flush()
sys.stderr.write(f"Reconnecting in {RECONNECT_DELAY}s...\n")
sys.stderr.flush()
await asyncio.sleep(RECONNECT_DELAY)
if __name__ == "__main__":
asyncio.run(connect())