| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import logging |
| 4 |
import os |
| 5 |
import ssl as ssl_module |
| 6 |
import traceback |
| 7 |
import urllib.parse |
| 8 |
from collections.abc import AsyncIterator, Generator, Sequence |
| 9 |
from types import TracebackType |
| 10 |
from typing import Any, Callable, Literal |
| 11 |
|
| 12 |
import trio |
| 13 |
|
| 14 |
from ..client import ClientProtocol, backoff, process_exception |
| 15 |
from ..datastructures import Headers, HeadersLike |
| 16 |
from ..exceptions import ( |
| 17 |
InvalidProxyMessage, |
| 18 |
InvalidProxyStatus, |
| 19 |
InvalidStatus, |
| 20 |
ProxyError, |
| 21 |
SecurityError, |
| 22 |
) |
| 23 |
from ..extensions.base import ClientExtensionFactory |
| 24 |
from ..extensions.permessage_deflate import enable_client_permessage_deflate |
| 25 |
from ..headers import validate_subprotocols |
| 26 |
from ..http11 import USER_AGENT, Response |
| 27 |
from ..protocol import CONNECTING, Event |
| 28 |
from ..proxy import Proxy, get_proxy, parse_proxy, prepare_connect_request |
| 29 |
from ..streams import StreamReader |
| 30 |
from ..typing import LoggerLike, Origin, PathLike, Subprotocol |
| 31 |
from ..uri import WebSocketURI, parse_uri |
| 32 |
from .connection import Connection |
| 33 |
from .utils import race_events |
| 34 |
|
| 35 |
|
| 36 |
__all__ = ["connect", "unix_connect", "ClientConnection"] |
| 37 |
|
| 38 |
MAX_REDIRECTS = int(os.environ.get("WEBSOCKETS_MAX_REDIRECTS", "10")) |
| 39 |
|
| 40 |
|
| 41 |
class ClientConnection(Connection): |
| 42 |
""" |
| 43 |
:mod:`trio` implementation of a WebSocket client connection. |
| 44 |
|
| 45 |
:class:`ClientConnection` provides :meth:`recv` and :meth:`send` coroutines |
| 46 |
for receiving and sending messages. |
| 47 |
|
| 48 |
It supports asynchronous iteration to receive messages:: |
| 49 |
|
| 50 |
async for message in websocket: |
| 51 |
await process(message) |
| 52 |
|
| 53 |
The iterator exits normally when the connection is closed with close code |
| 54 |
1000 (OK) or 1001 (going away) or without a close code. It raises a |
| 55 |
:exc:`~websockets.exceptions.ConnectionClosedError` when the connection is |
| 56 |
closed with any other code. |
| 57 |
|
| 58 |
The ``ping_interval``, ``ping_timeout``, ``close_timeout``, and |
| 59 |
``max_queue`` arguments have the same meaning as in :func:`connect`. |
| 60 |
|
| 61 |
Args: |
| 62 |
nursery: Trio nursery. |
| 63 |
stream: Trio stream connected to a WebSocket server. |
| 64 |
protocol: Sans-I/O connection. |
| 65 |
|
| 66 |
""" |
| 67 |
|
| 68 |
def __init__( |
| 69 |
self, |
| 70 |
nursery: trio.Nursery, |
| 71 |
stream: trio.abc.Stream, |
| 72 |
protocol: ClientProtocol, |
| 73 |
*, |
| 74 |
ping_interval: float | None = 20, |
| 75 |
ping_timeout: float | None = 20, |
| 76 |
close_timeout: float | None = 10, |
| 77 |
max_queue: int | None | tuple[int | None, int | None] = 16, |
| 78 |
) -> None: |
| 79 |
self.protocol: ClientProtocol |
| 80 |
super().__init__( |
| 81 |
nursery, |
| 82 |
stream, |
| 83 |
protocol, |
| 84 |
ping_interval=ping_interval, |
| 85 |
ping_timeout=ping_timeout, |
| 86 |
close_timeout=close_timeout, |
| 87 |
max_queue=max_queue, |
| 88 |
) |
| 89 |
self.response_rcvd = trio.Event() |
| 90 |
|
| 91 |
async def handshake( |
| 92 |
self, |
| 93 |
additional_headers: HeadersLike | None = None, |
| 94 |
user_agent_header: str | None = USER_AGENT, |
| 95 |
) -> None: |
| 96 |
""" |
| 97 |
Perform the opening handshake. |
| 98 |
|
| 99 |
""" |
| 100 |
self.request = self.protocol.connect() |
| 101 |
if additional_headers is not None: |
| 102 |
self.request.headers.update(additional_headers) |
| 103 |
if user_agent_header is not None: |
| 104 |
self.request.headers.setdefault("User-Agent", user_agent_header) |
| 105 |
async with self.send_context(expected_state=CONNECTING): |
| 106 |
self.protocol.send_request(self.request) |
| 107 |
|
| 108 |
await race_events(self.response_rcvd, self.stream_closed) |
| 109 |
|
| 110 |
# self.protocol.handshake_exc is set when the connection is lost before |
| 111 |
# receiving a response, when the response cannot be parsed, or when the |
| 112 |
# response fails the handshake. |
| 113 |
|
| 114 |
if self.protocol.handshake_exc is not None: |
| 115 |
raise self.protocol.handshake_exc |
| 116 |
|
| 117 |
def process_event(self, event: Event) -> None: |
| 118 |
""" |
| 119 |
Process one incoming event. |
| 120 |
|
| 121 |
""" |
| 122 |
# First event - handshake response. |
| 123 |
if self.response is None: |
| 124 |
assert isinstance(event, Response) |
| 125 |
self.response = event |
| 126 |
self.response_rcvd.set() |
| 127 |
# Later events - frames. |
| 128 |
else: |
| 129 |
super().process_event(event) |
| 130 |
|
| 131 |
|
| 132 |
# This is spelled in lower case because it's exposed as a callable in the API. |
| 133 |
class connect: |
| 134 |
""" |
| 135 |
Connect to the WebSocket server at ``uri``. |
| 136 |
|
| 137 |
:func:`connect` should be treated as an asynchronous context manager |
| 138 |
yielding a :class:`ClientConnection`, which can then receive and send |
| 139 |
messages:: |
| 140 |
|
| 141 |
from websockets.trio.client import connect |
| 142 |
|
| 143 |
async with connect(...) as websocket: |
| 144 |
... |
| 145 |
|
| 146 |
The connection is closed automatically when exiting the context. |
| 147 |
|
| 148 |
:func:`connect` can also be treated as an infinite asynchronous iterator |
| 149 |
to reconnect automatically on errors:: |
| 150 |
|
| 151 |
async for websocket in connect(...): |
| 152 |
try: |
| 153 |
... |
| 154 |
except websockets.exceptions.ConnectionClosed: |
| 155 |
continue |
| 156 |
|
| 157 |
If the connection fails with a transient error, it is retried with |
| 158 |
exponential backoff. If it fails with a fatal error, the exception is |
| 159 |
raised, breaking out of the loop. |
| 160 |
|
| 161 |
The connection is closed automatically after each iteration of the loop. |
| 162 |
|
| 163 |
:func:`connect` cannot be awaited directly. This is because it runs a task |
| 164 |
to manage the connection and Trio doesn't support spawning tasks without a |
| 165 |
context that ensures completion. |
| 166 |
|
| 167 |
Args: |
| 168 |
uri: URI of the WebSocket server. |
| 169 |
stream: Preexisting TCP stream. ``stream`` overrides the host and port |
| 170 |
from ``uri``. You may call :func:`~trio.open_tcp_stream` to create a |
| 171 |
suitable TCP stream. |
| 172 |
ssl: Configuration for enabling TLS on the connection. |
| 173 |
server_hostname: Host name for the TLS handshake. ``server_hostname`` |
| 174 |
overrides the host name from ``uri``. |
| 175 |
origin: Value of the ``Origin`` header, for servers that require it. |
| 176 |
extensions: List of supported extensions, in order in which they |
| 177 |
should be negotiated and run. |
| 178 |
subprotocols: List of supported subprotocols, in order of decreasing |
| 179 |
preference. |
| 180 |
compression: The "permessage-deflate" extension is enabled by default. |
| 181 |
Set ``compression`` to :obj:`None` to disable it. See the |
| 182 |
:doc:`compression guide <../../topics/compression>` for details. |
| 183 |
additional_headers: Arbitrary HTTP headers to add to the handshake |
| 184 |
request. |
| 185 |
user_agent_header: Value of the ``User-Agent`` request header. |
| 186 |
It defaults to ``"Python/x.y.z websockets/X.Y"``. |
| 187 |
Setting it to :obj:`None` removes the header. |
| 188 |
proxy: If a proxy is configured, it is used by default. Set ``proxy`` |
| 189 |
to :obj:`None` to disable the proxy or to the address of a proxy |
| 190 |
to override the system configuration. See the :doc:`proxy docs |
| 191 |
<../../topics/proxies>` for details. |
| 192 |
proxy_ssl: Configuration for enabling TLS on the proxy connection. |
| 193 |
proxy_server_hostname: Host name for the TLS handshake with the proxy. |
| 194 |
``proxy_server_hostname`` overrides the host name from ``proxy``. |
| 195 |
process_exception: When reconnecting automatically, tell whether an |
| 196 |
error is transient or fatal. The default behavior is defined by |
| 197 |
:func:`~websockets.client.process_exception`. Refer to its |
| 198 |
documentation for details. |
| 199 |
open_timeout: Timeout for opening the connection in seconds. |
| 200 |
:obj:`None` disables the timeout. |
| 201 |
ping_interval: Interval between keepalive pings in seconds. |
| 202 |
:obj:`None` disables keepalive. |
| 203 |
ping_timeout: Timeout for keepalive pings in seconds. |
| 204 |
:obj:`None` disables timeouts. |
| 205 |
close_timeout: Timeout for closing the connection in seconds. |
| 206 |
:obj:`None` disables the timeout. |
| 207 |
reconnect_delays: Delays in seconds between reconnection attempts. |
| 208 |
Default is exponential backoff with 5s jitter, capped at 60s. |
| 209 |
max_size: Maximum size of incoming messages in bytes. |
| 210 |
:obj:`None` disables the limit. You may pass a ``(max_message_size, |
| 211 |
max_fragment_size)`` tuple to set different limits for messages and |
| 212 |
fragments when you expect long messages sent in short fragments. |
| 213 |
max_queue: High-water mark of the buffer where frames are received. |
| 214 |
It defaults to 16 frames. The low-water mark defaults to ``max_queue |
| 215 |
// 4``. You may pass a ``(high, low)`` tuple to set the high-water |
| 216 |
and low-water marks. If you want to disable flow control entirely, |
| 217 |
you may set it to ``None``, although that's a bad idea. |
| 218 |
logger: Logger for this client. |
| 219 |
It defaults to ``logging.getLogger("websockets.client")``. |
| 220 |
See the :doc:`logging guide <../../topics/logging>` for details. |
| 221 |
create_connection: Factory for the :class:`ClientConnection` managing |
| 222 |
the connection. Set it to a wrapper or a subclass to customize |
| 223 |
connection handling. |
| 224 |
|
| 225 |
Any other keyword arguments are passed to :func:`~trio.open_tcp_stream`. |
| 226 |
For example, you can set ``host`` and ``port`` to connect to a different |
| 227 |
host and port from those found in ``uri``. This only changes the destination |
| 228 |
of the TCP connection. The host name from ``uri`` is still used in the TLS |
| 229 |
handshake for secure connections and in the ``Host`` header. |
| 230 |
|
| 231 |
Raises: |
| 232 |
InvalidURI: If ``uri`` isn't a valid WebSocket URI. |
| 233 |
InvalidProxy: If ``proxy`` isn't a valid proxy. |
| 234 |
OSError: If the TCP connection fails. |
| 235 |
InvalidHandshake: If the opening handshake fails. |
| 236 |
TimeoutError: If the opening handshake times out. |
| 237 |
|
| 238 |
""" |
| 239 |
|
| 240 |
# Arguments of type SSLContext don't render correctly in the documentation |
| 241 |
# because of https://github.com/sphinx-doc/sphinx/issues/13838. |
| 242 |
|
| 243 |
def __init__( |
| 244 |
self, |
| 245 |
uri: str, |
| 246 |
*, |
| 247 |
# TCP/TLS |
| 248 |
stream: trio.abc.Stream | None = None, |
| 249 |
ssl: ssl_module.SSLContext | None = None, |
| 250 |
server_hostname: str | None = None, |
| 251 |
# WebSocket |
| 252 |
origin: Origin | None = None, |
| 253 |
extensions: Sequence[ClientExtensionFactory] | None = None, |
| 254 |
subprotocols: Sequence[Subprotocol] | None = None, |
| 255 |
compression: str | None = "deflate", |
| 256 |
# HTTP |
| 257 |
additional_headers: HeadersLike | None = None, |
| 258 |
user_agent_header: str | None = USER_AGENT, |
| 259 |
proxy: str | Literal[True] | None = True, |
| 260 |
proxy_ssl: ssl_module.SSLContext | None = None, |
| 261 |
proxy_server_hostname: str | None = None, |
| 262 |
process_exception: Callable[[Exception], Exception | None] = process_exception, |
| 263 |
# Timeouts |
| 264 |
open_timeout: float | None = 10, |
| 265 |
ping_interval: float | None = 20, |
| 266 |
ping_timeout: float | None = 20, |
| 267 |
close_timeout: float | None = 10, |
| 268 |
reconnect_delays: Callable[[], Generator[float]] = backoff, |
| 269 |
# Limits |
| 270 |
max_size: int | None | tuple[int | None, int | None] = 2**20, |
| 271 |
max_queue: int | None | tuple[int | None, int | None] = 16, |
| 272 |
# Logging |
| 273 |
logger: LoggerLike | None = None, |
| 274 |
# Escape hatch for advanced customization |
| 275 |
create_connection: type[ClientConnection] | None = None, |
| 276 |
# Other keyword arguments are passed to trio.open_tcp_stream |
| 277 |
**kwargs: Any, |
| 278 |
) -> None: |
| 279 |
self.uri = uri |
| 280 |
self.ws_uri = parse_uri(uri) |
| 281 |
if not self.ws_uri.secure and ssl is not None: |
| 282 |
raise ValueError("ssl argument is incompatible with a ws:// URI") |
| 283 |
|
| 284 |
if subprotocols is not None: |
| 285 |
validate_subprotocols(subprotocols) |
| 286 |
|
| 287 |
if compression == "deflate": |
| 288 |
extensions = enable_client_permessage_deflate(extensions) |
| 289 |
elif compression is not None: |
| 290 |
raise ValueError(f"unsupported compression: {compression}") |
| 291 |
|
| 292 |
if logger is None: |
| 293 |
logger = logging.getLogger("websockets.client") |
| 294 |
|
| 295 |
if create_connection is None: |
| 296 |
create_connection = ClientConnection |
| 297 |
|
| 298 |
self.stream = stream |
| 299 |
self.ssl = ssl |
| 300 |
self.server_hostname = server_hostname |
| 301 |
self.additional_headers = additional_headers |
| 302 |
self.user_agent_header = user_agent_header |
| 303 |
self.proxy = proxy |
| 304 |
self.proxy_ssl = proxy_ssl |
| 305 |
self.proxy_server_hostname = proxy_server_hostname |
| 306 |
self.process_exception = process_exception |
| 307 |
self.open_timeout = open_timeout |
| 308 |
self.reconnect_delays = reconnect_delays |
| 309 |
self.logger = logger |
| 310 |
self.create_connection = create_connection |
| 311 |
self.open_tcp_stream_kwargs = kwargs |
| 312 |
self.protocol_kwargs = dict( |
| 313 |
origin=origin, |
| 314 |
extensions=extensions, |
| 315 |
subprotocols=subprotocols, |
| 316 |
max_size=max_size, |
| 317 |
logger=logger, |
| 318 |
) |
| 319 |
self.connection_kwargs = dict( |
| 320 |
ping_interval=ping_interval, |
| 321 |
ping_timeout=ping_timeout, |
| 322 |
close_timeout=close_timeout, |
| 323 |
max_queue=max_queue, |
| 324 |
) |
| 325 |
|
| 326 |
async def open_tcp_stream(self) -> trio.abc.Stream: |
| 327 |
"""Open a TCP or Unix connection to the server, possibly through a proxy.""" |
| 328 |
kwargs = self.open_tcp_stream_kwargs.copy() |
| 329 |
unix = kwargs.pop("unix", False) |
| 330 |
|
| 331 |
proxy = self.proxy |
| 332 |
if unix: |
| 333 |
proxy = None |
| 334 |
if proxy is True: |
| 335 |
proxy = get_proxy(self.ws_uri) |
| 336 |
|
| 337 |
if unix: |
| 338 |
return await trio.open_unix_socket(kwargs.pop("path")) |
| 339 |
|
| 340 |
elif proxy is not None: |
| 341 |
proxy_parsed = parse_proxy(proxy) |
| 342 |
|
| 343 |
if proxy_parsed.scheme[:5] == "socks": |
| 344 |
return await connect_socks_proxy( |
| 345 |
proxy_parsed, |
| 346 |
self.ws_uri, |
| 347 |
# websockets is consistent with trio while python_socks is |
| 348 |
# consistent across implementations. |
| 349 |
local_addr=kwargs.pop("local_address", None), |
| 350 |
) |
| 351 |
|
| 352 |
elif proxy_parsed.scheme[:4] == "http": |
| 353 |
if proxy_parsed.scheme != "https" and self.proxy_ssl is not None: |
| 354 |
raise ValueError( |
| 355 |
"proxy_ssl argument is incompatible with an http:// proxy" |
| 356 |
) |
| 357 |
return await connect_http_proxy( |
| 358 |
proxy_parsed, |
| 359 |
self.ws_uri, |
| 360 |
user_agent_header=self.user_agent_header, |
| 361 |
ssl=self.proxy_ssl, |
| 362 |
server_hostname=self.proxy_server_hostname, |
| 363 |
**kwargs, |
| 364 |
) |
| 365 |
|
| 366 |
else: |
| 367 |
raise AssertionError("parse_proxy returned unsupported proxy") |
| 368 |
|
| 369 |
else: # proxy is None |
| 370 |
kwargs.setdefault("host", self.ws_uri.host) |
| 371 |
kwargs.setdefault("port", self.ws_uri.port) |
| 372 |
return await trio.open_tcp_stream(**kwargs) |
| 373 |
|
| 374 |
async def enable_tls(self, stream: trio.abc.Stream) -> trio.abc.Stream: |
| 375 |
"""Enable TLS on the connection.""" |
| 376 |
if self.ssl is None: |
| 377 |
ssl = ssl_module.create_default_context() |
| 378 |
else: |
| 379 |
ssl = self.ssl |
| 380 |
if self.server_hostname is None: |
| 381 |
server_hostname = self.ws_uri.host |
| 382 |
else: |
| 383 |
server_hostname = self.server_hostname |
| 384 |
ssl_stream = trio.SSLStream( |
| 385 |
stream, |
| 386 |
ssl, |
| 387 |
server_hostname=server_hostname, |
| 388 |
https_compatible=True, |
| 389 |
) |
| 390 |
await ssl_stream.do_handshake() |
| 391 |
return ssl_stream |
| 392 |
|
| 393 |
async def open_connection(self, nursery: trio.Nursery) -> ClientConnection: |
| 394 |
"""Create a WebSocket connection.""" |
| 395 |
if self.stream is None: |
| 396 |
stream = await self.open_tcp_stream() |
| 397 |
else: |
| 398 |
stream = self.stream |
| 399 |
|
| 400 |
try: |
| 401 |
if self.ws_uri.secure: |
| 402 |
stream = await self.enable_tls(stream) |
| 403 |
|
| 404 |
protocol = ClientProtocol( |
| 405 |
self.ws_uri, |
| 406 |
**self.protocol_kwargs, # type: ignore |
| 407 |
) |
| 408 |
|
| 409 |
# self.create_connection defaults to ClientConnection. |
| 410 |
connection = self.create_connection( |
| 411 |
nursery, |
| 412 |
stream, |
| 413 |
protocol, |
| 414 |
**self.connection_kwargs, # type: ignore |
| 415 |
) |
| 416 |
|
| 417 |
await connection.handshake( |
| 418 |
self.additional_headers, |
| 419 |
self.user_agent_header, |
| 420 |
) |
| 421 |
|
| 422 |
except trio.Cancelled: |
| 423 |
await trio.aclose_forcefully(stream) |
| 424 |
# The nursery running this coroutine was canceled. |
| 425 |
# The next checkpoint raises trio.Cancelled. |
| 426 |
# aclose_forcefully() never returns. |
| 427 |
raise AssertionError("nursery should be canceled") |
| 428 |
except Exception: |
| 429 |
# Always close the connection even though keep-alive is the default |
| 430 |
# in HTTP/1.1 because the current implementation ties opening the |
| 431 |
# TCP/TLS connection with initializing the WebSocket protocol. |
| 432 |
await trio.aclose_forcefully(stream) |
| 433 |
raise |
| 434 |
|
| 435 |
return connection |
| 436 |
|
| 437 |
def process_redirect(self, exc: Exception) -> Exception | str: |
| 438 |
""" |
| 439 |
Determine whether a connection error is a redirect that can be followed. |
| 440 |
|
| 441 |
Return the new URI if it's a valid redirect. Else, return an exception. |
| 442 |
|
| 443 |
""" |
| 444 |
if not ( |
| 445 |
isinstance(exc, InvalidStatus) |
| 446 |
and exc.response.status_code |
| 447 |
in [ |
| 448 |
300, # Multiple Choices |
| 449 |
301, # Moved Permanently |
| 450 |
302, # Found |
| 451 |
303, # See Other |
| 452 |
307, # Temporary Redirect |
| 453 |
308, # Permanent Redirect |
| 454 |
] |
| 455 |
and "Location" in exc.response.headers |
| 456 |
): |
| 457 |
return exc |
| 458 |
|
| 459 |
old_ws_uri = self.ws_uri |
| 460 |
new_uri = urllib.parse.urljoin(self.uri, exc.response.headers["Location"]) |
| 461 |
new_ws_uri = parse_uri(new_uri) |
| 462 |
|
| 463 |
# If connect() received a stream, it is closed and cannot be reused. |
| 464 |
if self.stream is not None: |
| 465 |
return ValueError( |
| 466 |
f"cannot follow redirect to {new_uri} with a preexisting stream" |
| 467 |
) |
| 468 |
|
| 469 |
# TLS downgrade is forbidden. |
| 470 |
if old_ws_uri.secure and not new_ws_uri.secure: |
| 471 |
return SecurityError(f"cannot follow redirect to non-secure URI {new_uri}") |
| 472 |
|
| 473 |
# Apply restrictions to cross-origin redirects. |
| 474 |
if ( |
| 475 |
old_ws_uri.secure != new_ws_uri.secure |
| 476 |
or old_ws_uri.host != new_ws_uri.host |
| 477 |
or old_ws_uri.port != new_ws_uri.port |
| 478 |
): |
| 479 |
# Cross-origin redirects on Unix sockets don't quite make sense. |
| 480 |
if self.open_tcp_stream_kwargs.get("unix", False): |
| 481 |
return ValueError( |
| 482 |
f"cannot follow cross-origin redirect to {new_uri} " |
| 483 |
f"with a Unix socket" |
| 484 |
) |
| 485 |
|
| 486 |
# Cross-origin redirects when host and port are overridden are ill-defined. |
| 487 |
if ( |
| 488 |
self.open_tcp_stream_kwargs.get("host") is not None |
| 489 |
or self.open_tcp_stream_kwargs.get("port") is not None |
| 490 |
): |
| 491 |
return ValueError( |
| 492 |
f"cannot follow cross-origin redirect to {new_uri} " |
| 493 |
f"with an explicit host or port" |
| 494 |
) |
| 495 |
|
| 496 |
# Strip credentials to avoid leaking them to a different origin. |
| 497 |
if self.additional_headers is not None: |
| 498 |
self.additional_headers = Headers( |
| 499 |
( |
| 500 |
(key, value) |
| 501 |
for key, value in Headers(self.additional_headers).raw_items() |
| 502 |
if key.lower() |
| 503 |
not in ["authorization", "cookie", "proxy-authorization"] |
| 504 |
) |
| 505 |
) |
| 506 |
|
| 507 |
return new_uri |
| 508 |
|
| 509 |
async def connect(self, nursery: trio.Nursery) -> ClientConnection: |
| 510 |
try: |
| 511 |
with ( |
| 512 |
trio.CancelScope() |
| 513 |
if self.open_timeout is None |
| 514 |
else trio.fail_after(self.open_timeout) |
| 515 |
): |
| 516 |
for _ in range(MAX_REDIRECTS): |
| 517 |
try: |
| 518 |
connection = await self.open_connection(nursery) |
| 519 |
except Exception as exc: |
| 520 |
exc_or_uri = self.process_redirect(exc) |
| 521 |
if isinstance(exc_or_uri, Exception): |
| 522 |
# Response isn't a valid redirect; raise the exception. |
| 523 |
if exc_or_uri is exc: |
| 524 |
raise |
| 525 |
else: |
| 526 |
raise exc_or_uri from exc |
| 527 |
else: |
| 528 |
# Response is a valid redirect; follow it. |
| 529 |
self.uri = exc_or_uri |
| 530 |
self.ws_uri = parse_uri(exc_or_uri) |
| 531 |
continue |
| 532 |
|
| 533 |
else: |
| 534 |
connection.start_keepalive() |
| 535 |
return connection |
| 536 |
else: |
| 537 |
raise SecurityError(f"more than {MAX_REDIRECTS} redirects") |
| 538 |
|
| 539 |
except trio.TooSlowError as exc: |
| 540 |
# Re-raise exception with an informative error message. |
| 541 |
raise TimeoutError("timed out during opening handshake") from exc |
| 542 |
|
| 543 |
# Do not define __await__ for ... = await nursery.start(connect, ...) |
| 544 |
# because it doesn't look idiomatic in Trio. |
| 545 |
|
| 546 |
# async with connect(...) as ...: ... |
| 547 |
|
| 548 |
async def __aenter__(self) -> ClientConnection: |
| 549 |
await self.__aenter_nursery__() |
| 550 |
try: |
| 551 |
self.connection = await self.connect(self.nursery) |
| 552 |
return self.connection |
| 553 |
except BaseException as exc: |
| 554 |
await self.__aexit_nursery__(type(exc), exc, exc.__traceback__) |
| 555 |
raise AssertionError("expected __aexit_nursery__ to re-raise the exception") |
| 556 |
|
| 557 |
async def __aexit__( |
| 558 |
self, |
| 559 |
exc_type: type[BaseException] | None, |
| 560 |
exc_value: BaseException | None, |
| 561 |
traceback: TracebackType | None, |
| 562 |
) -> None: |
| 563 |
try: |
| 564 |
try: |
| 565 |
await self.connection.aclose() |
| 566 |
finally: |
| 567 |
del self.connection |
| 568 |
finally: |
| 569 |
await self.__aexit_nursery__(exc_type, exc_value, traceback) |
| 570 |
|
| 571 |
async def __aenter_nursery__(self) -> None: |
| 572 |
if hasattr(self, "nursery_manager"): |
| 573 |
raise RuntimeError("connect() isn't reentrant") |
| 574 |
self.nursery_manager = trio.open_nursery() |
| 575 |
self.nursery = await self.nursery_manager.__aenter__() |
| 576 |
|
| 577 |
async def __aexit_nursery__( |
| 578 |
self, |
| 579 |
exc_type: type[BaseException] | None, |
| 580 |
exc_value: BaseException | None, |
| 581 |
traceback: TracebackType | None, |
| 582 |
) -> None: |
| 583 |
# We need a nursery to start the recv_events and keepalive coroutines. |
| 584 |
# They aren't expected to raise exceptions; instead they catch and log |
| 585 |
# all unexpected errors. To keep the nursery an implementation detail, |
| 586 |
# unwrap exceptions raised by user code — per the second option here: |
| 587 |
# https://trio.readthedocs.io/en/stable/reference-core.html#designing-for-multiple-errors |
| 588 |
try: |
| 589 |
await self.nursery_manager.__aexit__(exc_type, exc_value, traceback) |
| 590 |
except BaseException as exc: |
| 591 |
assert isinstance(exc, BaseExceptionGroup) |
| 592 |
try: |
| 593 |
trio._util.raise_single_exception_from_group(exc) |
| 594 |
except trio._util.MultipleExceptionError: |
| 595 |
raise AssertionError( |
| 596 |
"unexpected multiple exceptions; please file a bug report" |
| 597 |
) from exc |
| 598 |
finally: |
| 599 |
del self.nursery_manager |
| 600 |
|
| 601 |
# async for ... in connect(...): |
| 602 |
|
| 603 |
async def __aiter__(self) -> AsyncIterator[ClientConnection]: |
| 604 |
delays: Generator[float] | None = None |
| 605 |
while True: |
| 606 |
try: |
| 607 |
async with self as connection: |
| 608 |
yield connection |
| 609 |
except Exception as exc: |
| 610 |
# Determine whether the exception is retryable or fatal. |
| 611 |
# The API of process_exception is "return an exception or None"; |
| 612 |
# "raise an exception" is also supported because it's a frequent |
| 613 |
# mistake. It isn't documented in order to keep the API simple. |
| 614 |
try: |
| 615 |
new_exc = self.process_exception(exc) |
| 616 |
except Exception as raised_exc: |
| 617 |
new_exc = raised_exc |
| 618 |
|
| 619 |
# The connection failed with a fatal error. |
| 620 |
# Raise the exception and exit the loop. |
| 621 |
if new_exc is exc: |
| 622 |
raise |
| 623 |
if new_exc is not None: |
| 624 |
raise new_exc from exc |
| 625 |
|
| 626 |
# The connection failed with a retryable error. |
| 627 |
# Start or continue backoff and reconnect. |
| 628 |
if delays is None: |
| 629 |
delays = self.reconnect_delays() |
| 630 |
delay = next(delays) |
| 631 |
self.logger.info( |
| 632 |
"connect failed; reconnecting in %.1f seconds: %s", |
| 633 |
delay, |
| 634 |
traceback.format_exception_only(exc)[0].strip(), |
| 635 |
) |
| 636 |
await trio.sleep(delay) |
| 637 |
|
| 638 |
else: |
| 639 |
# The connection succeeded. Reset backoff. |
| 640 |
delays = None |
| 641 |
|
| 642 |
|
| 643 |
def unix_connect( |
| 644 |
path: PathLike | None = None, |
| 645 |
uri: str | None = None, |
| 646 |
**kwargs: Any, |
| 647 |
) -> connect: |
| 648 |
""" |
| 649 |
Connect to a WebSocket server listening on a Unix socket. |
| 650 |
|
| 651 |
This function accepts the same keyword arguments as :func:`connect`. |
| 652 |
|
| 653 |
It's only available on Unix. |
| 654 |
|
| 655 |
It's mainly useful for debugging servers listening on Unix sockets. |
| 656 |
|
| 657 |
Args: |
| 658 |
path: File system path to the Unix socket. |
| 659 |
uri: URI of the WebSocket server. ``uri`` defaults to |
| 660 |
``ws://localhost/`` or, when a ``ssl`` argument is provided, to |
| 661 |
``wss://localhost/``. |
| 662 |
|
| 663 |
""" |
| 664 |
stream = kwargs.get("stream") |
| 665 |
if path is None and stream is None: |
| 666 |
raise ValueError("missing path argument") |
| 667 |
elif path is not None and stream is not None: |
| 668 |
raise ValueError("path is incompatible with stream") |
| 669 |
|
| 670 |
if uri is None: |
| 671 |
if kwargs.get("ssl") is None: |
| 672 |
uri = "ws://localhost/" |
| 673 |
else: |
| 674 |
uri = "wss://localhost/" |
| 675 |
|
| 676 |
return connect(uri=uri, unix=True, path=path, **kwargs) |
| 677 |
|
| 678 |
|
| 679 |
try: |
| 680 |
from python_socks import ProxyType |
| 681 |
from python_socks.async_.trio import Proxy as SocksProxy |
| 682 |
|
| 683 |
except ImportError: |
| 684 |
|
| 685 |
async def connect_socks_proxy( |
| 686 |
proxy: Proxy, |
| 687 |
ws_uri: WebSocketURI, |
| 688 |
**kwargs: Any, |
| 689 |
) -> trio.abc.Stream: |
| 690 |
raise ImportError("connecting through a SOCKS proxy requires python-socks") |
| 691 |
|
| 692 |
else: |
| 693 |
SOCKS_PROXY_TYPES = { |
| 694 |
"socks5h": ProxyType.SOCKS5, |
| 695 |
"socks5": ProxyType.SOCKS5, |
| 696 |
"socks4a": ProxyType.SOCKS4, |
| 697 |
"socks4": ProxyType.SOCKS4, |
| 698 |
} |
| 699 |
|
| 700 |
SOCKS_PROXY_RDNS = { |
| 701 |
"socks5h": True, |
| 702 |
"socks5": False, |
| 703 |
"socks4a": True, |
| 704 |
"socks4": False, |
| 705 |
} |
| 706 |
|
| 707 |
async def connect_socks_proxy( |
| 708 |
proxy: Proxy, |
| 709 |
ws_uri: WebSocketURI, |
| 710 |
**kwargs: Any, |
| 711 |
) -> trio.abc.Stream: |
| 712 |
"""Connect via a SOCKS proxy and return the socket.""" |
| 713 |
socks_proxy = SocksProxy( |
| 714 |
SOCKS_PROXY_TYPES[proxy.scheme], |
| 715 |
proxy.host, |
| 716 |
proxy.port, |
| 717 |
proxy.username, |
| 718 |
proxy.password, |
| 719 |
SOCKS_PROXY_RDNS[proxy.scheme], |
| 720 |
) |
| 721 |
# connect() is documented to raise OSError. |
| 722 |
# socks_proxy.connect() re-raises trio.TooSlowError as ProxyTimeoutError. |
| 723 |
# Wrap other exceptions in ProxyError, a subclass of InvalidHandshake. |
| 724 |
try: |
| 725 |
return trio.SocketStream( |
| 726 |
await socks_proxy.connect(ws_uri.host, ws_uri.port, **kwargs) |
| 727 |
) |
| 728 |
except OSError: |
| 729 |
raise |
| 730 |
except Exception as exc: |
| 731 |
raise ProxyError("failed to connect to SOCKS proxy") from exc |
| 732 |
|
| 733 |
|
| 734 |
async def read_connect_response(stream: trio.abc.Stream) -> Response: |
| 735 |
reader = StreamReader() |
| 736 |
parser = Response.parse( |
| 737 |
reader.read_line, |
| 738 |
reader.read_exact, |
| 739 |
reader.read_to_eof, |
| 740 |
proxy=True, |
| 741 |
) |
| 742 |
try: |
| 743 |
while True: |
| 744 |
data = await stream.receive_some(4096) |
| 745 |
if data: |
| 746 |
reader.feed_data(data) |
| 747 |
else: |
| 748 |
reader.feed_eof() |
| 749 |
next(parser) |
| 750 |
except StopIteration as exc: |
| 751 |
assert isinstance(exc.value, Response) # help mypy |
| 752 |
response = exc.value |
| 753 |
if 200 <= response.status_code < 300: |
| 754 |
return response |
| 755 |
else: |
| 756 |
raise InvalidProxyStatus(response) |
| 757 |
except Exception as exc: |
| 758 |
raise InvalidProxyMessage( |
| 759 |
"did not receive a valid HTTP response from proxy" |
| 760 |
) from exc |
| 761 |
|
| 762 |
|
| 763 |
async def connect_http_proxy( |
| 764 |
proxy: Proxy, |
| 765 |
ws_uri: WebSocketURI, |
| 766 |
*, |
| 767 |
user_agent_header: str | None = None, |
| 768 |
ssl: ssl_module.SSLContext | None = None, |
| 769 |
server_hostname: str | None = None, |
| 770 |
**kwargs: Any, |
| 771 |
) -> trio.abc.Stream: |
| 772 |
stream: trio.abc.Stream |
| 773 |
stream = await trio.open_tcp_stream(proxy.host, proxy.port, **kwargs) |
| 774 |
|
| 775 |
try: |
| 776 |
# Initialize TLS wrapper and perform TLS handshake |
| 777 |
if proxy.scheme == "https": |
| 778 |
if ssl is None: |
| 779 |
ssl = ssl_module.create_default_context() |
| 780 |
if server_hostname is None: |
| 781 |
server_hostname = proxy.host |
| 782 |
ssl_stream = trio.SSLStream( |
| 783 |
stream, |
| 784 |
ssl, |
| 785 |
server_hostname=server_hostname, |
| 786 |
https_compatible=True, |
| 787 |
) |
| 788 |
await ssl_stream.do_handshake() |
| 789 |
stream = ssl_stream |
| 790 |
|
| 791 |
# Send CONNECT request to the proxy and read response. |
| 792 |
request = prepare_connect_request(proxy, ws_uri, user_agent_header) |
| 793 |
await stream.send_all(request) |
| 794 |
await read_connect_response(stream) |
| 795 |
|
| 796 |
except (trio.Cancelled, Exception): |
| 797 |
await trio.aclose_forcefully(stream) |
| 798 |
raise |
| 799 |
|
| 800 |
return stream |