connection.py 47 KB

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