| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import logging |
| 4 |
import os |
| 5 |
import socket |
| 6 |
import ssl as ssl_module |
| 7 |
import threading |
| 8 |
import time |
| 9 |
import traceback |
| 10 |
import urllib.parse |
| 11 |
import warnings |
| 12 |
from collections.abc import Generator, Iterator, Sequence |
| 13 |
from types import TracebackType |
| 14 |
from typing import Any, Callable, Literal, TypeVar, cast, overload |
| 15 |
|
| 16 |
from ..client import ClientProtocol, backoff, process_exception |
| 17 |
from ..datastructures import Headers, HeadersLike |
| 18 |
from ..exceptions import ( |
| 19 |
InvalidProxyMessage, |
| 20 |
InvalidProxyStatus, |
| 21 |
InvalidStatus, |
| 22 |
ProxyError, |
| 23 |
SecurityError, |
| 24 |
) |
| 25 |
from ..extensions.base import ClientExtensionFactory |
| 26 |
from ..extensions.permessage_deflate import enable_client_permessage_deflate |
| 27 |
from ..headers import validate_subprotocols |
| 28 |
from ..http11 import USER_AGENT, Response |
| 29 |
from ..protocol import CONNECTING, Event |
| 30 |
from ..proxy import Proxy, get_proxy, parse_proxy, prepare_connect_request |
| 31 |
from ..streams import StreamReader |
| 32 |
from ..typing import BytesLike, LoggerLike, Origin, PathLike, Subprotocol |
| 33 |
from ..uri import WebSocketURI, parse_uri |
| 34 |
from .connection import Connection |
| 35 |
from .utils import Deadline |
| 36 |
|
| 37 |
|
| 38 |
__all__ = ["connect", "unix_connect", "reconnect", "unix_reconnect", "ClientConnection"] |
| 39 |
|
| 40 |
MAX_REDIRECTS = int(os.environ.get("WEBSOCKETS_MAX_REDIRECTS", "10")) |
| 41 |
|
| 42 |
|
| 43 |
class ClientConnection(Connection): |
| 44 |
""" |
| 45 |
:mod:`threading` implementation of a WebSocket client connection. |
| 46 |
|
| 47 |
:class:`ClientConnection` provides :meth:`recv` and :meth:`send` methods for |
| 48 |
receiving and sending messages. |
| 49 |
|
| 50 |
It supports iteration to receive messages:: |
| 51 |
|
| 52 |
for message in websocket: |
| 53 |
process(message) |
| 54 |
|
| 55 |
The iterator exits normally when the connection is closed with code |
| 56 |
1000 (OK) or 1001 (going away) or without a close code. It raises a |
| 57 |
:exc:`~websockets.exceptions.ConnectionClosedError` when the connection is |
| 58 |
closed with any other code. |
| 59 |
|
| 60 |
The ``ping_interval``, ``ping_timeout``, ``close_timeout``, and |
| 61 |
``max_queue`` arguments have the same meaning as in :func:`connect`. |
| 62 |
|
| 63 |
Args: |
| 64 |
socket: Socket connected to a WebSocket server. |
| 65 |
protocol: Sans-I/O connection. |
| 66 |
|
| 67 |
""" |
| 68 |
|
| 69 |
def __init__( |
| 70 |
self, |
| 71 |
sock: socket.socket, |
| 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 |
self.response_rcvd = threading.Event() |
| 81 |
self.pending_legacy_warning = True |
| 82 |
super().__init__( |
| 83 |
sock, |
| 84 |
protocol, |
| 85 |
ping_interval=ping_interval, |
| 86 |
ping_timeout=ping_timeout, |
| 87 |
close_timeout=close_timeout, |
| 88 |
max_queue=max_queue, |
| 89 |
) |
| 90 |
|
| 91 |
def __enter__(self) -> ClientConnection: |
| 92 |
self.pending_legacy_warning = False |
| 93 |
return super().__enter__() |
| 94 |
|
| 95 |
def maybe_raise_legacy_warning(self) -> None: |
| 96 |
if self.pending_legacy_warning: |
| 97 |
self.pending_legacy_warning = False |
| 98 |
warnings.warn( # deprecated in 17.1 |
| 99 |
"connect() must be used as a context manager: " |
| 100 |
"with connect(...) as websocket: ...; alternatively, use " |
| 101 |
"websocket = connect(..., legacy=True) to connect directly", |
| 102 |
DeprecationWarning, |
| 103 |
stacklevel=3, |
| 104 |
) |
| 105 |
|
| 106 |
def handshake( |
| 107 |
self, |
| 108 |
additional_headers: HeadersLike | None = None, |
| 109 |
user_agent_header: str | None = USER_AGENT, |
| 110 |
timeout: float | None = None, |
| 111 |
) -> None: |
| 112 |
""" |
| 113 |
Perform the opening handshake. |
| 114 |
|
| 115 |
""" |
| 116 |
self.request = self.protocol.connect() |
| 117 |
if additional_headers is not None: |
| 118 |
self.request.headers.update(additional_headers) |
| 119 |
if user_agent_header is not None: |
| 120 |
self.request.headers.setdefault("User-Agent", user_agent_header) |
| 121 |
with self.send_context(expected_state=CONNECTING): |
| 122 |
self.protocol.send_request(self.request) |
| 123 |
|
| 124 |
if not self.response_rcvd.wait(timeout): |
| 125 |
raise TimeoutError("timed out while waiting for handshake response") |
| 126 |
|
| 127 |
# self.protocol.handshake_exc is set when the connection is lost before |
| 128 |
# receiving a response, when the response cannot be parsed, or when the |
| 129 |
# response fails the handshake. |
| 130 |
|
| 131 |
if self.protocol.handshake_exc is not None: |
| 132 |
raise self.protocol.handshake_exc |
| 133 |
|
| 134 |
def process_event(self, event: Event) -> None: |
| 135 |
""" |
| 136 |
Process one incoming event. |
| 137 |
|
| 138 |
""" |
| 139 |
# First event - handshake response. |
| 140 |
if self.response is None: |
| 141 |
assert isinstance(event, Response) |
| 142 |
self.response = event |
| 143 |
self.response_rcvd.set() |
| 144 |
# Later events - frames. |
| 145 |
else: |
| 146 |
super().process_event(event) |
| 147 |
|
| 148 |
def recv_events(self) -> None: |
| 149 |
""" |
| 150 |
Read incoming data from the socket and process events. |
| 151 |
|
| 152 |
""" |
| 153 |
try: |
| 154 |
super().recv_events() |
| 155 |
finally: |
| 156 |
# If the connection is closed during the handshake, unblock it. |
| 157 |
self.response_rcvd.set() |
| 158 |
|
| 159 |
|
| 160 |
class reconnect: |
| 161 |
""" |
| 162 |
Similar to :func:`connect`, with support for automatic reconnection. |
| 163 |
|
| 164 |
:func:`reconnect` can also be treated as an infinite iterator to reconnect |
| 165 |
automatically on errors:: |
| 166 |
|
| 167 |
for websocket in reconnect(...): |
| 168 |
try: |
| 169 |
... |
| 170 |
except websockets.exceptions.ConnectionClosed: |
| 171 |
continue |
| 172 |
|
| 173 |
If the connection fails with a transient error, it is retried with |
| 174 |
exponential backoff. If it fails with a fatal error, the exception is |
| 175 |
raised, breaking out of the loop. |
| 176 |
|
| 177 |
The connection is closed automatically after each iteration of the loop. |
| 178 |
|
| 179 |
:func:`reconnect` accepts the same arguments as :func:`connect`, minus the |
| 180 |
``legacy`` flag, plus those listed below. It raises the same exceptions. |
| 181 |
|
| 182 |
Args: |
| 183 |
process_exception: When reconnecting automatically, tell whether an |
| 184 |
error is transient or fatal. The default behavior is defined by |
| 185 |
:func:`~websockets.client.process_exception`. Refer to its |
| 186 |
documentation for details. |
| 187 |
reconnect_delays: Delays in seconds between reconnection attempts. |
| 188 |
Default is exponential backoff with 5s jitter, capped at 60s. |
| 189 |
|
| 190 |
.. admonition:: Why is :func:`reconnect` a separate API from :func:`connect`? |
| 191 |
:class: tip |
| 192 |
|
| 193 |
A new API was necessary to maintain backwards compatibility with this |
| 194 |
historical behavior of :func:`connect`:: |
| 195 |
|
| 196 |
websocket = connect(...) |
| 197 |
for message in websocket: |
| 198 |
... |
| 199 |
|
| 200 |
Once the deprecation period elapses, :func:`connect` will be changed to |
| 201 |
behave like :func:`reconnect` by default. |
| 202 |
|
| 203 |
""" |
| 204 |
|
| 205 |
def __init__( |
| 206 |
self, |
| 207 |
uri: str, |
| 208 |
*, |
| 209 |
# TCP/TLS |
| 210 |
sock: socket.socket | None = None, |
| 211 |
ssl: ssl_module.SSLContext | None = None, |
| 212 |
server_hostname: str | None = None, |
| 213 |
# WebSocket |
| 214 |
origin: Origin | None = None, |
| 215 |
extensions: Sequence[ClientExtensionFactory] | None = None, |
| 216 |
subprotocols: Sequence[Subprotocol] | None = None, |
| 217 |
compression: str | None = "deflate", |
| 218 |
# HTTP |
| 219 |
additional_headers: HeadersLike | None = None, |
| 220 |
user_agent_header: str | None = USER_AGENT, |
| 221 |
proxy: str | Literal[True] | None = True, |
| 222 |
proxy_ssl: ssl_module.SSLContext | None = None, |
| 223 |
proxy_server_hostname: str | None = None, |
| 224 |
process_exception: Callable[[Exception], Exception | None] = process_exception, |
| 225 |
# Timeouts |
| 226 |
open_timeout: float | None = 10, |
| 227 |
ping_interval: float | None = 20, |
| 228 |
ping_timeout: float | None = 20, |
| 229 |
close_timeout: float | None = 10, |
| 230 |
reconnect_delays: Callable[[], Generator[float]] = backoff, |
| 231 |
# Limits |
| 232 |
max_size: int | None | tuple[int | None, int | None] = 2**20, |
| 233 |
max_queue: int | None | tuple[int | None, int | None] = 16, |
| 234 |
# Logging |
| 235 |
logger: LoggerLike | None = None, |
| 236 |
# Escape hatch for advanced customization |
| 237 |
create_connection: type[ClientConnection] | None = None, |
| 238 |
# Other keyword arguments are passed to socket.create_connection |
| 239 |
**kwargs: Any, |
| 240 |
) -> None: |
| 241 |
# Backwards compatibility: ssl used to be called ssl_context. |
| 242 |
if ssl is None and "ssl_context" in kwargs: |
| 243 |
ssl = kwargs.pop("ssl_context") |
| 244 |
warnings.warn( # deprecated in 13.0 - 2024-08-20 |
| 245 |
"ssl_context was renamed to ssl", |
| 246 |
DeprecationWarning, |
| 247 |
) |
| 248 |
|
| 249 |
self.uri = uri |
| 250 |
self.ws_uri = parse_uri(uri) |
| 251 |
if not self.ws_uri.secure and ssl is not None: |
| 252 |
raise ValueError("ssl argument is incompatible with a ws:// URI") |
| 253 |
|
| 254 |
if subprotocols is not None: |
| 255 |
validate_subprotocols(subprotocols) |
| 256 |
|
| 257 |
if compression == "deflate": |
| 258 |
extensions = enable_client_permessage_deflate(extensions) |
| 259 |
elif compression is not None: |
| 260 |
raise ValueError(f"unsupported compression: {compression}") |
| 261 |
|
| 262 |
if logger is None: |
| 263 |
logger = logging.getLogger("websockets.client") |
| 264 |
|
| 265 |
if create_connection is None: |
| 266 |
create_connection = ClientConnection |
| 267 |
|
| 268 |
self.sock = sock |
| 269 |
self.ssl = ssl |
| 270 |
self.server_hostname = server_hostname |
| 271 |
self.additional_headers = additional_headers |
| 272 |
self.user_agent_header = user_agent_header |
| 273 |
self.proxy = proxy |
| 274 |
self.proxy_ssl = proxy_ssl |
| 275 |
self.proxy_server_hostname = proxy_server_hostname |
| 276 |
self.process_exception = process_exception |
| 277 |
self.open_timeout = open_timeout |
| 278 |
self.reconnect_delays = reconnect_delays |
| 279 |
self.logger = logger |
| 280 |
self.create_connection = create_connection |
| 281 |
self.open_socket_kwargs = kwargs |
| 282 |
self.protocol_kwargs = dict( |
| 283 |
origin=origin, |
| 284 |
extensions=extensions, |
| 285 |
subprotocols=subprotocols, |
| 286 |
max_size=max_size, |
| 287 |
logger=logger, |
| 288 |
) |
| 289 |
self.connection_kwargs = dict( |
| 290 |
ping_interval=ping_interval, |
| 291 |
ping_timeout=ping_timeout, |
| 292 |
close_timeout=close_timeout, |
| 293 |
max_queue=max_queue, |
| 294 |
) |
| 295 |
|
| 296 |
def open_socket(self, deadline: Deadline) -> socket.socket: |
| 297 |
"""Open a TCP or Unix connection to the server, possibly through a proxy.""" |
| 298 |
kwargs = self.open_socket_kwargs.copy() |
| 299 |
unix = kwargs.pop("unix", False) |
| 300 |
|
| 301 |
proxy = self.proxy |
| 302 |
if unix: |
| 303 |
proxy = None |
| 304 |
if proxy is True: |
| 305 |
proxy = get_proxy(self.ws_uri) |
| 306 |
|
| 307 |
if unix: |
| 308 |
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) |
| 309 |
try: |
| 310 |
sock.settimeout(deadline.timeout()) |
| 311 |
sock.connect(os.fspath(kwargs.pop("path"))) |
| 312 |
except Exception: |
| 313 |
sock.close() |
| 314 |
raise |
| 315 |
|
| 316 |
elif proxy is not None: |
| 317 |
proxy_parsed = parse_proxy(proxy) |
| 318 |
|
| 319 |
if proxy_parsed.scheme[:5] == "socks": |
| 320 |
sock = connect_socks_proxy( |
| 321 |
proxy_parsed, |
| 322 |
self.ws_uri, |
| 323 |
deadline, |
| 324 |
# websockets is consistent with the socket module while |
| 325 |
# python_socks is consistent across implementations. |
| 326 |
local_addr=kwargs.pop("source_address", None), |
| 327 |
) |
| 328 |
|
| 329 |
elif proxy_parsed.scheme[:4] == "http": |
| 330 |
if proxy_parsed.scheme != "https" and self.proxy_ssl is not None: |
| 331 |
raise ValueError( |
| 332 |
"proxy_ssl argument is incompatible with an http:// proxy" |
| 333 |
) |
| 334 |
sock = connect_http_proxy( |
| 335 |
proxy_parsed, |
| 336 |
self.ws_uri, |
| 337 |
deadline, |
| 338 |
user_agent_header=self.user_agent_header, |
| 339 |
ssl=self.proxy_ssl, |
| 340 |
server_hostname=self.proxy_server_hostname, |
| 341 |
**kwargs, |
| 342 |
) |
| 343 |
|
| 344 |
else: |
| 345 |
raise AssertionError("parse_proxy returned unsupported proxy") |
| 346 |
|
| 347 |
else: # proxy is None |
| 348 |
kwargs.setdefault("address", (self.ws_uri.host, self.ws_uri.port)) |
| 349 |
kwargs.setdefault("timeout", deadline.timeout()) |
| 350 |
sock = socket.create_connection(**kwargs) |
| 351 |
|
| 352 |
sock.settimeout(None) |
| 353 |
return sock |
| 354 |
|
| 355 |
def enable_tls(self, sock: socket.socket, deadline: Deadline) -> socket.socket: |
| 356 |
"""Enable TLS on the connection.""" |
| 357 |
if self.ssl is None: |
| 358 |
ssl = ssl_module.create_default_context() |
| 359 |
else: |
| 360 |
ssl = self.ssl |
| 361 |
if self.server_hostname is None: |
| 362 |
server_hostname = self.ws_uri.host |
| 363 |
else: |
| 364 |
server_hostname = self.server_hostname |
| 365 |
sock.settimeout(deadline.timeout()) |
| 366 |
if self.proxy_ssl is None: |
| 367 |
sock = ssl.wrap_socket(sock, server_hostname=server_hostname) |
| 368 |
else: |
| 369 |
sock_2 = SSLSSLSocket(sock, ssl, server_hostname=server_hostname) |
| 370 |
# Let's pretend that sock is a socket, even though it isn't. |
| 371 |
sock = cast(socket.socket, sock_2) |
| 372 |
sock.settimeout(None) |
| 373 |
return sock |
| 374 |
|
| 375 |
def open_connection(self, deadline: Deadline) -> ClientConnection: |
| 376 |
"""Create a WebSocket connection.""" |
| 377 |
if self.sock is None: |
| 378 |
sock = self.open_socket(deadline) |
| 379 |
else: |
| 380 |
sock = self.sock |
| 381 |
|
| 382 |
try: |
| 383 |
if sock.family in {socket.AF_INET, socket.AF_INET6}: |
| 384 |
sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, True) |
| 385 |
|
| 386 |
if self.ws_uri.secure: |
| 387 |
sock = self.enable_tls(sock, deadline) |
| 388 |
|
| 389 |
protocol = ClientProtocol( |
| 390 |
self.ws_uri, |
| 391 |
**self.protocol_kwargs, # type: ignore |
| 392 |
) |
| 393 |
|
| 394 |
# self.create_connection defaults to ClientConnection. |
| 395 |
connection = self.create_connection( |
| 396 |
sock, |
| 397 |
protocol, |
| 398 |
**self.connection_kwargs, # type: ignore |
| 399 |
) |
| 400 |
|
| 401 |
except Exception: |
| 402 |
sock.close() |
| 403 |
raise |
| 404 |
|
| 405 |
try: |
| 406 |
connection.handshake( |
| 407 |
self.additional_headers, |
| 408 |
self.user_agent_header, |
| 409 |
deadline.timeout(), |
| 410 |
) |
| 411 |
except Exception: |
| 412 |
connection.close_socket() |
| 413 |
connection.recv_events_thread.join() |
| 414 |
raise |
| 415 |
|
| 416 |
return connection |
| 417 |
|
| 418 |
def process_redirect(self, exc: Exception) -> Exception | str: |
| 419 |
""" |
| 420 |
Determine whether a connection error is a redirect that can be followed. |
| 421 |
|
| 422 |
Return the new URI if it's a valid redirect. Else, return an exception. |
| 423 |
|
| 424 |
""" |
| 425 |
if not ( |
| 426 |
isinstance(exc, InvalidStatus) |
| 427 |
and exc.response.status_code |
| 428 |
in [ |
| 429 |
300, # Multiple Choices |
| 430 |
301, # Moved Permanently |
| 431 |
302, # Found |
| 432 |
303, # See Other |
| 433 |
307, # Temporary Redirect |
| 434 |
308, # Permanent Redirect |
| 435 |
] |
| 436 |
and "Location" in exc.response.headers |
| 437 |
): |
| 438 |
return exc |
| 439 |
|
| 440 |
old_ws_uri = self.ws_uri |
| 441 |
new_uri = urllib.parse.urljoin(self.uri, exc.response.headers["Location"]) |
| 442 |
new_ws_uri = parse_uri(new_uri) |
| 443 |
|
| 444 |
# If connect() received a socket, it is closed and cannot be reused. |
| 445 |
if self.sock is not None: |
| 446 |
return ValueError( |
| 447 |
f"cannot follow redirect to {new_uri} with a preexisting socket" |
| 448 |
) |
| 449 |
|
| 450 |
# TLS downgrade is forbidden. |
| 451 |
if old_ws_uri.secure and not new_ws_uri.secure: |
| 452 |
return SecurityError(f"cannot follow redirect to non-secure URI {new_uri}") |
| 453 |
|
| 454 |
# Apply restrictions to cross-origin redirects. |
| 455 |
if ( |
| 456 |
old_ws_uri.secure != new_ws_uri.secure |
| 457 |
or old_ws_uri.host != new_ws_uri.host |
| 458 |
or old_ws_uri.port != new_ws_uri.port |
| 459 |
): |
| 460 |
# Cross-origin redirects on Unix sockets don't quite make sense. |
| 461 |
if self.open_socket_kwargs.get("unix", False): |
| 462 |
return ValueError( |
| 463 |
f"cannot follow cross-origin redirect to {new_uri} " |
| 464 |
f"with a Unix socket" |
| 465 |
) |
| 466 |
|
| 467 |
# Cross-origin redirects when host and port are overridden are ill-defined. |
| 468 |
if self.open_socket_kwargs.get("address") is not None: |
| 469 |
return ValueError( |
| 470 |
f"cannot follow cross-origin redirect to {new_uri} " |
| 471 |
f"with an explicit host and port" |
| 472 |
) |
| 473 |
|
| 474 |
# Strip credentials to avoid leaking them to a different origin. |
| 475 |
if self.additional_headers is not None: |
| 476 |
self.additional_headers = Headers( |
| 477 |
( |
| 478 |
(key, value) |
| 479 |
for key, value in Headers(self.additional_headers).raw_items() |
| 480 |
if key.lower() |
| 481 |
not in ["authorization", "cookie", "proxy-authorization"] |
| 482 |
) |
| 483 |
) |
| 484 |
|
| 485 |
return new_uri |
| 486 |
|
| 487 |
def connect(self) -> ClientConnection: |
| 488 |
"""Connect to a WebSocket server, following redirects.""" |
| 489 |
# Calculate timeouts on the TCP, TLS, and WebSocket handshakes. |
| 490 |
# The TCP and TLS timeouts must be set on the socket, then removed |
| 491 |
# to avoid conflicting with the WebSocket timeout in handshake(). |
| 492 |
deadline = Deadline(self.open_timeout) |
| 493 |
|
| 494 |
for _ in range(MAX_REDIRECTS): |
| 495 |
try: |
| 496 |
connection = self.open_connection(deadline) |
| 497 |
except Exception as exc: |
| 498 |
exc_or_uri = self.process_redirect(exc) |
| 499 |
if isinstance(exc_or_uri, Exception): |
| 500 |
# Response isn't a valid redirect; raise the exception. |
| 501 |
if exc_or_uri is exc: |
| 502 |
raise |
| 503 |
else: |
| 504 |
raise exc_or_uri from exc |
| 505 |
else: |
| 506 |
# Response is a valid redirect; follow it. |
| 507 |
self.uri = exc_or_uri |
| 508 |
self.ws_uri = parse_uri(exc_or_uri) |
| 509 |
continue |
| 510 |
|
| 511 |
else: |
| 512 |
connection.start_keepalive() |
| 513 |
return connection |
| 514 |
else: |
| 515 |
raise SecurityError(f"more than {MAX_REDIRECTS} redirects") |
| 516 |
|
| 517 |
# with connect(...) as ...: ... |
| 518 |
|
| 519 |
def __enter__(self) -> ClientConnection: |
| 520 |
if hasattr(self, "connection"): |
| 521 |
raise RuntimeError("connect() isn't reentrant") |
| 522 |
self.connection = self.connect() |
| 523 |
self.connection.pending_legacy_warning = False |
| 524 |
return self.connection |
| 525 |
|
| 526 |
def __exit__( |
| 527 |
self, |
| 528 |
exc_type: type[BaseException] | None, |
| 529 |
exc_value: BaseException | None, |
| 530 |
exc_traceback: TracebackType | None, |
| 531 |
) -> None: |
| 532 |
try: |
| 533 |
self.connection.close() |
| 534 |
finally: |
| 535 |
del self.connection |
| 536 |
|
| 537 |
# for ... in reconnect(...): ... |
| 538 |
|
| 539 |
def __iter__(self) -> Iterator[ClientConnection]: |
| 540 |
delays: Generator[float] | None = None |
| 541 |
while True: |
| 542 |
try: |
| 543 |
with self as connection: |
| 544 |
yield connection |
| 545 |
except Exception as exc: |
| 546 |
# Determine whether the exception is retryable or fatal. |
| 547 |
# The API of process_exception is "return an exception or None"; |
| 548 |
# "raise an exception" is also supported because it's a frequent |
| 549 |
# mistake. It isn't documented in order to keep the API simple. |
| 550 |
try: |
| 551 |
new_exc = self.process_exception(exc) |
| 552 |
except Exception as raised_exc: |
| 553 |
new_exc = raised_exc |
| 554 |
|
| 555 |
# The connection failed with a fatal error. |
| 556 |
# Raise the exception and exit the loop. |
| 557 |
if new_exc is exc: |
| 558 |
raise |
| 559 |
if new_exc is not None: |
| 560 |
raise new_exc from exc |
| 561 |
|
| 562 |
# The connection failed with a retryable error. |
| 563 |
# Start or continue backoff and reconnect. |
| 564 |
if delays is None: |
| 565 |
delays = self.reconnect_delays() |
| 566 |
delay = next(delays) |
| 567 |
self.logger.info( |
| 568 |
"connect failed; reconnecting in %.1f seconds: %s", |
| 569 |
delay, |
| 570 |
traceback.format_exception_only(exc)[0].strip(), |
| 571 |
) |
| 572 |
time.sleep(delay) |
| 573 |
|
| 574 |
else: |
| 575 |
# The connection succeeded. Reset backoff. |
| 576 |
delays = None |
| 577 |
|
| 578 |
|
| 579 |
@overload |
| 580 |
def connect( |
| 581 |
uri: str, |
| 582 |
*, |
| 583 |
# TCP/TLS |
| 584 |
sock: socket.socket | None = ..., |
| 585 |
ssl: ssl_module.SSLContext | None = ..., |
| 586 |
server_hostname: str | None = ..., |
| 587 |
# WebSocket |
| 588 |
origin: Origin | None = ..., |
| 589 |
extensions: Sequence[ClientExtensionFactory] | None = ..., |
| 590 |
subprotocols: Sequence[Subprotocol] | None = ..., |
| 591 |
compression: str | None = ..., |
| 592 |
# HTTP |
| 593 |
additional_headers: HeadersLike | None = ..., |
| 594 |
user_agent_header: str | None = ..., |
| 595 |
proxy: str | Literal[True] | None = ..., |
| 596 |
proxy_ssl: ssl_module.SSLContext | None = ..., |
| 597 |
proxy_server_hostname: str | None = ..., |
| 598 |
# Timeouts |
| 599 |
open_timeout: float | None = ..., |
| 600 |
ping_interval: float | None = ..., |
| 601 |
ping_timeout: float | None = ..., |
| 602 |
close_timeout: float | None = ..., |
| 603 |
# Limits |
| 604 |
max_size: int | None | tuple[int | None, int | None] = ..., |
| 605 |
max_queue: int | None | tuple[int | None, int | None] = ..., |
| 606 |
# Logging |
| 607 |
logger: LoggerLike | None = ..., |
| 608 |
# Escape hatch for advanced customization |
| 609 |
create_connection: type[ClientConnection] | None = ..., |
| 610 |
# Backwards and forwards compatibility |
| 611 |
legacy: Literal[True] | None = ..., |
| 612 |
# Other keyword arguments are passed to socket.create_connection |
| 613 |
**kwargs: Any, |
| 614 |
) -> ClientConnection: ... |
| 615 |
|
| 616 |
|
| 617 |
@overload |
| 618 |
def connect( |
| 619 |
uri: str, |
| 620 |
*, |
| 621 |
# TCP/TLS |
| 622 |
sock: socket.socket | None = ..., |
| 623 |
ssl: ssl_module.SSLContext | None = ..., |
| 624 |
server_hostname: str | None = ..., |
| 625 |
# WebSocket |
| 626 |
origin: Origin | None = ..., |
| 627 |
extensions: Sequence[ClientExtensionFactory] | None = ..., |
| 628 |
subprotocols: Sequence[Subprotocol] | None = ..., |
| 629 |
compression: str | None = ..., |
| 630 |
# HTTP |
| 631 |
additional_headers: HeadersLike | None = ..., |
| 632 |
user_agent_header: str | None = ..., |
| 633 |
proxy: str | Literal[True] | None = ..., |
| 634 |
proxy_ssl: ssl_module.SSLContext | None = ..., |
| 635 |
proxy_server_hostname: str | None = ..., |
| 636 |
# Timeouts |
| 637 |
open_timeout: float | None = ..., |
| 638 |
ping_interval: float | None = ..., |
| 639 |
ping_timeout: float | None = ..., |
| 640 |
close_timeout: float | None = ..., |
| 641 |
# Limits |
| 642 |
max_size: int | None | tuple[int | None, int | None] = ..., |
| 643 |
max_queue: int | None | tuple[int | None, int | None] = ..., |
| 644 |
# Logging |
| 645 |
logger: LoggerLike | None = ..., |
| 646 |
# Escape hatch for advanced customization |
| 647 |
create_connection: type[ClientConnection] | None = ..., |
| 648 |
# Backwards and forwards compatibility |
| 649 |
legacy: Literal[False], |
| 650 |
# Other keyword arguments are passed to socket.create_connection |
| 651 |
**kwargs: Any, |
| 652 |
) -> reconnect: ... |
| 653 |
|
| 654 |
|
| 655 |
def connect( |
| 656 |
uri: str, |
| 657 |
*, |
| 658 |
# TCP/TLS |
| 659 |
sock: socket.socket | None = None, |
| 660 |
ssl: ssl_module.SSLContext | None = None, |
| 661 |
server_hostname: str | None = None, |
| 662 |
# WebSocket |
| 663 |
origin: Origin | None = None, |
| 664 |
extensions: Sequence[ClientExtensionFactory] | None = None, |
| 665 |
subprotocols: Sequence[Subprotocol] | None = None, |
| 666 |
compression: str | None = "deflate", |
| 667 |
# HTTP |
| 668 |
additional_headers: HeadersLike | None = None, |
| 669 |
user_agent_header: str | None = USER_AGENT, |
| 670 |
proxy: str | Literal[True] | None = True, |
| 671 |
proxy_ssl: ssl_module.SSLContext | None = None, |
| 672 |
proxy_server_hostname: str | None = None, |
| 673 |
# Timeouts |
| 674 |
open_timeout: float | None = 10, |
| 675 |
ping_interval: float | None = 20, |
| 676 |
ping_timeout: float | None = 20, |
| 677 |
close_timeout: float | None = 10, |
| 678 |
# Limits |
| 679 |
max_size: int | None | tuple[int | None, int | None] = 2**20, |
| 680 |
max_queue: int | None | tuple[int | None, int | None] = 16, |
| 681 |
# Logging |
| 682 |
logger: LoggerLike | None = None, |
| 683 |
# Escape hatch for advanced customization |
| 684 |
create_connection: type[ClientConnection] | None = None, |
| 685 |
# Backwards and forwards compatibility |
| 686 |
legacy: bool | None = None, |
| 687 |
# Other keyword arguments are passed to socket.create_connection |
| 688 |
**kwargs: Any, |
| 689 |
) -> ClientConnection | reconnect: |
| 690 |
""" |
| 691 |
Connect to the WebSocket server at ``uri``. |
| 692 |
|
| 693 |
:func:`connect` should be treated as a context manager yielding a |
| 694 |
:class:`ClientConnection`, which can then receive and send messages:: |
| 695 |
|
| 696 |
from websockets.sync.client import connect |
| 697 |
|
| 698 |
with connect(...) as websocket: |
| 699 |
... |
| 700 |
|
| 701 |
The connection is closed automatically when exiting the context. |
| 702 |
|
| 703 |
Use :func:`reconnect` to reconnect automatically on errors. |
| 704 |
|
| 705 |
For backwards compatibility, :func:`connect` can be called directly:: |
| 706 |
|
| 707 |
websocket = connect(..., legacy=True) |
| 708 |
|
| 709 |
In that case, you're responsible for closing the connection with |
| 710 |
:meth:`ClientConnection.close` when no longer needed. |
| 711 |
|
| 712 |
When the ``legacy`` flag is enabled, :func:`connect` returns directly a |
| 713 |
:class:`ClientConnection` and iterating that connection yields messages. |
| 714 |
Currently, this is the default behavior when ``legacy`` isn't specified. |
| 715 |
|
| 716 |
When the ``legacy`` flag is explicitly disabled, :func:`connect` behaves |
| 717 |
like :func:`reconnect`: using it as an iterator returns a new connection |
| 718 |
at each iteration, making it easy to reconnect automatically on errors. |
| 719 |
|
| 720 |
Args: |
| 721 |
uri: URI of the WebSocket server. |
| 722 |
sock: Preexisting TCP socket. ``sock`` overrides the host and port |
| 723 |
from ``uri``. You may call :func:`socket.create_connection` to |
| 724 |
create a suitable TCP socket. |
| 725 |
ssl: Configuration for enabling TLS on the connection. |
| 726 |
server_hostname: Host name for the TLS handshake. ``server_hostname`` |
| 727 |
overrides the host name from ``uri``. |
| 728 |
origin: Value of the ``Origin`` header, for servers that require it. |
| 729 |
extensions: List of supported extensions, in order in which they |
| 730 |
should be negotiated and run. |
| 731 |
subprotocols: List of supported subprotocols, in order of decreasing |
| 732 |
preference. |
| 733 |
compression: The "permessage-deflate" extension is enabled by default. |
| 734 |
Set ``compression`` to :obj:`None` to disable it. See the |
| 735 |
:doc:`compression guide <../../topics/compression>` for details. |
| 736 |
additional_headers: Arbitrary HTTP headers to add to the handshake |
| 737 |
request. |
| 738 |
user_agent_header: Value of the ``User-Agent`` request header. |
| 739 |
It defaults to ``"Python/x.y.z websockets/X.Y"``. |
| 740 |
Setting it to :obj:`None` removes the header. |
| 741 |
proxy: If a proxy is configured, it is used by default. Set ``proxy`` |
| 742 |
to :obj:`None` to disable the proxy or to the address of a proxy |
| 743 |
to override the system configuration. See the :doc:`proxy docs |
| 744 |
<../../topics/proxies>` for details. |
| 745 |
proxy_ssl: Configuration for enabling TLS on the proxy connection. |
| 746 |
proxy_server_hostname: Host name for the TLS handshake with the proxy. |
| 747 |
``proxy_server_hostname`` overrides the host name from ``proxy``. |
| 748 |
open_timeout: Timeout for opening the connection in seconds. |
| 749 |
:obj:`None` disables the timeout. |
| 750 |
ping_interval: Interval between keepalive pings in seconds. |
| 751 |
:obj:`None` disables keepalive. |
| 752 |
ping_timeout: Timeout for keepalive pings in seconds. |
| 753 |
:obj:`None` disables timeouts. |
| 754 |
close_timeout: Timeout for closing the connection in seconds. |
| 755 |
:obj:`None` disables the timeout. |
| 756 |
max_size: Maximum size of incoming messages in bytes. |
| 757 |
:obj:`None` disables the limit. You may pass a ``(max_message_size, |
| 758 |
max_fragment_size)`` tuple to set different limits for messages and |
| 759 |
fragments when you expect long messages sent in short fragments. |
| 760 |
max_queue: High-water mark of the buffer where frames are received. |
| 761 |
It defaults to 16 frames. The low-water mark defaults to ``max_queue |
| 762 |
// 4``. You may pass a ``(high, low)`` tuple to set the high-water |
| 763 |
and low-water marks. If you want to disable flow control entirely, |
| 764 |
you may set it to ``None``, although that's a bad idea. |
| 765 |
logger: Logger for this client. |
| 766 |
It defaults to ``logging.getLogger("websockets.client")``. |
| 767 |
See the :doc:`logging guide <../../topics/logging>` for details. |
| 768 |
legacy: Set to :obj:`True` to opt into the historical behavior of |
| 769 |
returning a :class:`ClientConnection`, without deprecation warning. |
| 770 |
create_connection: Factory for the :class:`ClientConnection` managing |
| 771 |
the connection. Set it to a wrapper or a subclass to customize |
| 772 |
connection handling. |
| 773 |
|
| 774 |
Any other keyword arguments are passed to :func:`~socket.create_connection`. |
| 775 |
For example, you can set ``address`` to a ``(host, port)`` tuple to connect |
| 776 |
to a different host and port from those found in ``uri``. This only changes |
| 777 |
the destination of the TCP connection. The host name from ``uri`` is still |
| 778 |
used in the TLS handshake for secure connections and in the ``Host`` header. |
| 779 |
|
| 780 |
Raises: |
| 781 |
InvalidURI: If ``uri`` isn't a valid WebSocket URI. |
| 782 |
InvalidProxy: If ``proxy`` isn't a valid proxy. |
| 783 |
OSError: If the TCP connection fails. |
| 784 |
InvalidHandshake: If the opening handshake fails. |
| 785 |
TimeoutError: If the opening handshake times out. |
| 786 |
|
| 787 |
""" |
| 788 |
connecter = reconnect( |
| 789 |
uri, |
| 790 |
sock=sock, |
| 791 |
ssl=ssl, |
| 792 |
server_hostname=server_hostname, |
| 793 |
origin=origin, |
| 794 |
extensions=extensions, |
| 795 |
subprotocols=subprotocols, |
| 796 |
compression=compression, |
| 797 |
additional_headers=additional_headers, |
| 798 |
user_agent_header=user_agent_header, |
| 799 |
proxy=proxy, |
| 800 |
proxy_ssl=proxy_ssl, |
| 801 |
proxy_server_hostname=proxy_server_hostname, |
| 802 |
open_timeout=open_timeout, |
| 803 |
ping_interval=ping_interval, |
| 804 |
ping_timeout=ping_timeout, |
| 805 |
close_timeout=close_timeout, |
| 806 |
max_size=max_size, |
| 807 |
max_queue=max_queue, |
| 808 |
logger=logger, |
| 809 |
create_connection=create_connection, |
| 810 |
**kwargs, |
| 811 |
) |
| 812 |
# For backwards compatibility, connect defaults to the historical behavior. |
| 813 |
# For forwards compatibility, the future behavior can be chosen explicitly. |
| 814 |
if legacy is False: |
| 815 |
return connecter |
| 816 |
connection = connecter.connect() |
| 817 |
# Users can opt in to the historical behavior to remain unaffected when the |
| 818 |
# future behavior becomes the default. |
| 819 |
if legacy: |
| 820 |
connection.pending_legacy_warning = False |
| 821 |
return connection |
| 822 |
|
| 823 |
|
| 824 |
def unix_reconnect( |
| 825 |
path: PathLike | None = None, |
| 826 |
uri: str | None = None, |
| 827 |
**kwargs: Any, |
| 828 |
) -> reconnect: |
| 829 |
""" |
| 830 |
Similar to :func:`unix_connect`, with support for automatic reconnection. |
| 831 |
|
| 832 |
Refer to the documentation of :func:`reconnect` for details on its behavior. |
| 833 |
|
| 834 |
""" |
| 835 |
sock = kwargs.get("sock") |
| 836 |
if path is None and sock is None: |
| 837 |
raise ValueError("missing path argument") |
| 838 |
elif path is not None and sock is not None: |
| 839 |
raise ValueError("path is incompatible with sock") |
| 840 |
|
| 841 |
if uri is None: |
| 842 |
# Backwards compatibility: ssl used to be called ssl_context. |
| 843 |
if kwargs.get("ssl") is None and kwargs.get("ssl_context") is None: |
| 844 |
uri = "ws://localhost/" |
| 845 |
else: |
| 846 |
uri = "wss://localhost/" |
| 847 |
|
| 848 |
return reconnect(uri=uri, unix=True, path=path, **kwargs) |
| 849 |
|
| 850 |
|
| 851 |
@overload |
| 852 |
def unix_connect( |
| 853 |
path: PathLike | None = ..., |
| 854 |
uri: str | None = ..., |
| 855 |
*, |
| 856 |
legacy: Literal[True] | None = ..., |
| 857 |
**kwargs: Any, |
| 858 |
) -> ClientConnection: ... |
| 859 |
|
| 860 |
|
| 861 |
@overload |
| 862 |
def unix_connect( |
| 863 |
path: PathLike | None = ..., |
| 864 |
uri: str | None = ..., |
| 865 |
*, |
| 866 |
legacy: Literal[False], |
| 867 |
**kwargs: Any, |
| 868 |
) -> reconnect: ... |
| 869 |
|
| 870 |
|
| 871 |
def unix_connect( |
| 872 |
path: PathLike | None = None, |
| 873 |
uri: str | None = None, |
| 874 |
*, |
| 875 |
legacy: bool | None = None, |
| 876 |
**kwargs: Any, |
| 877 |
) -> ClientConnection | reconnect: |
| 878 |
""" |
| 879 |
Connect to a WebSocket server listening on a Unix socket. |
| 880 |
|
| 881 |
This function accepts the same keyword arguments as :func:`connect`. |
| 882 |
|
| 883 |
It's only available on Unix. |
| 884 |
|
| 885 |
It's mainly useful for debugging servers listening on Unix sockets. |
| 886 |
|
| 887 |
Args: |
| 888 |
path: File system path to the Unix socket. |
| 889 |
uri: URI of the WebSocket server. ``uri`` defaults to |
| 890 |
``ws://localhost/`` or, when a ``ssl`` is provided, to |
| 891 |
``wss://localhost/``. |
| 892 |
|
| 893 |
""" |
| 894 |
connecter = unix_reconnect(path, uri, **kwargs) |
| 895 |
# For backwards compatibility, connect defaults to the historical behavior. |
| 896 |
# For forwards compatibility, the future behavior can be chosen explicitly. |
| 897 |
if legacy is False: |
| 898 |
return connecter |
| 899 |
connection = connecter.connect() |
| 900 |
# Users can opt in to the historical behavior to remain unaffected when the |
| 901 |
# future behavior becomes the default. |
| 902 |
if legacy: |
| 903 |
connection.pending_legacy_warning = False |
| 904 |
return connection |
| 905 |
|
| 906 |
|
| 907 |
try: |
| 908 |
from python_socks import ProxyType |
| 909 |
from python_socks.sync import Proxy as SocksProxy |
| 910 |
|
| 911 |
except ImportError: |
| 912 |
|
| 913 |
def connect_socks_proxy( |
| 914 |
proxy: Proxy, |
| 915 |
ws_uri: WebSocketURI, |
| 916 |
deadline: Deadline, |
| 917 |
**kwargs: Any, |
| 918 |
) -> socket.socket: |
| 919 |
raise ImportError("connecting through a SOCKS proxy requires python-socks") |
| 920 |
|
| 921 |
else: |
| 922 |
SOCKS_PROXY_TYPES = { |
| 923 |
"socks5h": ProxyType.SOCKS5, |
| 924 |
"socks5": ProxyType.SOCKS5, |
| 925 |
"socks4a": ProxyType.SOCKS4, |
| 926 |
"socks4": ProxyType.SOCKS4, |
| 927 |
} |
| 928 |
|
| 929 |
SOCKS_PROXY_RDNS = { |
| 930 |
"socks5h": True, |
| 931 |
"socks5": False, |
| 932 |
"socks4a": True, |
| 933 |
"socks4": False, |
| 934 |
} |
| 935 |
|
| 936 |
def connect_socks_proxy( |
| 937 |
proxy: Proxy, |
| 938 |
ws_uri: WebSocketURI, |
| 939 |
deadline: Deadline, |
| 940 |
**kwargs: Any, |
| 941 |
) -> socket.socket: |
| 942 |
"""Connect via a SOCKS proxy and return the socket.""" |
| 943 |
socks_proxy = SocksProxy( |
| 944 |
SOCKS_PROXY_TYPES[proxy.scheme], |
| 945 |
proxy.host, |
| 946 |
proxy.port, |
| 947 |
proxy.username, |
| 948 |
proxy.password, |
| 949 |
SOCKS_PROXY_RDNS[proxy.scheme], |
| 950 |
) |
| 951 |
kwargs.setdefault("timeout", deadline.timeout()) |
| 952 |
# connect() is documented to raise OSError and TimeoutError. |
| 953 |
# Wrap other exceptions in ProxyError, a subclass of InvalidHandshake. |
| 954 |
try: |
| 955 |
return socks_proxy.connect(ws_uri.host, ws_uri.port, **kwargs) |
| 956 |
except (OSError, TimeoutError, socket.timeout): |
| 957 |
raise |
| 958 |
except Exception as exc: |
| 959 |
raise ProxyError("failed to connect to SOCKS proxy") from exc |
| 960 |
|
| 961 |
|
| 962 |
def read_connect_response(sock: socket.socket, deadline: Deadline) -> Response: |
| 963 |
reader = StreamReader() |
| 964 |
parser = Response.parse( |
| 965 |
reader.read_line, |
| 966 |
reader.read_exact, |
| 967 |
reader.read_to_eof, |
| 968 |
proxy=True, |
| 969 |
) |
| 970 |
try: |
| 971 |
while True: |
| 972 |
sock.settimeout(deadline.timeout()) |
| 973 |
data = sock.recv(4096) |
| 974 |
if data: |
| 975 |
reader.feed_data(data) |
| 976 |
else: |
| 977 |
reader.feed_eof() |
| 978 |
next(parser) |
| 979 |
except StopIteration as exc: |
| 980 |
assert isinstance(exc.value, Response) # help mypy |
| 981 |
response = exc.value |
| 982 |
if 200 <= response.status_code < 300: |
| 983 |
return response |
| 984 |
else: |
| 985 |
raise InvalidProxyStatus(response) |
| 986 |
except socket.timeout: |
| 987 |
raise TimeoutError("timed out while connecting to HTTP proxy") |
| 988 |
except Exception as exc: |
| 989 |
raise InvalidProxyMessage( |
| 990 |
"did not receive a valid HTTP response from proxy" |
| 991 |
) from exc |
| 992 |
finally: |
| 993 |
sock.settimeout(None) |
| 994 |
|
| 995 |
|
| 996 |
def connect_http_proxy( |
| 997 |
proxy: Proxy, |
| 998 |
ws_uri: WebSocketURI, |
| 999 |
deadline: Deadline, |
| 1000 |
*, |
| 1001 |
user_agent_header: str | None = None, |
| 1002 |
ssl: ssl_module.SSLContext | None = None, |
| 1003 |
server_hostname: str | None = None, |
| 1004 |
**kwargs: Any, |
| 1005 |
) -> socket.socket: |
| 1006 |
# Connect socket |
| 1007 |
|
| 1008 |
kwargs.setdefault("timeout", deadline.timeout()) |
| 1009 |
sock = socket.create_connection((proxy.host, proxy.port), **kwargs) |
| 1010 |
|
| 1011 |
# Initialize TLS wrapper and perform TLS handshake |
| 1012 |
|
| 1013 |
if proxy.scheme == "https": |
| 1014 |
if ssl is None: |
| 1015 |
ssl = ssl_module.create_default_context() |
| 1016 |
if server_hostname is None: |
| 1017 |
server_hostname = proxy.host |
| 1018 |
sock.settimeout(deadline.timeout()) |
| 1019 |
sock = ssl.wrap_socket(sock, server_hostname=server_hostname) |
| 1020 |
sock.settimeout(None) |
| 1021 |
|
| 1022 |
# Send CONNECT request to the proxy and read response. |
| 1023 |
|
| 1024 |
request = prepare_connect_request(proxy, ws_uri, user_agent_header) |
| 1025 |
sock.sendall(request) |
| 1026 |
try: |
| 1027 |
read_connect_response(sock, deadline) |
| 1028 |
except Exception: |
| 1029 |
sock.close() |
| 1030 |
raise |
| 1031 |
|
| 1032 |
return sock |
| 1033 |
|
| 1034 |
|
| 1035 |
T = TypeVar("T") |
| 1036 |
F = TypeVar("F", bound=Callable[..., T]) |
| 1037 |
|
| 1038 |
|
| 1039 |
class SSLSSLSocket: |
| 1040 |
""" |
| 1041 |
Socket-like object providing TLS-in-TLS. |
| 1042 |
|
| 1043 |
Only methods that are used by websockets are implemented. |
| 1044 |
|
| 1045 |
""" |
| 1046 |
|
| 1047 |
recv_bufsize = 65536 |
| 1048 |
|
| 1049 |
def __init__( |
| 1050 |
self, |
| 1051 |
sock: socket.socket, |
| 1052 |
ssl_context: ssl_module.SSLContext, |
| 1053 |
server_hostname: str | None = None, |
| 1054 |
) -> None: |
| 1055 |
self.incoming = ssl_module.MemoryBIO() |
| 1056 |
self.outgoing = ssl_module.MemoryBIO() |
| 1057 |
self.ssl_socket = sock |
| 1058 |
self.ssl_object = ssl_context.wrap_bio( |
| 1059 |
self.incoming, |
| 1060 |
self.outgoing, |
| 1061 |
server_hostname=server_hostname, |
| 1062 |
) |
| 1063 |
self.run_io(self.ssl_object.do_handshake) |
| 1064 |
|
| 1065 |
def run_io(self, func: Callable[..., T], *args: Any) -> T: |
| 1066 |
while True: |
| 1067 |
want_read = False |
| 1068 |
want_write = False |
| 1069 |
try: |
| 1070 |
result = func(*args) |
| 1071 |
except ssl_module.SSLWantReadError: |
| 1072 |
want_read = True |
| 1073 |
except ssl_module.SSLWantWriteError: # pragma: no cover |
| 1074 |
want_write = True |
| 1075 |
|
| 1076 |
# Write outgoing data in all cases. |
| 1077 |
data = self.outgoing.read() |
| 1078 |
if data: |
| 1079 |
self.ssl_socket.sendall(data) |
| 1080 |
|
| 1081 |
# Read incoming data and retry on SSLWantReadError. |
| 1082 |
if want_read: |
| 1083 |
data = self.ssl_socket.recv(self.recv_bufsize) |
| 1084 |
if data: |
| 1085 |
self.incoming.write(data) |
| 1086 |
else: |
| 1087 |
self.incoming.write_eof() |
| 1088 |
continue |
| 1089 |
# Retry after writing outgoing data on SSLWantWriteError. |
| 1090 |
if want_write: # pragma: no cover |
| 1091 |
continue |
| 1092 |
# Return result if no error happened. |
| 1093 |
return result |
| 1094 |
|
| 1095 |
def recv(self, buflen: int) -> bytes: |
| 1096 |
try: |
| 1097 |
return self.run_io(self.ssl_object.read, buflen) |
| 1098 |
except ssl_module.SSLEOFError: |
| 1099 |
return b"" # always ignore ragged EOFs |
| 1100 |
|
| 1101 |
def send(self, data: BytesLike) -> int: |
| 1102 |
return self.run_io(self.ssl_object.write, data) |
| 1103 |
|
| 1104 |
def sendall(self, data: BytesLike) -> None: |
| 1105 |
# adapted from ssl_module.SSLSocket.sendall() |
| 1106 |
count = 0 |
| 1107 |
with memoryview(data) as view, view.cast("B") as byte_view: |
| 1108 |
amount = len(byte_view) |
| 1109 |
while count < amount: |
| 1110 |
count += self.send(byte_view[count:]) |
| 1111 |
|
| 1112 |
# recv_into(), recvfrom(), recvfrom_into(), sendto(), unwrap(), and the |
| 1113 |
# flags argument aren't implemented because websockets doesn't need them. |
| 1114 |
|
| 1115 |
def __getattr__(self, name: str) -> Any: |
| 1116 |
return getattr(self.ssl_socket, name) |