Debian Codegraph @

third_party/python/aiohttp/aiohttp/connector.py

raw
1 import asyncio
2 import functools
3 import random
4 import socket
5 import sys
6 import traceback
7 import warnings
8 from collections import OrderedDict, defaultdict
9 from contextlib import suppress
10 from http import HTTPStatus
11 from itertools import chain, cycle, islice
12 from time import monotonic
13 from types import TracebackType
14 from typing import (
15 TYPE_CHECKING,
16 Any,
17 Awaitable,
18 Callable,
19 DefaultDict,
20 Dict,
21 Iterator,
22 List,
23 Literal,
24 Optional,
25 Sequence,
26 Set,
27 Tuple,
28 Type,
29 Union,
30 cast,
31 )
32
33 import aiohappyeyeballs
34 import attr
35
36 from . import hdrs, helpers
37 from .abc import AbstractResolver, ResolveResult
38 from .client_exceptions import (
39 ClientConnectionError,
40 ClientConnectorCertificateError,
41 ClientConnectorDNSError,
42 ClientConnectorError,
43 ClientConnectorSSLError,
44 ClientHttpProxyError,
45 ClientProxyConnectionError,
46 ServerFingerprintMismatch,
47 UnixClientConnectorError,
48 cert_errors,
49 ssl_errors,
50 )
51 from .client_proto import ResponseHandler
52 from .client_reqrep import ClientRequest, Fingerprint, _merge_ssl_params
53 from .helpers import (
54 ceil_timeout,
55 is_ip_address,
56 noop,
57 sentinel,
58 set_exception,
59 set_result,
60 )
61 from .resolver import DefaultResolver
62
63 try:
64 import ssl
65
66 SSLContext = ssl.SSLContext
67 except ImportError: # pragma: no cover
68 ssl = None # type: ignore[assignment]
69 SSLContext = object # type: ignore[misc,assignment]
70
71
72 EMPTY_SCHEMA_SET = frozenset({""})
73 HTTP_SCHEMA_SET = frozenset({"http", "https"})
74 WS_SCHEMA_SET = frozenset({"ws", "wss"})
75
76 HTTP_AND_EMPTY_SCHEMA_SET = HTTP_SCHEMA_SET | EMPTY_SCHEMA_SET
77 HIGH_LEVEL_SCHEMA_SET = HTTP_AND_EMPTY_SCHEMA_SET | WS_SCHEMA_SET
78
79 NEEDS_CLEANUP_CLOSED = (3, 13, 0) <= sys.version_info < (
80 3,
81 13,
82 1,
83 ) or sys.version_info < (3, 12, 7)
84 # Cleanup closed is no longer needed after https://github.com/python/cpython/pull/118960
85 # which first appeared in Python 3.12.7 and 3.13.1
86
87
88 __all__ = ("BaseConnector", "TCPConnector", "UnixConnector", "NamedPipeConnector")
89
90
91 if TYPE_CHECKING:
92 from .client import ClientTimeout
93 from .client_reqrep import ConnectionKey
94 from .tracing import Trace
95
96
97 class _DeprecationWaiter:
98 __slots__ = ("_awaitable", "_awaited")
99
100 def __init__(self, awaitable: Awaitable[Any]) -> None:
101 self._awaitable = awaitable
102 self._awaited = False
103
104 def __await__(self) -> Any:
105 self._awaited = True
106 return self._awaitable.__await__()
107
108 def __del__(self) -> None:
109 if not self._awaited:
110 warnings.warn(
111 "Connector.close() is a coroutine, "
112 "please use await connector.close()",
113 DeprecationWarning,
114 )
115
116
117 class Connection:
118
119 _source_traceback = None
120
121 def __init__(
122 self,
123 connector: "BaseConnector",
124 key: "ConnectionKey",
125 protocol: ResponseHandler,
126 loop: asyncio.AbstractEventLoop,
127 ) -> None:
128 self._key = key
129 self._connector = connector
130 self._loop = loop
131 self._protocol: Optional[ResponseHandler] = protocol
132 self._callbacks: List[Callable[[], None]] = []
133
134 if loop.get_debug():
135 self._source_traceback = traceback.extract_stack(sys._getframe(1))
136
137 def __repr__(self) -> str:
138 return f"Connection<{self._key}>"
139
140 def __del__(self, _warnings: Any = warnings) -> None:
141 if self._protocol is not None:
142 kwargs = {"source": self}
143 _warnings.warn(f"Unclosed connection {self!r}", ResourceWarning, **kwargs)
144 if self._loop.is_closed():
145 return
146
147 self._connector._release(self._key, self._protocol, should_close=True)
148
149 context = {"client_connection": self, "message": "Unclosed connection"}
150 if self._source_traceback is not None:
151 context["source_traceback"] = self._source_traceback
152 self._loop.call_exception_handler(context)
153
154 def __bool__(self) -> Literal[True]:
155 """Force subclasses to not be falsy, to make checks simpler."""
156 return True
157
158 @property
159 def loop(self) -> asyncio.AbstractEventLoop:
160 warnings.warn(
161 "connector.loop property is deprecated", DeprecationWarning, stacklevel=2
162 )
163 return self._loop
164
165 @property
166 def transport(self) -> Optional[asyncio.Transport]:
167 if self._protocol is None:
168 return None
169 return self._protocol.transport
170
171 @property
172 def protocol(self) -> Optional[ResponseHandler]:
173 return self._protocol
174
175 def add_callback(self, callback: Callable[[], None]) -> None:
176 if callback is not None:
177 self._callbacks.append(callback)
178
179 def _notify_release(self) -> None:
180 callbacks, self._callbacks = self._callbacks[:], []
181
182 for cb in callbacks:
183 with suppress(Exception):
184 cb()
185
186 def close(self) -> None:
187 self._notify_release()
188
189 if self._protocol is not None:
190 self._connector._release(self._key, self._protocol, should_close=True)
191 self._protocol = None
192
193 def release(self) -> None:
194 self._notify_release()
195
196 if self._protocol is not None:
197 self._connector._release(self._key, self._protocol)
198 self._protocol = None
199
200 @property
201 def closed(self) -> bool:
202 return self._protocol is None or not self._protocol.is_connected()
203
204
205 class _TransportPlaceholder:
206 """placeholder for BaseConnector.connect function"""
207
208 __slots__ = ()
209
210 def close(self) -> None:
211 """Close the placeholder transport."""
212
213
214 class BaseConnector:
215 """Base connector class.
216
217 keepalive_timeout - (optional) Keep-alive timeout.
218 force_close - Set to True to force close and do reconnect
219 after each request (and between redirects).
220 limit - The total number of simultaneous connections.
221 limit_per_host - Number of simultaneous connections to one host.
222 enable_cleanup_closed - Enables clean-up closed ssl transports.
223 Disabled by default.
224 timeout_ceil_threshold - Trigger ceiling of timeout values when
225 it's above timeout_ceil_threshold.
226 loop - Optional event loop.
227 """
228
229 _closed = True # prevent AttributeError in __del__ if ctor was failed
230 _source_traceback = None
231
232 # abort transport after 2 seconds (cleanup broken connections)
233 _cleanup_closed_period = 2.0
234
235 allowed_protocol_schema_set = HIGH_LEVEL_SCHEMA_SET
236
237 def __init__(
238 self,
239 *,
240 keepalive_timeout: Union[object, None, float] = sentinel,
241 force_close: bool = False,
242 limit: int = 100,
243 limit_per_host: int = 0,
244 enable_cleanup_closed: bool = False,
245 loop: Optional[asyncio.AbstractEventLoop] = None,
246 timeout_ceil_threshold: float = 5,
247 ) -> None:
248
249 if force_close:
250 if keepalive_timeout is not None and keepalive_timeout is not sentinel:
251 raise ValueError(
252 "keepalive_timeout cannot " "be set if force_close is True"
253 )
254 else:
255 if keepalive_timeout is sentinel:
256 keepalive_timeout = 15.0
257
258 loop = loop or asyncio.get_running_loop()
259 self._timeout_ceil_threshold = timeout_ceil_threshold
260
261 self._closed = False
262 if loop.get_debug():
263 self._source_traceback = traceback.extract_stack(sys._getframe(1))
264
265 self._conns: Dict[ConnectionKey, List[Tuple[ResponseHandler, float]]] = {}
266 self._limit = limit
267 self._limit_per_host = limit_per_host
268 self._acquired: Set[ResponseHandler] = set()
269 self._acquired_per_host: DefaultDict[ConnectionKey, Set[ResponseHandler]] = (
270 defaultdict(set)
271 )
272 self._keepalive_timeout = cast(float, keepalive_timeout)
273 self._force_close = force_close
274
275 # {host_key: FIFO list of waiters}
276 # The FIFO is implemented with an OrderedDict with None keys because
277 # python does not have an ordered set.
278 self._waiters: DefaultDict[
279 ConnectionKey, OrderedDict[asyncio.Future[None], None]
280 ] = defaultdict(OrderedDict)
281
282 self._loop = loop
283 self._factory = functools.partial(ResponseHandler, loop=loop)
284
285 # start keep-alive connection cleanup task
286 self._cleanup_handle: Optional[asyncio.TimerHandle] = None
287
288 # start cleanup closed transports task
289 self._cleanup_closed_handle: Optional[asyncio.TimerHandle] = None
290
291 if enable_cleanup_closed and not NEEDS_CLEANUP_CLOSED:
292 warnings.warn(
293 "enable_cleanup_closed ignored because "
294 "https://github.com/python/cpython/pull/118960 is fixed "
295 f"in Python version {sys.version_info}",
296 DeprecationWarning,
297 stacklevel=2,
298 )
299 enable_cleanup_closed = False
300
301 self._cleanup_closed_disabled = not enable_cleanup_closed
302 self._cleanup_closed_transports: List[Optional[asyncio.Transport]] = []
303 self._cleanup_closed()
304
305 def __del__(self, _warnings: Any = warnings) -> None:
306 if self._closed:
307 return
308 if not self._conns:
309 return
310
311 conns = [repr(c) for c in self._conns.values()]
312
313 self._close()
314
315 kwargs = {"source": self}
316 _warnings.warn(f"Unclosed connector {self!r}", ResourceWarning, **kwargs)
317 context = {
318 "connector": self,
319 "connections": conns,
320 "message": "Unclosed connector",
321 }
322 if self._source_traceback is not None:
323 context["source_traceback"] = self._source_traceback
324 self._loop.call_exception_handler(context)
325
326 def __enter__(self) -> "BaseConnector":
327 warnings.warn(
328 '"with Connector():" is deprecated, '
329 'use "async with Connector():" instead',
330 DeprecationWarning,
331 )
332 return self
333
334 def __exit__(self, *exc: Any) -> None:
335 self._close()
336
337 async def __aenter__(self) -> "BaseConnector":
338 return self
339
340 async def __aexit__(
341 self,
342 exc_type: Optional[Type[BaseException]] = None,
343 exc_value: Optional[BaseException] = None,
344 exc_traceback: Optional[TracebackType] = None,
345 ) -> None:
346 await self.close()
347
348 @property
349 def force_close(self) -> bool:
350 """Ultimately close connection on releasing if True."""
351 return self._force_close
352
353 @property
354 def limit(self) -> int:
355 """The total number for simultaneous connections.
356
357 If limit is 0 the connector has no limit.
358 The default limit size is 100.
359 """
360 return self._limit
361
362 @property
363 def limit_per_host(self) -> int:
364 """The limit for simultaneous connections to the same endpoint.
365
366 Endpoints are the same if they are have equal
367 (host, port, is_ssl) triple.
368 """
369 return self._limit_per_host
370
371 def _cleanup(self) -> None:
372 """Cleanup unused transports."""
373 if self._cleanup_handle:
374 self._cleanup_handle.cancel()
375 # _cleanup_handle should be unset, otherwise _release() will not
376 # recreate it ever!
377 self._cleanup_handle = None
378
379 now = monotonic()
380 timeout = self._keepalive_timeout
381
382 if self._conns:
383 connections = {}
384 deadline = now - timeout
385 for key, conns in self._conns.items():
386 alive: List[Tuple[ResponseHandler, float]] = []
387 for proto, use_time in conns:
388 if proto.is_connected() and use_time - deadline >= 0:
389 alive.append((proto, use_time))
390 continue
391 transport = proto.transport
392 proto.close()
393 if not self._cleanup_closed_disabled and key.is_ssl:
394 self._cleanup_closed_transports.append(transport)
395
396 if alive:
397 connections[key] = alive
398
399 self._conns = connections
400
401 if self._conns:
402 self._cleanup_handle = helpers.weakref_handle(
403 self,
404 "_cleanup",
405 timeout,
406 self._loop,
407 timeout_ceil_threshold=self._timeout_ceil_threshold,
408 )
409
410 def _cleanup_closed(self) -> None:
411 """Double confirmation for transport close.
412
413 Some broken ssl servers may leave socket open without proper close.
414 """
415 if self._cleanup_closed_handle:
416 self._cleanup_closed_handle.cancel()
417
418 for transport in self._cleanup_closed_transports:
419 if transport is not None:
420 transport.abort()
421
422 self._cleanup_closed_transports = []
423
424 if not self._cleanup_closed_disabled:
425 self._cleanup_closed_handle = helpers.weakref_handle(
426 self,
427 "_cleanup_closed",
428 self._cleanup_closed_period,
429 self._loop,
430 timeout_ceil_threshold=self._timeout_ceil_threshold,
431 )
432
433 def close(self) -> Awaitable[None]:
434 """Close all opened transports."""
435 self._close()
436 return _DeprecationWaiter(noop())
437
438 def _close(self) -> None:
439 if self._closed:
440 return
441
442 self._closed = True
443
444 try:
445 if self._loop.is_closed():
446 return
447
448 # cancel cleanup task
449 if self._cleanup_handle:
450 self._cleanup_handle.cancel()
451
452 # cancel cleanup close task
453 if self._cleanup_closed_handle:
454 self._cleanup_closed_handle.cancel()
455
456 for data in self._conns.values():
457 for proto, t0 in data:
458 proto.close()
459
460 for proto in self._acquired:
461 proto.close()
462
463 for transport in self._cleanup_closed_transports:
464 if transport is not None:
465 transport.abort()
466
467 finally:
468 self._conns.clear()
469 self._acquired.clear()
470 for keyed_waiters in self._waiters.values():
471 for keyed_waiter in keyed_waiters:
472 keyed_waiter.cancel()
473 self._waiters.clear()
474 self._cleanup_handle = None
475 self._cleanup_closed_transports.clear()
476 self._cleanup_closed_handle = None
477
478 @property
479 def closed(self) -> bool:
480 """Is connector closed.
481
482 A readonly property.
483 """
484 return self._closed
485
486 def _available_connections(self, key: "ConnectionKey") -> int:
487 """
488 Return number of available connections.
489
490 The limit, limit_per_host and the connection key are taken into account.
491
492 If it returns less than 1 means that there are no connections
493 available.
494 """
495 # check total available connections
496 # If there are no limits, this will always return 1
497 total_remain = 1
498
499 if self._limit and (total_remain := self._limit - len(self._acquired)) <= 0:
500 return total_remain
501
502 # check limit per host
503 if host_remain := self._limit_per_host:
504 if acquired := self._acquired_per_host.get(key):
505 host_remain -= len(acquired)
506 if total_remain > host_remain:
507 return host_remain
508
509 return total_remain
510
511 async def connect(
512 self, req: ClientRequest, traces: List["Trace"], timeout: "ClientTimeout"
513 ) -> Connection:
514 """Get from pool or create new connection."""
515 key = req.connection_key
516 if (conn := await self._get(key, traces)) is not None:
517 # If we do not have to wait and we can get a connection from the pool
518 # we can avoid the timeout ceil logic and directly return the connection
519 return conn
520
521 async with ceil_timeout(timeout.connect, timeout.ceil_threshold):
522 if self._available_connections(key) <= 0:
523 await self._wait_for_available_connection(key, traces)
524 if (conn := await self._get(key, traces)) is not None:
525 return conn
526
527 placeholder = cast(ResponseHandler, _TransportPlaceholder())
528 self._acquired.add(placeholder)
529 self._acquired_per_host[key].add(placeholder)
530
531 try:
532 # Traces are done inside the try block to ensure that the
533 # that the placeholder is still cleaned up if an exception
534 # is raised.
535 if traces:
536 for trace in traces:
537 await trace.send_connection_create_start()
538 proto = await self._create_connection(req, traces, timeout)
539 if traces:
540 for trace in traces:
541 await trace.send_connection_create_end()
542 except BaseException:
543 self._release_acquired(key, placeholder)
544 raise
545 else:
546 if self._closed:
547 proto.close()
548 raise ClientConnectionError("Connector is closed.")
549
550 # The connection was successfully created, drop the placeholder
551 # and add the real connection to the acquired set. There should
552 # be no awaits after the proto is added to the acquired set
553 # to ensure that the connection is not left in the acquired set
554 # on cancellation.
555 acquired_per_host = self._acquired_per_host[key]
556 self._acquired.remove(placeholder)
557 acquired_per_host.remove(placeholder)
558 self._acquired.add(proto)
559 acquired_per_host.add(proto)
560 return Connection(self, key, proto, self._loop)
561
562 async def _wait_for_available_connection(
563 self, key: "ConnectionKey", traces: List["Trace"]
564 ) -> None:
565 """Wait for an available connection slot."""
566 # We loop here because there is a race between
567 # the connection limit check and the connection
568 # being acquired. If the connection is acquired
569 # between the check and the await statement, we
570 # need to loop again to check if the connection
571 # slot is still available.
572 attempts = 0
573 while True:
574 fut: asyncio.Future[None] = self._loop.create_future()
575 keyed_waiters = self._waiters[key]
576 keyed_waiters[fut] = None
577 if attempts:
578 # If we have waited before, we need to move the waiter
579 # to the front of the queue as otherwise we might get
580 # starved and hit the timeout.
581 keyed_waiters.move_to_end(fut, last=False)
582
583 try:
584 # Traces happen in the try block to ensure that the
585 # the waiter is still cleaned up if an exception is raised.
586 if traces:
587 for trace in traces:
588 await trace.send_connection_queued_start()
589 await fut
590 if traces:
591 for trace in traces:
592 await trace.send_connection_queued_end()
593 finally:
594 # pop the waiter from the queue if its still
595 # there and not already removed by _release_waiter
596 keyed_waiters.pop(fut, None)
597 if not self._waiters.get(key, True):
598 del self._waiters[key]
599
600 if self._available_connections(key) > 0:
601 break
602 attempts += 1
603
604 async def _get(
605 self, key: "ConnectionKey", traces: List["Trace"]
606 ) -> Optional[Connection]:
607 """Get next reusable connection for the key or None.
608
609 The connection will be marked as acquired.
610 """
611 try:
612 conns = self._conns[key]
613 except KeyError:
614 return None
615
616 t1 = monotonic()
617 while conns:
618 proto, t0 = conns.pop()
619 # We will we reuse the connection if its connected and
620 # the keepalive timeout has not been exceeded
621 if proto.is_connected() and t1 - t0 <= self._keepalive_timeout:
622 if not conns:
623 # The very last connection was reclaimed: drop the key
624 del self._conns[key]
625 self._acquired.add(proto)
626 self._acquired_per_host[key].add(proto)
627 if traces:
628 for trace in traces:
629 try:
630 await trace.send_connection_reuseconn()
631 except BaseException:
632 self._release_acquired(key, proto)
633 raise
634 return Connection(self, key, proto, self._loop)
635
636 # Connection cannot be reused, close it
637 transport = proto.transport
638 proto.close()
639 # only for SSL transports
640 if not self._cleanup_closed_disabled and key.is_ssl:
641 self._cleanup_closed_transports.append(transport)
642
643 # No more connections: drop the key
644 del self._conns[key]
645 return None
646
647 def _release_waiter(self) -> None:
648 """
649 Iterates over all waiters until one to be released is found.
650
651 The one to be released is not finished and
652 belongs to a host that has available connections.
653 """
654 if not self._waiters:
655 return
656
657 # Having the dict keys ordered this avoids to iterate
658 # at the same order at each call.
659 queues = list(self._waiters)
660 random.shuffle(queues)
661
662 for key in queues:
663 if self._available_connections(key) < 1:
664 continue
665
666 waiters = self._waiters[key]
667 while waiters:
668 waiter, _ = waiters.popitem(last=False)
669 if not waiter.done():
670 waiter.set_result(None)
671 return
672
673 def _release_acquired(self, key: "ConnectionKey", proto: ResponseHandler) -> None:
674 """Release acquired connection."""
675 if self._closed:
676 # acquired connection is already released on connector closing
677 return
678
679 self._acquired.discard(proto)
680 if conns := self._acquired_per_host.get(key):
681 conns.discard(proto)
682 if not conns:
683 del self._acquired_per_host[key]
684 self._release_waiter()
685
686 def _release(
687 self,
688 key: "ConnectionKey",
689 protocol: ResponseHandler,
690 *,
691 should_close: bool = False,
692 ) -> None:
693 if self._closed:
694 # acquired connection is already released on connector closing
695 return
696
697 self._release_acquired(key, protocol)
698
699 if self._force_close:
700 should_close = True
701
702 if should_close or protocol.should_close:
703 transport = protocol.transport
704 protocol.close()
705
706 if key.is_ssl and not self._cleanup_closed_disabled:
707 self._cleanup_closed_transports.append(transport)
708 return
709
710 conns = self._conns.get(key)
711 if conns is None:
712 conns = self._conns[key] = []
713 conns.append((protocol, monotonic()))
714
715 if self._cleanup_handle is None:
716 self._cleanup_handle = helpers.weakref_handle(
717 self,
718 "_cleanup",
719 self._keepalive_timeout,
720 self._loop,
721 timeout_ceil_threshold=self._timeout_ceil_threshold,
722 )
723
724 async def _create_connection(
725 self, req: ClientRequest, traces: List["Trace"], timeout: "ClientTimeout"
726 ) -> ResponseHandler:
727 raise NotImplementedError()
728
729
730 class _DNSCacheTable:
731 def __init__(self, ttl: Optional[float] = None) -> None:
732 self._addrs_rr: Dict[Tuple[str, int], Tuple[Iterator[ResolveResult], int]] = {}
733 self._timestamps: Dict[Tuple[str, int], float] = {}
734 self._ttl = ttl
735
736 def __contains__(self, host: object) -> bool:
737 return host in self._addrs_rr
738
739 def add(self, key: Tuple[str, int], addrs: List[ResolveResult]) -> None:
740 self._addrs_rr[key] = (cycle(addrs), len(addrs))
741
742 if self._ttl is not None:
743 self._timestamps[key] = monotonic()
744
745 def remove(self, key: Tuple[str, int]) -> None:
746 self._addrs_rr.pop(key, None)
747
748 if self._ttl is not None:
749 self._timestamps.pop(key, None)
750
751 def clear(self) -> None:
752 self._addrs_rr.clear()
753 self._timestamps.clear()
754
755 def next_addrs(self, key: Tuple[str, int]) -> List[ResolveResult]:
756 loop, length = self._addrs_rr[key]
757 addrs = list(islice(loop, length))
758 # Consume one more element to shift internal state of `cycle`
759 next(loop)
760 return addrs
761
762 def expired(self, key: Tuple[str, int]) -> bool:
763 if self._ttl is None:
764 return False
765
766 return self._timestamps[key] + self._ttl < monotonic()
767
768
769 def _make_ssl_context(verified: bool) -> SSLContext:
770 """Create SSL context.
771
772 This method is not async-friendly and should be called from a thread
773 because it will load certificates from disk and do other blocking I/O.
774 """
775 if ssl is None:
776 # No ssl support
777 return None
778 if verified:
779 return ssl.create_default_context()
780 sslcontext = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
781 sslcontext.options |= ssl.OP_NO_SSLv2
782 sslcontext.options |= ssl.OP_NO_SSLv3
783 sslcontext.check_hostname = False
784 sslcontext.verify_mode = ssl.CERT_NONE
785 sslcontext.options |= ssl.OP_NO_COMPRESSION
786 sslcontext.set_default_verify_paths()
787 return sslcontext
788
789
790 # The default SSLContext objects are created at import time
791 # since they do blocking I/O to load certificates from disk,
792 # and imports should always be done before the event loop starts
793 # or in a thread.
794 _SSL_CONTEXT_VERIFIED = _make_ssl_context(True)
795 _SSL_CONTEXT_UNVERIFIED = _make_ssl_context(False)
796
797
798 class TCPConnector(BaseConnector):
799 """TCP connector.
800
801 verify_ssl - Set to True to check ssl certifications.
802 fingerprint - Pass the binary sha256
803 digest of the expected certificate in DER format to verify
804 that the certificate the server presents matches. See also
805 https://en.wikipedia.org/wiki/HTTP_Public_Key_Pinning
806 resolver - Enable DNS lookups and use this
807 resolver
808 use_dns_cache - Use memory cache for DNS lookups.
809 ttl_dns_cache - Max seconds having cached a DNS entry, None forever.
810 family - socket address family
811 local_addr - local tuple of (host, port) to bind socket to
812
813 keepalive_timeout - (optional) Keep-alive timeout.
814 force_close - Set to True to force close and do reconnect
815 after each request (and between redirects).
816 limit - The total number of simultaneous connections.
817 limit_per_host - Number of simultaneous connections to one host.
818 enable_cleanup_closed - Enables clean-up closed ssl transports.
819 Disabled by default.
820 happy_eyeballs_delay - This is the “Connection Attempt Delay”
821 as defined in RFC 8305. To disable
822 the happy eyeballs algorithm, set to None.
823 interleave - “First Address Family Count” as defined in RFC 8305
824 loop - Optional event loop.
825 """
826
827 allowed_protocol_schema_set = HIGH_LEVEL_SCHEMA_SET | frozenset({"tcp"})
828
829 def __init__(
830 self,
831 *,
832 verify_ssl: bool = True,
833 fingerprint: Optional[bytes] = None,
834 use_dns_cache: bool = True,
835 ttl_dns_cache: Optional[int] = 10,
836 family: socket.AddressFamily = socket.AddressFamily.AF_UNSPEC,
837 ssl_context: Optional[SSLContext] = None,
838 ssl: Union[bool, Fingerprint, SSLContext] = True,
839 local_addr: Optional[Tuple[str, int]] = None,
840 resolver: Optional[AbstractResolver] = None,
841 keepalive_timeout: Union[None, float, object] = sentinel,
842 force_close: bool = False,
843 limit: int = 100,
844 limit_per_host: int = 0,
845 enable_cleanup_closed: bool = False,
846 loop: Optional[asyncio.AbstractEventLoop] = None,
847 timeout_ceil_threshold: float = 5,
848 happy_eyeballs_delay: Optional[float] = 0.25,
849 interleave: Optional[int] = None,
850 ):
851 super().__init__(
852 keepalive_timeout=keepalive_timeout,
853 force_close=force_close,
854 limit=limit,
855 limit_per_host=limit_per_host,
856 enable_cleanup_closed=enable_cleanup_closed,
857 loop=loop,
858 timeout_ceil_threshold=timeout_ceil_threshold,
859 )
860
861 self._ssl = _merge_ssl_params(ssl, verify_ssl, ssl_context, fingerprint)
862 if resolver is None:
863 resolver = DefaultResolver(loop=self._loop)
864 self._resolver = resolver
865
866 self._use_dns_cache = use_dns_cache
867 self._cached_hosts = _DNSCacheTable(ttl=ttl_dns_cache)
868 self._throttle_dns_futures: Dict[
869 Tuple[str, int], Set["asyncio.Future[None]"]
870 ] = {}
871 self._family = family
872 self._local_addr_infos = aiohappyeyeballs.addr_to_addr_infos(local_addr)
873 self._happy_eyeballs_delay = happy_eyeballs_delay
874 self._interleave = interleave
875 self._resolve_host_tasks: Set["asyncio.Task[List[ResolveResult]]"] = set()
876
877 def close(self) -> Awaitable[None]:
878 """Close all ongoing DNS calls."""
879 for fut in chain.from_iterable(self._throttle_dns_futures.values()):
880 fut.cancel()
881
882 for t in self._resolve_host_tasks:
883 t.cancel()
884
885 return super().close()
886
887 @property
888 def family(self) -> int:
889 """Socket family like AF_INET."""
890 return self._family
891
892 @property
893 def use_dns_cache(self) -> bool:
894 """True if local DNS caching is enabled."""
895 return self._use_dns_cache
896
897 def clear_dns_cache(
898 self, host: Optional[str] = None, port: Optional[int] = None
899 ) -> None:
900 """Remove specified host/port or clear all dns local cache."""
901 if host is not None and port is not None:
902 self._cached_hosts.remove((host, port))
903 elif host is not None or port is not None:
904 raise ValueError("either both host and port " "or none of them are allowed")
905 else:
906 self._cached_hosts.clear()
907
908 async def _resolve_host(
909 self, host: str, port: int, traces: Optional[Sequence["Trace"]] = None
910 ) -> List[ResolveResult]:
911 """Resolve host and return list of addresses."""
912 if is_ip_address(host):
913 return [
914 {
915 "hostname": host,
916 "host": host,
917 "port": port,
918 "family": self._family,
919 "proto": 0,
920 "flags": 0,
921 }
922 ]
923
924 if not self._use_dns_cache:
925
926 if traces:
927 for trace in traces:
928 await trace.send_dns_resolvehost_start(host)
929
930 res = await self._resolver.resolve(host, port, family=self._family)
931
932 if traces:
933 for trace in traces:
934 await trace.send_dns_resolvehost_end(host)
935
936 return res
937
938 key = (host, port)
939 if key in self._cached_hosts and not self._cached_hosts.expired(key):
940 # get result early, before any await (#4014)
941 result = self._cached_hosts.next_addrs(key)
942
943 if traces:
944 for trace in traces:
945 await trace.send_dns_cache_hit(host)
946 return result
947
948 futures: Set["asyncio.Future[None]"]
949 #
950 # If multiple connectors are resolving the same host, we wait
951 # for the first one to resolve and then use the result for all of them.
952 # We use a throttle to ensure that we only resolve the host once
953 # and then use the result for all the waiters.
954 #
955 if key in self._throttle_dns_futures:
956 # get futures early, before any await (#4014)
957 futures = self._throttle_dns_futures[key]
958 future: asyncio.Future[None] = self._loop.create_future()
959 futures.add(future)
960 if traces:
961 for trace in traces:
962 await trace.send_dns_cache_hit(host)
963 try:
964 await future
965 finally:
966 futures.discard(future)
967 return self._cached_hosts.next_addrs(key)
968
969 # update dict early, before any await (#4014)
970 self._throttle_dns_futures[key] = futures = set()
971 # In this case we need to create a task to ensure that we can shield
972 # the task from cancellation as cancelling this lookup should not cancel
973 # the underlying lookup or else the cancel event will get broadcast to
974 # all the waiters across all connections.
975 #
976 coro = self._resolve_host_with_throttle(key, host, port, futures, traces)
977 loop = asyncio.get_running_loop()
978 if sys.version_info >= (3, 12):
979 # Optimization for Python 3.12, try to send immediately
980 resolved_host_task = asyncio.Task(coro, loop=loop, eager_start=True)
981 else:
982 resolved_host_task = loop.create_task(coro)
983
984 if not resolved_host_task.done():
985 self._resolve_host_tasks.add(resolved_host_task)
986 resolved_host_task.add_done_callback(self._resolve_host_tasks.discard)
987
988 try:
989 return await asyncio.shield(resolved_host_task)
990 except asyncio.CancelledError:
991
992 def drop_exception(fut: "asyncio.Future[List[ResolveResult]]") -> None:
993 with suppress(Exception, asyncio.CancelledError):
994 fut.result()
995
996 resolved_host_task.add_done_callback(drop_exception)
997 raise
998
999 async def _resolve_host_with_throttle(
1000 self,
1001 key: Tuple[str, int],
1002 host: str,
1003 port: int,
1004 futures: Set["asyncio.Future[None]"],
1005 traces: Optional[Sequence["Trace"]],
1006 ) -> List[ResolveResult]:
1007 """Resolve host and set result for all waiters.
1008
1009 This method must be run in a task and shielded from cancellation
1010 to avoid cancelling the underlying lookup.
1011 """
1012 if traces:
1013 for trace in traces:
1014 await trace.send_dns_cache_miss(host)
1015 try:
1016 if traces:
1017 for trace in traces:
1018 await trace.send_dns_resolvehost_start(host)
1019
1020 addrs = await self._resolver.resolve(host, port, family=self._family)
1021 if traces:
1022 for trace in traces:
1023 await trace.send_dns_resolvehost_end(host)
1024
1025 self._cached_hosts.add(key, addrs)
1026 for fut in futures:
1027 set_result(fut, None)
1028 except BaseException as e:
1029 # any DNS exception is set for the waiters to raise the same exception.
1030 # This coro is always run in task that is shielded from cancellation so
1031 # we should never be propagating cancellation here.
1032 for fut in futures:
1033 set_exception(fut, e)
1034 raise
1035 finally:
1036 self._throttle_dns_futures.pop(key)
1037
1038 return self._cached_hosts.next_addrs(key)
1039
1040 async def _create_connection(
1041 self, req: ClientRequest, traces: List["Trace"], timeout: "ClientTimeout"
1042 ) -> ResponseHandler:
1043 """Create connection.
1044
1045 Has same keyword arguments as BaseEventLoop.create_connection.
1046 """
1047 if req.proxy:
1048 _, proto = await self._create_proxy_connection(req, traces, timeout)
1049 else:
1050 _, proto = await self._create_direct_connection(req, traces, timeout)
1051
1052 return proto
1053
1054 def _get_ssl_context(self, req: ClientRequest) -> Optional[SSLContext]:
1055 """Logic to get the correct SSL context
1056
1057 0. if req.ssl is false, return None
1058
1059 1. if ssl_context is specified in req, use it
1060 2. if _ssl_context is specified in self, use it
1061 3. otherwise:
1062 1. if verify_ssl is not specified in req, use self.ssl_context
1063 (will generate a default context according to self.verify_ssl)
1064 2. if verify_ssl is True in req, generate a default SSL context
1065 3. if verify_ssl is False in req, generate a SSL context that
1066 won't verify
1067 """
1068 if not req.is_ssl():
1069 return None
1070
1071 if ssl is None: # pragma: no cover
1072 raise RuntimeError("SSL is not supported.")
1073 sslcontext = req.ssl
1074 if isinstance(sslcontext, ssl.SSLContext):
1075 return sslcontext
1076 if sslcontext is not True:
1077 # not verified or fingerprinted
1078 return _SSL_CONTEXT_UNVERIFIED
1079 sslcontext = self._ssl
1080 if isinstance(sslcontext, ssl.SSLContext):
1081 return sslcontext
1082 if sslcontext is not True:
1083 # not verified or fingerprinted
1084 return _SSL_CONTEXT_UNVERIFIED
1085 return _SSL_CONTEXT_VERIFIED
1086
1087 def _get_fingerprint(self, req: ClientRequest) -> Optional["Fingerprint"]:
1088 ret = req.ssl
1089 if isinstance(ret, Fingerprint):
1090 return ret
1091 ret = self._ssl
1092 if isinstance(ret, Fingerprint):
1093 return ret
1094 return None
1095
1096 async def _wrap_create_connection(
1097 self,
1098 *args: Any,
1099 addr_infos: List[aiohappyeyeballs.AddrInfoType],
1100 req: ClientRequest,
1101 timeout: "ClientTimeout",
1102 client_error: Type[Exception] = ClientConnectorError,
1103 **kwargs: Any,
1104 ) -> Tuple[asyncio.Transport, ResponseHandler]:
1105 try:
1106 async with ceil_timeout(
1107 timeout.sock_connect, ceil_threshold=timeout.ceil_threshold
1108 ):
1109 sock = await aiohappyeyeballs.start_connection(
1110 addr_infos=addr_infos,
1111 local_addr_infos=self._local_addr_infos,
1112 happy_eyeballs_delay=self._happy_eyeballs_delay,
1113 interleave=self._interleave,
1114 loop=self._loop,
1115 )
1116 return await self._loop.create_connection(*args, **kwargs, sock=sock)
1117 except cert_errors as exc:
1118 raise ClientConnectorCertificateError(req.connection_key, exc) from exc
1119 except ssl_errors as exc:
1120 raise ClientConnectorSSLError(req.connection_key, exc) from exc
1121 except OSError as exc:
1122 if exc.errno is None and isinstance(exc, asyncio.TimeoutError):
1123 raise
1124 raise client_error(req.connection_key, exc) from exc
1125
1126 async def _wrap_existing_connection(
1127 self,
1128 *args: Any,
1129 req: ClientRequest,
1130 timeout: "ClientTimeout",
1131 client_error: Type[Exception] = ClientConnectorError,
1132 **kwargs: Any,
1133 ) -> Tuple[asyncio.Transport, ResponseHandler]:
1134 try:
1135 async with ceil_timeout(
1136 timeout.sock_connect, ceil_threshold=timeout.ceil_threshold
1137 ):
1138 return await self._loop.create_connection(*args, **kwargs)
1139 except cert_errors as exc:
1140 raise ClientConnectorCertificateError(req.connection_key, exc) from exc
1141 except ssl_errors as exc:
1142 raise ClientConnectorSSLError(req.connection_key, exc) from exc
1143 except OSError as exc:
1144 if exc.errno is None and isinstance(exc, asyncio.TimeoutError):
1145 raise
1146 raise client_error(req.connection_key, exc) from exc
1147
1148 def _fail_on_no_start_tls(self, req: "ClientRequest") -> None:
1149 """Raise a :py:exc:`RuntimeError` on missing ``start_tls()``.
1150
1151 It is necessary for TLS-in-TLS so that it is possible to
1152 send HTTPS queries through HTTPS proxies.
1153
1154 This doesn't affect regular HTTP requests, though.
1155 """
1156 if not req.is_ssl():
1157 return
1158
1159 proxy_url = req.proxy
1160 assert proxy_url is not None
1161 if proxy_url.scheme != "https":
1162 return
1163
1164 self._check_loop_for_start_tls()
1165
1166 def _check_loop_for_start_tls(self) -> None:
1167 try:
1168 self._loop.start_tls
1169 except AttributeError as attr_exc:
1170 raise RuntimeError(
1171 "An HTTPS request is being sent through an HTTPS proxy. "
1172 "This needs support for TLS in TLS but it is not implemented "
1173 "in your runtime for the stdlib asyncio.\n\n"
1174 "Please upgrade to Python 3.11 or higher. For more details, "
1175 "please see:\n"
1176 "* https://bugs.python.org/issue37179\n"
1177 "* https://github.com/python/cpython/pull/28073\n"
1178 "* https://docs.aiohttp.org/en/stable/"
1179 "client_advanced.html#proxy-support\n"
1180 "* https://github.com/aio-libs/aiohttp/discussions/6044\n",
1181 ) from attr_exc
1182
1183 def _loop_supports_start_tls(self) -> bool:
1184 try:
1185 self._check_loop_for_start_tls()
1186 except RuntimeError:
1187 return False
1188 else:
1189 return True
1190
1191 def _warn_about_tls_in_tls(
1192 self,
1193 underlying_transport: asyncio.Transport,
1194 req: ClientRequest,
1195 ) -> None:
1196 """Issue a warning if the requested URL has HTTPS scheme."""
1197 if req.request_info.url.scheme != "https":
1198 return
1199
1200 asyncio_supports_tls_in_tls = getattr(
1201 underlying_transport,
1202 "_start_tls_compatible",
1203 False,
1204 )
1205
1206 if asyncio_supports_tls_in_tls:
1207 return
1208
1209 warnings.warn(
1210 "An HTTPS request is being sent through an HTTPS proxy. "
1211 "This support for TLS in TLS is known to be disabled "
1212 "in the stdlib asyncio (Python <3.11). This is why you'll probably see "
1213 "an error in the log below.\n\n"
1214 "It is possible to enable it via monkeypatching. "
1215 "For more details, see:\n"
1216 "* https://bugs.python.org/issue37179\n"
1217 "* https://github.com/python/cpython/pull/28073\n\n"
1218 "You can temporarily patch this as follows:\n"
1219 "* https://docs.aiohttp.org/en/stable/client_advanced.html#proxy-support\n"
1220 "* https://github.com/aio-libs/aiohttp/discussions/6044\n",
1221 RuntimeWarning,
1222 source=self,
1223 # Why `4`? At least 3 of the calls in the stack originate
1224 # from the methods in this class.
1225 stacklevel=3,
1226 )
1227
1228 async def _start_tls_connection(
1229 self,
1230 underlying_transport: asyncio.Transport,
1231 req: ClientRequest,
1232 timeout: "ClientTimeout",
1233 client_error: Type[Exception] = ClientConnectorError,
1234 ) -> Tuple[asyncio.BaseTransport, ResponseHandler]:
1235 """Wrap the raw TCP transport with TLS."""
1236 tls_proto = self._factory() # Create a brand new proto for TLS
1237 sslcontext = self._get_ssl_context(req)
1238 if TYPE_CHECKING:
1239 # _start_tls_connection is unreachable in the current code path
1240 # if sslcontext is None.
1241 assert sslcontext is not None
1242
1243 try:
1244 async with ceil_timeout(
1245 timeout.sock_connect, ceil_threshold=timeout.ceil_threshold
1246 ):
1247 try:
1248 tls_transport = await self._loop.start_tls(
1249 underlying_transport,
1250 tls_proto,
1251 sslcontext,
1252 server_hostname=req.server_hostname or req.host,
1253 ssl_handshake_timeout=timeout.total,
1254 )
1255 except BaseException:
1256 # We need to close the underlying transport since
1257 # `start_tls()` probably failed before it had a
1258 # chance to do this:
1259 underlying_transport.close()
1260 raise
1261 except cert_errors as exc:
1262 raise ClientConnectorCertificateError(req.connection_key, exc) from exc
1263 except ssl_errors as exc:
1264 raise ClientConnectorSSLError(req.connection_key, exc) from exc
1265 except OSError as exc:
1266 if exc.errno is None and isinstance(exc, asyncio.TimeoutError):
1267 raise
1268 raise client_error(req.connection_key, exc) from exc
1269 except TypeError as type_err:
1270 # Example cause looks like this:
1271 # TypeError: transport <asyncio.sslproto._SSLProtocolTransport
1272 # object at 0x7f760615e460> is not supported by start_tls()
1273
1274 raise ClientConnectionError(
1275 "Cannot initialize a TLS-in-TLS connection to host "
1276 f"{req.host!s}:{req.port:d} through an underlying connection "
1277 f"to an HTTPS proxy {req.proxy!s} ssl:{req.ssl or 'default'} "
1278 f"[{type_err!s}]"
1279 ) from type_err
1280 else:
1281 if tls_transport is None:
1282 msg = "Failed to start TLS (possibly caused by closing transport)"
1283 raise client_error(req.connection_key, OSError(msg))
1284 tls_proto.connection_made(
1285 tls_transport
1286 ) # Kick the state machine of the new TLS protocol
1287
1288 return tls_transport, tls_proto
1289
1290 def _convert_hosts_to_addr_infos(
1291 self, hosts: List[ResolveResult]
1292 ) -> List[aiohappyeyeballs.AddrInfoType]:
1293 """Converts the list of hosts to a list of addr_infos.
1294
1295 The list of hosts is the result of a DNS lookup. The list of
1296 addr_infos is the result of a call to `socket.getaddrinfo()`.
1297 """
1298 addr_infos: List[aiohappyeyeballs.AddrInfoType] = []
1299 for hinfo in hosts:
1300 host = hinfo["host"]
1301 is_ipv6 = ":" in host
1302 family = socket.AF_INET6 if is_ipv6 else socket.AF_INET
1303 if self._family and self._family != family:
1304 continue
1305 addr = (host, hinfo["port"], 0, 0) if is_ipv6 else (host, hinfo["port"])
1306 addr_infos.append(
1307 (family, socket.SOCK_STREAM, socket.IPPROTO_TCP, "", addr)
1308 )
1309 return addr_infos
1310
1311 async def _create_direct_connection(
1312 self,
1313 req: ClientRequest,
1314 traces: List["Trace"],
1315 timeout: "ClientTimeout",
1316 *,
1317 client_error: Type[Exception] = ClientConnectorError,
1318 ) -> Tuple[asyncio.Transport, ResponseHandler]:
1319 sslcontext = self._get_ssl_context(req)
1320 fingerprint = self._get_fingerprint(req)
1321
1322 host = req.url.raw_host
1323 assert host is not None
1324 # Replace multiple trailing dots with a single one.
1325 # A trailing dot is only present for fully-qualified domain names.
1326 # See https://github.com/aio-libs/aiohttp/pull/7364.
1327 if host.endswith(".."):
1328 host = host.rstrip(".") + "."
1329 port = req.port
1330 assert port is not None
1331 try:
1332 # Cancelling this lookup should not cancel the underlying lookup
1333 # or else the cancel event will get broadcast to all the waiters
1334 # across all connections.
1335 hosts = await self._resolve_host(host, port, traces=traces)
1336 except OSError as exc:
1337 if exc.errno is None and isinstance(exc, asyncio.TimeoutError):
1338 raise
1339 # in case of proxy it is not ClientProxyConnectionError
1340 # it is problem of resolving proxy ip itself
1341 raise ClientConnectorDNSError(req.connection_key, exc) from exc
1342
1343 last_exc: Optional[Exception] = None
1344 addr_infos = self._convert_hosts_to_addr_infos(hosts)
1345 while addr_infos:
1346 # Strip trailing dots, certificates contain FQDN without dots.
1347 # See https://github.com/aio-libs/aiohttp/issues/3636
1348 server_hostname = (
1349 (req.server_hostname or host).rstrip(".") if sslcontext else None
1350 )
1351
1352 try:
1353 transp, proto = await self._wrap_create_connection(
1354 self._factory,
1355 timeout=timeout,
1356 ssl=sslcontext,
1357 addr_infos=addr_infos,
1358 server_hostname=server_hostname,
1359 req=req,
1360 client_error=client_error,
1361 )
1362 except (ClientConnectorError, asyncio.TimeoutError) as exc:
1363 last_exc = exc
1364 aiohappyeyeballs.pop_addr_infos_interleave(addr_infos, self._interleave)
1365 continue
1366
1367 if req.is_ssl() and fingerprint:
1368 try:
1369 fingerprint.check(transp)
1370 except ServerFingerprintMismatch as exc:
1371 transp.close()
1372 if not self._cleanup_closed_disabled:
1373 self._cleanup_closed_transports.append(transp)
1374 last_exc = exc
1375 # Remove the bad peer from the list of addr_infos
1376 sock: socket.socket = transp.get_extra_info("socket")
1377 bad_peer = sock.getpeername()
1378 aiohappyeyeballs.remove_addr_infos(addr_infos, bad_peer)
1379 continue
1380
1381 return transp, proto
1382 else:
1383 assert last_exc is not None
1384 raise last_exc
1385
1386 async def _create_proxy_connection(
1387 self, req: ClientRequest, traces: List["Trace"], timeout: "ClientTimeout"
1388 ) -> Tuple[asyncio.BaseTransport, ResponseHandler]:
1389 self._fail_on_no_start_tls(req)
1390 runtime_has_start_tls = self._loop_supports_start_tls()
1391
1392 headers: Dict[str, str] = {}
1393 if req.proxy_headers is not None:
1394 headers = req.proxy_headers # type: ignore[assignment]
1395 headers[hdrs.HOST] = req.headers[hdrs.HOST]
1396
1397 url = req.proxy
1398 assert url is not None
1399 proxy_req = ClientRequest(
1400 hdrs.METH_GET,
1401 url,
1402 headers=headers,
1403 auth=req.proxy_auth,
1404 loop=self._loop,
1405 ssl=req.ssl,
1406 )
1407
1408 # create connection to proxy server
1409 transport, proto = await self._create_direct_connection(
1410 proxy_req, [], timeout, client_error=ClientProxyConnectionError
1411 )
1412
1413 # Many HTTP proxies has buggy keepalive support. Let's not
1414 # reuse connection but close it after processing every
1415 # response.
1416 proto.force_close()
1417
1418 auth = proxy_req.headers.pop(hdrs.AUTHORIZATION, None)
1419 if auth is not None:
1420 if not req.is_ssl():
1421 req.headers[hdrs.PROXY_AUTHORIZATION] = auth
1422 else:
1423 proxy_req.headers[hdrs.PROXY_AUTHORIZATION] = auth
1424
1425 if req.is_ssl():
1426 if runtime_has_start_tls:
1427 self._warn_about_tls_in_tls(transport, req)
1428
1429 # For HTTPS requests over HTTP proxy
1430 # we must notify proxy to tunnel connection
1431 # so we send CONNECT command:
1432 # CONNECT www.python.org:443 HTTP/1.1
1433 # Host: www.python.org
1434 #
1435 # next we must do TLS handshake and so on
1436 # to do this we must wrap raw socket into secure one
1437 # asyncio handles this perfectly
1438 proxy_req.method = hdrs.METH_CONNECT
1439 proxy_req.url = req.url
1440 key = attr.evolve(
1441 req.connection_key, proxy=None, proxy_auth=None, proxy_headers_hash=None
1442 )
1443 conn = Connection(self, key, proto, self._loop)
1444 proxy_resp = await proxy_req.send(conn)
1445 try:
1446 protocol = conn._protocol
1447 assert protocol is not None
1448
1449 # read_until_eof=True will ensure the connection isn't closed
1450 # once the response is received and processed allowing
1451 # START_TLS to work on the connection below.
1452 protocol.set_response_params(
1453 read_until_eof=runtime_has_start_tls,
1454 timeout_ceil_threshold=self._timeout_ceil_threshold,
1455 )
1456 resp = await proxy_resp.start(conn)
1457 except BaseException:
1458 proxy_resp.close()
1459 conn.close()
1460 raise
1461 else:
1462 conn._protocol = None
1463 try:
1464 if resp.status != 200:
1465 message = resp.reason
1466 if message is None:
1467 message = HTTPStatus(resp.status).phrase
1468 raise ClientHttpProxyError(
1469 proxy_resp.request_info,
1470 resp.history,
1471 status=resp.status,
1472 message=message,
1473 headers=resp.headers,
1474 )
1475 if not runtime_has_start_tls:
1476 rawsock = transport.get_extra_info("socket", default=None)
1477 if rawsock is None:
1478 raise RuntimeError(
1479 "Transport does not expose socket instance"
1480 )
1481 # Duplicate the socket, so now we can close proxy transport
1482 rawsock = rawsock.dup()
1483 except BaseException:
1484 # It shouldn't be closed in `finally` because it's fed to
1485 # `loop.start_tls()` and the docs say not to touch it after
1486 # passing there.
1487 transport.close()
1488 raise
1489 finally:
1490 if not runtime_has_start_tls:
1491 transport.close()
1492
1493 if not runtime_has_start_tls:
1494 # HTTP proxy with support for upgrade to HTTPS
1495 sslcontext = self._get_ssl_context(req)
1496 return await self._wrap_existing_connection(
1497 self._factory,
1498 timeout=timeout,
1499 ssl=sslcontext,
1500 sock=rawsock,
1501 server_hostname=req.host,
1502 req=req,
1503 )
1504
1505 return await self._start_tls_connection(
1506 # Access the old transport for the last time before it's
1507 # closed and forgotten forever:
1508 transport,
1509 req=req,
1510 timeout=timeout,
1511 )
1512 finally:
1513 proxy_resp.close()
1514
1515 return transport, proto
1516
1517
1518 class UnixConnector(BaseConnector):
1519 """Unix socket connector.
1520
1521 path - Unix socket path.
1522 keepalive_timeout - (optional) Keep-alive timeout.
1523 force_close - Set to True to force close and do reconnect
1524 after each request (and between redirects).
1525 limit - The total number of simultaneous connections.
1526 limit_per_host - Number of simultaneous connections to one host.
1527 loop - Optional event loop.
1528 """
1529
1530 allowed_protocol_schema_set = HIGH_LEVEL_SCHEMA_SET | frozenset({"unix"})
1531
1532 def __init__(
1533 self,
1534 path: str,
1535 force_close: bool = False,
1536 keepalive_timeout: Union[object, float, None] = sentinel,
1537 limit: int = 100,
1538 limit_per_host: int = 0,
1539 loop: Optional[asyncio.AbstractEventLoop] = None,
1540 ) -> None:
1541 super().__init__(
1542 force_close=force_close,
1543 keepalive_timeout=keepalive_timeout,
1544 limit=limit,
1545 limit_per_host=limit_per_host,
1546 loop=loop,
1547 )
1548 self._path = path
1549
1550 @property
1551 def path(self) -> str:
1552 """Path to unix socket."""
1553 return self._path
1554
1555 async def _create_connection(
1556 self, req: ClientRequest, traces: List["Trace"], timeout: "ClientTimeout"
1557 ) -> ResponseHandler:
1558 try:
1559 async with ceil_timeout(
1560 timeout.sock_connect, ceil_threshold=timeout.ceil_threshold
1561 ):
1562 _, proto = await self._loop.create_unix_connection(
1563 self._factory, self._path
1564 )
1565 except OSError as exc:
1566 if exc.errno is None and isinstance(exc, asyncio.TimeoutError):
1567 raise
1568 raise UnixClientConnectorError(self.path, req.connection_key, exc) from exc
1569
1570 return proto
1571
1572
1573 class NamedPipeConnector(BaseConnector):
1574 """Named pipe connector.
1575
1576 Only supported by the proactor event loop.
1577 See also: https://docs.python.org/3/library/asyncio-eventloop.html
1578
1579 path - Windows named pipe path.
1580 keepalive_timeout - (optional) Keep-alive timeout.
1581 force_close - Set to True to force close and do reconnect
1582 after each request (and between redirects).
1583 limit - The total number of simultaneous connections.
1584 limit_per_host - Number of simultaneous connections to one host.
1585 loop - Optional event loop.
1586 """
1587
1588 allowed_protocol_schema_set = HIGH_LEVEL_SCHEMA_SET | frozenset({"npipe"})
1589
1590 def __init__(
1591 self,
1592 path: str,
1593 force_close: bool = False,
1594 keepalive_timeout: Union[object, float, None] = sentinel,
1595 limit: int = 100,
1596 limit_per_host: int = 0,
1597 loop: Optional[asyncio.AbstractEventLoop] = None,
1598 ) -> None:
1599 super().__init__(
1600 force_close=force_close,
1601 keepalive_timeout=keepalive_timeout,
1602 limit=limit,
1603 limit_per_host=limit_per_host,
1604 loop=loop,
1605 )
1606 if not isinstance(
1607 self._loop, asyncio.ProactorEventLoop # type: ignore[attr-defined]
1608 ):
1609 raise RuntimeError(
1610 "Named Pipes only available in proactor " "loop under windows"
1611 )
1612 self._path = path
1613
1614 @property
1615 def path(self) -> str:
1616 """Path to the named pipe."""
1617 return self._path
1618
1619 async def _create_connection(
1620 self, req: ClientRequest, traces: List["Trace"], timeout: "ClientTimeout"
1621 ) -> ResponseHandler:
1622 try:
1623 async with ceil_timeout(
1624 timeout.sock_connect, ceil_threshold=timeout.ceil_threshold
1625 ):
1626 _, proto = await self._loop.create_pipe_connection( # type: ignore[attr-defined]
1627 self._factory, self._path
1628 )
1629 # the drain is required so that the connection_made is called
1630 # and transport is set otherwise it is not set before the
1631 # `assert conn.transport is not None`
1632 # in client.py's _request method
1633 await asyncio.sleep(0)
1634 # other option is to manually set transport like
1635 # `proto.transport = trans`
1636 except OSError as exc:
1637 if exc.errno is None and isinstance(exc, asyncio.TimeoutError):
1638 raise
1639 raise ClientConnectorError(req.connection_key, exc) from exc
1640
1641 return cast(ResponseHandler, proto)