| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import asyncio |
| 4 |
import functools |
| 5 |
import logging |
| 6 |
import os |
| 7 |
import random |
| 8 |
import traceback |
| 9 |
import urllib.parse |
| 10 |
import warnings |
| 11 |
from collections.abc import AsyncIterator, Generator, Sequence |
| 12 |
from types import TracebackType |
| 13 |
from typing import Any, Callable, cast |
| 14 |
|
| 15 |
from ..datastructures import Headers, HeadersLike |
| 16 |
from ..exceptions import ( |
| 17 |
InvalidHeader, |
| 18 |
InvalidHeaderValue, |
| 19 |
InvalidMessage, |
| 20 |
NegotiationError, |
| 21 |
SecurityError, |
| 22 |
) |
| 23 |
from ..extensions import ClientExtensionFactory, Extension |
| 24 |
from ..extensions.permessage_deflate import enable_client_permessage_deflate |
| 25 |
from ..headers import ( |
| 26 |
build_authorization_basic, |
| 27 |
build_extension, |
| 28 |
build_host, |
| 29 |
build_subprotocol, |
| 30 |
parse_extension, |
| 31 |
parse_subprotocol, |
| 32 |
validate_subprotocols, |
| 33 |
) |
| 34 |
from ..http11 import USER_AGENT |
| 35 |
from ..typing import ExtensionHeader, LoggerLike, Origin, Subprotocol |
| 36 |
from ..uri import WebSocketURI, parse_uri |
| 37 |
from .exceptions import InvalidStatusCode, RedirectHandshake |
| 38 |
from .handshake import build_request, check_response |
| 39 |
from .http import read_response |
| 40 |
from .protocol import WebSocketCommonProtocol |
| 41 |
|
| 42 |
|
| 43 |
__all__ = ["connect", "unix_connect", "WebSocketClientProtocol"] |
| 44 |
|
| 45 |
|
| 46 |
class WebSocketClientProtocol(WebSocketCommonProtocol): |
| 47 |
""" |
| 48 |
WebSocket client connection. |
| 49 |
|
| 50 |
:class:`WebSocketClientProtocol` provides :meth:`recv` and :meth:`send` |
| 51 |
coroutines for receiving and sending messages. |
| 52 |
|
| 53 |
It supports asynchronous iteration to receive messages:: |
| 54 |
|
| 55 |
async for message in websocket: |
| 56 |
await process(message) |
| 57 |
|
| 58 |
The iterator exits normally when the connection is closed with close code |
| 59 |
1000 (OK) or 1001 (going away) or without a close code. It raises |
| 60 |
a :exc:`~websockets.exceptions.ConnectionClosedError` when the connection |
| 61 |
is closed with any other code. |
| 62 |
|
| 63 |
See :func:`connect` for the documentation of ``logger``, ``origin``, |
| 64 |
``extensions``, ``subprotocols``, ``extra_headers``, and |
| 65 |
``user_agent_header``. |
| 66 |
|
| 67 |
See :class:`~websockets.legacy.protocol.WebSocketCommonProtocol` for the |
| 68 |
documentation of ``ping_interval``, ``ping_timeout``, ``close_timeout``, |
| 69 |
``max_size``, ``max_queue``, ``read_limit``, and ``write_limit``. |
| 70 |
|
| 71 |
""" |
| 72 |
|
| 73 |
is_client = True |
| 74 |
side = "client" |
| 75 |
|
| 76 |
def __init__( |
| 77 |
self, |
| 78 |
*, |
| 79 |
logger: LoggerLike | None = None, |
| 80 |
origin: Origin | None = None, |
| 81 |
extensions: Sequence[ClientExtensionFactory] | None = None, |
| 82 |
subprotocols: Sequence[Subprotocol] | None = None, |
| 83 |
extra_headers: HeadersLike | None = None, |
| 84 |
user_agent_header: str | None = USER_AGENT, |
| 85 |
**kwargs: Any, |
| 86 |
) -> None: |
| 87 |
if logger is None: |
| 88 |
logger = logging.getLogger("websockets.client") |
| 89 |
super().__init__(logger=logger, **kwargs) |
| 90 |
self.origin = origin |
| 91 |
self.available_extensions = extensions |
| 92 |
self.available_subprotocols = subprotocols |
| 93 |
self.extra_headers = extra_headers |
| 94 |
self.user_agent_header = user_agent_header |
| 95 |
|
| 96 |
def write_http_request(self, path: str, headers: Headers) -> None: |
| 97 |
""" |
| 98 |
Write request line and headers to the HTTP request. |
| 99 |
|
| 100 |
""" |
| 101 |
self.path = path |
| 102 |
self.request_headers = headers |
| 103 |
|
| 104 |
if self.debug: |
| 105 |
self.logger.debug("> GET %s HTTP/1.1", path) |
| 106 |
for key, value in headers.raw_items(): |
| 107 |
self.logger.debug("> %s: %s", key, value) |
| 108 |
|
| 109 |
# Since the path and headers only contain ASCII characters, |
| 110 |
# we can keep this simple. |
| 111 |
request = f"GET {path} HTTP/1.1\r\n" |
| 112 |
request += str(headers) |
| 113 |
|
| 114 |
self.transport.write(request.encode()) |
| 115 |
|
| 116 |
async def read_http_response(self) -> tuple[int, Headers]: |
| 117 |
""" |
| 118 |
Read status line and headers from the HTTP response. |
| 119 |
|
| 120 |
If the response contains a body, it may be read from ``self.reader`` |
| 121 |
after this coroutine returns. |
| 122 |
|
| 123 |
Raises: |
| 124 |
InvalidMessage: If the HTTP message is malformed or isn't an |
| 125 |
HTTP/1.1 GET response. |
| 126 |
|
| 127 |
""" |
| 128 |
try: |
| 129 |
status_code, reason, headers = await read_response(self.reader) |
| 130 |
except Exception as exc: |
| 131 |
raise InvalidMessage("did not receive a valid HTTP response") from exc |
| 132 |
|
| 133 |
if self.debug: |
| 134 |
self.logger.debug("< HTTP/1.1 %d %s", status_code, reason) |
| 135 |
for key, value in headers.raw_items(): |
| 136 |
self.logger.debug("< %s: %s", key, value) |
| 137 |
|
| 138 |
self.response_headers = headers |
| 139 |
|
| 140 |
return status_code, self.response_headers |
| 141 |
|
| 142 |
@staticmethod |
| 143 |
def process_extensions( |
| 144 |
headers: Headers, |
| 145 |
available_extensions: Sequence[ClientExtensionFactory] | None, |
| 146 |
) -> list[Extension]: |
| 147 |
""" |
| 148 |
Handle the Sec-WebSocket-Extensions HTTP response header. |
| 149 |
|
| 150 |
Check that each extension is supported, as well as its parameters. |
| 151 |
|
| 152 |
Return the list of accepted extensions. |
| 153 |
|
| 154 |
Raise :exc:`~websockets.exceptions.InvalidHandshake` to abort the |
| 155 |
connection. |
| 156 |
|
| 157 |
:rfc:`6455` leaves the rules up to the specification of each |
| 158 |
:extension. |
| 159 |
|
| 160 |
To provide this level of flexibility, for each extension accepted by |
| 161 |
the server, we check for a match with each extension available in the |
| 162 |
client configuration. If no match is found, an exception is raised. |
| 163 |
|
| 164 |
If several variants of the same extension are accepted by the server, |
| 165 |
it may be configured several times, which won't make sense in general. |
| 166 |
Extensions must implement their own requirements. For this purpose, |
| 167 |
the list of previously accepted extensions is provided. |
| 168 |
|
| 169 |
Other requirements, for example related to mandatory extensions or the |
| 170 |
order of extensions, may be implemented by overriding this method. |
| 171 |
|
| 172 |
""" |
| 173 |
accepted_extensions: list[Extension] = [] |
| 174 |
|
| 175 |
header_values = headers.get_all("Sec-WebSocket-Extensions") |
| 176 |
|
| 177 |
if header_values: |
| 178 |
if available_extensions is None: |
| 179 |
raise NegotiationError("no extensions supported") |
| 180 |
|
| 181 |
parsed_header_values: list[ExtensionHeader] = sum( |
| 182 |
[parse_extension(header_value) for header_value in header_values], [] |
| 183 |
) |
| 184 |
|
| 185 |
for name, response_params in parsed_header_values: |
| 186 |
for extension_factory in available_extensions: |
| 187 |
# Skip non-matching extensions based on their name. |
| 188 |
if extension_factory.name != name: |
| 189 |
continue |
| 190 |
|
| 191 |
# Skip non-matching extensions based on their params. |
| 192 |
try: |
| 193 |
extension = extension_factory.process_response_params( |
| 194 |
response_params, accepted_extensions |
| 195 |
) |
| 196 |
except NegotiationError: |
| 197 |
continue |
| 198 |
|
| 199 |
# Add matching extension to the final list. |
| 200 |
accepted_extensions.append(extension) |
| 201 |
|
| 202 |
# Break out of the loop once we have a match. |
| 203 |
break |
| 204 |
|
| 205 |
# If we didn't break from the loop, no extension in our list |
| 206 |
# matched what the server sent. Fail the connection. |
| 207 |
else: |
| 208 |
raise NegotiationError( |
| 209 |
f"Unsupported extension: " |
| 210 |
f"name = {name}, params = {response_params}" |
| 211 |
) |
| 212 |
|
| 213 |
return accepted_extensions |
| 214 |
|
| 215 |
@staticmethod |
| 216 |
def process_subprotocol( |
| 217 |
headers: Headers, available_subprotocols: Sequence[Subprotocol] | None |
| 218 |
) -> Subprotocol | None: |
| 219 |
""" |
| 220 |
Handle the Sec-WebSocket-Protocol HTTP response header. |
| 221 |
|
| 222 |
Check that it contains exactly one supported subprotocol. |
| 223 |
|
| 224 |
Return the selected subprotocol. |
| 225 |
|
| 226 |
""" |
| 227 |
subprotocol: Subprotocol | None = None |
| 228 |
|
| 229 |
header_values = headers.get_all("Sec-WebSocket-Protocol") |
| 230 |
|
| 231 |
if header_values: |
| 232 |
if available_subprotocols is None: |
| 233 |
raise NegotiationError("no subprotocols supported") |
| 234 |
|
| 235 |
parsed_header_values: Sequence[Subprotocol] = sum( |
| 236 |
[parse_subprotocol(header_value) for header_value in header_values], [] |
| 237 |
) |
| 238 |
|
| 239 |
if len(parsed_header_values) > 1: |
| 240 |
raise InvalidHeaderValue( |
| 241 |
"Sec-WebSocket-Protocol", |
| 242 |
f"multiple values: {', '.join(parsed_header_values)}", |
| 243 |
) |
| 244 |
|
| 245 |
subprotocol = parsed_header_values[0] |
| 246 |
|
| 247 |
if subprotocol not in available_subprotocols: |
| 248 |
raise NegotiationError(f"unsupported subprotocol: {subprotocol}") |
| 249 |
|
| 250 |
return subprotocol |
| 251 |
|
| 252 |
async def handshake( |
| 253 |
self, |
| 254 |
wsuri: WebSocketURI, |
| 255 |
origin: Origin | None = None, |
| 256 |
available_extensions: Sequence[ClientExtensionFactory] | None = None, |
| 257 |
available_subprotocols: Sequence[Subprotocol] | None = None, |
| 258 |
extra_headers: HeadersLike | None = None, |
| 259 |
) -> None: |
| 260 |
""" |
| 261 |
Perform the client side of the opening handshake. |
| 262 |
|
| 263 |
Args: |
| 264 |
wsuri: URI of the WebSocket server. |
| 265 |
origin: Value of the ``Origin`` header. |
| 266 |
extensions: List of supported extensions, in order in which they |
| 267 |
should be negotiated and run. |
| 268 |
subprotocols: List of supported subprotocols, in order of decreasing |
| 269 |
preference. |
| 270 |
extra_headers: Arbitrary HTTP headers to add to the handshake request. |
| 271 |
|
| 272 |
Raises: |
| 273 |
InvalidHandshake: If the handshake fails. |
| 274 |
|
| 275 |
""" |
| 276 |
request_headers = Headers() |
| 277 |
|
| 278 |
request_headers["Host"] = build_host(wsuri.host, wsuri.port, wsuri.secure) |
| 279 |
|
| 280 |
if wsuri.user_info: |
| 281 |
request_headers["Authorization"] = build_authorization_basic( |
| 282 |
*wsuri.user_info |
| 283 |
) |
| 284 |
|
| 285 |
if origin is not None: |
| 286 |
request_headers["Origin"] = origin |
| 287 |
|
| 288 |
key = build_request(request_headers) |
| 289 |
|
| 290 |
if available_extensions is not None: |
| 291 |
extensions_header = build_extension( |
| 292 |
[ |
| 293 |
(extension_factory.name, extension_factory.get_request_params()) |
| 294 |
for extension_factory in available_extensions |
| 295 |
] |
| 296 |
) |
| 297 |
request_headers["Sec-WebSocket-Extensions"] = extensions_header |
| 298 |
|
| 299 |
if available_subprotocols is not None: |
| 300 |
protocol_header = build_subprotocol(available_subprotocols) |
| 301 |
request_headers["Sec-WebSocket-Protocol"] = protocol_header |
| 302 |
|
| 303 |
if self.extra_headers is not None: |
| 304 |
request_headers.update(self.extra_headers) |
| 305 |
|
| 306 |
if self.user_agent_header: |
| 307 |
request_headers.setdefault("User-Agent", self.user_agent_header) |
| 308 |
|
| 309 |
self.write_http_request(wsuri.resource_name, request_headers) |
| 310 |
|
| 311 |
status_code, response_headers = await self.read_http_response() |
| 312 |
if status_code in (301, 302, 303, 307, 308): |
| 313 |
if "Location" not in response_headers: |
| 314 |
raise InvalidHeader("Location") |
| 315 |
raise RedirectHandshake(response_headers["Location"]) |
| 316 |
elif status_code != 101: |
| 317 |
raise InvalidStatusCode(status_code, response_headers) |
| 318 |
|
| 319 |
check_response(response_headers, key) |
| 320 |
|
| 321 |
self.extensions = self.process_extensions( |
| 322 |
response_headers, available_extensions |
| 323 |
) |
| 324 |
|
| 325 |
self.subprotocol = self.process_subprotocol( |
| 326 |
response_headers, available_subprotocols |
| 327 |
) |
| 328 |
|
| 329 |
self.connection_open() |
| 330 |
|
| 331 |
|
| 332 |
class Connect: |
| 333 |
""" |
| 334 |
Connect to the WebSocket server at ``uri``. |
| 335 |
|
| 336 |
Awaiting :func:`connect` yields a :class:`WebSocketClientProtocol` which |
| 337 |
can then be used to send and receive messages. |
| 338 |
|
| 339 |
:func:`connect` can be used as a asynchronous context manager:: |
| 340 |
|
| 341 |
async with connect(...) as websocket: |
| 342 |
... |
| 343 |
|
| 344 |
The connection is closed automatically when exiting the context. |
| 345 |
|
| 346 |
:func:`connect` can be used as an infinite asynchronous iterator to |
| 347 |
reconnect automatically on errors:: |
| 348 |
|
| 349 |
async for websocket in connect(...): |
| 350 |
try: |
| 351 |
... |
| 352 |
except websockets.exceptions.ConnectionClosed: |
| 353 |
continue |
| 354 |
|
| 355 |
The connection is closed automatically after each iteration of the loop. |
| 356 |
|
| 357 |
If an error occurs while establishing the connection, :func:`connect` |
| 358 |
retries with exponential backoff. The backoff delay starts at three |
| 359 |
seconds and increases up to one minute. |
| 360 |
|
| 361 |
If an error occurs in the body of the loop, you can handle the exception |
| 362 |
and :func:`connect` will reconnect with the next iteration; or you can |
| 363 |
let the exception bubble up and break out of the loop. This lets you |
| 364 |
decide which errors trigger a reconnection and which errors are fatal. |
| 365 |
|
| 366 |
Args: |
| 367 |
uri: URI of the WebSocket server. |
| 368 |
create_protocol: Factory for the :class:`asyncio.Protocol` managing |
| 369 |
the connection. It defaults to :class:`WebSocketClientProtocol`. |
| 370 |
Set it to a wrapper or a subclass to customize connection handling. |
| 371 |
logger: Logger for this client. |
| 372 |
It defaults to ``logging.getLogger("websockets.client")``. |
| 373 |
See the :doc:`logging guide <../../topics/logging>` for details. |
| 374 |
compression: The "permessage-deflate" extension is enabled by default. |
| 375 |
Set ``compression`` to :obj:`None` to disable it. See the |
| 376 |
:doc:`compression guide <../../topics/compression>` for details. |
| 377 |
origin: Value of the ``Origin`` header, for servers that require it. |
| 378 |
extensions: List of supported extensions, in order in which they |
| 379 |
should be negotiated and run. |
| 380 |
subprotocols: List of supported subprotocols, in order of decreasing |
| 381 |
preference. |
| 382 |
extra_headers: Arbitrary HTTP headers to add to the handshake request. |
| 383 |
user_agent_header: Value of the ``User-Agent`` request header. |
| 384 |
It defaults to ``"Python/x.y.z websockets/X.Y"``. |
| 385 |
Setting it to :obj:`None` removes the header. |
| 386 |
open_timeout: Timeout for opening the connection in seconds. |
| 387 |
:obj:`None` disables the timeout. |
| 388 |
|
| 389 |
See :class:`~websockets.legacy.protocol.WebSocketCommonProtocol` for the |
| 390 |
documentation of ``ping_interval``, ``ping_timeout``, ``close_timeout``, |
| 391 |
``max_size``, ``max_queue``, ``read_limit``, and ``write_limit``. |
| 392 |
|
| 393 |
Any other keyword arguments are passed the event loop's |
| 394 |
:meth:`~asyncio.loop.create_connection` method. |
| 395 |
|
| 396 |
For example: |
| 397 |
|
| 398 |
* You can set ``ssl`` to a :class:`~ssl.SSLContext` to enforce TLS |
| 399 |
settings. When connecting to a ``wss://`` URI, if ``ssl`` isn't |
| 400 |
provided, a TLS context is created |
| 401 |
with :func:`~ssl.create_default_context`. |
| 402 |
|
| 403 |
* You can set ``host`` and ``port`` to connect to a different host and |
| 404 |
port from those found in ``uri``. This only changes the destination of |
| 405 |
the TCP connection. The host name from ``uri`` is still used in the TLS |
| 406 |
handshake for secure connections and in the ``Host`` header. |
| 407 |
|
| 408 |
Raises: |
| 409 |
InvalidURI: If ``uri`` isn't a valid WebSocket URI. |
| 410 |
OSError: If the TCP connection fails. |
| 411 |
InvalidHandshake: If the opening handshake fails. |
| 412 |
~asyncio.TimeoutError: If the opening handshake times out. |
| 413 |
|
| 414 |
""" |
| 415 |
|
| 416 |
MAX_REDIRECTS_ALLOWED = int(os.environ.get("WEBSOCKETS_MAX_REDIRECTS", "10")) |
| 417 |
|
| 418 |
def __init__( |
| 419 |
self, |
| 420 |
uri: str, |
| 421 |
*, |
| 422 |
create_protocol: Callable[..., WebSocketClientProtocol] | None = None, |
| 423 |
logger: LoggerLike | None = None, |
| 424 |
compression: str | None = "deflate", |
| 425 |
origin: Origin | None = None, |
| 426 |
extensions: Sequence[ClientExtensionFactory] | None = None, |
| 427 |
subprotocols: Sequence[Subprotocol] | None = None, |
| 428 |
extra_headers: HeadersLike | None = None, |
| 429 |
user_agent_header: str | None = USER_AGENT, |
| 430 |
open_timeout: float | None = 10, |
| 431 |
ping_interval: float | None = 20, |
| 432 |
ping_timeout: float | None = 20, |
| 433 |
close_timeout: float | None = None, |
| 434 |
max_size: int | None = 2**20, |
| 435 |
max_queue: int | None = 2**5, |
| 436 |
read_limit: int = 2**16, |
| 437 |
write_limit: int = 2**16, |
| 438 |
**kwargs: Any, |
| 439 |
) -> None: |
| 440 |
# Backwards compatibility: close_timeout used to be called timeout. |
| 441 |
timeout: float | None = kwargs.pop("timeout", None) |
| 442 |
if timeout is None: |
| 443 |
timeout = 10 |
| 444 |
else: |
| 445 |
warnings.warn("rename timeout to close_timeout", DeprecationWarning) |
| 446 |
# If both are specified, timeout is ignored. |
| 447 |
if close_timeout is None: |
| 448 |
close_timeout = timeout |
| 449 |
|
| 450 |
# Backwards compatibility: create_protocol used to be called klass. |
| 451 |
klass: type[WebSocketClientProtocol] | None = kwargs.pop("klass", None) |
| 452 |
if klass is None: |
| 453 |
klass = WebSocketClientProtocol |
| 454 |
else: |
| 455 |
warnings.warn("rename klass to create_protocol", DeprecationWarning) |
| 456 |
# If both are specified, klass is ignored. |
| 457 |
if create_protocol is None: |
| 458 |
create_protocol = klass |
| 459 |
|
| 460 |
# Backwards compatibility: recv() used to return None on closed connections |
| 461 |
legacy_recv: bool = kwargs.pop("legacy_recv", False) |
| 462 |
|
| 463 |
# Backwards compatibility: the loop parameter used to be supported. |
| 464 |
_loop: asyncio.AbstractEventLoop | None = kwargs.pop("loop", None) |
| 465 |
if _loop is None: |
| 466 |
loop = asyncio.get_event_loop() |
| 467 |
else: |
| 468 |
loop = _loop |
| 469 |
warnings.warn("remove loop argument", DeprecationWarning) |
| 470 |
|
| 471 |
wsuri = parse_uri(uri) |
| 472 |
if wsuri.secure: |
| 473 |
kwargs.setdefault("ssl", True) |
| 474 |
elif kwargs.get("ssl") is not None: |
| 475 |
raise ValueError( |
| 476 |
"connect() received a ssl argument for a ws:// URI, " |
| 477 |
"use a wss:// URI to enable TLS" |
| 478 |
) |
| 479 |
|
| 480 |
if compression == "deflate": |
| 481 |
extensions = enable_client_permessage_deflate(extensions) |
| 482 |
elif compression is not None: |
| 483 |
raise ValueError(f"unsupported compression: {compression}") |
| 484 |
|
| 485 |
if subprotocols is not None: |
| 486 |
validate_subprotocols(subprotocols) |
| 487 |
|
| 488 |
# Help mypy and avoid this error: "type[WebSocketClientProtocol] | |
| 489 |
# Callable[..., WebSocketClientProtocol]" not callable [misc] |
| 490 |
create_protocol = cast(Callable[..., WebSocketClientProtocol], create_protocol) |
| 491 |
factory = functools.partial( |
| 492 |
create_protocol, |
| 493 |
logger=logger, |
| 494 |
origin=origin, |
| 495 |
extensions=extensions, |
| 496 |
subprotocols=subprotocols, |
| 497 |
extra_headers=extra_headers, |
| 498 |
user_agent_header=user_agent_header, |
| 499 |
ping_interval=ping_interval, |
| 500 |
ping_timeout=ping_timeout, |
| 501 |
close_timeout=close_timeout, |
| 502 |
max_size=max_size, |
| 503 |
max_queue=max_queue, |
| 504 |
read_limit=read_limit, |
| 505 |
write_limit=write_limit, |
| 506 |
host=wsuri.host, |
| 507 |
port=wsuri.port, |
| 508 |
secure=wsuri.secure, |
| 509 |
legacy_recv=legacy_recv, |
| 510 |
loop=_loop, |
| 511 |
) |
| 512 |
|
| 513 |
if kwargs.pop("unix", False): |
| 514 |
path: str | None = kwargs.pop("path", None) |
| 515 |
create_connection = functools.partial( |
| 516 |
loop.create_unix_connection, factory, path, **kwargs |
| 517 |
) |
| 518 |
else: |
| 519 |
host: str | None |
| 520 |
port: int | None |
| 521 |
if kwargs.get("sock") is None: |
| 522 |
host, port = wsuri.host, wsuri.port |
| 523 |
else: |
| 524 |
# If sock is given, host and port shouldn't be specified. |
| 525 |
host, port = None, None |
| 526 |
if kwargs.get("ssl"): |
| 527 |
kwargs.setdefault("server_hostname", wsuri.host) |
| 528 |
# If host and port are given, override values from the URI. |
| 529 |
host = kwargs.pop("host", host) |
| 530 |
port = kwargs.pop("port", port) |
| 531 |
create_connection = functools.partial( |
| 532 |
loop.create_connection, factory, host, port, **kwargs |
| 533 |
) |
| 534 |
|
| 535 |
self.open_timeout = open_timeout |
| 536 |
if logger is None: |
| 537 |
logger = logging.getLogger("websockets.client") |
| 538 |
self.logger = logger |
| 539 |
|
| 540 |
# This is a coroutine function. |
| 541 |
self._create_connection = create_connection |
| 542 |
self._uri = uri |
| 543 |
self._wsuri = wsuri |
| 544 |
|
| 545 |
def handle_redirect(self, uri: str) -> None: |
| 546 |
# Update the state of this instance to connect to a new URI. |
| 547 |
old_uri = self._uri |
| 548 |
old_wsuri = self._wsuri |
| 549 |
new_uri = urllib.parse.urljoin(old_uri, uri) |
| 550 |
new_wsuri = parse_uri(new_uri) |
| 551 |
|
| 552 |
# Forbid TLS downgrade. |
| 553 |
if old_wsuri.secure and not new_wsuri.secure: |
| 554 |
raise SecurityError("redirect from WSS to WS") |
| 555 |
|
| 556 |
same_origin = ( |
| 557 |
old_wsuri.secure == new_wsuri.secure |
| 558 |
and old_wsuri.host == new_wsuri.host |
| 559 |
and old_wsuri.port == new_wsuri.port |
| 560 |
) |
| 561 |
|
| 562 |
# Rewrite secure, host, and port for cross-origin redirects. |
| 563 |
# This preserves connection overrides with the host and port |
| 564 |
# arguments if the redirect points to the same host and port. |
| 565 |
if not same_origin: |
| 566 |
factory = self._create_connection.args[0] |
| 567 |
# Support TLS upgrade. |
| 568 |
if not old_wsuri.secure and new_wsuri.secure: |
| 569 |
factory.keywords["secure"] = True |
| 570 |
self._create_connection.keywords.setdefault("ssl", True) |
| 571 |
# Strip credentials to avoid leaking them to a different origin. |
| 572 |
extra_headers = factory.keywords.get("extra_headers") |
| 573 |
if extra_headers is not None: # pragma: no cover |
| 574 |
factory.keywords["extra_headers"] = Headers( |
| 575 |
( |
| 576 |
(key, value) |
| 577 |
for key, value in Headers(extra_headers).raw_items() |
| 578 |
if key.lower() |
| 579 |
not in ["authorization", "cookie", "proxy-authorization"] |
| 580 |
) |
| 581 |
) |
| 582 |
# Replace secure, host, and port arguments of the protocol factory. |
| 583 |
factory = functools.partial( |
| 584 |
factory.func, |
| 585 |
*factory.args, |
| 586 |
**dict(factory.keywords, host=new_wsuri.host, port=new_wsuri.port), |
| 587 |
) |
| 588 |
# Replace secure, host, and port arguments of create_connection. |
| 589 |
self._create_connection = functools.partial( |
| 590 |
self._create_connection.func, |
| 591 |
*(factory, new_wsuri.host, new_wsuri.port), |
| 592 |
**self._create_connection.keywords, |
| 593 |
) |
| 594 |
|
| 595 |
# Set the new WebSocket URI. This suffices for same-origin redirects. |
| 596 |
self._uri = new_uri |
| 597 |
self._wsuri = new_wsuri |
| 598 |
|
| 599 |
# async for ... in connect(...): |
| 600 |
|
| 601 |
BACKOFF_INITIAL = float(os.environ.get("WEBSOCKETS_BACKOFF_INITIAL_DELAY", "5")) |
| 602 |
BACKOFF_MIN = float(os.environ.get("WEBSOCKETS_BACKOFF_MIN_DELAY", "3.1")) |
| 603 |
BACKOFF_MAX = float(os.environ.get("WEBSOCKETS_BACKOFF_MAX_DELAY", "90.0")) |
| 604 |
BACKOFF_FACTOR = float(os.environ.get("WEBSOCKETS_BACKOFF_FACTOR", "1.618")) |
| 605 |
|
| 606 |
async def __aiter__(self) -> AsyncIterator[WebSocketClientProtocol]: |
| 607 |
backoff_delay = self.BACKOFF_MIN / self.BACKOFF_FACTOR |
| 608 |
while True: |
| 609 |
try: |
| 610 |
async with self as protocol: |
| 611 |
yield protocol |
| 612 |
except Exception as exc: |
| 613 |
# Add a random initial delay between 0 and 5 seconds. |
| 614 |
# See 7.2.3. Recovering from Abnormal Closure in RFC 6455. |
| 615 |
if backoff_delay == self.BACKOFF_MIN: |
| 616 |
initial_delay = random.random() * self.BACKOFF_INITIAL |
| 617 |
self.logger.info( |
| 618 |
"connect failed; reconnecting in %.1f seconds: %s", |
| 619 |
initial_delay, |
| 620 |
traceback.format_exception_only(exc)[0].strip(), |
| 621 |
) |
| 622 |
await asyncio.sleep(initial_delay) |
| 623 |
else: |
| 624 |
self.logger.info( |
| 625 |
"connect failed again; retrying in %d seconds: %s", |
| 626 |
int(backoff_delay), |
| 627 |
traceback.format_exception_only(exc)[0].strip(), |
| 628 |
) |
| 629 |
await asyncio.sleep(int(backoff_delay)) |
| 630 |
# Increase delay with truncated exponential backoff. |
| 631 |
backoff_delay = backoff_delay * self.BACKOFF_FACTOR |
| 632 |
backoff_delay = min(backoff_delay, self.BACKOFF_MAX) |
| 633 |
continue |
| 634 |
else: |
| 635 |
# Connection succeeded - reset backoff delay |
| 636 |
backoff_delay = self.BACKOFF_MIN |
| 637 |
|
| 638 |
# async with connect(...) as ...: |
| 639 |
|
| 640 |
async def __aenter__(self) -> WebSocketClientProtocol: |
| 641 |
return await self |
| 642 |
|
| 643 |
async def __aexit__( |
| 644 |
self, |
| 645 |
exc_type: type[BaseException] | None, |
| 646 |
exc_value: BaseException | None, |
| 647 |
traceback: TracebackType | None, |
| 648 |
) -> None: |
| 649 |
await self.protocol.close() |
| 650 |
|
| 651 |
# ... = await connect(...) |
| 652 |
|
| 653 |
def __await__(self) -> Generator[Any, None, WebSocketClientProtocol]: |
| 654 |
# Create a suitable iterator by calling __await__ on a coroutine. |
| 655 |
return self.__await_impl__().__await__() |
| 656 |
|
| 657 |
async def __await_impl__(self) -> WebSocketClientProtocol: |
| 658 |
async with asyncio.timeout(self.open_timeout): |
| 659 |
for _redirects in range(self.MAX_REDIRECTS_ALLOWED): |
| 660 |
_transport, protocol = await self._create_connection() |
| 661 |
try: |
| 662 |
await protocol.handshake( |
| 663 |
self._wsuri, |
| 664 |
origin=protocol.origin, |
| 665 |
available_extensions=protocol.available_extensions, |
| 666 |
available_subprotocols=protocol.available_subprotocols, |
| 667 |
extra_headers=protocol.extra_headers, |
| 668 |
) |
| 669 |
except RedirectHandshake as exc: |
| 670 |
protocol.fail_connection() |
| 671 |
await protocol.wait_closed() |
| 672 |
self.handle_redirect(exc.uri) |
| 673 |
# Avoid leaking a connected socket when the handshake fails. |
| 674 |
except (Exception, asyncio.CancelledError): |
| 675 |
protocol.fail_connection() |
| 676 |
await protocol.wait_closed() |
| 677 |
raise |
| 678 |
else: |
| 679 |
self.protocol = protocol |
| 680 |
return protocol |
| 681 |
else: |
| 682 |
raise SecurityError("too many redirects") |
| 683 |
|
| 684 |
|
| 685 |
connect = Connect |
| 686 |
|
| 687 |
|
| 688 |
def unix_connect( |
| 689 |
path: str | None = None, |
| 690 |
uri: str = "ws://localhost/", |
| 691 |
**kwargs: Any, |
| 692 |
) -> Connect: |
| 693 |
""" |
| 694 |
Similar to :func:`connect`, but for connecting to a Unix socket. |
| 695 |
|
| 696 |
This function builds upon the event loop's |
| 697 |
:meth:`~asyncio.loop.create_unix_connection` method. |
| 698 |
|
| 699 |
It is only available on Unix. |
| 700 |
|
| 701 |
It's mainly useful for debugging servers listening on Unix sockets. |
| 702 |
|
| 703 |
Args: |
| 704 |
path: File system path to the Unix socket. |
| 705 |
uri: URI of the WebSocket server; the host is used in the TLS |
| 706 |
handshake for secure connections and in the ``Host`` header. |
| 707 |
|
| 708 |
""" |
| 709 |
return connect(uri=uri, path=path, unix=True, **kwargs) |