client.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793
  1. from __future__ import annotations
  2. import asyncio
  3. import logging
  4. import os
  5. import socket
  6. import ssl as ssl_module
  7. import traceback
  8. import urllib.parse
  9. from collections.abc import AsyncIterator, Generator, Sequence
  10. from types import TracebackType
  11. from typing import Any, Callable, Literal, cast
  12. from ..client import ClientProtocol, backoff, process_exception
  13. from ..datastructures import Headers, HeadersLike
  14. from ..exceptions import (
  15. InvalidProxyMessage,
  16. InvalidProxyStatus,
  17. InvalidStatus,
  18. ProxyError,
  19. SecurityError,
  20. )
  21. from ..extensions.base import ClientExtensionFactory
  22. from ..extensions.permessage_deflate import enable_client_permessage_deflate
  23. from ..headers import validate_subprotocols
  24. from ..http11 import USER_AGENT, Response
  25. from ..protocol import CONNECTING, Event
  26. from ..proxy import Proxy, get_proxy, parse_proxy, prepare_connect_request
  27. from ..streams import StreamReader
  28. from ..typing import LoggerLike, Origin, PathLike, Subprotocol
  29. from ..uri import WebSocketURI, parse_uri
  30. from .connection import Connection
  31. __all__ = ["connect", "unix_connect", "ClientConnection"]
  32. MAX_REDIRECTS = int(os.environ.get("WEBSOCKETS_MAX_REDIRECTS", "10"))
  33. class ClientConnection(Connection):
  34. """
  35. :mod:`asyncio` implementation of a WebSocket client connection.
  36. :class:`ClientConnection` provides :meth:`recv` and :meth:`send` coroutines
  37. for receiving and sending messages.
  38. It supports asynchronous iteration to receive messages::
  39. async for message in websocket:
  40. await process(message)
  41. The iterator exits normally when the connection is closed with code
  42. 1000 (OK) or 1001 (going away) or without a close code. It raises a
  43. :exc:`~websockets.exceptions.ConnectionClosedError` when the connection is
  44. closed with any other code.
  45. The ``ping_interval``, ``ping_timeout``, ``close_timeout``, ``max_queue``,
  46. and ``write_limit`` arguments have the same meaning as in :func:`connect`.
  47. Args:
  48. protocol: Sans-I/O connection.
  49. """
  50. def __init__(
  51. self,
  52. protocol: ClientProtocol,
  53. *,
  54. ping_interval: float | None = 20,
  55. ping_timeout: float | None = 20,
  56. close_timeout: float | None = 10,
  57. max_queue: int | None | tuple[int | None, int | None] = 16,
  58. write_limit: int | tuple[int, int | None] = 2**15,
  59. ) -> None:
  60. self.protocol: ClientProtocol
  61. super().__init__(
  62. protocol,
  63. ping_interval=ping_interval,
  64. ping_timeout=ping_timeout,
  65. close_timeout=close_timeout,
  66. max_queue=max_queue,
  67. write_limit=write_limit,
  68. )
  69. self.response_rcvd: asyncio.Future[None] = self.loop.create_future()
  70. async def handshake(
  71. self,
  72. additional_headers: HeadersLike | None = None,
  73. user_agent_header: str | None = USER_AGENT,
  74. ) -> None:
  75. """
  76. Perform the opening handshake.
  77. """
  78. self.request = self.protocol.connect()
  79. if additional_headers is not None:
  80. self.request.headers.update(additional_headers)
  81. if user_agent_header is not None:
  82. self.request.headers.setdefault("User-Agent", user_agent_header)
  83. async with self.send_context(expected_state=CONNECTING):
  84. self.protocol.send_request(self.request)
  85. await asyncio.wait(
  86. [self.response_rcvd, self.connection_lost_waiter],
  87. return_when=asyncio.FIRST_COMPLETED,
  88. )
  89. # self.protocol.handshake_exc is set when the connection is lost before
  90. # receiving a response, when the response cannot be parsed, or when the
  91. # response fails the handshake.
  92. if self.protocol.handshake_exc is not None:
  93. raise self.protocol.handshake_exc
  94. def process_event(self, event: Event) -> None:
  95. """
  96. Process one incoming event.
  97. """
  98. # First event - handshake response.
  99. if self.response is None:
  100. assert isinstance(event, Response)
  101. self.response = event
  102. self.response_rcvd.set_result(None)
  103. # Later events - frames.
  104. else:
  105. super().process_event(event)
  106. # This is spelled in lower case because it's exposed as a callable in the API.
  107. class connect:
  108. """
  109. Connect to the WebSocket server at ``uri``.
  110. :func:`connect` should be treated as an asynchronous context manager
  111. yielding a :class:`ClientConnection`, which can then receive and send
  112. messages::
  113. from websockets.asyncio.client import connect
  114. async with connect(...) as websocket:
  115. ...
  116. The connection is closed automatically when exiting the context.
  117. :func:`connect` can also be treated as an infinite asynchronous iterator
  118. to reconnect automatically on errors::
  119. async for websocket in connect(...):
  120. try:
  121. ...
  122. except websockets.exceptions.ConnectionClosed:
  123. continue
  124. If the connection fails with a transient error, it is retried with
  125. exponential backoff. If it fails with a fatal error, the exception is
  126. raised, breaking out of the loop.
  127. The connection is closed automatically after each iteration of the loop.
  128. :func:`connect` can be awaited directly::
  129. websocket = await connect(...)
  130. In that case, you're responsible for closing the connection with
  131. :meth:`ClientConnection.close` when no longer needed.
  132. Args:
  133. uri: URI of the WebSocket server.
  134. origin: Value of the ``Origin`` header, for servers that require it.
  135. extensions: List of supported extensions, in order in which they
  136. should be negotiated and run.
  137. subprotocols: List of supported subprotocols, in order of decreasing
  138. preference.
  139. compression: The "permessage-deflate" extension is enabled by default.
  140. Set ``compression`` to :obj:`None` to disable it. See the
  141. :doc:`compression guide <../../topics/compression>` for details.
  142. additional_headers: Arbitrary HTTP headers to add to the handshake
  143. request.
  144. user_agent_header: Value of the ``User-Agent`` request header.
  145. It defaults to ``"Python/x.y.z websockets/X.Y"``.
  146. Setting it to :obj:`None` removes the header.
  147. proxy: If a proxy is configured, it is used by default. Set ``proxy``
  148. to :obj:`None` to disable the proxy or to the address of a proxy
  149. to override the system configuration. See the :doc:`proxy docs
  150. <../../topics/proxies>` for details.
  151. process_exception: When reconnecting automatically, tell whether an
  152. error is transient or fatal. The default behavior is defined by
  153. :func:`~websockets.client.process_exception`. Refer to its
  154. documentation for details.
  155. open_timeout: Timeout for opening the connection in seconds.
  156. :obj:`None` disables the timeout.
  157. ping_interval: Interval between keepalive pings in seconds.
  158. :obj:`None` disables keepalive.
  159. ping_timeout: Timeout for keepalive pings in seconds.
  160. :obj:`None` disables timeouts.
  161. close_timeout: Timeout for closing the connection in seconds.
  162. :obj:`None` disables the timeout.
  163. reconnect_delays: Delays in seconds between reconnection attempts.
  164. Default is exponential backoff with 5s jitter, capped at 60s.
  165. max_size: Maximum size of incoming messages in bytes.
  166. :obj:`None` disables the limit. You may pass a ``(max_message_size,
  167. max_fragment_size)`` tuple to set different limits for messages and
  168. fragments when you expect long messages sent in short fragments.
  169. max_queue: High-water mark of the buffer where frames are received.
  170. It defaults to 16 frames. The low-water mark defaults to ``max_queue
  171. // 4``. You may pass a ``(high, low)`` tuple to set the high-water
  172. and low-water marks. If you want to disable flow control entirely,
  173. you may set it to ``None``, although that's a bad idea.
  174. write_limit: High-water mark of write buffer in bytes. It is passed to
  175. :meth:`~asyncio.WriteTransport.set_write_buffer_limits`. It defaults
  176. to 32 KiB. You may pass a ``(high, low)`` tuple to set the
  177. high-water and low-water marks.
  178. logger: Logger for this client.
  179. It defaults to ``logging.getLogger("websockets.client")``.
  180. See the :doc:`logging guide <../../topics/logging>` for details.
  181. create_connection: Factory for the :class:`ClientConnection` managing
  182. the connection. Set it to a wrapper or a subclass to customize
  183. connection handling.
  184. Any other keyword arguments are passed to the event loop's
  185. :meth:`~asyncio.loop.create_connection` method.
  186. For example:
  187. * You can set ``sock`` to provide a preexisting TCP socket. You may call
  188. :func:`socket.create_connection` (not to be confused with the event loop's
  189. :meth:`~asyncio.loop.create_connection` method) to create a suitable
  190. client socket and customize it.
  191. * You can set ``ssl`` to a :class:`~ssl.SSLContext` to enforce TLS settings.
  192. When connecting to a ``wss://`` URI, if ``ssl`` isn't provided, a TLS
  193. context is created with :func:`~ssl.create_default_context`.
  194. * You can set ``server_hostname`` to override the host name from ``uri`` in
  195. the TLS handshake.
  196. * You can configure ``ssl_handshake_timeout`` and ``ssl_shutdown_timeout``.
  197. * You can set ``host`` and ``port`` to connect to a different host and port
  198. from those found in ``uri``. This only changes the destination of the TCP
  199. connection. The host name from ``uri`` is still used in the TLS handshake
  200. for secure connections and in the ``Host`` header.
  201. When using a proxy:
  202. * Prefix keyword arguments with ``proxy_`` for configuring TLS between the
  203. client and an HTTPS proxy: ``proxy_ssl``, ``proxy_server_hostname``,
  204. ``proxy_ssl_handshake_timeout``, and ``proxy_ssl_shutdown_timeout``.
  205. * Use the standard keyword arguments for configuring TLS between the proxy
  206. and the WebSocket server: ``ssl``, ``server_hostname``,
  207. ``ssl_handshake_timeout``, and ``ssl_shutdown_timeout``.
  208. * Other keyword arguments are used only for connecting to the proxy.
  209. Raises:
  210. InvalidURI: If ``uri`` isn't a valid WebSocket URI.
  211. InvalidProxy: If ``proxy`` isn't a valid proxy.
  212. OSError: If the TCP connection fails.
  213. InvalidHandshake: If the opening handshake fails.
  214. TimeoutError: If the opening handshake times out.
  215. """
  216. def __init__(
  217. self,
  218. uri: str,
  219. *,
  220. # WebSocket
  221. origin: Origin | None = None,
  222. extensions: Sequence[ClientExtensionFactory] | None = None,
  223. subprotocols: Sequence[Subprotocol] | None = None,
  224. compression: str | None = "deflate",
  225. # HTTP
  226. additional_headers: HeadersLike | None = None,
  227. user_agent_header: str | None = USER_AGENT,
  228. proxy: str | Literal[True] | None = True,
  229. process_exception: Callable[[Exception], Exception | None] = process_exception,
  230. # Timeouts
  231. open_timeout: float | None = 10,
  232. ping_interval: float | None = 20,
  233. ping_timeout: float | None = 20,
  234. close_timeout: float | None = 10,
  235. reconnect_delays: Callable[[], Generator[float]] = backoff,
  236. # Limits
  237. max_size: int | None | tuple[int | None, int | None] = 2**20,
  238. max_queue: int | None | tuple[int | None, int | None] = 16,
  239. write_limit: int | tuple[int, int | None] = 2**15,
  240. # Logging
  241. logger: LoggerLike | None = None,
  242. # Escape hatches for advanced customization
  243. create_connection: type[ClientConnection] | None = None,
  244. # Other keyword arguments are passed to loop.create_connection
  245. **kwargs: Any,
  246. ) -> None:
  247. self.uri = uri
  248. self.ws_uri = parse_uri(uri)
  249. if not self.ws_uri.secure and kwargs.get("ssl") is not None:
  250. raise ValueError("ssl argument is incompatible with a ws:// URI")
  251. if subprotocols is not None:
  252. validate_subprotocols(subprotocols)
  253. if compression == "deflate":
  254. extensions = enable_client_permessage_deflate(extensions)
  255. elif compression is not None:
  256. raise ValueError(f"unsupported compression: {compression}")
  257. if logger is None:
  258. logger = logging.getLogger("websockets.client")
  259. if create_connection is None:
  260. create_connection = ClientConnection
  261. self.additional_headers = additional_headers
  262. self.user_agent_header = user_agent_header
  263. self.proxy = proxy
  264. self.process_exception = process_exception
  265. self.open_timeout = open_timeout
  266. self.reconnect_delays = reconnect_delays
  267. self.logger = logger
  268. self.create_connection_kwargs = kwargs
  269. def factory(uri: WebSocketURI) -> ClientConnection:
  270. # This is a protocol in the Sans-I/O implementation of websockets.
  271. protocol = ClientProtocol(
  272. uri,
  273. origin=origin,
  274. extensions=extensions,
  275. subprotocols=subprotocols,
  276. max_size=max_size,
  277. logger=logger,
  278. )
  279. # This is a connection in websockets and a protocol in asyncio.
  280. # create_connection defaults to ClientConnection.
  281. connection = create_connection(
  282. protocol,
  283. ping_interval=ping_interval,
  284. ping_timeout=ping_timeout,
  285. close_timeout=close_timeout,
  286. max_queue=max_queue,
  287. write_limit=write_limit,
  288. )
  289. return connection
  290. self.factory = factory
  291. async def open_tcp_connection(self) -> ClientConnection:
  292. """Open a TCP or Unix connection to the server, possibly through a proxy."""
  293. loop = asyncio.get_running_loop()
  294. kwargs = self.create_connection_kwargs.copy()
  295. proxy = self.proxy
  296. if kwargs.get("unix", False):
  297. proxy = None
  298. if kwargs.get("sock") is not None:
  299. proxy = None
  300. if proxy is True:
  301. proxy = get_proxy(self.ws_uri)
  302. def factory() -> ClientConnection:
  303. return self.factory(self.ws_uri)
  304. if self.ws_uri.secure:
  305. kwargs.setdefault("ssl", True)
  306. if kwargs.get("ssl") is None:
  307. raise ValueError("ssl=None is incompatible with a wss:// URI")
  308. kwargs.setdefault("server_hostname", self.ws_uri.host)
  309. if kwargs.pop("unix", False):
  310. _, connection = await loop.create_unix_connection(factory, **kwargs)
  311. return connection
  312. if proxy is not None:
  313. proxy_parsed = parse_proxy(proxy)
  314. if proxy_parsed.scheme[:5] == "socks":
  315. # Connect to the server through the SOCKS proxy.
  316. sock = await connect_socks_proxy(
  317. proxy_parsed,
  318. self.ws_uri,
  319. # python_socks uses local_addr like asyncio.
  320. local_addr=kwargs.pop("local_addr", None),
  321. )
  322. # Initialize WebSocket connection via the proxy.
  323. _, connection = await loop.create_connection(
  324. factory,
  325. sock=sock,
  326. **kwargs,
  327. )
  328. return connection
  329. elif proxy_parsed.scheme[:4] == "http":
  330. # Split keyword arguments between the proxy and the server.
  331. all_kwargs, proxy_kwargs, kwargs = kwargs, {}, {}
  332. for key, value in all_kwargs.items():
  333. if key.startswith("ssl") or key == "server_hostname":
  334. kwargs[key] = value
  335. elif key.startswith("proxy_"):
  336. proxy_kwargs[key[6:]] = value
  337. else:
  338. proxy_kwargs[key] = value
  339. # Validate the proxy_ssl argument.
  340. if proxy_parsed.scheme == "https":
  341. proxy_kwargs.setdefault("ssl", True)
  342. if proxy_kwargs.get("ssl") is None:
  343. raise ValueError(
  344. "proxy_ssl=None is incompatible with an https:// proxy"
  345. )
  346. else:
  347. if proxy_kwargs.get("ssl") is not None:
  348. raise ValueError(
  349. "proxy_ssl argument is incompatible with an http:// proxy"
  350. )
  351. # Connect to the server through the HTTP proxy.
  352. transport = await connect_http_proxy(
  353. proxy_parsed,
  354. self.ws_uri,
  355. user_agent_header=self.user_agent_header,
  356. **proxy_kwargs,
  357. )
  358. # Initialize WebSocket connection via the proxy.
  359. connection = factory()
  360. transport.set_protocol(connection)
  361. ssl = kwargs.pop("ssl", None)
  362. if ssl is True:
  363. ssl = ssl_module.create_default_context()
  364. if ssl is not None:
  365. new_transport = await loop.start_tls(
  366. transport, connection, ssl, **kwargs
  367. )
  368. assert new_transport is not None # help mypy
  369. transport = new_transport
  370. connection.connection_made(transport)
  371. return connection
  372. else:
  373. raise AssertionError("parse_proxy returned unsupported proxy")
  374. else: # proxy is None
  375. # Connect to the server directly.
  376. if kwargs.get("sock") is None:
  377. kwargs.setdefault("host", self.ws_uri.host)
  378. kwargs.setdefault("port", self.ws_uri.port)
  379. # Initialize WebSocket connection.
  380. _, connection = await loop.create_connection(factory, **kwargs)
  381. return connection
  382. def process_redirect(self, exc: Exception) -> Exception | str:
  383. """
  384. Determine whether a connection error is a redirect that can be followed.
  385. Return the new URI if it's a valid redirect. Else, return an exception.
  386. """
  387. if not (
  388. isinstance(exc, InvalidStatus)
  389. and exc.response.status_code
  390. in [
  391. 300, # Multiple Choices
  392. 301, # Moved Permanently
  393. 302, # Found
  394. 303, # See Other
  395. 307, # Temporary Redirect
  396. 308, # Permanent Redirect
  397. ]
  398. and "Location" in exc.response.headers
  399. ):
  400. return exc
  401. old_ws_uri = self.ws_uri
  402. new_uri = urllib.parse.urljoin(self.uri, exc.response.headers["Location"])
  403. new_ws_uri = parse_uri(new_uri)
  404. # If connect() received a socket, it is closed and cannot be reused.
  405. if self.create_connection_kwargs.get("sock") is not None:
  406. return ValueError(
  407. f"cannot follow redirect to {new_uri} with a preexisting socket"
  408. )
  409. # TLS downgrade is forbidden.
  410. if old_ws_uri.secure and not new_ws_uri.secure:
  411. return SecurityError(f"cannot follow redirect to non-secure URI {new_uri}")
  412. # Apply restrictions to cross-origin redirects.
  413. if (
  414. old_ws_uri.secure != new_ws_uri.secure
  415. or old_ws_uri.host != new_ws_uri.host
  416. or old_ws_uri.port != new_ws_uri.port
  417. ):
  418. # Cross-origin redirects on Unix sockets don't quite make sense.
  419. if self.create_connection_kwargs.get("unix", False):
  420. return ValueError(
  421. f"cannot follow cross-origin redirect to {new_uri} "
  422. f"with a Unix socket"
  423. )
  424. # Cross-origin redirects when host and port are overridden are ill-defined.
  425. if (
  426. self.create_connection_kwargs.get("host") is not None
  427. or self.create_connection_kwargs.get("port") is not None
  428. ):
  429. return ValueError(
  430. f"cannot follow cross-origin redirect to {new_uri} "
  431. f"with an explicit host or port"
  432. )
  433. # Strip credentials to avoid leaking them to a different origin.
  434. if self.additional_headers is not None:
  435. self.additional_headers = Headers(
  436. (
  437. (key, value)
  438. for key, value in Headers(self.additional_headers).raw_items()
  439. if key.lower()
  440. not in ["authorization", "cookie", "proxy-authorization"]
  441. )
  442. )
  443. return new_uri
  444. async def connect(self) -> ClientConnection:
  445. try:
  446. async with asyncio.timeout(self.open_timeout):
  447. for _ in range(MAX_REDIRECTS):
  448. connection = await self.open_tcp_connection()
  449. try:
  450. await connection.handshake(
  451. self.additional_headers,
  452. self.user_agent_header,
  453. )
  454. except asyncio.CancelledError:
  455. connection.transport.abort()
  456. raise
  457. except Exception as exc:
  458. # Always close the connection even though keep-alive is
  459. # the default in HTTP/1.1 because create_connection ties
  460. # opening the network connection with initializing the
  461. # protocol. In the current design of connect(), there is
  462. # no easy way to reuse the network connection that works
  463. # in every case nor to reinitialize the protocol.
  464. connection.transport.abort()
  465. exc_or_uri = self.process_redirect(exc)
  466. if isinstance(exc_or_uri, Exception):
  467. # Response isn't a valid redirect; raise the exception.
  468. if exc_or_uri is exc:
  469. raise
  470. else:
  471. raise exc_or_uri from exc
  472. else:
  473. # Response is a valid redirect; follow it.
  474. self.uri = exc_or_uri
  475. self.ws_uri = parse_uri(exc_or_uri)
  476. continue
  477. else:
  478. connection.start_keepalive()
  479. return connection
  480. else:
  481. raise SecurityError(f"more than {MAX_REDIRECTS} redirects")
  482. except TimeoutError as exc:
  483. # Re-raise exception with an informative error message.
  484. raise TimeoutError("timed out during opening handshake") from exc
  485. # ... = await connect(...)
  486. def __await__(self) -> Generator[Any, None, ClientConnection]:
  487. # Create a suitable iterator by calling __await__ on a coroutine.
  488. return self.connect().__await__()
  489. # async with connect(...) as ...: ...
  490. async def __aenter__(self) -> ClientConnection:
  491. if hasattr(self, "connection"):
  492. raise RuntimeError("connect() isn't reentrant")
  493. self.connection = await self
  494. return self.connection
  495. async def __aexit__(
  496. self,
  497. exc_type: type[BaseException] | None,
  498. exc_value: BaseException | None,
  499. traceback: TracebackType | None,
  500. ) -> None:
  501. try:
  502. await self.connection.close()
  503. finally:
  504. del self.connection
  505. # async for ... in connect(...):
  506. async def __aiter__(self) -> AsyncIterator[ClientConnection]:
  507. delays: Generator[float] | None = None
  508. while True:
  509. try:
  510. async with self as connection:
  511. yield connection
  512. except Exception as exc:
  513. # Determine whether the exception is retryable or fatal.
  514. # The API of process_exception is "return an exception or None";
  515. # "raise an exception" is also supported because it's a frequent
  516. # mistake. It isn't documented in order to keep the API simple.
  517. try:
  518. new_exc = self.process_exception(exc)
  519. except Exception as raised_exc:
  520. new_exc = raised_exc
  521. # The connection failed with a fatal error.
  522. # Raise the exception and exit the loop.
  523. if new_exc is exc:
  524. raise
  525. if new_exc is not None:
  526. raise new_exc from exc
  527. # The connection failed with a retryable error.
  528. # Start or continue backoff and reconnect.
  529. if delays is None:
  530. delays = self.reconnect_delays()
  531. delay = next(delays)
  532. self.logger.info(
  533. "connect failed; reconnecting in %.1f seconds: %s",
  534. delay,
  535. traceback.format_exception_only(exc)[0].strip(),
  536. )
  537. await asyncio.sleep(delay)
  538. else:
  539. # The connection succeeded. Reset backoff.
  540. delays = None
  541. def unix_connect(
  542. path: PathLike | None = None,
  543. uri: str | None = None,
  544. **kwargs: Any,
  545. ) -> connect:
  546. """
  547. Connect to a WebSocket server listening on a Unix socket.
  548. This function accepts the same keyword arguments as :func:`connect`.
  549. It's only available on Unix.
  550. It's mainly useful for debugging servers listening on Unix sockets.
  551. Args:
  552. path: File system path to the Unix socket.
  553. uri: URI of the WebSocket server. ``uri`` defaults to
  554. ``ws://localhost/`` or, when a ``ssl`` argument is provided, to
  555. ``wss://localhost/``.
  556. """
  557. if uri is None:
  558. if kwargs.get("ssl") is None:
  559. uri = "ws://localhost/"
  560. else:
  561. uri = "wss://localhost/"
  562. return connect(uri=uri, unix=True, path=path, **kwargs)
  563. try:
  564. from python_socks import ProxyType
  565. from python_socks.async_.asyncio import Proxy as SocksProxy
  566. except ImportError:
  567. async def connect_socks_proxy(
  568. proxy: Proxy,
  569. ws_uri: WebSocketURI,
  570. **kwargs: Any,
  571. ) -> socket.socket:
  572. raise ImportError("connecting through a SOCKS proxy requires python-socks")
  573. else:
  574. SOCKS_PROXY_TYPES = {
  575. "socks5h": ProxyType.SOCKS5,
  576. "socks5": ProxyType.SOCKS5,
  577. "socks4a": ProxyType.SOCKS4,
  578. "socks4": ProxyType.SOCKS4,
  579. }
  580. SOCKS_PROXY_RDNS = {
  581. "socks5h": True,
  582. "socks5": False,
  583. "socks4a": True,
  584. "socks4": False,
  585. }
  586. async def connect_socks_proxy(
  587. proxy: Proxy,
  588. ws_uri: WebSocketURI,
  589. **kwargs: Any,
  590. ) -> socket.socket:
  591. """Connect via a SOCKS proxy and return the socket."""
  592. socks_proxy = SocksProxy(
  593. SOCKS_PROXY_TYPES[proxy.scheme],
  594. proxy.host,
  595. proxy.port,
  596. proxy.username,
  597. proxy.password,
  598. SOCKS_PROXY_RDNS[proxy.scheme],
  599. )
  600. # connect() is documented to raise OSError.
  601. # socks_proxy.connect() doesn't raise TimeoutError; it gets canceled.
  602. # Wrap other exceptions in ProxyError, a subclass of InvalidHandshake.
  603. try:
  604. return await socks_proxy.connect(ws_uri.host, ws_uri.port, **kwargs)
  605. except OSError:
  606. raise
  607. except Exception as exc:
  608. raise ProxyError("failed to connect to SOCKS proxy") from exc
  609. class HTTPProxyConnection(asyncio.Protocol):
  610. def __init__(
  611. self,
  612. ws_uri: WebSocketURI,
  613. proxy: Proxy,
  614. user_agent_header: str | None = None,
  615. ):
  616. self.ws_uri = ws_uri
  617. self.proxy = proxy
  618. self.user_agent_header = user_agent_header
  619. self.reader = StreamReader()
  620. self.parser = Response.parse(
  621. self.reader.read_line,
  622. self.reader.read_exact,
  623. self.reader.read_to_eof,
  624. proxy=True,
  625. )
  626. loop = asyncio.get_running_loop()
  627. self.response: asyncio.Future[Response] = loop.create_future()
  628. def run_parser(self) -> None:
  629. try:
  630. next(self.parser)
  631. except StopIteration as exc:
  632. response = exc.value
  633. if 200 <= response.status_code < 300:
  634. self.response.set_result(response)
  635. else:
  636. self.response.set_exception(InvalidProxyStatus(response))
  637. except Exception as exc:
  638. proxy_exc = InvalidProxyMessage(
  639. "did not receive a valid HTTP response from proxy"
  640. )
  641. proxy_exc.__cause__ = exc
  642. self.response.set_exception(proxy_exc)
  643. def connection_made(self, transport: asyncio.BaseTransport) -> None:
  644. transport = cast(asyncio.Transport, transport)
  645. self.transport = transport
  646. self.transport.write(
  647. prepare_connect_request(self.proxy, self.ws_uri, self.user_agent_header)
  648. )
  649. def data_received(self, data: bytes) -> None:
  650. self.reader.feed_data(data)
  651. self.run_parser()
  652. def eof_received(self) -> None:
  653. self.reader.feed_eof()
  654. self.run_parser()
  655. def connection_lost(self, exc: Exception | None) -> None:
  656. self.reader.feed_eof()
  657. self.run_parser()
  658. async def connect_http_proxy(
  659. proxy: Proxy,
  660. ws_uri: WebSocketURI,
  661. *,
  662. user_agent_header: str | None = None,
  663. **kwargs: Any,
  664. ) -> asyncio.Transport:
  665. transport, protocol = await asyncio.get_running_loop().create_connection(
  666. lambda: HTTPProxyConnection(ws_uri, proxy, user_agent_header),
  667. proxy.host,
  668. proxy.port,
  669. **kwargs,
  670. )
  671. try:
  672. # This raises exceptions if the connection to the proxy fails.
  673. await protocol.response
  674. except (asyncio.CancelledError, Exception):
  675. transport.abort()
  676. raise
  677. return transport