Debian Codegraph @

src/urllib3/http2/connection.py

raw
1 from __future__ import annotations
2
3 import logging
4 import re
5 import threading
6 import types
7 import typing
8
9 import h2.config
10 import h2.connection
11 import h2.events
12
13 from .._base_connection import _TYPE_BODY
14 from .._collections import HTTPHeaderDict
15 from ..connection import HTTPSConnection, _get_default_user_agent
16 from ..exceptions import ConnectionError
17 from ..response import BaseHTTPResponse
18
19 orig_HTTPSConnection = HTTPSConnection
20
21 T = typing.TypeVar("T")
22
23 log = logging.getLogger(__name__)
24
25 RE_IS_LEGAL_HEADER_NAME = re.compile(rb"^[!#$%&'*+\-.^_`|~0-9a-z]+$")
26 RE_IS_ILLEGAL_HEADER_VALUE = re.compile(rb"[\0\x00\x0a\x0d\r\n]|^[ \r\n\t]|[ \r\n\t]$")
27
28
29 def _is_legal_header_name(name: bytes) -> bool:
30 """
31 "An implementation that validates fields according to the definitions in Sections
32 5.1 and 5.5 of [HTTP] only needs an additional check that field names do not
33 include uppercase characters." (https://httpwg.org/specs/rfc9113.html#n-field-validity)
34
35 `http.client._is_legal_header_name` does not validate the field name according to the
36 HTTP 1.1 spec, so we do that here, in addition to checking for uppercase characters.
37
38 This does not allow for the `:` character in the header name, so should not
39 be used to validate pseudo-headers.
40 """
41 return bool(RE_IS_LEGAL_HEADER_NAME.match(name))
42
43
44 def _is_illegal_header_value(value: bytes) -> bool:
45 """
46 "A field value MUST NOT contain the zero value (ASCII NUL, 0x00), line feed
47 (ASCII LF, 0x0a), or carriage return (ASCII CR, 0x0d) at any position. A field
48 value MUST NOT start or end with an ASCII whitespace character (ASCII SP or HTAB,
49 0x20 or 0x09)." (https://httpwg.org/specs/rfc9113.html#n-field-validity)
50 """
51 return bool(RE_IS_ILLEGAL_HEADER_VALUE.search(value))
52
53
54 class _LockedObject(typing.Generic[T]):
55 """
56 A wrapper class that hides a specific object behind a lock.
57 The goal here is to provide a simple way to protect access to an object
58 that cannot safely be simultaneously accessed from multiple threads. The
59 intended use of this class is simple: take hold of it with a context
60 manager, which returns the protected object.
61 """
62
63 __slots__ = (
64 "lock",
65 "_obj",
66 )
67
68 def __init__(self, obj: T):
69 self.lock = threading.RLock()
70 self._obj = obj
71
72 def __enter__(self) -> T:
73 self.lock.acquire()
74 return self._obj
75
76 def __exit__(
77 self,
78 exc_type: type[BaseException] | None,
79 exc_val: BaseException | None,
80 exc_tb: types.TracebackType | None,
81 ) -> None:
82 self.lock.release()
83
84
85 class HTTP2Connection(HTTPSConnection):
86 def __init__(
87 self, host: str, port: int | None = None, **kwargs: typing.Any
88 ) -> None:
89 self._h2_conn = self._new_h2_conn()
90 self._h2_stream: int | None = None
91 self._headers: list[tuple[bytes, bytes]] = []
92
93 if "proxy" in kwargs or "proxy_config" in kwargs: # Defensive:
94 raise NotImplementedError("Proxies aren't supported with HTTP/2")
95
96 super().__init__(host, port, **kwargs)
97
98 if self._tunnel_host is not None:
99 raise NotImplementedError("Tunneling isn't supported with HTTP/2")
100
101 def _new_h2_conn(self) -> _LockedObject[h2.connection.H2Connection]:
102 config = h2.config.H2Configuration(client_side=True)
103 return _LockedObject(h2.connection.H2Connection(config=config))
104
105 def connect(self) -> None:
106 super().connect()
107 with self._h2_conn as conn:
108 conn.initiate_connection()
109 if data_to_send := conn.data_to_send():
110 self.sock.sendall(data_to_send)
111
112 def putrequest( # type: ignore[override]
113 self,
114 method: str,
115 url: str,
116 **kwargs: typing.Any,
117 ) -> None:
118 """putrequest
119 This deviates from the HTTPConnection method signature since we never need to override
120 sending accept-encoding headers or the host header.
121 """
122 if "skip_host" in kwargs:
123 raise NotImplementedError("`skip_host` isn't supported")
124 if "skip_accept_encoding" in kwargs:
125 raise NotImplementedError("`skip_accept_encoding` isn't supported")
126
127 self._request_url = url or "/"
128 self._validate_path(url) # type: ignore[attr-defined]
129
130 port = self.port if self.port is not None else 443
131 if ":" in self.host:
132 authority = f"[{self.host}]:{port}"
133 else:
134 authority = f"{self.host}:{port}"
135
136 self._headers.append((b":scheme", b"https"))
137 self._headers.append((b":method", method.encode()))
138 self._headers.append((b":authority", authority.encode()))
139 self._headers.append((b":path", url.encode()))
140
141 with self._h2_conn as conn:
142 self._h2_stream = conn.get_next_available_stream_id()
143
144 def putheader(self, header: str | bytes, *values: str | bytes) -> None: # type: ignore[override]
145 # TODO SKIPPABLE_HEADERS from urllib3 are ignored.
146 header = header.encode() if isinstance(header, str) else header
147 header = header.lower() # A lot of upstream code uses capitalized headers.
148 if not _is_legal_header_name(header):
149 raise ValueError(f"Illegal header name {str(header)}")
150
151 for value in values:
152 value = value.encode() if isinstance(value, str) else value
153 if _is_illegal_header_value(value):
154 raise ValueError(f"Illegal header value {str(value)}")
155 self._headers.append((header, value))
156
157 def endheaders(self, message_body: typing.Any = None) -> None: # type: ignore[override]
158 if self._h2_stream is None:
159 raise ConnectionError("Must call `putrequest` first.")
160
161 with self._h2_conn as conn:
162 conn.send_headers(
163 stream_id=self._h2_stream,
164 headers=self._headers,
165 end_stream=(message_body is None),
166 )
167 if data_to_send := conn.data_to_send():
168 self.sock.sendall(data_to_send)
169 self._headers = [] # Reset headers for the next request.
170
171 def send(self, data: typing.Any) -> None:
172 """Send data to the server.
173 `data` can be: `str`, `bytes`, an iterable, or file-like objects
174 that support a .read() method.
175 """
176 if self._h2_stream is None:
177 raise ConnectionError("Must call `putrequest` first.")
178
179 with self._h2_conn as conn:
180 if data_to_send := conn.data_to_send():
181 self.sock.sendall(data_to_send)
182
183 if hasattr(data, "read"): # file-like objects
184 while True:
185 chunk = data.read(self.blocksize)
186 if not chunk:
187 break
188 if isinstance(chunk, str):
189 chunk = chunk.encode()
190 conn.send_data(self._h2_stream, chunk, end_stream=False)
191 if data_to_send := conn.data_to_send():
192 self.sock.sendall(data_to_send)
193 conn.end_stream(self._h2_stream)
194 return
195
196 if isinstance(data, str): # str -> bytes
197 data = data.encode()
198
199 try:
200 if isinstance(data, bytes):
201 conn.send_data(self._h2_stream, data, end_stream=True)
202 if data_to_send := conn.data_to_send():
203 self.sock.sendall(data_to_send)
204 else:
205 for chunk in data:
206 conn.send_data(self._h2_stream, chunk, end_stream=False)
207 if data_to_send := conn.data_to_send():
208 self.sock.sendall(data_to_send)
209 conn.end_stream(self._h2_stream)
210 except TypeError:
211 raise TypeError(
212 "`data` should be str, bytes, iterable, or file. got %r"
213 % type(data)
214 )
215
216 def set_tunnel(
217 self,
218 host: str,
219 port: int | None = None,
220 headers: typing.Mapping[str, str] | None = None,
221 scheme: str = "http",
222 ) -> None:
223 raise NotImplementedError(
224 "HTTP/2 does not support setting up a tunnel through a proxy"
225 )
226
227 def getresponse( # type: ignore[override]
228 self,
229 ) -> HTTP2Response:
230 status = None
231 data = bytearray()
232 with self._h2_conn as conn:
233 end_stream = False
234 while not end_stream:
235 # TODO: Arbitrary read value.
236 if received_data := self.sock.recv(65535):
237 events = conn.receive_data(received_data)
238 for event in events:
239 if isinstance(event, h2.events.ResponseReceived):
240 headers = HTTPHeaderDict()
241 for header, value in event.headers:
242 if header == b":status":
243 status = int(value.decode())
244 else:
245 headers.add(
246 header.decode("ascii"), value.decode("ascii")
247 )
248
249 elif isinstance(event, h2.events.DataReceived):
250 data += event.data
251 conn.acknowledge_received_data(
252 event.flow_controlled_length, event.stream_id
253 )
254
255 elif isinstance(event, h2.events.StreamEnded):
256 end_stream = True
257
258 if data_to_send := conn.data_to_send():
259 self.sock.sendall(data_to_send)
260
261 assert status is not None
262 return HTTP2Response(
263 status=status,
264 headers=headers,
265 request_url=self._request_url,
266 data=bytes(data),
267 )
268
269 def request( # type: ignore[override]
270 self,
271 method: str,
272 url: str,
273 body: _TYPE_BODY | None = None,
274 headers: typing.Mapping[str, str] | None = None,
275 *,
276 preload_content: bool = True,
277 decode_content: bool = True,
278 enforce_content_length: bool = True,
279 **kwargs: typing.Any,
280 ) -> None:
281 """Send an HTTP/2 request"""
282 if "chunked" in kwargs:
283 # TODO this is often present from upstream.
284 # raise NotImplementedError("`chunked` isn't supported with HTTP/2")
285 pass
286
287 if self.sock is not None:
288 self.sock.settimeout(self.timeout)
289
290 self.putrequest(method, url)
291
292 headers = headers or {}
293 for k, v in headers.items():
294 if k.lower() == "transfer-encoding" and v == "chunked":
295 continue
296 else:
297 self.putheader(k, v)
298
299 if b"user-agent" not in dict(self._headers):
300 self.putheader(b"user-agent", _get_default_user_agent())
301
302 if body:
303 self.endheaders(message_body=body)
304 self.send(body)
305 else:
306 self.endheaders()
307
308 def close(self) -> None:
309 with self._h2_conn as conn:
310 try:
311 conn.close_connection()
312 if data := conn.data_to_send():
313 self.sock.sendall(data)
314 except Exception:
315 pass
316
317 # Reset all our HTTP/2 connection state.
318 self._h2_conn = self._new_h2_conn()
319 self._h2_stream = None
320 self._headers = []
321
322 super().close()
323
324
325 class HTTP2Response(BaseHTTPResponse):
326 # TODO: This is a woefully incomplete response object, but works for non-streaming.
327 def __init__(
328 self,
329 status: int,
330 headers: HTTPHeaderDict,
331 request_url: str,
332 data: bytes,
333 decode_content: bool = False, # TODO: support decoding
334 ) -> None:
335 super().__init__(
336 status=status,
337 headers=headers,
338 # Following CPython, we map HTTP versions to major * 10 + minor integers
339 version=20,
340 version_string="HTTP/2",
341 # No reason phrase in HTTP/2
342 reason=None,
343 decode_content=decode_content,
344 request_url=request_url,
345 )
346 self._data = data
347 self.length_remaining = 0
348
349 @property
350 def data(self) -> bytes:
351 return self._data
352
353 def get_redirect_location(self) -> None:
354 return None
355
356 def close(self) -> None:
357 pass