Given (host, port) and PoolOptions, return a NetworkingInterface wrapping a configured socket. Can raise socket.error, ConnectionFailure, or _CertificateError. Sets socket's SSL and timeout options.
(address: _Address, options: PoolOptions)
| 471 | |
| 472 | |
| 473 | def _configured_socket_interface(address: _Address, options: PoolOptions) -> NetworkingInterface: |
| 474 | """Given (host, port) and PoolOptions, return a NetworkingInterface wrapping a configured socket. |
| 475 | |
| 476 | Can raise socket.error, ConnectionFailure, or _CertificateError. |
| 477 | |
| 478 | Sets socket's SSL and timeout options. |
| 479 | """ |
| 480 | sock = _create_connection(address, options) |
| 481 | ssl_context = options._ssl_context |
| 482 | |
| 483 | if ssl_context is None: |
| 484 | sock.settimeout(options.socket_timeout) |
| 485 | return NetworkingInterface(sock) |
| 486 | |
| 487 | host = address[0] |
| 488 | try: |
| 489 | # We have to pass hostname / ip address to wrap_socket |
| 490 | # to use SSLContext.check_hostname. |
| 491 | if _has_sni(True): |
| 492 | ssl_sock = ssl_context.wrap_socket(sock, server_hostname=host) |
| 493 | else: |
| 494 | ssl_sock = ssl_context.wrap_socket(sock) |
| 495 | except _CertificateError: |
| 496 | sock.close() |
| 497 | # Raise _CertificateError directly like we do after match_hostname |
| 498 | # below. |
| 499 | raise |
| 500 | except (OSError, *SSLErrors) as exc: |
| 501 | sock.close() |
| 502 | # We raise AutoReconnect for transient and permanent SSL handshake |
| 503 | # failures alike. Permanent handshake failures, like protocol |
| 504 | # mismatch, will be turned into ServerSelectionTimeoutErrors later. |
| 505 | details = _get_timeout_details(options) |
| 506 | _raise_connection_failure(address, exc, "SSL handshake failed: ", timeout_details=details) |
| 507 | if ( |
| 508 | ssl_context.verify_mode |
| 509 | and not ssl_context.check_hostname |
| 510 | and not options.tls_allow_invalid_hostnames |
| 511 | ): |
| 512 | try: |
| 513 | ssl.match_hostname(ssl_sock.getpeercert(), hostname=host) # type:ignore[attr-defined,unused-ignore] |
| 514 | except _CertificateError: |
| 515 | ssl_sock.close() |
| 516 | raise |
| 517 | |
| 518 | ssl_sock.settimeout(options.socket_timeout) |
| 519 | return NetworkingInterface(ssl_sock) |
no test coverage detected