Debian Codegraph @

src/websockets/client.py

raw
1 from __future__ import annotations
2
3 import os
4 import random
5 import warnings
6 from collections.abc import Generator, Sequence
7 from typing import Any
8
9 from .datastructures import Headers, MultipleValuesError
10 from .exceptions import (
11 InvalidHandshake,
12 InvalidHeader,
13 InvalidHeaderValue,
14 InvalidMessage,
15 InvalidStatus,
16 InvalidUpgrade,
17 NegotiationError,
18 StatusLineTooLong,
19 )
20 from .extensions import ClientExtensionFactory, Extension
21 from .headers import (
22 build_authorization_basic,
23 build_extension,
24 build_host,
25 build_subprotocol,
26 parse_connection,
27 parse_extension,
28 parse_subprotocol,
29 parse_upgrade,
30 )
31 from .http11 import Request, Response
32 from .imports import lazy_import
33 from .protocol import CLIENT, CONNECTING, OPEN, Protocol, State
34 from .typing import (
35 ConnectionOption,
36 ExtensionHeader,
37 LoggerLike,
38 Origin,
39 Subprotocol,
40 UpgradeProtocol,
41 )
42 from .uri import WebSocketURI
43 from .utils import accept_key, generate_key
44
45
46 __all__ = ["ClientProtocol"]
47
48
49 class ClientProtocol(Protocol):
50 """
51 Sans-I/O implementation of a WebSocket client connection.
52
53 Args:
54 uri: URI of the WebSocket server, parsed
55 with :func:`~websockets.uri.parse_uri`.
56 origin: Value of the ``Origin`` header. This is useful when connecting
57 to a server that validates the ``Origin`` header to defend against
58 Cross-Site WebSocket Hijacking attacks.
59 extensions: List of supported extensions, in order in which they
60 should be tried.
61 subprotocols: List of supported subprotocols, in order of decreasing
62 preference.
63 state: Initial state of the WebSocket connection.
64 max_size: Maximum size of incoming messages in bytes.
65 :obj:`None` disables the limit. You may pass a ``(max_message_size,
66 max_fragment_size)`` tuple to set different limits for messages and
67 fragments when you expect long messages sent in short fragments.
68 logger: Logger for this connection;
69 defaults to ``logging.getLogger("websockets.client")``;
70 see the :doc:`logging guide <../../topics/logging>` for details.
71
72 """
73
74 def __init__(
75 self,
76 uri: WebSocketURI,
77 *,
78 origin: Origin | None = None,
79 extensions: Sequence[ClientExtensionFactory] | None = None,
80 subprotocols: Sequence[Subprotocol] | None = None,
81 state: State = CONNECTING,
82 max_size: int | None | tuple[int | None, int | None] = 2**20,
83 logger: LoggerLike | None = None,
84 ) -> None:
85 super().__init__(
86 side=CLIENT,
87 state=state,
88 max_size=max_size,
89 logger=logger,
90 )
91 self.uri = uri
92 self.origin = origin
93 self.available_extensions = extensions
94 self.available_subprotocols = subprotocols
95 self.key = generate_key()
96
97 def connect(self) -> Request:
98 """
99 Create a handshake request to open a connection.
100
101 You must send the handshake request with :meth:`send_request`.
102
103 You can modify it before sending it, for example to add HTTP headers.
104
105 Returns:
106 WebSocket handshake request event to send to the server.
107
108 """
109 headers = Headers()
110 headers["Host"] = build_host(self.uri.host, self.uri.port, self.uri.secure)
111 if self.uri.user_info:
112 headers["Authorization"] = build_authorization_basic(*self.uri.user_info)
113 if self.origin is not None:
114 headers["Origin"] = self.origin
115 headers["Upgrade"] = "websocket"
116 headers["Connection"] = "Upgrade"
117 headers["Sec-WebSocket-Key"] = self.key
118 headers["Sec-WebSocket-Version"] = "13"
119 if self.available_extensions is not None:
120 headers["Sec-WebSocket-Extensions"] = build_extension(
121 [
122 (extension_factory.name, extension_factory.get_request_params())
123 for extension_factory in self.available_extensions
124 ]
125 )
126 if self.available_subprotocols is not None:
127 headers["Sec-WebSocket-Protocol"] = build_subprotocol(
128 self.available_subprotocols
129 )
130 return Request(self.uri.resource_name, headers)
131
132 def process_response(self, response: Response) -> None:
133 """
134 Check a handshake response.
135
136 Args:
137 request: WebSocket handshake response received from the server.
138
139 Raises:
140 InvalidHandshake: If the handshake response is invalid.
141
142 """
143
144 if response.status_code != 101:
145 raise InvalidStatus(response)
146
147 headers = response.headers
148
149 connection: list[ConnectionOption] = sum(
150 [parse_connection(value) for value in headers.get_all("Connection")], []
151 )
152 if not any(value.lower() == "upgrade" for value in connection):
153 raise InvalidUpgrade(
154 "Connection", ", ".join(connection) if connection else None
155 )
156
157 upgrade: list[UpgradeProtocol] = sum(
158 [parse_upgrade(value) for value in headers.get_all("Upgrade")], []
159 )
160 # For compatibility with non-strict implementations, ignore case when
161 # checking the Upgrade header. It's supposed to be 'WebSocket'.
162 if not (len(upgrade) == 1 and upgrade[0].lower() == "websocket"):
163 raise InvalidUpgrade("Upgrade", ", ".join(upgrade) if upgrade else None)
164
165 try:
166 s_w_accept = headers["Sec-WebSocket-Accept"]
167 except KeyError:
168 raise InvalidHeader("Sec-WebSocket-Accept") from None
169 except MultipleValuesError:
170 raise InvalidHeader("Sec-WebSocket-Accept", "multiple values") from None
171 if s_w_accept != accept_key(self.key):
172 raise InvalidHeaderValue("Sec-WebSocket-Accept", s_w_accept)
173
174 self.extensions = self.process_extensions(headers)
175 self.subprotocol = self.process_subprotocol(headers)
176
177 def process_extensions(self, headers: Headers) -> list[Extension]:
178 """
179 Handle the Sec-WebSocket-Extensions HTTP response header.
180
181 Check that each extension is supported, as well as its parameters.
182
183 :rfc:`6455` leaves the rules up to the specification of each
184 extension.
185
186 To provide this level of flexibility, for each extension accepted by
187 the server, we check for a match with each extension available in the
188 client configuration. If no match is found, an exception is raised.
189
190 If several variants of the same extension are accepted by the server,
191 it may be configured several times, which won't make sense in general.
192 Extensions must implement their own requirements. For this purpose,
193 the list of previously accepted extensions is provided.
194
195 Other requirements, for example related to mandatory extensions or the
196 order of extensions, may be implemented by overriding this method.
197
198 Args:
199 headers: WebSocket handshake response headers.
200
201 Returns:
202 List of accepted extensions.
203
204 Raises:
205 InvalidHandshake: To abort the handshake.
206
207 """
208 accepted_extensions: list[Extension] = []
209
210 extensions = headers.get_all("Sec-WebSocket-Extensions")
211
212 if extensions:
213 if self.available_extensions is None:
214 raise NegotiationError("no extensions supported")
215
216 parsed_extensions: list[ExtensionHeader] = sum(
217 [parse_extension(header_value) for header_value in extensions], []
218 )
219
220 for name, response_params in parsed_extensions:
221 for extension_factory in self.available_extensions:
222 # Skip non-matching extensions based on their name.
223 if extension_factory.name != name:
224 continue
225
226 # Skip non-matching extensions based on their params.
227 try:
228 extension = extension_factory.process_response_params(
229 response_params, accepted_extensions
230 )
231 except NegotiationError:
232 continue
233
234 # Add matching extension to the final list.
235 accepted_extensions.append(extension)
236
237 # Break out of the loop once we have a match.
238 break
239
240 # If we didn't break from the loop, no extension in our list
241 # matched what the server sent. Fail the connection.
242 else:
243 raise NegotiationError(
244 f"Unsupported extension: "
245 f"name = {name}, params = {response_params}"
246 )
247
248 return accepted_extensions
249
250 def process_subprotocol(self, headers: Headers) -> Subprotocol | None:
251 """
252 Handle the Sec-WebSocket-Protocol HTTP response header.
253
254 If provided, check that it contains exactly one supported subprotocol.
255
256 Args:
257 headers: WebSocket handshake response headers.
258
259 Returns:
260 Subprotocol, if one was selected.
261
262 """
263 subprotocol: Subprotocol | None = None
264
265 subprotocols = headers.get_all("Sec-WebSocket-Protocol")
266
267 if subprotocols:
268 if self.available_subprotocols is None:
269 raise NegotiationError("no subprotocols supported")
270
271 parsed_subprotocols: Sequence[Subprotocol] = sum(
272 [parse_subprotocol(header_value) for header_value in subprotocols], []
273 )
274 if len(parsed_subprotocols) > 1:
275 raise InvalidHeader(
276 "Sec-WebSocket-Protocol",
277 f"multiple values: {', '.join(parsed_subprotocols)}",
278 )
279
280 subprotocol = parsed_subprotocols[0]
281 if subprotocol not in self.available_subprotocols:
282 raise NegotiationError(f"unsupported subprotocol: {subprotocol}")
283
284 return subprotocol
285
286 def send_request(self, request: Request) -> None:
287 """
288 Send a handshake request to the server.
289
290 Args:
291 request: WebSocket handshake request event.
292
293 """
294 if self.debug:
295 self.logger.debug("> GET %s HTTP/1.1", request.path)
296 for key, value in request.headers.raw_items():
297 self.logger.debug("> %s: %s", key, value)
298
299 self.writes.append(request.serialize())
300
301 def parse(self) -> Generator[None]:
302 if self.state is CONNECTING:
303 try:
304 response = yield from Response.parse(
305 self.reader.read_line,
306 self.reader.read_exact,
307 self.reader.read_to_eof,
308 )
309 except StatusLineTooLong as exc:
310 self.handshake_exc = exc
311 self.send_eof()
312 self.parser = self.discard()
313 next(self.parser) # start coroutine
314 yield
315 except Exception as exc:
316 self.handshake_exc = InvalidMessage(
317 "did not receive a valid HTTP response"
318 )
319 self.handshake_exc.__cause__ = exc
320 self.send_eof()
321 self.parser = self.discard()
322 next(self.parser) # start coroutine
323 yield
324
325 if self.debug:
326 code, phrase = response.status_code, response.reason_phrase
327 self.logger.debug("< HTTP/1.1 %d %s", code, phrase)
328 for key, value in response.headers.raw_items():
329 self.logger.debug("< %s: %s", key, value)
330 if response.body:
331 self.logger.debug("< [body] (%d bytes)", len(response.body))
332
333 try:
334 self.process_response(response)
335 except InvalidHandshake as exc:
336 response._exception = exc
337 self.events.append(response)
338 self.handshake_exc = exc
339 self.send_eof()
340 self.parser = self.discard()
341 next(self.parser) # start coroutine
342 yield
343
344 assert self.state is CONNECTING
345 self.state = OPEN
346 self.events.append(response)
347
348 yield from super().parse()
349
350
351 class ClientConnection(ClientProtocol):
352 def __init__(self, *args: Any, **kwargs: Any) -> None:
353 warnings.warn( # deprecated in 11.0 - 2023-04-02
354 "ClientConnection was renamed to ClientProtocol",
355 DeprecationWarning,
356 )
357 super().__init__(*args, **kwargs)
358
359
360 def process_exception(exc: Exception) -> Exception | None:
361 """
362 Determine whether a connection error is retryable or fatal.
363
364 When reconnecting automatically with ``async for ... in connect(...)``
365 (:mod:`asyncio`, :mod:`trio`) or ``for ... in reconnect(...)``
366 (:mod:`threading`), whenever a connection attempt fails,
367 :func:`process_exception` determines whether to retry connecting or to raise
368 the exception.
369
370 This function defines the default behavior, which is to retry on:
371
372 * :exc:`OSError` and :exc:`asyncio.TimeoutError`: network errors;
373 * :exc:`~websockets.exceptions.InvalidMessage` when it stems from an
374 :exc:`EOFError`: also network errors;
375 * :exc:`~websockets.exceptions.InvalidStatus` when the status code is 500,
376 502, 503, or 504: server or proxy errors.
377
378 All other exceptions are considered fatal.
379
380 You can change this behavior with the ``process_exception`` argument of
381 :func:`~websockets.asyncio.client.connect` (:mod:`asyncio`),
382 :func:`~websockets.trio.client.connect` (:mod:`trio`), or
383 :func:`~websockets.sync.client.reconnect` (:mod:`threading`).
384
385 Return :obj:`None` if the exception is retryable i.e. when the error could
386 be transient and trying to reconnect with the same parameters could succeed.
387 The exception will be logged at the ``INFO`` level.
388
389 Return an exception, either ``exc`` or a new exception, if the exception is
390 fatal i.e. when trying to reconnect will most likely produce the same error.
391 That exception will be raised, breaking out of the retry loop.
392
393 """
394 # This catches python-socks' ProxyConnectionError and ProxyTimeoutError.
395 if isinstance(exc, (OSError, TimeoutError)):
396 return None
397 if isinstance(exc, InvalidMessage) and isinstance(exc.__cause__, EOFError):
398 return None
399 if isinstance(exc, InvalidStatus) and exc.response.status_code in [
400 500, # Internal Server Error
401 502, # Bad Gateway
402 503, # Service Unavailable
403 504, # Gateway Timeout
404 ]:
405 return None
406 return exc
407
408
409 BACKOFF_INITIAL_DELAY = float(os.environ.get("WEBSOCKETS_BACKOFF_INITIAL_DELAY", "5"))
410 BACKOFF_MIN_DELAY = float(os.environ.get("WEBSOCKETS_BACKOFF_MIN_DELAY", "3.1"))
411 BACKOFF_MAX_DELAY = float(os.environ.get("WEBSOCKETS_BACKOFF_MAX_DELAY", "90.0"))
412 BACKOFF_FACTOR = float(os.environ.get("WEBSOCKETS_BACKOFF_FACTOR", "1.618"))
413
414
415 def backoff(
416 initial_delay: float = BACKOFF_INITIAL_DELAY,
417 min_delay: float = BACKOFF_MIN_DELAY,
418 max_delay: float = BACKOFF_MAX_DELAY,
419 factor: float = BACKOFF_FACTOR,
420 ) -> Generator[float]:
421 """
422 Generate a series of backoff delays between reconnection attempts.
423
424 Yields:
425 How many seconds to wait before retrying to connect.
426
427 """
428 # Add a random initial delay between 0 and 5 seconds.
429 # See 7.2.3. Recovering from Abnormal Closure in RFC 6455.
430 yield random.random() * initial_delay
431 delay = min_delay
432 while delay < max_delay:
433 yield delay
434 delay *= factor
435 while True:
436 yield max_delay
437
438
439 lazy_import(
440 globals(),
441 deprecated_aliases={
442 # deprecated in 14.0 - 2024-11-09
443 "WebSocketClientProtocol": ".legacy.client",
444 "connect": ".legacy.client",
445 "unix_connect": ".legacy.client",
446 },
447 )