Spaces:
Sleeping

File size: 5,904 Bytes
6d783c9
a10a71b
61c70f7
a58b458
40493f6
6213c99
f0aa03d
5f0778b
a10a71b
61c70f7
 
6213c99
19d8d59
a10a71b
40493f6
 
 
 
0b75117
 
 
 
 
 
 
 
19d8d59
0b75117
 
 
 
 
584b341
0b75117
 
 
 
 
 
 
 
 
 
 
 
40493f6
 
 
 
 
 
 
c35a34a
40493f6
 
 
 
 
c35a34a
6d783c9
 
 
 
 
0b75117
a0dea2a
40493f6
 
 
 
6213c99
6d783c9
9c6b4e5
19d8d59
 
 
6d783c9
a0dea2a
 
 
6d783c9
6213c99
6d783c9
a0dea2a
0b75117
 
 
 
 
 
40493f6
a0dea2a
 
 
 
 
19d8d59
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a0dea2a
6d783c9
a0dea2a
 
 
 
 
 
 
9c6b4e5
a0dea2a
 
 
9c6b4e5
a0dea2a
 
 
 
40493f6
6d783c9
 
 
 
a0dea2a
 
40493f6
 
6d783c9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a0dea2a
 
 
a10a71b
a58b458
a0dea2a
a58b458
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
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)