Spaces:
Sleeping
Sleeping
full WebSocket tunnel server with aiohttp
Browse filesFiles changed (4)
- Dockerfile+3-1
- app.py+130-11
- requirements.txtAdded+1
- tunnel_client.pyAdded+67
12345FROM python:3.11-slimWORKDIR /appCOPY app.py .EXPOSE 7860CMD ["python3", "-u", "app.py"]1234567FROM python:3.11-slimWORKDIR /appCOPY requirements.txt ./RUN pip install --no-cache-dir -r requirements.txtCOPY app.py .EXPOSE 7860CMD ["python3", "-u", "app.py"]
12345678910111213141516171819202122import http.serverimport jsonimport osimport sysPORT = int(os.environ.get("PORT", 7860))class Handler(http.server.BaseHTTPRequestHandler):def do_GET(self):self.send_response(200)self.send_header("Content-Type", "application/json")self.send_header("Access-Control-Allow-Origin", "*")self.end_headers()self.wfile.write(json.dumps({"status": "ok", "path": self.path, "port": PORT}).encode())def log_message(self, format, *args):passif __name__ == "__main__":sys.stderr.write(f"Starting on 0.0.0.0:{PORT}\n")sys.stderr.flush()http.server.HTTPServer(("0.0.0.0", PORT), Handler).serve_forever()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141import aiohttpimport asyncioimport jsonimport osimport sysfrom aiohttp import web, WSMsgTypefrom urllib.parse import urlencodePORT = int(os.environ.get("PORT", 7860))TARGET_ORIGIN = "https://shabakaty.com"clients = {}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") == "pong":continueexcept 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(id(request))futures = {}event = asyncio.Event()result = {}async def on_msg(ws_msg):nonlocal resultif ws_msg.type == aiohttp.WSMsgType.TEXT:try:data = json.loads(ws_msg.data)if data.get("rid") == rid and data.get("type") == "response":result = dataevent.set()except json.JSONDecodeError:passlistener_task = Nonews = next(iter(clients.values()))try:listener_task = asyncio.create_task(_listen_for_rid(ws, rid, event, result))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)if result.get("status") and result["status"] != 200:return web.json_response({"error": result.get("body", "upstream error")}, status=result["status"])body = result.get("body", "")ct = result.get("content_type", "text/html")return web.Response(body=body, content_type=ct)finally:if listener_task:listener_task.cancel()async def _listen_for_rid(ws, rid, event, result):try:async for msg in ws:if msg.type == aiohttp.WSMsgType.TEXT:try:data = json.loads(msg.data)if data.get("rid") == rid and data.get("type") == "response":result.update(data)event.set()breakexcept json.JSONDecodeError:passelif msg.type in (aiohttp.WSMsgType.CLOSED, aiohttp.WSMsgType.ERROR):breakexcept (asyncio.CancelledError, Exception):passasync 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})async def cors_middleware(app, handler):async def middleware(request):if request.method == "OPTIONS":resp = web.Response()resp.headers["Access-Control-Allow-Origin"] = "*"resp.headers["Access-Control-Allow-Methods"] = "GET, POST, OPTIONS"resp.headers["Access-Control-Allow-Headers"] = "*"return respresp = await handler(request)resp.headers["Access-Control-Allow-Origin"] = "*"return respreturn middlewareapp = 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)
1aiohttp>=3.9.012345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667#!/usr/bin/env python3"""WebSocket tunnel client for OpenWRT router.Connects to HF Space tunnel server, forwards CGI requests from serverto local shabakaty.com via wget."""
import asyncioimport jsonimport osimport subprocessimport sysimport 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())Dockerfile+3-1
app.py+130-11
requirements.txtAdded+1
tunnel_client.pyAdded+67