您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符
 
 
 
 

1094 行
42 KiB

  1. from __future__ import annotations
  2. import datetime
  3. import http.client
  4. import logging
  5. import os
  6. import re
  7. import socket
  8. import sys
  9. import threading
  10. import typing
  11. import warnings
  12. from http.client import HTTPConnection as _HTTPConnection
  13. from http.client import HTTPException as HTTPException # noqa: F401
  14. from http.client import ResponseNotReady
  15. from socket import timeout as SocketTimeout
  16. if typing.TYPE_CHECKING:
  17. from .response import HTTPResponse
  18. from .util.ssl_ import _TYPE_PEER_CERT_RET_DICT
  19. from .util.ssltransport import SSLTransport
  20. from ._collections import HTTPHeaderDict
  21. from .http2 import probe as http2_probe
  22. from .util.response import assert_header_parsing
  23. from .util.timeout import _DEFAULT_TIMEOUT, _TYPE_TIMEOUT, Timeout
  24. from .util.util import to_str
  25. from .util.wait import wait_for_read
  26. try: # Compiled with SSL?
  27. import ssl
  28. BaseSSLError = ssl.SSLError
  29. except (ImportError, AttributeError):
  30. ssl = None # type: ignore[assignment]
  31. class BaseSSLError(BaseException): # type: ignore[no-redef]
  32. pass
  33. from ._base_connection import _TYPE_BODY
  34. from ._base_connection import ProxyConfig as ProxyConfig
  35. from ._base_connection import _ResponseOptions as _ResponseOptions
  36. from ._version import __version__
  37. from .exceptions import (
  38. ConnectTimeoutError,
  39. HeaderParsingError,
  40. NameResolutionError,
  41. NewConnectionError,
  42. ProxyError,
  43. SystemTimeWarning,
  44. )
  45. from .util import SKIP_HEADER, SKIPPABLE_HEADERS, connection, ssl_
  46. from .util.request import body_to_chunks
  47. from .util.ssl_ import assert_fingerprint as _assert_fingerprint
  48. from .util.ssl_ import (
  49. create_urllib3_context,
  50. is_ipaddress,
  51. resolve_cert_reqs,
  52. resolve_ssl_version,
  53. ssl_wrap_socket,
  54. )
  55. from .util.ssl_match_hostname import CertificateError, match_hostname
  56. from .util.url import Url
  57. # Not a no-op, we're adding this to the namespace so it can be imported.
  58. ConnectionError = ConnectionError
  59. BrokenPipeError = BrokenPipeError
  60. log = logging.getLogger(__name__)
  61. port_by_scheme = {"http": 80, "https": 443}
  62. # When it comes time to update this value as a part of regular maintenance
  63. # (ie test_recent_date is failing) update it to ~6 months before the current date.
  64. RECENT_DATE = datetime.date(2025, 1, 1)
  65. _CONTAINS_CONTROL_CHAR_RE = re.compile(r"[^-!#$%&'*+.^_`|~0-9a-zA-Z]")
  66. class HTTPConnection(_HTTPConnection):
  67. """
  68. Based on :class:`http.client.HTTPConnection` but provides an extra constructor
  69. backwards-compatibility layer between older and newer Pythons.
  70. Additional keyword parameters are used to configure attributes of the connection.
  71. Accepted parameters include:
  72. - ``source_address``: Set the source address for the current connection.
  73. - ``socket_options``: Set specific options on the underlying socket. If not specified, then
  74. defaults are loaded from ``HTTPConnection.default_socket_options`` which includes disabling
  75. Nagle's algorithm (sets TCP_NODELAY to 1) unless the connection is behind a proxy.
  76. For example, if you wish to enable TCP Keep Alive in addition to the defaults,
  77. you might pass:
  78. .. code-block:: python
  79. HTTPConnection.default_socket_options + [
  80. (socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1),
  81. ]
  82. Or you may want to disable the defaults by passing an empty list (e.g., ``[]``).
  83. """
  84. default_port: typing.ClassVar[int] = port_by_scheme["http"] # type: ignore[misc]
  85. #: Disable Nagle's algorithm by default.
  86. #: ``[(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)]``
  87. default_socket_options: typing.ClassVar[connection._TYPE_SOCKET_OPTIONS] = [
  88. (socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
  89. ]
  90. #: Whether this connection verifies the host's certificate.
  91. is_verified: bool = False
  92. #: Whether this proxy connection verified the proxy host's certificate.
  93. # If no proxy is currently connected to the value will be ``None``.
  94. proxy_is_verified: bool | None = None
  95. blocksize: int
  96. source_address: tuple[str, int] | None
  97. socket_options: connection._TYPE_SOCKET_OPTIONS | None
  98. _has_connected_to_proxy: bool
  99. _response_options: _ResponseOptions | None
  100. _tunnel_host: str | None
  101. _tunnel_port: int | None
  102. _tunnel_scheme: str | None
  103. def __init__(
  104. self,
  105. host: str,
  106. port: int | None = None,
  107. *,
  108. timeout: _TYPE_TIMEOUT = _DEFAULT_TIMEOUT,
  109. source_address: tuple[str, int] | None = None,
  110. blocksize: int = 16384,
  111. socket_options: None | (
  112. connection._TYPE_SOCKET_OPTIONS
  113. ) = default_socket_options,
  114. proxy: Url | None = None,
  115. proxy_config: ProxyConfig | None = None,
  116. ) -> None:
  117. super().__init__(
  118. host=host,
  119. port=port,
  120. timeout=Timeout.resolve_default_timeout(timeout),
  121. source_address=source_address,
  122. blocksize=blocksize,
  123. )
  124. self.socket_options = socket_options
  125. self.proxy = proxy
  126. self.proxy_config = proxy_config
  127. self._has_connected_to_proxy = False
  128. self._response_options = None
  129. self._tunnel_host: str | None = None
  130. self._tunnel_port: int | None = None
  131. self._tunnel_scheme: str | None = None
  132. @property
  133. def host(self) -> str:
  134. """
  135. Getter method to remove any trailing dots that indicate the hostname is an FQDN.
  136. In general, SSL certificates don't include the trailing dot indicating a
  137. fully-qualified domain name, and thus, they don't validate properly when
  138. checked against a domain name that includes the dot. In addition, some
  139. servers may not expect to receive the trailing dot when provided.
  140. However, the hostname with trailing dot is critical to DNS resolution; doing a
  141. lookup with the trailing dot will properly only resolve the appropriate FQDN,
  142. whereas a lookup without a trailing dot will search the system's search domain
  143. list. Thus, it's important to keep the original host around for use only in
  144. those cases where it's appropriate (i.e., when doing DNS lookup to establish the
  145. actual TCP connection across which we're going to send HTTP requests).
  146. """
  147. return self._dns_host.rstrip(".")
  148. @host.setter
  149. def host(self, value: str) -> None:
  150. """
  151. Setter for the `host` property.
  152. We assume that only urllib3 uses the _dns_host attribute; httplib itself
  153. only uses `host`, and it seems reasonable that other libraries follow suit.
  154. """
  155. self._dns_host = value
  156. def _new_conn(self) -> socket.socket:
  157. """Establish a socket connection and set nodelay settings on it.
  158. :return: New socket connection.
  159. """
  160. try:
  161. sock = connection.create_connection(
  162. (self._dns_host, self.port),
  163. self.timeout,
  164. source_address=self.source_address,
  165. socket_options=self.socket_options,
  166. )
  167. except socket.gaierror as e:
  168. raise NameResolutionError(self.host, self, e) from e
  169. except SocketTimeout as e:
  170. raise ConnectTimeoutError(
  171. self,
  172. f"Connection to {self.host} timed out. (connect timeout={self.timeout})",
  173. ) from e
  174. except OSError as e:
  175. raise NewConnectionError(
  176. self, f"Failed to establish a new connection: {e}"
  177. ) from e
  178. sys.audit("http.client.connect", self, self.host, self.port)
  179. return sock
  180. def set_tunnel(
  181. self,
  182. host: str,
  183. port: int | None = None,
  184. headers: typing.Mapping[str, str] | None = None,
  185. scheme: str = "http",
  186. ) -> None:
  187. if scheme not in ("http", "https"):
  188. raise ValueError(
  189. f"Invalid proxy scheme for tunneling: {scheme!r}, must be either 'http' or 'https'"
  190. )
  191. super().set_tunnel(host, port=port, headers=headers)
  192. self._tunnel_scheme = scheme
  193. if sys.version_info < (3, 11, 9) or ((3, 12) <= sys.version_info < (3, 12, 3)):
  194. # Taken from python/cpython#100986 which was backported in 3.11.9 and 3.12.3.
  195. # When using connection_from_host, host will come without brackets.
  196. def _wrap_ipv6(self, ip: bytes) -> bytes:
  197. if b":" in ip and ip[0] != b"["[0]:
  198. return b"[" + ip + b"]"
  199. return ip
  200. if sys.version_info < (3, 11, 9):
  201. # `_tunnel` copied from 3.11.13 backporting
  202. # https://github.com/python/cpython/commit/0d4026432591d43185568dd31cef6a034c4b9261
  203. # and https://github.com/python/cpython/commit/6fbc61070fda2ffb8889e77e3b24bca4249ab4d1
  204. def _tunnel(self) -> None:
  205. _MAXLINE = http.client._MAXLINE # type: ignore[attr-defined]
  206. connect = b"CONNECT %s:%d HTTP/1.0\r\n" % ( # type: ignore[str-format]
  207. self._wrap_ipv6(self._tunnel_host.encode("ascii")), # type: ignore[union-attr]
  208. self._tunnel_port,
  209. )
  210. headers = [connect]
  211. for header, value in self._tunnel_headers.items(): # type: ignore[attr-defined]
  212. headers.append(f"{header}: {value}\r\n".encode("latin-1"))
  213. headers.append(b"\r\n")
  214. # Making a single send() call instead of one per line encourages
  215. # the host OS to use a more optimal packet size instead of
  216. # potentially emitting a series of small packets.
  217. self.send(b"".join(headers))
  218. del headers
  219. response = self.response_class(self.sock, method=self._method) # type: ignore[attr-defined]
  220. try:
  221. (version, code, message) = response._read_status() # type: ignore[attr-defined]
  222. if code != http.HTTPStatus.OK:
  223. self.close()
  224. raise OSError(
  225. f"Tunnel connection failed: {code} {message.strip()}"
  226. )
  227. while True:
  228. line = response.fp.readline(_MAXLINE + 1)
  229. if len(line) > _MAXLINE:
  230. raise http.client.LineTooLong("header line")
  231. if not line:
  232. # for sites which EOF without sending a trailer
  233. break
  234. if line in (b"\r\n", b"\n", b""):
  235. break
  236. if self.debuglevel > 0:
  237. print("header:", line.decode())
  238. finally:
  239. response.close()
  240. elif (3, 12) <= sys.version_info < (3, 12, 3):
  241. # `_tunnel` copied from 3.12.11 backporting
  242. # https://github.com/python/cpython/commit/23aef575c7629abcd4aaf028ebd226fb41a4b3c8
  243. def _tunnel(self) -> None: # noqa: F811
  244. connect = b"CONNECT %s:%d HTTP/1.1\r\n" % ( # type: ignore[str-format]
  245. self._wrap_ipv6(self._tunnel_host.encode("idna")), # type: ignore[union-attr]
  246. self._tunnel_port,
  247. )
  248. headers = [connect]
  249. for header, value in self._tunnel_headers.items(): # type: ignore[attr-defined]
  250. headers.append(f"{header}: {value}\r\n".encode("latin-1"))
  251. headers.append(b"\r\n")
  252. # Making a single send() call instead of one per line encourages
  253. # the host OS to use a more optimal packet size instead of
  254. # potentially emitting a series of small packets.
  255. self.send(b"".join(headers))
  256. del headers
  257. response = self.response_class(self.sock, method=self._method) # type: ignore[attr-defined]
  258. try:
  259. (version, code, message) = response._read_status() # type: ignore[attr-defined]
  260. self._raw_proxy_headers = http.client._read_headers(response.fp) # type: ignore[attr-defined]
  261. if self.debuglevel > 0:
  262. for header in self._raw_proxy_headers:
  263. print("header:", header.decode())
  264. if code != http.HTTPStatus.OK:
  265. self.close()
  266. raise OSError(
  267. f"Tunnel connection failed: {code} {message.strip()}"
  268. )
  269. finally:
  270. response.close()
  271. def connect(self) -> None:
  272. self.sock = self._new_conn()
  273. if self._tunnel_host:
  274. # If we're tunneling it means we're connected to our proxy.
  275. self._has_connected_to_proxy = True
  276. # TODO: Fix tunnel so it doesn't depend on self.sock state.
  277. self._tunnel()
  278. # If there's a proxy to be connected to we are fully connected.
  279. # This is set twice (once above and here) due to forwarding proxies
  280. # not using tunnelling.
  281. self._has_connected_to_proxy = bool(self.proxy)
  282. if self._has_connected_to_proxy:
  283. self.proxy_is_verified = False
  284. @property
  285. def is_closed(self) -> bool:
  286. return self.sock is None
  287. @property
  288. def is_connected(self) -> bool:
  289. if self.sock is None:
  290. return False
  291. return not wait_for_read(self.sock, timeout=0.0)
  292. @property
  293. def has_connected_to_proxy(self) -> bool:
  294. return self._has_connected_to_proxy
  295. @property
  296. def proxy_is_forwarding(self) -> bool:
  297. """
  298. Return True if a forwarding proxy is configured, else return False
  299. """
  300. return bool(self.proxy) and self._tunnel_host is None
  301. @property
  302. def proxy_is_tunneling(self) -> bool:
  303. """
  304. Return True if a tunneling proxy is configured, else return False
  305. """
  306. return self._tunnel_host is not None
  307. def close(self) -> None:
  308. try:
  309. super().close()
  310. finally:
  311. # Reset all stateful properties so connection
  312. # can be re-used without leaking prior configs.
  313. self.sock = None
  314. self.is_verified = False
  315. self.proxy_is_verified = None
  316. self._has_connected_to_proxy = False
  317. self._response_options = None
  318. self._tunnel_host = None
  319. self._tunnel_port = None
  320. self._tunnel_scheme = None
  321. def putrequest(
  322. self,
  323. method: str,
  324. url: str,
  325. skip_host: bool = False,
  326. skip_accept_encoding: bool = False,
  327. ) -> None:
  328. """"""
  329. # Empty docstring because the indentation of CPython's implementation
  330. # is broken but we don't want this method in our documentation.
  331. match = _CONTAINS_CONTROL_CHAR_RE.search(method)
  332. if match:
  333. raise ValueError(
  334. f"Method cannot contain non-token characters {method!r} (found at least {match.group()!r})"
  335. )
  336. return super().putrequest(
  337. method, url, skip_host=skip_host, skip_accept_encoding=skip_accept_encoding
  338. )
  339. def putheader(self, header: str, *values: str) -> None: # type: ignore[override]
  340. """"""
  341. if not any(isinstance(v, str) and v == SKIP_HEADER for v in values):
  342. super().putheader(header, *values)
  343. elif to_str(header.lower()) not in SKIPPABLE_HEADERS:
  344. skippable_headers = "', '".join(
  345. [str.title(header) for header in sorted(SKIPPABLE_HEADERS)]
  346. )
  347. raise ValueError(
  348. f"urllib3.util.SKIP_HEADER only supports '{skippable_headers}'"
  349. )
  350. # `request` method's signature intentionally violates LSP.
  351. # urllib3's API is different from `http.client.HTTPConnection` and the subclassing is only incidental.
  352. def request( # type: ignore[override]
  353. self,
  354. method: str,
  355. url: str,
  356. body: _TYPE_BODY | None = None,
  357. headers: typing.Mapping[str, str] | None = None,
  358. *,
  359. chunked: bool = False,
  360. preload_content: bool = True,
  361. decode_content: bool = True,
  362. enforce_content_length: bool = True,
  363. ) -> None:
  364. # Update the inner socket's timeout value to send the request.
  365. # This only triggers if the connection is re-used.
  366. if self.sock is not None:
  367. self.sock.settimeout(self.timeout)
  368. # Store these values to be fed into the HTTPResponse
  369. # object later. TODO: Remove this in favor of a real
  370. # HTTP lifecycle mechanism.
  371. # We have to store these before we call .request()
  372. # because sometimes we can still salvage a response
  373. # off the wire even if we aren't able to completely
  374. # send the request body.
  375. self._response_options = _ResponseOptions(
  376. request_method=method,
  377. request_url=url,
  378. preload_content=preload_content,
  379. decode_content=decode_content,
  380. enforce_content_length=enforce_content_length,
  381. )
  382. if headers is None:
  383. headers = {}
  384. header_keys = frozenset(to_str(k.lower()) for k in headers)
  385. skip_accept_encoding = "accept-encoding" in header_keys
  386. skip_host = "host" in header_keys
  387. self.putrequest(
  388. method, url, skip_accept_encoding=skip_accept_encoding, skip_host=skip_host
  389. )
  390. # Transform the body into an iterable of sendall()-able chunks
  391. # and detect if an explicit Content-Length is doable.
  392. chunks_and_cl = body_to_chunks(body, method=method, blocksize=self.blocksize)
  393. chunks = chunks_and_cl.chunks
  394. content_length = chunks_and_cl.content_length
  395. # When chunked is explicit set to 'True' we respect that.
  396. if chunked:
  397. if "transfer-encoding" not in header_keys:
  398. self.putheader("Transfer-Encoding", "chunked")
  399. else:
  400. # Detect whether a framing mechanism is already in use. If so
  401. # we respect that value, otherwise we pick chunked vs content-length
  402. # depending on the type of 'body'.
  403. if "content-length" in header_keys:
  404. chunked = False
  405. elif "transfer-encoding" in header_keys:
  406. chunked = True
  407. # Otherwise we go off the recommendation of 'body_to_chunks()'.
  408. else:
  409. chunked = False
  410. if content_length is None:
  411. if chunks is not None:
  412. chunked = True
  413. self.putheader("Transfer-Encoding", "chunked")
  414. else:
  415. self.putheader("Content-Length", str(content_length))
  416. # Now that framing headers are out of the way we send all the other headers.
  417. if "user-agent" not in header_keys:
  418. self.putheader("User-Agent", _get_default_user_agent())
  419. for header, value in headers.items():
  420. self.putheader(header, value)
  421. self.endheaders()
  422. # If we're given a body we start sending that in chunks.
  423. if chunks is not None:
  424. for chunk in chunks:
  425. # Sending empty chunks isn't allowed for TE: chunked
  426. # as it indicates the end of the body.
  427. if not chunk:
  428. continue
  429. if isinstance(chunk, str):
  430. chunk = chunk.encode("utf-8")
  431. if chunked:
  432. self.send(b"%x\r\n%b\r\n" % (len(chunk), chunk))
  433. else:
  434. self.send(chunk)
  435. # Regardless of whether we have a body or not, if we're in
  436. # chunked mode we want to send an explicit empty chunk.
  437. if chunked:
  438. self.send(b"0\r\n\r\n")
  439. def request_chunked(
  440. self,
  441. method: str,
  442. url: str,
  443. body: _TYPE_BODY | None = None,
  444. headers: typing.Mapping[str, str] | None = None,
  445. ) -> None:
  446. """
  447. Alternative to the common request method, which sends the
  448. body with chunked encoding and not as one block
  449. """
  450. warnings.warn(
  451. "HTTPConnection.request_chunked() is deprecated and will be removed "
  452. "in urllib3 v2.1.0. Instead use HTTPConnection.request(..., chunked=True).",
  453. category=DeprecationWarning,
  454. stacklevel=2,
  455. )
  456. self.request(method, url, body=body, headers=headers, chunked=True)
  457. def getresponse( # type: ignore[override]
  458. self,
  459. ) -> HTTPResponse:
  460. """
  461. Get the response from the server.
  462. If the HTTPConnection is in the correct state, returns an instance of HTTPResponse or of whatever object is returned by the response_class variable.
  463. If a request has not been sent or if 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.
  464. """
  465. # Raise the same error as http.client.HTTPConnection
  466. if self._response_options is None:
  467. raise ResponseNotReady()
  468. # Reset this attribute for being used again.
  469. resp_options = self._response_options
  470. self._response_options = None
  471. # Since the connection's timeout value may have been updated
  472. # we need to set the timeout on the socket.
  473. self.sock.settimeout(self.timeout)
  474. # This is needed here to avoid circular import errors
  475. from .response import HTTPResponse
  476. # Save a reference to the shutdown function before ownership is passed
  477. # to httplib_response
  478. # TODO should we implement it everywhere?
  479. _shutdown = getattr(self.sock, "shutdown", None)
  480. # Get the response from http.client.HTTPConnection
  481. httplib_response = super().getresponse()
  482. try:
  483. assert_header_parsing(httplib_response.msg)
  484. except (HeaderParsingError, TypeError) as hpe:
  485. log.warning(
  486. "Failed to parse headers (url=%s): %s",
  487. _url_from_connection(self, resp_options.request_url),
  488. hpe,
  489. exc_info=True,
  490. )
  491. headers = HTTPHeaderDict(httplib_response.msg.items())
  492. response = HTTPResponse(
  493. body=httplib_response,
  494. headers=headers,
  495. status=httplib_response.status,
  496. version=httplib_response.version,
  497. version_string=getattr(self, "_http_vsn_str", "HTTP/?"),
  498. reason=httplib_response.reason,
  499. preload_content=resp_options.preload_content,
  500. decode_content=resp_options.decode_content,
  501. original_response=httplib_response,
  502. enforce_content_length=resp_options.enforce_content_length,
  503. request_method=resp_options.request_method,
  504. request_url=resp_options.request_url,
  505. sock_shutdown=_shutdown,
  506. )
  507. return response
  508. class HTTPSConnection(HTTPConnection):
  509. """
  510. Many of the parameters to this constructor are passed to the underlying SSL
  511. socket by means of :py:func:`urllib3.util.ssl_wrap_socket`.
  512. """
  513. default_port = port_by_scheme["https"] # type: ignore[misc]
  514. cert_reqs: int | str | None = None
  515. ca_certs: str | None = None
  516. ca_cert_dir: str | None = None
  517. ca_cert_data: None | str | bytes = None
  518. ssl_version: int | str | None = None
  519. ssl_minimum_version: int | None = None
  520. ssl_maximum_version: int | None = None
  521. assert_fingerprint: str | None = None
  522. _connect_callback: typing.Callable[..., None] | None = None
  523. def __init__(
  524. self,
  525. host: str,
  526. port: int | None = None,
  527. *,
  528. timeout: _TYPE_TIMEOUT = _DEFAULT_TIMEOUT,
  529. source_address: tuple[str, int] | None = None,
  530. blocksize: int = 16384,
  531. socket_options: None | (
  532. connection._TYPE_SOCKET_OPTIONS
  533. ) = HTTPConnection.default_socket_options,
  534. proxy: Url | None = None,
  535. proxy_config: ProxyConfig | None = None,
  536. cert_reqs: int | str | None = None,
  537. assert_hostname: None | str | typing.Literal[False] = None,
  538. assert_fingerprint: str | None = None,
  539. server_hostname: str | None = None,
  540. ssl_context: ssl.SSLContext | None = None,
  541. ca_certs: str | None = None,
  542. ca_cert_dir: str | None = None,
  543. ca_cert_data: None | str | bytes = None,
  544. ssl_minimum_version: int | None = None,
  545. ssl_maximum_version: int | None = None,
  546. ssl_version: int | str | None = None, # Deprecated
  547. cert_file: str | None = None,
  548. key_file: str | None = None,
  549. key_password: str | None = None,
  550. ) -> None:
  551. super().__init__(
  552. host,
  553. port=port,
  554. timeout=timeout,
  555. source_address=source_address,
  556. blocksize=blocksize,
  557. socket_options=socket_options,
  558. proxy=proxy,
  559. proxy_config=proxy_config,
  560. )
  561. self.key_file = key_file
  562. self.cert_file = cert_file
  563. self.key_password = key_password
  564. self.ssl_context = ssl_context
  565. self.server_hostname = server_hostname
  566. self.assert_hostname = assert_hostname
  567. self.assert_fingerprint = assert_fingerprint
  568. self.ssl_version = ssl_version
  569. self.ssl_minimum_version = ssl_minimum_version
  570. self.ssl_maximum_version = ssl_maximum_version
  571. self.ca_certs = ca_certs and os.path.expanduser(ca_certs)
  572. self.ca_cert_dir = ca_cert_dir and os.path.expanduser(ca_cert_dir)
  573. self.ca_cert_data = ca_cert_data
  574. # cert_reqs depends on ssl_context so calculate last.
  575. if cert_reqs is None:
  576. if self.ssl_context is not None:
  577. cert_reqs = self.ssl_context.verify_mode
  578. else:
  579. cert_reqs = resolve_cert_reqs(None)
  580. self.cert_reqs = cert_reqs
  581. self._connect_callback = None
  582. def set_cert(
  583. self,
  584. key_file: str | None = None,
  585. cert_file: str | None = None,
  586. cert_reqs: int | str | None = None,
  587. key_password: str | None = None,
  588. ca_certs: str | None = None,
  589. assert_hostname: None | str | typing.Literal[False] = None,
  590. assert_fingerprint: str | None = None,
  591. ca_cert_dir: str | None = None,
  592. ca_cert_data: None | str | bytes = None,
  593. ) -> None:
  594. """
  595. This method should only be called once, before the connection is used.
  596. """
  597. warnings.warn(
  598. "HTTPSConnection.set_cert() is deprecated and will be removed "
  599. "in urllib3 v2.1.0. Instead provide the parameters to the "
  600. "HTTPSConnection constructor.",
  601. category=DeprecationWarning,
  602. stacklevel=2,
  603. )
  604. # If cert_reqs is not provided we'll assume CERT_REQUIRED unless we also
  605. # have an SSLContext object in which case we'll use its verify_mode.
  606. if cert_reqs is None:
  607. if self.ssl_context is not None:
  608. cert_reqs = self.ssl_context.verify_mode
  609. else:
  610. cert_reqs = resolve_cert_reqs(None)
  611. self.key_file = key_file
  612. self.cert_file = cert_file
  613. self.cert_reqs = cert_reqs
  614. self.key_password = key_password
  615. self.assert_hostname = assert_hostname
  616. self.assert_fingerprint = assert_fingerprint
  617. self.ca_certs = ca_certs and os.path.expanduser(ca_certs)
  618. self.ca_cert_dir = ca_cert_dir and os.path.expanduser(ca_cert_dir)
  619. self.ca_cert_data = ca_cert_data
  620. def connect(self) -> None:
  621. # Today we don't need to be doing this step before the /actual/ socket
  622. # connection, however in the future we'll need to decide whether to
  623. # create a new socket or re-use an existing "shared" socket as a part
  624. # of the HTTP/2 handshake dance.
  625. if self._tunnel_host is not None and self._tunnel_port is not None:
  626. probe_http2_host = self._tunnel_host
  627. probe_http2_port = self._tunnel_port
  628. else:
  629. probe_http2_host = self.host
  630. probe_http2_port = self.port
  631. # Check if the target origin supports HTTP/2.
  632. # If the value comes back as 'None' it means that the current thread
  633. # is probing for HTTP/2 support. Otherwise, we're waiting for another
  634. # probe to complete, or we get a value right away.
  635. target_supports_http2: bool | None
  636. if "h2" in ssl_.ALPN_PROTOCOLS:
  637. target_supports_http2 = http2_probe.acquire_and_get(
  638. host=probe_http2_host, port=probe_http2_port
  639. )
  640. else:
  641. # If HTTP/2 isn't going to be offered it doesn't matter if
  642. # the target supports HTTP/2. Don't want to make a probe.
  643. target_supports_http2 = False
  644. if self._connect_callback is not None:
  645. self._connect_callback(
  646. "before connect",
  647. thread_id=threading.get_ident(),
  648. target_supports_http2=target_supports_http2,
  649. )
  650. try:
  651. sock: socket.socket | ssl.SSLSocket
  652. self.sock = sock = self._new_conn()
  653. server_hostname: str = self.host
  654. tls_in_tls = False
  655. # Do we need to establish a tunnel?
  656. if self.proxy_is_tunneling:
  657. # We're tunneling to an HTTPS origin so need to do TLS-in-TLS.
  658. if self._tunnel_scheme == "https":
  659. # _connect_tls_proxy will verify and assign proxy_is_verified
  660. self.sock = sock = self._connect_tls_proxy(self.host, sock)
  661. tls_in_tls = True
  662. elif self._tunnel_scheme == "http":
  663. self.proxy_is_verified = False
  664. # If we're tunneling it means we're connected to our proxy.
  665. self._has_connected_to_proxy = True
  666. self._tunnel()
  667. # Override the host with the one we're requesting data from.
  668. server_hostname = typing.cast(str, self._tunnel_host)
  669. if self.server_hostname is not None:
  670. server_hostname = self.server_hostname
  671. is_time_off = datetime.date.today() < RECENT_DATE
  672. if is_time_off:
  673. warnings.warn(
  674. (
  675. f"System time is way off (before {RECENT_DATE}). This will probably "
  676. "lead to SSL verification errors"
  677. ),
  678. SystemTimeWarning,
  679. )
  680. # Remove trailing '.' from fqdn hostnames to allow certificate validation
  681. server_hostname_rm_dot = server_hostname.rstrip(".")
  682. sock_and_verified = _ssl_wrap_socket_and_match_hostname(
  683. sock=sock,
  684. cert_reqs=self.cert_reqs,
  685. ssl_version=self.ssl_version,
  686. ssl_minimum_version=self.ssl_minimum_version,
  687. ssl_maximum_version=self.ssl_maximum_version,
  688. ca_certs=self.ca_certs,
  689. ca_cert_dir=self.ca_cert_dir,
  690. ca_cert_data=self.ca_cert_data,
  691. cert_file=self.cert_file,
  692. key_file=self.key_file,
  693. key_password=self.key_password,
  694. server_hostname=server_hostname_rm_dot,
  695. ssl_context=self.ssl_context,
  696. tls_in_tls=tls_in_tls,
  697. assert_hostname=self.assert_hostname,
  698. assert_fingerprint=self.assert_fingerprint,
  699. )
  700. self.sock = sock_and_verified.socket
  701. # If an error occurs during connection/handshake we may need to release
  702. # our lock so another connection can probe the origin.
  703. except BaseException:
  704. if self._connect_callback is not None:
  705. self._connect_callback(
  706. "after connect failure",
  707. thread_id=threading.get_ident(),
  708. target_supports_http2=target_supports_http2,
  709. )
  710. if target_supports_http2 is None:
  711. http2_probe.set_and_release(
  712. host=probe_http2_host, port=probe_http2_port, supports_http2=None
  713. )
  714. raise
  715. # If this connection doesn't know if the origin supports HTTP/2
  716. # we report back to the HTTP/2 probe our result.
  717. if target_supports_http2 is None:
  718. supports_http2 = sock_and_verified.socket.selected_alpn_protocol() == "h2"
  719. http2_probe.set_and_release(
  720. host=probe_http2_host,
  721. port=probe_http2_port,
  722. supports_http2=supports_http2,
  723. )
  724. # Forwarding proxies can never have a verified target since
  725. # the proxy is the one doing the verification. Should instead
  726. # use a CONNECT tunnel in order to verify the target.
  727. # See: https://github.com/urllib3/urllib3/issues/3267.
  728. if self.proxy_is_forwarding:
  729. self.is_verified = False
  730. else:
  731. self.is_verified = sock_and_verified.is_verified
  732. # If there's a proxy to be connected to we are fully connected.
  733. # This is set twice (once above and here) due to forwarding proxies
  734. # not using tunnelling.
  735. self._has_connected_to_proxy = bool(self.proxy)
  736. # Set `self.proxy_is_verified` unless it's already set while
  737. # establishing a tunnel.
  738. if self._has_connected_to_proxy and self.proxy_is_verified is None:
  739. self.proxy_is_verified = sock_and_verified.is_verified
  740. def _connect_tls_proxy(self, hostname: str, sock: socket.socket) -> ssl.SSLSocket:
  741. """
  742. Establish a TLS connection to the proxy using the provided SSL context.
  743. """
  744. # `_connect_tls_proxy` is called when self._tunnel_host is truthy.
  745. proxy_config = typing.cast(ProxyConfig, self.proxy_config)
  746. ssl_context = proxy_config.ssl_context
  747. sock_and_verified = _ssl_wrap_socket_and_match_hostname(
  748. sock,
  749. cert_reqs=self.cert_reqs,
  750. ssl_version=self.ssl_version,
  751. ssl_minimum_version=self.ssl_minimum_version,
  752. ssl_maximum_version=self.ssl_maximum_version,
  753. ca_certs=self.ca_certs,
  754. ca_cert_dir=self.ca_cert_dir,
  755. ca_cert_data=self.ca_cert_data,
  756. server_hostname=hostname,
  757. ssl_context=ssl_context,
  758. assert_hostname=proxy_config.assert_hostname,
  759. assert_fingerprint=proxy_config.assert_fingerprint,
  760. # Features that aren't implemented for proxies yet:
  761. cert_file=None,
  762. key_file=None,
  763. key_password=None,
  764. tls_in_tls=False,
  765. )
  766. self.proxy_is_verified = sock_and_verified.is_verified
  767. return sock_and_verified.socket # type: ignore[return-value]
  768. class _WrappedAndVerifiedSocket(typing.NamedTuple):
  769. """
  770. Wrapped socket and whether the connection is
  771. verified after the TLS handshake
  772. """
  773. socket: ssl.SSLSocket | SSLTransport
  774. is_verified: bool
  775. def _ssl_wrap_socket_and_match_hostname(
  776. sock: socket.socket,
  777. *,
  778. cert_reqs: None | str | int,
  779. ssl_version: None | str | int,
  780. ssl_minimum_version: int | None,
  781. ssl_maximum_version: int | None,
  782. cert_file: str | None,
  783. key_file: str | None,
  784. key_password: str | None,
  785. ca_certs: str | None,
  786. ca_cert_dir: str | None,
  787. ca_cert_data: None | str | bytes,
  788. assert_hostname: None | str | typing.Literal[False],
  789. assert_fingerprint: str | None,
  790. server_hostname: str | None,
  791. ssl_context: ssl.SSLContext | None,
  792. tls_in_tls: bool = False,
  793. ) -> _WrappedAndVerifiedSocket:
  794. """Logic for constructing an SSLContext from all TLS parameters, passing
  795. that down into ssl_wrap_socket, and then doing certificate verification
  796. either via hostname or fingerprint. This function exists to guarantee
  797. that both proxies and targets have the same behavior when connecting via TLS.
  798. """
  799. default_ssl_context = False
  800. if ssl_context is None:
  801. default_ssl_context = True
  802. context = create_urllib3_context(
  803. ssl_version=resolve_ssl_version(ssl_version),
  804. ssl_minimum_version=ssl_minimum_version,
  805. ssl_maximum_version=ssl_maximum_version,
  806. cert_reqs=resolve_cert_reqs(cert_reqs),
  807. )
  808. else:
  809. context = ssl_context
  810. context.verify_mode = resolve_cert_reqs(cert_reqs)
  811. # In some cases, we want to verify hostnames ourselves
  812. if (
  813. # `ssl` can't verify fingerprints or alternate hostnames
  814. assert_fingerprint
  815. or assert_hostname
  816. # assert_hostname can be set to False to disable hostname checking
  817. or assert_hostname is False
  818. # We still support OpenSSL 1.0.2, which prevents us from verifying
  819. # hostnames easily: https://github.com/pyca/pyopenssl/pull/933
  820. or ssl_.IS_PYOPENSSL
  821. or not ssl_.HAS_NEVER_CHECK_COMMON_NAME
  822. ):
  823. context.check_hostname = False
  824. # Try to load OS default certs if none are given. We need to do the hasattr() check
  825. # for custom pyOpenSSL SSLContext objects because they don't support
  826. # load_default_certs().
  827. if (
  828. not ca_certs
  829. and not ca_cert_dir
  830. and not ca_cert_data
  831. and default_ssl_context
  832. and hasattr(context, "load_default_certs")
  833. ):
  834. context.load_default_certs()
  835. # Ensure that IPv6 addresses are in the proper format and don't have a
  836. # scope ID. Python's SSL module fails to recognize scoped IPv6 addresses
  837. # and interprets them as DNS hostnames.
  838. if server_hostname is not None:
  839. normalized = server_hostname.strip("[]")
  840. if "%" in normalized:
  841. normalized = normalized[: normalized.rfind("%")]
  842. if is_ipaddress(normalized):
  843. server_hostname = normalized
  844. ssl_sock = ssl_wrap_socket(
  845. sock=sock,
  846. keyfile=key_file,
  847. certfile=cert_file,
  848. key_password=key_password,
  849. ca_certs=ca_certs,
  850. ca_cert_dir=ca_cert_dir,
  851. ca_cert_data=ca_cert_data,
  852. server_hostname=server_hostname,
  853. ssl_context=context,
  854. tls_in_tls=tls_in_tls,
  855. )
  856. try:
  857. if assert_fingerprint:
  858. _assert_fingerprint(
  859. ssl_sock.getpeercert(binary_form=True), assert_fingerprint
  860. )
  861. elif (
  862. context.verify_mode != ssl.CERT_NONE
  863. and not context.check_hostname
  864. and assert_hostname is not False
  865. ):
  866. cert: _TYPE_PEER_CERT_RET_DICT = ssl_sock.getpeercert() # type: ignore[assignment]
  867. # Need to signal to our match_hostname whether to use 'commonName' or not.
  868. # If we're using our own constructed SSLContext we explicitly set 'False'
  869. # because PyPy hard-codes 'True' from SSLContext.hostname_checks_common_name.
  870. if default_ssl_context:
  871. hostname_checks_common_name = False
  872. else:
  873. hostname_checks_common_name = (
  874. getattr(context, "hostname_checks_common_name", False) or False
  875. )
  876. _match_hostname(
  877. cert,
  878. assert_hostname or server_hostname, # type: ignore[arg-type]
  879. hostname_checks_common_name,
  880. )
  881. return _WrappedAndVerifiedSocket(
  882. socket=ssl_sock,
  883. is_verified=context.verify_mode == ssl.CERT_REQUIRED
  884. or bool(assert_fingerprint),
  885. )
  886. except BaseException:
  887. ssl_sock.close()
  888. raise
  889. def _match_hostname(
  890. cert: _TYPE_PEER_CERT_RET_DICT | None,
  891. asserted_hostname: str,
  892. hostname_checks_common_name: bool = False,
  893. ) -> None:
  894. # Our upstream implementation of ssl.match_hostname()
  895. # only applies this normalization to IP addresses so it doesn't
  896. # match DNS SANs so we do the same thing!
  897. stripped_hostname = asserted_hostname.strip("[]")
  898. if is_ipaddress(stripped_hostname):
  899. asserted_hostname = stripped_hostname
  900. try:
  901. match_hostname(cert, asserted_hostname, hostname_checks_common_name)
  902. except CertificateError as e:
  903. log.warning(
  904. "Certificate did not match expected hostname: %s. Certificate: %s",
  905. asserted_hostname,
  906. cert,
  907. )
  908. # Add cert to exception and reraise so client code can inspect
  909. # the cert when catching the exception, if they want to
  910. e._peer_cert = cert # type: ignore[attr-defined]
  911. raise
  912. def _wrap_proxy_error(err: Exception, proxy_scheme: str | None) -> ProxyError:
  913. # Look for the phrase 'wrong version number', if found
  914. # then we should warn the user that we're very sure that
  915. # this proxy is HTTP-only and they have a configuration issue.
  916. error_normalized = " ".join(re.split("[^a-z]", str(err).lower()))
  917. is_likely_http_proxy = (
  918. "wrong version number" in error_normalized
  919. or "unknown protocol" in error_normalized
  920. or "record layer failure" in error_normalized
  921. )
  922. http_proxy_warning = (
  923. ". Your proxy appears to only use HTTP and not HTTPS, "
  924. "try changing your proxy URL to be HTTP. See: "
  925. "https://urllib3.readthedocs.io/en/latest/advanced-usage.html"
  926. "#https-proxy-error-http-proxy"
  927. )
  928. new_err = ProxyError(
  929. f"Unable to connect to proxy"
  930. f"{http_proxy_warning if is_likely_http_proxy and proxy_scheme == 'https' else ''}",
  931. err,
  932. )
  933. new_err.__cause__ = err
  934. return new_err
  935. def _get_default_user_agent() -> str:
  936. return f"python-urllib3/{__version__}"
  937. class DummyConnection:
  938. """Used to detect a failed ConnectionCls import."""
  939. if not ssl:
  940. HTTPSConnection = DummyConnection # type: ignore[misc, assignment] # noqa: F811
  941. VerifiedHTTPSConnection = HTTPSConnection
  942. def _url_from_connection(
  943. conn: HTTPConnection | HTTPSConnection, path: str | None = None
  944. ) -> str:
  945. """Returns the URL from a given connection. This is mainly used for testing and logging."""
  946. scheme = "https" if isinstance(conn, HTTPSConnection) else "http"
  947. return Url(scheme=scheme, host=conn.host, port=conn.port, path=path).url