Debian Codegraph @

src/websockets/asyncio/client.py

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