import datetime import http.client import logging import os import re import socket import sys import threading import typing import warnings from http.client import HTTPConnection as _HTTPConnection from http.client import HTTPException as HTTPException # noqa: F401 from http.client import ResponseNotReady from socket import timeout as SocketTimeout
if typing.TYPE_CHECKING: from .response import HTTPResponse from .util.ssl_ import _TYPE_PEER_CERT_RET_DICT from .util.ssltransport import SSLTransport
from ._collections import HTTPHeaderDict from .http2 import probe as http2_probe from .util.response import assert_header_parsing from .util.timeout import _DEFAULT_TIMEOUT, _TYPE_TIMEOUT, Timeout from .util.util import to_str from .util.wait import wait_for_read
class BaseSSLError(BaseException): # type: ignore[no-redef] pass
from ._base_connection import _TYPE_BODY from ._base_connection import ProxyConfig as ProxyConfig from ._base_connection import _ResponseOptions as _ResponseOptions from ._version import __version__ from .exceptions import (
ConnectTimeoutError,
HeaderParsingError,
NameResolutionError,
NewConnectionError,
ProxyError,
SystemTimeWarning,
) from .util import SKIP_HEADER, SKIPPABLE_HEADERS, connection, ssl_ from .util.request import body_to_chunks from .util.ssl_ import assert_fingerprint as _assert_fingerprint from .util.ssl_ import (
create_urllib3_context,
is_ipaddress,
resolve_cert_reqs,
resolve_ssl_version,
ssl_wrap_socket,
) from .util.ssl_match_hostname import CertificateError, match_hostname from .util.url import Url
# Not a no-op, we're adding this to the namespace so it can be imported.
ConnectionError = ConnectionError
BrokenPipeError = BrokenPipeError
log = logging.getLogger(__name__)
port_by_scheme = {"http": 80, "https": 443}
# When it comes time to update this value as a part of regular maintenance # (ie test_recent_date is failing) update it to ~6 months before the current date.
RECENT_DATE = datetime.date(2025, 1, 1)
class HTTPConnection(_HTTPConnection): """
Based on :class:`http.client.HTTPConnection` but provides an extra constructor
backwards-compatibility layer between older and newer Pythons.
Additional keyword parameters are used to configure attributes of the connection.
Accepted parameters include:
- ``source_address``: Set the source address for the current connection.
- ``socket_options``: Set specific options on the underlying socket. Ifnot specified, then
defaults are loaded from ``HTTPConnection.default_socket_options`` which includes disabling
Nagle's algorithm (sets TCP_NODELAY to 1) unless the connection is behind a proxy.
For example, if you wish to enable TCP Keep Alive in addition to the defaults,
you might pass:
#: Whether this connection verifies the host's certificate.
is_verified: bool = False
#: Whether this proxy connection verified the proxy host's certificate. # If no proxy is currently connected to the value will be ``None``.
proxy_is_verified: bool | None = None
@property def host(self) -> str: """
Getter method to remove any trailing dots that indicate the hostname is an FQDN.
In general, SSL certificates don't include the trailing dot indicating a
fully-qualified domain name, and thus, they don't validate properly when
checked against a domain name that includes the dot. In addition, some
servers may not expect to receive the trailing dot when provided.
However, the hostname with trailing dot is critical to DNS resolution; doing a
lookup with the trailing dot will properly only resolve the appropriate FQDN,
whereas a lookup without a trailing dot will search the system's search domain
list. Thus, it's important to keep the original host around for use only in
those cases where it's appropriate (i.e., when doing DNS lookup to establish the
actual TCP connection across which we're going to send HTTP requests). """ return self._dns_host.rstrip(".")
@host.setter def host(self, value: str) -> None: """
Setter for the `host` property.
We assume that only urllib3 uses the _dns_host attribute; httplib itself
only uses `host`, and it seems reasonable that other libraries follow suit. """
self._dns_host = value
def _new_conn(self) -> socket.socket: """Establish a socket connection and set nodelay settings on it.
:return: New socket connection. """ try:
sock = connection.create_connection(
(self._dns_host, self.port),
self.timeout,
source_address=self.source_address,
socket_options=self.socket_options,
) except socket.gaierror as e: raise NameResolutionError(self.host, self, e) from e except SocketTimeout as e: raise ConnectTimeoutError(
self,
f"Connection to {self.host} timed out. (connect timeout={self.timeout})",
) from e
except OSError as e: raise NewConnectionError(
self, f"Failed to establish a new connection: {e}"
) from e
def set_tunnel(
self,
host: str,
port: int | None = None,
headers: typing.Mapping[str, str] | None = None,
scheme: str = "http",
) -> None: if scheme notin ("http", "https"): raise ValueError(
f"Invalid proxy scheme for tunneling: {scheme!r}, must be either 'http' or 'https'"
)
super().set_tunnel(host, port=port, headers=headers)
self._tunnel_scheme = scheme
if sys.version_info < (3, 11, 9) or ((3, 12) <= sys.version_info < (3, 12, 3)): # Taken from python/cpython#100986 which was backported in 3.11.9 and 3.12.3. # When using connection_from_host, host will come without brackets. def _wrap_ipv6(self, ip: bytes) -> bytes: if b":"in ip and ip[0] != b"["[0]: return b"[" + ip + b"]" return ip
if sys.version_info < (3, 11, 9): # `_tunnel` copied from 3.11.13 backporting # https://github.com/python/cpython/commit/0d4026432591d43185568dd31cef6a034c4b9261 # and https://github.com/python/cpython/commit/6fbc61070fda2ffb8889e77e3b24bca4249ab4d1 def _tunnel(self) -> None:
_MAXLINE = http.client._MAXLINE # type: ignore[attr-defined]
connect = b"CONNECT %s:%d HTTP/1.0\r\n" % ( # type: ignore[str-format]
self._wrap_ipv6(self._tunnel_host.encode("ascii")), # type: ignore[union-attr]
self._tunnel_port,
)
headers = [connect] for header, value in self._tunnel_headers.items(): # type: ignore[attr-defined]
headers.append(f"{header}: {value}\r\n".encode("latin-1"))
headers.append(b"\r\n") # Making a single send() call instead of one per line encourages # the host OS to use a more optimal packet size instead of # potentially emitting a series of small packets.
self.send(b"".join(headers)) del headers
if code != http.HTTPStatus.OK:
self.close() raise OSError(
f"Tunnel connection failed: {code} {message.strip()}"
) whileTrue:
line = response.fp.readline(_MAXLINE + 1) if len(line) > _MAXLINE: raise http.client.LineTooLong("header line") ifnot line: # for sites which EOF without sending a trailer break if line in (b"\r\n", b"\n", b""): break
if self.debuglevel > 0:
print("header:", line.decode()) finally:
response.close()
elif (3, 12) <= sys.version_info < (3, 12, 3): # `_tunnel` copied from 3.12.11 backporting # https://github.com/python/cpython/commit/23aef575c7629abcd4aaf028ebd226fb41a4b3c8 def _tunnel(self) -> None: # noqa: F811
connect = b"CONNECT %s:%d HTTP/1.1\r\n" % ( # type: ignore[str-format]
self._wrap_ipv6(self._tunnel_host.encode("idna")), # type: ignore[union-attr]
self._tunnel_port,
)
headers = [connect] for header, value in self._tunnel_headers.items(): # type: ignore[attr-defined]
headers.append(f"{header}: {value}\r\n".encode("latin-1"))
headers.append(b"\r\n") # Making a single send() call instead of one per line encourages # the host OS to use a more optimal packet size instead of # potentially emitting a series of small packets.
self.send(b"".join(headers)) del headers
def connect(self) -> None:
self.sock = self._new_conn() if self._tunnel_host: # If we're tunneling it means we're connected to our proxy.
self._has_connected_to_proxy = True
# TODO: Fix tunnel so it doesn't depend on self.sock state.
self._tunnel()
# If there's a proxy to be connected to we are fully connected. # This is set twice (once above and here) due to forwarding proxies # not using tunnelling.
self._has_connected_to_proxy = bool(self.proxy)
if self._has_connected_to_proxy:
self.proxy_is_verified = False
@property def proxy_is_forwarding(self) -> bool: """ ReturnTrueif a forwarding proxy is configured, elsereturnFalse """ return bool(self.proxy) and self._tunnel_host isNone
@property def proxy_is_tunneling(self) -> bool: """ ReturnTrueif a tunneling proxy is configured, elsereturnFalse """ return self._tunnel_host isnotNone
def close(self) -> None: try:
super().close() finally: # Reset all stateful properties so connection # can be re-used without leaking prior configs.
self.sock = None
self.is_verified = False
self.proxy_is_verified = None
self._has_connected_to_proxy = False
self._response_options = None
self._tunnel_host = None
self._tunnel_port = None
self._tunnel_scheme = None
def putrequest(
self,
method: str,
url: str,
skip_host: bool = False,
skip_accept_encoding: bool = False,
) -> None: """""" # Empty docstring because the indentation of CPython's implementation # is broken but we don't want this method in our documentation.
match = _CONTAINS_CONTROL_CHAR_RE.search(method) if match: raise ValueError(
f"Method cannot contain non-token characters {method!r} (found at least {match.group()!r})"
)
def putheader(self, header: str, *values: str) -> None: # type: ignore[override] """""" ifnot any(isinstance(v, str) and v == SKIP_HEADER for v in values):
super().putheader(header, *values) elif to_str(header.lower()) notin SKIPPABLE_HEADERS:
skippable_headers = "', '".join(
[str.title(header) for header in sorted(SKIPPABLE_HEADERS)]
) raise ValueError(
f"urllib3.util.SKIP_HEADER only supports '{skippable_headers}'"
)
# `request` method's signature intentionally violates LSP. # urllib3's API is different from `http.client.HTTPConnection` and the subclassing is only incidental. def request( # type: ignore[override]
self,
method: str,
url: str,
body: _TYPE_BODY | None = None,
headers: typing.Mapping[str, str] | None = None,
*,
chunked: bool = False,
preload_content: bool = True,
decode_content: bool = True,
enforce_content_length: bool = True,
) -> None: # Update the inner socket's timeout value to send the request. # This only triggers if the connection is re-used. if self.sock isnotNone:
self.sock.settimeout(self.timeout)
# Store these values to be fed into the HTTPResponse # object later. TODO: Remove this in favor of a real # HTTP lifecycle mechanism.
# We have to store these before we call .request() # because sometimes we can still salvage a response # off the wire even if we aren't able to completely # send the request body.
self._response_options = _ResponseOptions(
request_method=method,
request_url=url,
preload_content=preload_content,
decode_content=decode_content,
enforce_content_length=enforce_content_length,
)
if headers isNone:
headers = {}
header_keys = frozenset(to_str(k.lower()) for k in headers)
skip_accept_encoding = "accept-encoding"in header_keys
skip_host = "host"in header_keys
self.putrequest(
method, url, skip_accept_encoding=skip_accept_encoding, skip_host=skip_host
)
# Transform the body into an iterable of sendall()-able chunks # and detect if an explicit Content-Length is doable.
chunks_and_cl = body_to_chunks(body, method=method, blocksize=self.blocksize)
chunks = chunks_and_cl.chunks
content_length = chunks_and_cl.content_length
# When chunked is explicit set to 'True' we respect that. if chunked: if"transfer-encoding"notin header_keys:
self.putheader("Transfer-Encoding", "chunked") else: # Detect whether a framing mechanism is already in use. If so # we respect that value, otherwise we pick chunked vs content-length # depending on the type of 'body'. if"content-length"in header_keys:
chunked = False elif"transfer-encoding"in header_keys:
chunked = True
# Otherwise we go off the recommendation of 'body_to_chunks()'. else:
chunked = False if content_length isNone: if chunks isnotNone:
chunked = True
self.putheader("Transfer-Encoding", "chunked") else:
self.putheader("Content-Length", str(content_length))
# Now that framing headers are out of the way we send all the other headers. if"user-agent"notin header_keys:
self.putheader("User-Agent", _get_default_user_agent()) for header, value in headers.items():
self.putheader(header, value)
self.endheaders()
# If we're given a body we start sending that in chunks. if chunks isnotNone: for chunk in chunks: # Sending empty chunks isn't allowed for TE: chunked # as it indicates the end of the body. ifnot chunk: continue if isinstance(chunk, str):
chunk = chunk.encode("utf-8") if chunked:
self.send(b"%x\r\n%b\r\n" % (len(chunk), chunk)) else:
self.send(chunk)
# Regardless of whether we have a body or not, if we're in # chunked mode we want to send an explicit empty chunk. if chunked:
self.send(b"0\r\n\r\n")
def request_chunked(
self,
method: str,
url: str,
body: _TYPE_BODY | None = None,
headers: typing.Mapping[str, str] | None = None,
) -> None: """
Alternative to the common request method, which sends the
body with chunked encoding andnotas one block """
warnings.warn( "HTTPConnection.request_chunked() is deprecated and will be removed " "in urllib3 v2.1.0. Instead use HTTPConnection.request(..., chunked=True).",
category=DeprecationWarning,
stacklevel=2,
)
self.request(method, url, body=body, headers=headers, chunked=True)
def getresponse( # type: ignore[override]
self,
) -> HTTPResponse: """
Get the response from the server.
If the HTTPConnection isin the correct state, returns an instance of HTTPResponse or of whatever object is returned by the response_class variable.
If a request has not been sent orif a previous response has not be handled, ResponseNotReady is raised. If the HTTP response indicates that the connection should be closed, then it will be closed before the response is returned. When the connection is closed, the underlying socket is closed. """ # Raise the same error as http.client.HTTPConnection if self._response_options isNone: raise ResponseNotReady()
# Reset this attribute for being used again.
resp_options = self._response_options
self._response_options = None
# Since the connection's timeout value may have been updated # we need to set the timeout on the socket.
self.sock.settimeout(self.timeout)
# This is needed here to avoid circular import errors from .response import HTTPResponse
# Save a reference to the shutdown function before ownership is passed # to httplib_response # TODO should we implement it everywhere?
_shutdown = getattr(self.sock, "shutdown", None)
# Get the response from http.client.HTTPConnection
httplib_response = super().getresponse()
try:
assert_header_parsing(httplib_response.msg) except (HeaderParsingError, TypeError) as hpe:
log.warning( "Failed to parse headers (url=%s): %s",
_url_from_connection(self, resp_options.request_url),
hpe,
exc_info=True,
)
class HTTPSConnection(HTTPConnection): """
Many of the parameters to this constructor are passed to the underlying SSL
socket by means of :py:func:`urllib3.util.ssl_wrap_socket`. """
# cert_reqs depends on ssl_context so calculate last. if cert_reqs isNone: if self.ssl_context isnotNone:
cert_reqs = self.ssl_context.verify_mode else:
cert_reqs = resolve_cert_reqs(None)
self.cert_reqs = cert_reqs
self._connect_callback = None
def set_cert(
self,
key_file: str | None = None,
cert_file: str | None = None,
cert_reqs: int | str | None = None,
key_password: str | None = None,
ca_certs: str | None = None,
assert_hostname: None | str | typing.Literal[False] = None,
assert_fingerprint: str | None = None,
ca_cert_dir: str | None = None,
ca_cert_data: None | str | bytes = None,
) -> None: """
This method should only be called once, before the connection is used. """
warnings.warn( "HTTPSConnection.set_cert() is deprecated and will be removed " "in urllib3 v2.1.0. Instead provide the parameters to the " "HTTPSConnection constructor.",
category=DeprecationWarning,
stacklevel=2,
)
# If cert_reqs is not provided we'll assume CERT_REQUIRED unless we also # have an SSLContext object in which case we'll use its verify_mode. if cert_reqs isNone: if self.ssl_context isnotNone:
cert_reqs = self.ssl_context.verify_mode else:
cert_reqs = resolve_cert_reqs(None)
def connect(self) -> None: # Today we don't need to be doing this step before the /actual/ socket # connection, however in the future we'll need to decide whether to # create a new socket or re-use an existing "shared" socket as a part # of the HTTP/2 handshake dance. if self._tunnel_host isnotNoneand self._tunnel_port isnotNone:
probe_http2_host = self._tunnel_host
probe_http2_port = self._tunnel_port else:
probe_http2_host = self.host
probe_http2_port = self.port
# Check if the target origin supports HTTP/2. # If the value comes back as 'None' it means that the current thread # is probing for HTTP/2 support. Otherwise, we're waiting for another # probe to complete, or we get a value right away.
target_supports_http2: bool | None if"h2"in ssl_.ALPN_PROTOCOLS:
target_supports_http2 = http2_probe.acquire_and_get(
host=probe_http2_host, port=probe_http2_port
) else: # If HTTP/2 isn't going to be offered it doesn't matter if # the target supports HTTP/2. Don't want to make a probe.
target_supports_http2 = False
if self._connect_callback isnotNone:
self._connect_callback( "before connect",
thread_id=threading.get_ident(),
target_supports_http2=target_supports_http2,
)
# Do we need to establish a tunnel? if self.proxy_is_tunneling: # We're tunneling to an HTTPS origin so need to do TLS-in-TLS. if self._tunnel_scheme == "https": # _connect_tls_proxy will verify and assign proxy_is_verified
self.sock = sock = self._connect_tls_proxy(self.host, sock)
tls_in_tls = True elif self._tunnel_scheme == "http":
self.proxy_is_verified = False
# If we're tunneling it means we're connected to our proxy.
self._has_connected_to_proxy = True
self._tunnel() # Override the host with the one we're requesting data from.
server_hostname = typing.cast(str, self._tunnel_host)
if self.server_hostname isnotNone:
server_hostname = self.server_hostname
is_time_off = datetime.date.today() < RECENT_DATE if is_time_off:
warnings.warn(
(
f"System time is way off (before {RECENT_DATE}). This will probably " "lead to SSL verification errors"
),
SystemTimeWarning,
)
# Remove trailing '.' from fqdn hostnames to allow certificate validation
server_hostname_rm_dot = server_hostname.rstrip(".")
# If an error occurs during connection/handshake we may need to release # our lock so another connection can probe the origin. except BaseException: if self._connect_callback isnotNone:
self._connect_callback( "after connect failure",
thread_id=threading.get_ident(),
target_supports_http2=target_supports_http2,
)
if target_supports_http2 isNone:
http2_probe.set_and_release(
host=probe_http2_host, port=probe_http2_port, supports_http2=None
) raise
# If this connection doesn't know if the origin supports HTTP/2 # we report back to the HTTP/2 probe our result. if target_supports_http2 isNone:
supports_http2 = sock_and_verified.socket.selected_alpn_protocol() == "h2"
http2_probe.set_and_release(
host=probe_http2_host,
port=probe_http2_port,
supports_http2=supports_http2,
)
# Forwarding proxies can never have a verified target since # the proxy is the one doing the verification. Should instead # use a CONNECT tunnel in order to verify the target. # See: https://github.com/urllib3/urllib3/issues/3267. if self.proxy_is_forwarding:
self.is_verified = False else:
self.is_verified = sock_and_verified.is_verified
# If there's a proxy to be connected to we are fully connected. # This is set twice (once above and here) due to forwarding proxies # not using tunnelling.
self._has_connected_to_proxy = bool(self.proxy)
# Set `self.proxy_is_verified` unless it's already set while # establishing a tunnel. if self._has_connected_to_proxy and self.proxy_is_verified isNone:
self.proxy_is_verified = sock_and_verified.is_verified
def _connect_tls_proxy(self, hostname: str, sock: socket.socket) -> ssl.SSLSocket: """
Establish a TLS connection to the proxy using the provided SSL context. """ # `_connect_tls_proxy` is called when self._tunnel_host is truthy.
proxy_config = typing.cast(ProxyConfig, self.proxy_config)
ssl_context = proxy_config.ssl_context
sock_and_verified = _ssl_wrap_socket_and_match_hostname(
sock,
cert_reqs=self.cert_reqs,
ssl_version=self.ssl_version,
ssl_minimum_version=self.ssl_minimum_version,
ssl_maximum_version=self.ssl_maximum_version,
ca_certs=self.ca_certs,
ca_cert_dir=self.ca_cert_dir,
ca_cert_data=self.ca_cert_data,
server_hostname=hostname,
ssl_context=ssl_context,
assert_hostname=proxy_config.assert_hostname,
assert_fingerprint=proxy_config.assert_fingerprint, # Features that aren't implemented for proxies yet:
cert_file=None,
key_file=None,
key_password=None,
tls_in_tls=False,
)
self.proxy_is_verified = sock_and_verified.is_verified return sock_and_verified.socket # type: ignore[return-value]
class _WrappedAndVerifiedSocket(typing.NamedTuple): """
Wrapped socket and whether the connection is
verified after the TLS handshake """
# In some cases, we want to verify hostnames ourselves if ( # `ssl` can't verify fingerprints or alternate hostnames
assert_fingerprint or assert_hostname # assert_hostname can be set to False to disable hostname checking or assert_hostname isFalse # We still support OpenSSL 1.0.2, which prevents us from verifying # hostnames easily: https://github.com/pyca/pyopenssl/pull/933 or ssl_.IS_PYOPENSSL ornot ssl_.HAS_NEVER_CHECK_COMMON_NAME
):
context.check_hostname = False
# Try to load OS default certs if none are given. We need to do the hasattr() check # for custom pyOpenSSL SSLContext objects because they don't support # load_default_certs(). if ( not ca_certs andnot ca_cert_dir andnot ca_cert_data and default_ssl_context and hasattr(context, "load_default_certs")
):
context.load_default_certs()
# Ensure that IPv6 addresses are in the proper format and don't have a # scope ID. Python's SSL module fails to recognize scoped IPv6 addresses # and interprets them as DNS hostnames. if server_hostname isnotNone:
normalized = server_hostname.strip("[]") if"%"in normalized:
normalized = normalized[: normalized.rfind("%")] if is_ipaddress(normalized):
server_hostname = normalized
# Need to signal to our match_hostname whether to use 'commonName' or not. # If we're using our own constructed SSLContext we explicitly set 'False' # because PyPy hard-codes 'True' from SSLContext.hostname_checks_common_name. if default_ssl_context:
hostname_checks_common_name = False else:
hostname_checks_common_name = (
getattr(context, "hostname_checks_common_name", False) orFalse
)
_match_hostname(
cert,
assert_hostname or server_hostname, # type: ignore[arg-type]
hostname_checks_common_name,
)
def _match_hostname(
cert: _TYPE_PEER_CERT_RET_DICT | None,
asserted_hostname: str,
hostname_checks_common_name: bool = False,
) -> None: # Our upstream implementation of ssl.match_hostname() # only applies this normalization to IP addresses so it doesn't # match DNS SANs so we do the same thing!
stripped_hostname = asserted_hostname.strip("[]") if is_ipaddress(stripped_hostname):
asserted_hostname = stripped_hostname
try:
match_hostname(cert, asserted_hostname, hostname_checks_common_name) except CertificateError as e:
log.warning( "Certificate did not match expected hostname: %s. Certificate: %s",
asserted_hostname,
cert,
) # Add cert to exception and reraise so client code can inspect # the cert when catching the exception, if they want to
e._peer_cert = cert # type: ignore[attr-defined] raise
def _wrap_proxy_error(err: Exception, proxy_scheme: str | None) -> ProxyError: # Look for the phrase 'wrong version number', if found # then we should warn the user that we're very sure that # this proxy is HTTP-only and they have a configuration issue.
error_normalized = " ".join(re.split("[^a-z]", str(err).lower()))
is_likely_http_proxy = ( "wrong version number"in error_normalized or"unknown protocol"in error_normalized or"record layer failure"in error_normalized
)
http_proxy_warning = ( ". Your proxy appears to only use HTTP and not HTTPS, " "try changing your proxy URL to be HTTP. See: " "https://urllib3.readthedocs.io/en/latest/advanced-usage.html" "#https-proxy-error-http-proxy"
)
new_err = ProxyError(
f"Unable to connect to proxy"
f"{http_proxy_warning if is_likely_http_proxy and proxy_scheme == 'https' else ''}",
err,
)
new_err.__cause__ = err return new_err
def _url_from_connection(
conn: HTTPConnection | HTTPSConnection, path: str | None = None
) -> str: """Returns the URL from a given connection. This is mainly used for testing and logging."""
Die Informationen auf dieser Webseite wurden
nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit,
noch Qualität der bereit gestellten Informationen zugesichert.
Bemerkung:
Die farbliche Syntaxdarstellung und die Messung sind noch experimentell.