You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

821 lines
31 KiB

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