| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import asyncio |
| 4 |
import os |
| 5 |
import re |
| 6 |
|
| 7 |
from ..datastructures import Headers |
| 8 |
from ..exceptions import SecurityError |
| 9 |
|
| 10 |
|
| 11 |
__all__ = ["read_request", "read_response"] |
| 12 |
|
| 13 |
MAX_NUM_HEADERS = int(os.environ.get("WEBSOCKETS_MAX_NUM_HEADERS", "128")) |
| 14 |
MAX_LINE_LENGTH = int(os.environ.get("WEBSOCKETS_MAX_LINE_LENGTH", "8192")) |
| 15 |
|
| 16 |
|
| 17 |
def d(value: bytes) -> str: |
| 18 |
""" |
| 19 |
Decode a bytestring for interpolating into an error message. |
| 20 |
|
| 21 |
""" |
| 22 |
return value.decode(errors="backslashreplace") |
| 23 |
|
| 24 |
|
| 25 |
# See https://datatracker.ietf.org/doc/html/rfc7230#appendix-B. |
| 26 |
|
| 27 |
# Regex for validating header names. |
| 28 |
|
| 29 |
_token_re = re.compile(rb"[-!#$%&\'*+.^_`|~0-9a-zA-Z]+") |
| 30 |
|
| 31 |
# Regex for validating header values. |
| 32 |
|
| 33 |
# We don't attempt to support obsolete line folding. |
| 34 |
|
| 35 |
# Include HTAB (\x09), SP (\x20), VCHAR (\x21-\x7e), obs-text (\x80-\xff). |
| 36 |
|
| 37 |
# The ABNF is complicated because it attempts to express that optional |
| 38 |
# whitespace is ignored. We strip whitespace and don't revalidate that. |
| 39 |
|
| 40 |
# See also https://www.rfc-editor.org/errata_search.php?rfc=7230&eid=4189 |
| 41 |
|
| 42 |
_value_re = re.compile(rb"[\x09\x20-\x7e\x80-\xff]*") |
| 43 |
|
| 44 |
|
| 45 |
async def read_request(stream: asyncio.StreamReader) -> tuple[str, Headers]: |
| 46 |
""" |
| 47 |
Read an HTTP/1.1 GET request and return ``(path, headers)``. |
| 48 |
|
| 49 |
``path`` isn't URL-decoded or validated in any way. |
| 50 |
|
| 51 |
``path`` and ``headers`` are expected to contain only ASCII characters. |
| 52 |
Other characters are represented with surrogate escapes. |
| 53 |
|
| 54 |
:func:`read_request` doesn't attempt to read the request body because |
| 55 |
WebSocket handshake requests don't have one. If the request contains a |
| 56 |
body, it may be read from ``stream`` after this coroutine returns. |
| 57 |
|
| 58 |
Args: |
| 59 |
stream: Input to read the request from. |
| 60 |
|
| 61 |
Raises: |
| 62 |
EOFError: If the connection is closed without a full HTTP request. |
| 63 |
SecurityError: If the request exceeds a security limit. |
| 64 |
ValueError: If the request isn't well formatted. |
| 65 |
|
| 66 |
""" |
| 67 |
# https://datatracker.ietf.org/doc/html/rfc7230#section-3.1.1 |
| 68 |
|
| 69 |
# Parsing is simple because fixed values are expected for method and |
| 70 |
# version and because path isn't checked. Since WebSocket software tends |
| 71 |
# to implement HTTP/1.1 strictly, there's little need for lenient parsing. |
| 72 |
|
| 73 |
try: |
| 74 |
request_line = await read_line(stream) |
| 75 |
except EOFError as exc: |
| 76 |
raise EOFError("connection closed while reading HTTP request line") from exc |
| 77 |
|
| 78 |
try: |
| 79 |
method, raw_path, version = request_line.split(b" ", 2) |
| 80 |
except ValueError: # not enough values to unpack (expected 3, got 1-2) |
| 81 |
raise ValueError(f"invalid HTTP request line: {d(request_line)}") from None |
| 82 |
|
| 83 |
if method != b"GET": |
| 84 |
raise ValueError(f"unsupported HTTP method: {d(method)}") |
| 85 |
if version != b"HTTP/1.1": |
| 86 |
raise ValueError(f"unsupported HTTP version: {d(version)}") |
| 87 |
path = raw_path.decode("ascii", "surrogateescape") |
| 88 |
|
| 89 |
headers = await read_headers(stream) |
| 90 |
|
| 91 |
return path, headers |
| 92 |
|
| 93 |
|
| 94 |
async def read_response(stream: asyncio.StreamReader) -> tuple[int, str, Headers]: |
| 95 |
""" |
| 96 |
Read an HTTP/1.1 response and return ``(status_code, reason, headers)``. |
| 97 |
|
| 98 |
``reason`` and ``headers`` are expected to contain only ASCII characters. |
| 99 |
Other characters are represented with surrogate escapes. |
| 100 |
|
| 101 |
:func:`read_request` doesn't attempt to read the response body because |
| 102 |
WebSocket handshake responses don't have one. If the response contains a |
| 103 |
body, it may be read from ``stream`` after this coroutine returns. |
| 104 |
|
| 105 |
Args: |
| 106 |
stream: Input to read the response from. |
| 107 |
|
| 108 |
Raises: |
| 109 |
EOFError: If the connection is closed without a full HTTP response. |
| 110 |
SecurityError: If the response exceeds a security limit. |
| 111 |
ValueError: If the response isn't well formatted. |
| 112 |
|
| 113 |
""" |
| 114 |
# https://datatracker.ietf.org/doc/html/rfc7230#section-3.1.2 |
| 115 |
|
| 116 |
# As in read_request, parsing is simple because a fixed value is expected |
| 117 |
# for version, status_code is a 3-digit number, and reason can be ignored. |
| 118 |
|
| 119 |
try: |
| 120 |
status_line = await read_line(stream) |
| 121 |
except EOFError as exc: |
| 122 |
raise EOFError("connection closed while reading HTTP status line") from exc |
| 123 |
|
| 124 |
try: |
| 125 |
version, raw_status_code, raw_reason = status_line.split(b" ", 2) |
| 126 |
except ValueError: # not enough values to unpack (expected 3, got 1-2) |
| 127 |
raise ValueError(f"invalid HTTP status line: {d(status_line)}") from None |
| 128 |
|
| 129 |
if version != b"HTTP/1.1": |
| 130 |
raise ValueError(f"unsupported HTTP version: {d(version)}") |
| 131 |
try: |
| 132 |
status_code = int(raw_status_code) |
| 133 |
except ValueError: # invalid literal for int() with base 10 |
| 134 |
raise ValueError(f"invalid HTTP status code: {d(raw_status_code)}") from None |
| 135 |
if not 100 <= status_code < 1000: |
| 136 |
raise ValueError(f"unsupported HTTP status code: {d(raw_status_code)}") |
| 137 |
if not _value_re.fullmatch(raw_reason): |
| 138 |
raise ValueError(f"invalid HTTP reason phrase: {d(raw_reason)}") |
| 139 |
reason = raw_reason.decode() |
| 140 |
|
| 141 |
headers = await read_headers(stream) |
| 142 |
|
| 143 |
return status_code, reason, headers |
| 144 |
|
| 145 |
|
| 146 |
async def read_headers(stream: asyncio.StreamReader) -> Headers: |
| 147 |
""" |
| 148 |
Read HTTP headers from ``stream``. |
| 149 |
|
| 150 |
Non-ASCII characters are represented with surrogate escapes. |
| 151 |
|
| 152 |
""" |
| 153 |
# https://datatracker.ietf.org/doc/html/rfc7230#section-3.2 |
| 154 |
|
| 155 |
# We don't attempt to support obsolete line folding. |
| 156 |
|
| 157 |
headers = Headers() |
| 158 |
for _ in range(MAX_NUM_HEADERS + 1): |
| 159 |
try: |
| 160 |
line = await read_line(stream) |
| 161 |
except EOFError as exc: |
| 162 |
raise EOFError("connection closed while reading HTTP headers") from exc |
| 163 |
if line == b"": |
| 164 |
break |
| 165 |
|
| 166 |
try: |
| 167 |
raw_name, raw_value = line.split(b":", 1) |
| 168 |
except ValueError: # not enough values to unpack (expected 2, got 1) |
| 169 |
raise ValueError(f"invalid HTTP header line: {d(line)}") from None |
| 170 |
if not _token_re.fullmatch(raw_name): |
| 171 |
raise ValueError(f"invalid HTTP header name: {d(raw_name)}") |
| 172 |
raw_value = raw_value.strip(b" \t") |
| 173 |
if not _value_re.fullmatch(raw_value): |
| 174 |
raise ValueError(f"invalid HTTP header value: {d(raw_value)}") |
| 175 |
|
| 176 |
name = raw_name.decode("ascii") # guaranteed to be ASCII at this point |
| 177 |
value = raw_value.decode("ascii", "surrogateescape") |
| 178 |
headers[name] = value |
| 179 |
|
| 180 |
else: |
| 181 |
raise SecurityError("too many HTTP headers") |
| 182 |
|
| 183 |
return headers |
| 184 |
|
| 185 |
|
| 186 |
async def read_line(stream: asyncio.StreamReader) -> bytes: |
| 187 |
""" |
| 188 |
Read a single line from ``stream``. |
| 189 |
|
| 190 |
CRLF is stripped from the return value. |
| 191 |
|
| 192 |
""" |
| 193 |
# Security: this is bounded by the StreamReader's limit (default = 32 KiB). |
| 194 |
line = await stream.readline() |
| 195 |
# Security: this guarantees header values are small (hard-coded = 8 KiB) |
| 196 |
if len(line) > MAX_LINE_LENGTH: |
| 197 |
raise SecurityError("line too long") |
| 198 |
# Not mandatory but safe - https://datatracker.ietf.org/doc/html/rfc7230#section-3.5 |
| 199 |
if not line.endswith(b"\r\n"): |
| 200 |
raise EOFError("line without CRLF") |
| 201 |
return line[:-2] |