| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
from functools import partial |
| 4 |
from io import BytesIO |
| 5 |
from typing import Callable, List, Optional, Tuple |
| 6 |
|
| 7 |
from .typing import ( |
| 8 |
ASGIFramework, |
| 9 |
ASGIReceiveCallable, |
| 10 |
ASGISendCallable, |
| 11 |
HTTPScope, |
| 12 |
Scope, |
| 13 |
WSGIFramework, |
| 14 |
) |
| 15 |
|
| 16 |
|
| 17 |
class InvalidPathError(Exception): |
| 18 |
pass |
| 19 |
|
| 20 |
|
| 21 |
class ASGIWrapper: |
| 22 |
def __init__(self, app: ASGIFramework) -> None: |
| 23 |
self.app = app |
| 24 |
|
| 25 |
async def __call__( |
| 26 |
self, |
| 27 |
scope: Scope, |
| 28 |
receive: ASGIReceiveCallable, |
| 29 |
send: ASGISendCallable, |
| 30 |
sync_spawn: Callable, |
| 31 |
call_soon: Callable, |
| 32 |
) -> None: |
| 33 |
await self.app(scope, receive, send) |
| 34 |
|
| 35 |
|
| 36 |
class WSGIWrapper: |
| 37 |
def __init__(self, app: WSGIFramework, max_body_size: int) -> None: |
| 38 |
self.app = app |
| 39 |
self.max_body_size = max_body_size |
| 40 |
|
| 41 |
async def __call__( |
| 42 |
self, |
| 43 |
scope: Scope, |
| 44 |
receive: ASGIReceiveCallable, |
| 45 |
send: ASGISendCallable, |
| 46 |
sync_spawn: Callable, |
| 47 |
call_soon: Callable, |
| 48 |
) -> None: |
| 49 |
if scope["type"] == "http": |
| 50 |
await self.handle_http(scope, receive, send, sync_spawn, call_soon) |
| 51 |
elif scope["type"] == "websocket": |
| 52 |
await send({"type": "websocket.close"}) # type: ignore |
| 53 |
elif scope["type"] == "lifespan": |
| 54 |
return |
| 55 |
else: |
| 56 |
raise Exception(f"Unknown scope type, {scope['type']}") |
| 57 |
|
| 58 |
async def handle_http( |
| 59 |
self, |
| 60 |
scope: HTTPScope, |
| 61 |
receive: ASGIReceiveCallable, |
| 62 |
send: ASGISendCallable, |
| 63 |
sync_spawn: Callable, |
| 64 |
call_soon: Callable, |
| 65 |
) -> None: |
| 66 |
body = bytearray() |
| 67 |
while True: |
| 68 |
message = await receive() |
| 69 |
body.extend(message.get("body", b"")) # type: ignore |
| 70 |
if len(body) > self.max_body_size: |
| 71 |
await send({"type": "http.response.start", "status": 400, "headers": []}) |
| 72 |
await send({"type": "http.response.body", "body": b"", "more_body": False}) |
| 73 |
return |
| 74 |
if not message.get("more_body"): |
| 75 |
break |
| 76 |
|
| 77 |
try: |
| 78 |
environ = _build_environ(scope, body) |
| 79 |
except InvalidPathError: |
| 80 |
await send({"type": "http.response.start", "status": 404, "headers": []}) |
| 81 |
else: |
| 82 |
await sync_spawn(self.run_app, environ, partial(call_soon, send)) |
| 83 |
await send({"type": "http.response.body", "body": b"", "more_body": False}) |
| 84 |
|
| 85 |
def run_app(self, environ: dict, send: Callable) -> None: |
| 86 |
headers: List[Tuple[bytes, bytes]] |
| 87 |
status_code: Optional[int] = None |
| 88 |
|
| 89 |
def start_response( |
| 90 |
status: str, |
| 91 |
response_headers: List[Tuple[str, str]], |
| 92 |
exc_info: Optional[Exception] = None, |
| 93 |
) -> None: |
| 94 |
nonlocal headers, status_code |
| 95 |
|
| 96 |
raw, _ = status.split(" ", 1) |
| 97 |
status_code = int(raw) |
| 98 |
headers = [ |
| 99 |
(name.lower().encode("ascii"), value.encode("ascii")) |
| 100 |
for name, value in response_headers |
| 101 |
] |
| 102 |
send({"type": "http.response.start", "status": status_code, "headers": headers}) |
| 103 |
|
| 104 |
for output in self.app(environ, start_response): |
| 105 |
send({"type": "http.response.body", "body": output, "more_body": True}) |
| 106 |
|
| 107 |
|
| 108 |
def _build_environ(scope: HTTPScope, body: bytes) -> dict: |
| 109 |
server = scope.get("server") or ("localhost", 80) |
| 110 |
path = scope["path"] |
| 111 |
script_name = scope.get("root_path", "") |
| 112 |
if path.startswith(script_name): |
| 113 |
path = path[len(script_name) :] |
| 114 |
path = path if path != "" else "/" |
| 115 |
else: |
| 116 |
raise InvalidPathError() |
| 117 |
|
| 118 |
environ = { |
| 119 |
"REQUEST_METHOD": scope["method"], |
| 120 |
"SCRIPT_NAME": script_name.encode("utf8").decode("latin1"), |
| 121 |
"PATH_INFO": path.encode("utf8").decode("latin1"), |
| 122 |
"QUERY_STRING": scope["query_string"].decode("ascii"), |
| 123 |
"SERVER_NAME": server[0], |
| 124 |
"SERVER_PORT": server[1], |
| 125 |
"SERVER_PROTOCOL": "HTTP/%s" % scope["http_version"], |
| 126 |
"wsgi.version": (1, 0), |
| 127 |
"wsgi.url_scheme": scope.get("scheme", "http"), |
| 128 |
"wsgi.input": BytesIO(body), |
| 129 |
"wsgi.errors": BytesIO(), |
| 130 |
"wsgi.multithread": True, |
| 131 |
"wsgi.multiprocess": True, |
| 132 |
"wsgi.run_once": False, |
| 133 |
} |
| 134 |
|
| 135 |
if scope.get("client") is not None: |
| 136 |
environ["REMOTE_ADDR"] = scope["client"][0] |
| 137 |
|
| 138 |
for raw_name, raw_value in scope.get("headers", []): |
| 139 |
name = raw_name.decode("latin1") |
| 140 |
if name == "content-length": |
| 141 |
corrected_name = "CONTENT_LENGTH" |
| 142 |
elif name == "content-type": |
| 143 |
corrected_name = "CONTENT_TYPE" |
| 144 |
else: |
| 145 |
corrected_name = "HTTP_%s" % name.upper().replace("-", "_") |
| 146 |
# HTTPbis say only ASCII chars are allowed in headers, but we latin1 just in case |
| 147 |
value = raw_value.decode("latin1") |
| 148 |
if corrected_name in environ: |
| 149 |
value = environ[corrected_name] + "," + value # type: ignore |
| 150 |
environ[corrected_name] = value |
| 151 |
return environ |