import asyncio import json import os import sys import time import uuid import urllib.parse from aiohttp import web PORT = int(os.environ.get("PORT", 7860)) pending = {} poll_cond = asyncio.Condition() CACHE = {} CACHE_MAX = 200 CACHE_TTL = 300 MAGIC_SIGNATURES = [ (b'\xff\xd8\xff', 'image/jpeg'), (b'\x89PNG\r\n\x1a\n', 'image/png'), (b'GIF87a', 'image/gif'), (b'GIF89a', 'image/gif'), (b'RIFF', 'image/webp', lambda b: b[8:12] == b'WEBP'), (b'%PDF', 'application/pdf'), (b'PK\x03\x04', 'application/zip'), (b'\x1aE\xdf\xa3', 'application/octet-stream'), ] def detect_content_type(body, fallback="application/octet-stream"): for sig in MAGIC_SIGNATURES: condition = True if len(sig) == 2: magic, ct = sig else: magic, ct, extra_check = sig condition = extra_check(body[:16]) if callable(extra_check) else True if body.startswith(magic) and condition: return ct try: body.decode('utf-8') return fallback except (UnicodeDecodeError, ValueError): return "application/octet-stream" def cache_get(url): if url in CACHE: entry = CACHE[url] if time.time() - entry["ts"] < CACHE_TTL: return entry del CACHE[url] return None def cache_set(url, status, ct, body): if len(CACHE) >= CACHE_MAX: oldest = min(CACHE.keys(), key=lambda k: CACHE[k]["ts"]) del CACHE[oldest] CACHE[url] = {"ts": time.time(), "status": status, "ct": ct, "body": body} 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 = "https://" + target_url.lstrip("/") cached = cache_get(target_url) if cached: return web.Response(body=cached["body"], status=cached["status"], content_type=cached["ct"]) rid = str(uuid.uuid4()) event = asyncio.Event() result = {"body": b"", "status": 502, "content_type": "text/plain"} async with poll_cond: pending[rid] = {"event": event, "result": result, "url": target_url, "claimed": False} poll_cond.notify_all() 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) body = result.get("body", b"upstream error") ct = result.get("content_type", "text/html") if ct in ("text/html", "text/plain", "application/octet-stream"): detected = detect_content_type(body, ct) if detected != ct: ct = detected cache_set(target_url, status, ct, body) if status != 200: return web.Response(body=body, status=status, content_type="text/plain") return web.Response(body=body, content_type=ct) async def poll_handler(request): async with poll_cond: for rid, info in list(pending.items()): if not info["claimed"]: info["claimed"] = True return web.json_response({ "rid": rid, "url": info["url"], "url_encoded": urllib.parse.quote(info["url"], safe='') }) try: await asyncio.wait_for(poll_cond.wait(), timeout=5.0) except asyncio.TimeoutError: return web.json_response({}) for rid, info in list(pending.items()): if not info["claimed"]: info["claimed"] = True return web.json_response({ "rid": rid, "url": info["url"], "url_encoded": urllib.parse.quote(info["url"], safe='') }) 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"].update({ "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, "cache": len(CACHE)}) async def root(request): return web.json_response({ "status": "ok", "service": "HTTP Long-Poll Tunnel Server", "pending": len(pending), "port": PORT, "cache": len(CACHE) }) 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 resp resp = await handler(request) resp.headers["Access-Control-Allow-Origin"] = "*" return resp return middleware app = 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)