Spaces:
Sleeping
Sleeping
File size: 3,005 Bytes
6d783c9 | 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 | #!/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())
|