connectionpool.py 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108
  1. from __future__ import absolute_import
  2. import errno
  3. import logging
  4. import re
  5. import socket
  6. import sys
  7. import warnings
  8. from socket import error as SocketError
  9. from socket import timeout as SocketTimeout
  10. from .connection import (
  11. BaseSSLError,
  12. BrokenPipeError,
  13. DummyConnection,
  14. HTTPConnection,
  15. HTTPException,
  16. HTTPSConnection,
  17. VerifiedHTTPSConnection,
  18. port_by_scheme,
  19. )
  20. from .exceptions import (
  21. ClosedPoolError,
  22. EmptyPoolError,
  23. HeaderParsingError,
  24. HostChangedError,
  25. InsecureRequestWarning,
  26. LocationValueError,
  27. MaxRetryError,
  28. NewConnectionError,
  29. ProtocolError,
  30. ProxyError,
  31. ReadTimeoutError,
  32. SSLError,
  33. TimeoutError,
  34. )
  35. from .packages import six
  36. from .packages.six.moves import queue
  37. from .request import RequestMethods
  38. from .response import HTTPResponse
  39. from .util.connection import is_connection_dropped
  40. from .util.proxy import connection_requires_http_tunnel
  41. from .util.queue import LifoQueue
  42. from .util.request import set_file_position
  43. from .util.response import assert_header_parsing
  44. from .util.retry import Retry
  45. from .util.ssl_match_hostname import CertificateError
  46. from .util.timeout import Timeout
  47. from .util.url import Url, _encode_target
  48. from .util.url import _normalize_host as normalize_host
  49. from .util.url import get_host, parse_url
  50. xrange = six.moves.xrange
  51. log = logging.getLogger(__name__)
  52. _Default = object()
  53. # Pool objects
  54. class ConnectionPool(object):
  55. """
  56. Base class for all connection pools, such as
  57. :class:`.HTTPConnectionPool` and :class:`.HTTPSConnectionPool`.
  58. .. note::
  59. ConnectionPool.urlopen() does not normalize or percent-encode target URIs
  60. which is useful if your target server doesn't support percent-encoded
  61. target URIs.
  62. """
  63. scheme = None
  64. QueueCls = LifoQueue
  65. def __init__(self, host, port=None):
  66. if not host:
  67. raise LocationValueError("No host specified.")
  68. self.host = _normalize_host(host, scheme=self.scheme)
  69. self._proxy_host = host.lower()
  70. self.port = port
  71. def __str__(self):
  72. return "%s(host=%r, port=%r)" % (type(self).__name__, self.host, self.port)
  73. def __enter__(self):
  74. return self
  75. def __exit__(self, exc_type, exc_val, exc_tb):
  76. self.close()
  77. # Return False to re-raise any potential exceptions
  78. return False
  79. def close(self):
  80. """
  81. Close all pooled connections and disable the pool.
  82. """
  83. pass
  84. # This is taken from http://hg.python.org/cpython/file/7aaba721ebc0/Lib/socket.py#l252
  85. _blocking_errnos = {errno.EAGAIN, errno.EWOULDBLOCK}
  86. class HTTPConnectionPool(ConnectionPool, RequestMethods):
  87. """
  88. Thread-safe connection pool for one host.
  89. :param host:
  90. Host used for this HTTP Connection (e.g. "localhost"), passed into
  91. :class:`http.client.HTTPConnection`.
  92. :param port:
  93. Port used for this HTTP Connection (None is equivalent to 80), passed
  94. into :class:`http.client.HTTPConnection`.
  95. :param strict:
  96. Causes BadStatusLine to be raised if the status line can't be parsed
  97. as a valid HTTP/1.0 or 1.1 status line, passed into
  98. :class:`http.client.HTTPConnection`.
  99. .. note::
  100. Only works in Python 2. This parameter is ignored in Python 3.
  101. :param timeout:
  102. Socket timeout in seconds for each individual connection. This can
  103. be a float or integer, which sets the timeout for the HTTP request,
  104. or an instance of :class:`urllib3.util.Timeout` which gives you more
  105. fine-grained control over request timeouts. After the constructor has
  106. been parsed, this is always a `urllib3.util.Timeout` object.
  107. :param maxsize:
  108. Number of connections to save that can be reused. More than 1 is useful
  109. in multithreaded situations. If ``block`` is set to False, more
  110. connections will be created but they will not be saved once they've
  111. been used.
  112. :param block:
  113. If set to True, no more than ``maxsize`` connections will be used at
  114. a time. When no free connections are available, the call will block
  115. until a connection has been released. This is a useful side effect for
  116. particular multithreaded situations where one does not want to use more
  117. than maxsize connections per host to prevent flooding.
  118. :param headers:
  119. Headers to include with all requests, unless other headers are given
  120. explicitly.
  121. :param retries:
  122. Retry configuration to use by default with requests in this pool.
  123. :param _proxy:
  124. Parsed proxy URL, should not be used directly, instead, see
  125. :class:`urllib3.ProxyManager`
  126. :param _proxy_headers:
  127. A dictionary with proxy headers, should not be used directly,
  128. instead, see :class:`urllib3.ProxyManager`
  129. :param \\**conn_kw:
  130. Additional parameters are used to create fresh :class:`urllib3.connection.HTTPConnection`,
  131. :class:`urllib3.connection.HTTPSConnection` instances.
  132. """
  133. scheme = "http"
  134. ConnectionCls = HTTPConnection
  135. ResponseCls = HTTPResponse
  136. def __init__(
  137. self,
  138. host,
  139. port=None,
  140. strict=False,
  141. timeout=Timeout.DEFAULT_TIMEOUT,
  142. maxsize=1,
  143. block=False,
  144. headers=None,
  145. retries=None,
  146. _proxy=None,
  147. _proxy_headers=None,
  148. _proxy_config=None,
  149. **conn_kw
  150. ):
  151. ConnectionPool.__init__(self, host, port)
  152. RequestMethods.__init__(self, headers)
  153. self.strict = strict
  154. if not isinstance(timeout, Timeout):
  155. timeout = Timeout.from_float(timeout)
  156. if retries is None:
  157. retries = Retry.DEFAULT
  158. self.timeout = timeout
  159. self.retries = retries
  160. self.pool = self.QueueCls(maxsize)
  161. self.block = block
  162. self.proxy = _proxy
  163. self.proxy_headers = _proxy_headers or {}
  164. self.proxy_config = _proxy_config
  165. # Fill the queue up so that doing get() on it will block properly
  166. for _ in xrange(maxsize):
  167. self.pool.put(None)
  168. # These are mostly for testing and debugging purposes.
  169. self.num_connections = 0
  170. self.num_requests = 0
  171. self.conn_kw = conn_kw
  172. if self.proxy:
  173. # Enable Nagle's algorithm for proxies, to avoid packet fragmentation.
  174. # We cannot know if the user has added default socket options, so we cannot replace the
  175. # list.
  176. self.conn_kw.setdefault("socket_options", [])
  177. self.conn_kw["proxy"] = self.proxy
  178. self.conn_kw["proxy_config"] = self.proxy_config
  179. def _new_conn(self):
  180. """
  181. Return a fresh :class:`HTTPConnection`.
  182. """
  183. self.num_connections += 1
  184. log.debug(
  185. "Starting new HTTP connection (%d): %s:%s",
  186. self.num_connections,
  187. self.host,
  188. self.port or "80",
  189. )
  190. conn = self.ConnectionCls(
  191. host=self.host,
  192. port=self.port,
  193. timeout=self.timeout.connect_timeout,
  194. strict=self.strict,
  195. **self.conn_kw
  196. )
  197. return conn
  198. def _get_conn(self, timeout=None):
  199. """
  200. Get a connection. Will return a pooled connection if one is available.
  201. If no connections are available and :prop:`.block` is ``False``, then a
  202. fresh connection is returned.
  203. :param timeout:
  204. Seconds to wait before giving up and raising
  205. :class:`urllib3.exceptions.EmptyPoolError` if the pool is empty and
  206. :prop:`.block` is ``True``.
  207. """
  208. conn = None
  209. try:
  210. conn = self.pool.get(block=self.block, timeout=timeout)
  211. except AttributeError: # self.pool is None
  212. raise ClosedPoolError(self, "Pool is closed.")
  213. except queue.Empty:
  214. if self.block:
  215. raise EmptyPoolError(
  216. self,
  217. "Pool reached maximum size and no more connections are allowed.",
  218. )
  219. pass # Oh well, we'll create a new connection then
  220. # If this is a persistent connection, check if it got disconnected
  221. if conn and is_connection_dropped(conn):
  222. log.debug("Resetting dropped connection: %s", self.host)
  223. conn.close()
  224. if getattr(conn, "auto_open", 1) == 0:
  225. # This is a proxied connection that has been mutated by
  226. # http.client._tunnel() and cannot be reused (since it would
  227. # attempt to bypass the proxy)
  228. conn = None
  229. return conn or self._new_conn()
  230. def _put_conn(self, conn):
  231. """
  232. Put a connection back into the pool.
  233. :param conn:
  234. Connection object for the current host and port as returned by
  235. :meth:`._new_conn` or :meth:`._get_conn`.
  236. If the pool is already full, the connection is closed and discarded
  237. because we exceeded maxsize. If connections are discarded frequently,
  238. then maxsize should be increased.
  239. If the pool is closed, then the connection will be closed and discarded.
  240. """
  241. try:
  242. self.pool.put(conn, block=False)
  243. return # Everything is dandy, done.
  244. except AttributeError:
  245. # self.pool is None.
  246. pass
  247. except queue.Full:
  248. # This should never happen if self.block == True
  249. log.warning(
  250. "Connection pool is full, discarding connection: %s. Connection pool size: %s",
  251. self.host,
  252. self.pool.qsize(),
  253. )
  254. # Connection never got put back into the pool, close it.
  255. if conn:
  256. conn.close()
  257. def _validate_conn(self, conn):
  258. """
  259. Called right before a request is made, after the socket is created.
  260. """
  261. pass
  262. def _prepare_proxy(self, conn):
  263. # Nothing to do for HTTP connections.
  264. pass
  265. def _get_timeout(self, timeout):
  266. """Helper that always returns a :class:`urllib3.util.Timeout`"""
  267. if timeout is _Default:
  268. return self.timeout.clone()
  269. if isinstance(timeout, Timeout):
  270. return timeout.clone()
  271. else:
  272. # User passed us an int/float. This is for backwards compatibility,
  273. # can be removed later
  274. return Timeout.from_float(timeout)
  275. def _raise_timeout(self, err, url, timeout_value):
  276. """Is the error actually a timeout? Will raise a ReadTimeout or pass"""
  277. if isinstance(err, SocketTimeout):
  278. raise ReadTimeoutError(
  279. self, url, "Read timed out. (read timeout=%s)" % timeout_value
  280. )
  281. # See the above comment about EAGAIN in Python 3. In Python 2 we have
  282. # to specifically catch it and throw the timeout error
  283. if hasattr(err, "errno") and err.errno in _blocking_errnos:
  284. raise ReadTimeoutError(
  285. self, url, "Read timed out. (read timeout=%s)" % timeout_value
  286. )
  287. # Catch possible read timeouts thrown as SSL errors. If not the
  288. # case, rethrow the original. We need to do this because of:
  289. # http://bugs.python.org/issue10272
  290. if "timed out" in str(err) or "did not complete (read)" in str(
  291. err
  292. ): # Python < 2.7.4
  293. raise ReadTimeoutError(
  294. self, url, "Read timed out. (read timeout=%s)" % timeout_value
  295. )
  296. def _make_request(
  297. self, conn, method, url, timeout=_Default, chunked=False, **httplib_request_kw
  298. ):
  299. """
  300. Perform a request on a given urllib connection object taken from our
  301. pool.
  302. :param conn:
  303. a connection from one of our connection pools
  304. :param timeout:
  305. Socket timeout in seconds for the request. This can be a
  306. float or integer, which will set the same timeout value for
  307. the socket connect and the socket read, or an instance of
  308. :class:`urllib3.util.Timeout`, which gives you more fine-grained
  309. control over your timeouts.
  310. """
  311. self.num_requests += 1
  312. timeout_obj = self._get_timeout(timeout)
  313. timeout_obj.start_connect()
  314. conn.timeout = timeout_obj.connect_timeout
  315. # Trigger any extra validation we need to do.
  316. try:
  317. self._validate_conn(conn)
  318. except (SocketTimeout, BaseSSLError) as e:
  319. # Py2 raises this as a BaseSSLError, Py3 raises it as socket timeout.
  320. self._raise_timeout(err=e, url=url, timeout_value=conn.timeout)
  321. raise
  322. # conn.request() calls http.client.*.request, not the method in
  323. # urllib3.request. It also calls makefile (recv) on the socket.
  324. try:
  325. if chunked:
  326. conn.request_chunked(method, url, **httplib_request_kw)
  327. else:
  328. conn.request(method, url, **httplib_request_kw)
  329. # We are swallowing BrokenPipeError (errno.EPIPE) since the server is
  330. # legitimately able to close the connection after sending a valid response.
  331. # With this behaviour, the received response is still readable.
  332. except BrokenPipeError:
  333. # Python 3
  334. pass
  335. except IOError as e:
  336. # Python 2 and macOS/Linux
  337. # EPIPE and ESHUTDOWN are BrokenPipeError on Python 2, and EPROTOTYPE is needed on macOS
  338. # https://erickt.github.io/blog/2014/11/19/adventures-in-debugging-a-potential-osx-kernel-bug/
  339. if e.errno not in {
  340. errno.EPIPE,
  341. errno.ESHUTDOWN,
  342. errno.EPROTOTYPE,
  343. }:
  344. raise
  345. # Reset the timeout for the recv() on the socket
  346. read_timeout = timeout_obj.read_timeout
  347. # App Engine doesn't have a sock attr
  348. if getattr(conn, "sock", None):
  349. # In Python 3 socket.py will catch EAGAIN and return None when you
  350. # try and read into the file pointer created by http.client, which
  351. # instead raises a BadStatusLine exception. Instead of catching
  352. # the exception and assuming all BadStatusLine exceptions are read
  353. # timeouts, check for a zero timeout before making the request.
  354. if read_timeout == 0:
  355. raise ReadTimeoutError(
  356. self, url, "Read timed out. (read timeout=%s)" % read_timeout
  357. )
  358. if read_timeout is Timeout.DEFAULT_TIMEOUT:
  359. conn.sock.settimeout(socket.getdefaulttimeout())
  360. else: # None or a value
  361. conn.sock.settimeout(read_timeout)
  362. # Receive the response from the server
  363. try:
  364. try:
  365. # Python 2.7, use buffering of HTTP responses
  366. httplib_response = conn.getresponse(buffering=True)
  367. except TypeError:
  368. # Python 3
  369. try:
  370. httplib_response = conn.getresponse()
  371. except BaseException as e:
  372. # Remove the TypeError from the exception chain in
  373. # Python 3 (including for exceptions like SystemExit).
  374. # Otherwise it looks like a bug in the code.
  375. six.raise_from(e, None)
  376. except (SocketTimeout, BaseSSLError, SocketError) as e:
  377. self._raise_timeout(err=e, url=url, timeout_value=read_timeout)
  378. raise
  379. # AppEngine doesn't have a version attr.
  380. http_version = getattr(conn, "_http_vsn_str", "HTTP/?")
  381. log.debug(
  382. '%s://%s:%s "%s %s %s" %s %s',
  383. self.scheme,
  384. self.host,
  385. self.port,
  386. method,
  387. url,
  388. http_version,
  389. httplib_response.status,
  390. httplib_response.length,
  391. )
  392. try:
  393. assert_header_parsing(httplib_response.msg)
  394. except (HeaderParsingError, TypeError) as hpe: # Platform-specific: Python 3
  395. log.warning(
  396. "Failed to parse headers (url=%s): %s",
  397. self._absolute_url(url),
  398. hpe,
  399. exc_info=True,
  400. )
  401. return httplib_response
  402. def _absolute_url(self, path):
  403. return Url(scheme=self.scheme, host=self.host, port=self.port, path=path).url
  404. def close(self):
  405. """
  406. Close all pooled connections and disable the pool.
  407. """
  408. if self.pool is None:
  409. return
  410. # Disable access to the pool
  411. old_pool, self.pool = self.pool, None
  412. try:
  413. while True:
  414. conn = old_pool.get(block=False)
  415. if conn:
  416. conn.close()
  417. except queue.Empty:
  418. pass # Done.
  419. def is_same_host(self, url):
  420. """
  421. Check if the given ``url`` is a member of the same host as this
  422. connection pool.
  423. """
  424. if url.startswith("/"):
  425. return True
  426. # TODO: Add optional support for socket.gethostbyname checking.
  427. scheme, host, port = get_host(url)
  428. if host is not None:
  429. host = _normalize_host(host, scheme=scheme)
  430. # Use explicit default port for comparison when none is given
  431. if self.port and not port:
  432. port = port_by_scheme.get(scheme)
  433. elif not self.port and port == port_by_scheme.get(scheme):
  434. port = None
  435. return (scheme, host, port) == (self.scheme, self.host, self.port)
  436. def urlopen(
  437. self,
  438. method,
  439. url,
  440. body=None,
  441. headers=None,
  442. retries=None,
  443. redirect=True,
  444. assert_same_host=True,
  445. timeout=_Default,
  446. pool_timeout=None,
  447. release_conn=None,
  448. chunked=False,
  449. body_pos=None,
  450. **response_kw
  451. ):
  452. """
  453. Get a connection from the pool and perform an HTTP request. This is the
  454. lowest level call for making a request, so you'll need to specify all
  455. the raw details.
  456. .. note::
  457. More commonly, it's appropriate to use a convenience method provided
  458. by :class:`.RequestMethods`, such as :meth:`request`.
  459. .. note::
  460. `release_conn` will only behave as expected if
  461. `preload_content=False` because we want to make
  462. `preload_content=False` the default behaviour someday soon without
  463. breaking backwards compatibility.
  464. :param method:
  465. HTTP request method (such as GET, POST, PUT, etc.)
  466. :param url:
  467. The URL to perform the request on.
  468. :param body:
  469. Data to send in the request body, either :class:`str`, :class:`bytes`,
  470. an iterable of :class:`str`/:class:`bytes`, or a file-like object.
  471. :param headers:
  472. Dictionary of custom headers to send, such as User-Agent,
  473. If-None-Match, etc. If None, pool headers are used. If provided,
  474. these headers completely replace any pool-specific headers.
  475. :param retries:
  476. Configure the number of retries to allow before raising a
  477. :class:`~urllib3.exceptions.MaxRetryError` exception.
  478. Pass ``None`` to retry until you receive a response. Pass a
  479. :class:`~urllib3.util.retry.Retry` object for fine-grained control
  480. over different types of retries.
  481. Pass an integer number to retry connection errors that many times,
  482. but no other types of errors. Pass zero to never retry.
  483. If ``False``, then retries are disabled and any exception is raised
  484. immediately. Also, instead of raising a MaxRetryError on redirects,
  485. the redirect response will be returned.
  486. :type retries: :class:`~urllib3.util.retry.Retry`, False, or an int.
  487. :param redirect:
  488. If True, automatically handle redirects (status codes 301, 302,
  489. 303, 307, 308). Each redirect counts as a retry. Disabling retries
  490. will disable redirect, too.
  491. :param assert_same_host:
  492. If ``True``, will make sure that the host of the pool requests is
  493. consistent else will raise HostChangedError. When ``False``, you can
  494. use the pool on an HTTP proxy and request foreign hosts.
  495. :param timeout:
  496. If specified, overrides the default timeout for this one
  497. request. It may be a float (in seconds) or an instance of
  498. :class:`urllib3.util.Timeout`.
  499. :param pool_timeout:
  500. If set and the pool is set to block=True, then this method will
  501. block for ``pool_timeout`` seconds and raise EmptyPoolError if no
  502. connection is available within the time period.
  503. :param release_conn:
  504. If False, then the urlopen call will not release the connection
  505. back into the pool once a response is received (but will release if
  506. you read the entire contents of the response such as when
  507. `preload_content=True`). This is useful if you're not preloading
  508. the response's content immediately. You will need to call
  509. ``r.release_conn()`` on the response ``r`` to return the connection
  510. back into the pool. If None, it takes the value of
  511. ``response_kw.get('preload_content', True)``.
  512. :param chunked:
  513. If True, urllib3 will send the body using chunked transfer
  514. encoding. Otherwise, urllib3 will send the body using the standard
  515. content-length form. Defaults to False.
  516. :param int body_pos:
  517. Position to seek to in file-like body in the event of a retry or
  518. redirect. Typically this won't need to be set because urllib3 will
  519. auto-populate the value when needed.
  520. :param \\**response_kw:
  521. Additional parameters are passed to
  522. :meth:`urllib3.response.HTTPResponse.from_httplib`
  523. """
  524. parsed_url = parse_url(url)
  525. destination_scheme = parsed_url.scheme
  526. if headers is None:
  527. headers = self.headers
  528. if not isinstance(retries, Retry):
  529. retries = Retry.from_int(retries, redirect=redirect, default=self.retries)
  530. if release_conn is None:
  531. release_conn = response_kw.get("preload_content", True)
  532. # Check host
  533. if assert_same_host and not self.is_same_host(url):
  534. raise HostChangedError(self, url, retries)
  535. # Ensure that the URL we're connecting to is properly encoded
  536. if url.startswith("/"):
  537. url = six.ensure_str(_encode_target(url))
  538. else:
  539. url = six.ensure_str(parsed_url.url)
  540. conn = None
  541. # Track whether `conn` needs to be released before
  542. # returning/raising/recursing. Update this variable if necessary, and
  543. # leave `release_conn` constant throughout the function. That way, if
  544. # the function recurses, the original value of `release_conn` will be
  545. # passed down into the recursive call, and its value will be respected.
  546. #
  547. # See issue #651 [1] for details.
  548. #
  549. # [1] <https://github.com/urllib3/urllib3/issues/651>
  550. release_this_conn = release_conn
  551. http_tunnel_required = connection_requires_http_tunnel(
  552. self.proxy, self.proxy_config, destination_scheme
  553. )
  554. # Merge the proxy headers. Only done when not using HTTP CONNECT. We
  555. # have to copy the headers dict so we can safely change it without those
  556. # changes being reflected in anyone else's copy.
  557. if not http_tunnel_required:
  558. headers = headers.copy()
  559. headers.update(self.proxy_headers)
  560. # Must keep the exception bound to a separate variable or else Python 3
  561. # complains about UnboundLocalError.
  562. err = None
  563. # Keep track of whether we cleanly exited the except block. This
  564. # ensures we do proper cleanup in finally.
  565. clean_exit = False
  566. # Rewind body position, if needed. Record current position
  567. # for future rewinds in the event of a redirect/retry.
  568. body_pos = set_file_position(body, body_pos)
  569. try:
  570. # Request a connection from the queue.
  571. timeout_obj = self._get_timeout(timeout)
  572. conn = self._get_conn(timeout=pool_timeout)
  573. conn.timeout = timeout_obj.connect_timeout
  574. is_new_proxy_conn = self.proxy is not None and not getattr(
  575. conn, "sock", None
  576. )
  577. if is_new_proxy_conn and http_tunnel_required:
  578. self._prepare_proxy(conn)
  579. # Make the request on the httplib connection object.
  580. httplib_response = self._make_request(
  581. conn,
  582. method,
  583. url,
  584. timeout=timeout_obj,
  585. body=body,
  586. headers=headers,
  587. chunked=chunked,
  588. )
  589. # If we're going to release the connection in ``finally:``, then
  590. # the response doesn't need to know about the connection. Otherwise
  591. # it will also try to release it and we'll have a double-release
  592. # mess.
  593. response_conn = conn if not release_conn else None
  594. # Pass method to Response for length checking
  595. response_kw["request_method"] = method
  596. # Import httplib's response into our own wrapper object
  597. response = self.ResponseCls.from_httplib(
  598. httplib_response,
  599. pool=self,
  600. connection=response_conn,
  601. retries=retries,
  602. **response_kw
  603. )
  604. # Everything went great!
  605. clean_exit = True
  606. except EmptyPoolError:
  607. # Didn't get a connection from the pool, no need to clean up
  608. clean_exit = True
  609. release_this_conn = False
  610. raise
  611. except (
  612. TimeoutError,
  613. HTTPException,
  614. SocketError,
  615. ProtocolError,
  616. BaseSSLError,
  617. SSLError,
  618. CertificateError,
  619. ) as e:
  620. # Discard the connection for these exceptions. It will be
  621. # replaced during the next _get_conn() call.
  622. clean_exit = False
  623. def _is_ssl_error_message_from_http_proxy(ssl_error):
  624. # We're trying to detect the message 'WRONG_VERSION_NUMBER' but
  625. # SSLErrors are kinda all over the place when it comes to the message,
  626. # so we try to cover our bases here!
  627. message = " ".join(re.split("[^a-z]", str(ssl_error).lower()))
  628. return (
  629. "wrong version number" in message or "unknown protocol" in message
  630. )
  631. # Try to detect a common user error with proxies which is to
  632. # set an HTTP proxy to be HTTPS when it should be 'http://'
  633. # (ie {'http': 'http://proxy', 'https': 'https://proxy'})
  634. # Instead we add a nice error message and point to a URL.
  635. if (
  636. isinstance(e, BaseSSLError)
  637. and self.proxy
  638. and _is_ssl_error_message_from_http_proxy(e)
  639. ):
  640. e = ProxyError(
  641. "Your proxy appears to only use HTTP and not HTTPS, "
  642. "try changing your proxy URL to be HTTP. See: "
  643. "https://urllib3.readthedocs.io/en/1.26.x/advanced-usage.html"
  644. "#https-proxy-error-http-proxy",
  645. SSLError(e),
  646. )
  647. elif isinstance(e, (BaseSSLError, CertificateError)):
  648. e = SSLError(e)
  649. elif isinstance(e, (SocketError, NewConnectionError)) and self.proxy:
  650. e = ProxyError("Cannot connect to proxy.", e)
  651. elif isinstance(e, (SocketError, HTTPException)):
  652. e = ProtocolError("Connection aborted.", e)
  653. retries = retries.increment(
  654. method, url, error=e, _pool=self, _stacktrace=sys.exc_info()[2]
  655. )
  656. retries.sleep()
  657. # Keep track of the error for the retry warning.
  658. err = e
  659. finally:
  660. if not clean_exit:
  661. # We hit some kind of exception, handled or otherwise. We need
  662. # to throw the connection away unless explicitly told not to.
  663. # Close the connection, set the variable to None, and make sure
  664. # we put the None back in the pool to avoid leaking it.
  665. conn = conn and conn.close()
  666. release_this_conn = True
  667. if release_this_conn:
  668. # Put the connection back to be reused. If the connection is
  669. # expired then it will be None, which will get replaced with a
  670. # fresh connection during _get_conn.
  671. self._put_conn(conn)
  672. if not conn:
  673. # Try again
  674. log.warning(
  675. "Retrying (%r) after connection broken by '%r': %s", retries, err, url
  676. )
  677. return self.urlopen(
  678. method,
  679. url,
  680. body,
  681. headers,
  682. retries,
  683. redirect,
  684. assert_same_host,
  685. timeout=timeout,
  686. pool_timeout=pool_timeout,
  687. release_conn=release_conn,
  688. chunked=chunked,
  689. body_pos=body_pos,
  690. **response_kw
  691. )
  692. # Handle redirect?
  693. redirect_location = redirect and response.get_redirect_location()
  694. if redirect_location:
  695. if response.status == 303:
  696. method = "GET"
  697. try:
  698. retries = retries.increment(method, url, response=response, _pool=self)
  699. except MaxRetryError:
  700. if retries.raise_on_redirect:
  701. response.drain_conn()
  702. raise
  703. return response
  704. response.drain_conn()
  705. retries.sleep_for_retry(response)
  706. log.debug("Redirecting %s -> %s", url, redirect_location)
  707. return self.urlopen(
  708. method,
  709. redirect_location,
  710. body,
  711. headers,
  712. retries=retries,
  713. redirect=redirect,
  714. assert_same_host=assert_same_host,
  715. timeout=timeout,
  716. pool_timeout=pool_timeout,
  717. release_conn=release_conn,
  718. chunked=chunked,
  719. body_pos=body_pos,
  720. **response_kw
  721. )
  722. # Check if we should retry the HTTP response.
  723. has_retry_after = bool(response.getheader("Retry-After"))
  724. if retries.is_retry(method, response.status, has_retry_after):
  725. try:
  726. retries = retries.increment(method, url, response=response, _pool=self)
  727. except MaxRetryError:
  728. if retries.raise_on_status:
  729. response.drain_conn()
  730. raise
  731. return response
  732. response.drain_conn()
  733. retries.sleep(response)
  734. log.debug("Retry: %s", url)
  735. return self.urlopen(
  736. method,
  737. url,
  738. body,
  739. headers,
  740. retries=retries,
  741. redirect=redirect,
  742. assert_same_host=assert_same_host,
  743. timeout=timeout,
  744. pool_timeout=pool_timeout,
  745. release_conn=release_conn,
  746. chunked=chunked,
  747. body_pos=body_pos,
  748. **response_kw
  749. )
  750. return response
  751. class HTTPSConnectionPool(HTTPConnectionPool):
  752. """
  753. Same as :class:`.HTTPConnectionPool`, but HTTPS.
  754. :class:`.HTTPSConnection` uses one of ``assert_fingerprint``,
  755. ``assert_hostname`` and ``host`` in this order to verify connections.
  756. If ``assert_hostname`` is False, no verification is done.
  757. The ``key_file``, ``cert_file``, ``cert_reqs``, ``ca_certs``,
  758. ``ca_cert_dir``, ``ssl_version``, ``key_password`` are only used if :mod:`ssl`
  759. is available and are fed into :meth:`urllib3.util.ssl_wrap_socket` to upgrade
  760. the connection socket into an SSL socket.
  761. """
  762. scheme = "https"
  763. ConnectionCls = HTTPSConnection
  764. def __init__(
  765. self,
  766. host,
  767. port=None,
  768. strict=False,
  769. timeout=Timeout.DEFAULT_TIMEOUT,
  770. maxsize=1,
  771. block=False,
  772. headers=None,
  773. retries=None,
  774. _proxy=None,
  775. _proxy_headers=None,
  776. key_file=None,
  777. cert_file=None,
  778. cert_reqs=None,
  779. key_password=None,
  780. ca_certs=None,
  781. ssl_version=None,
  782. assert_hostname=None,
  783. assert_fingerprint=None,
  784. ca_cert_dir=None,
  785. **conn_kw
  786. ):
  787. HTTPConnectionPool.__init__(
  788. self,
  789. host,
  790. port,
  791. strict,
  792. timeout,
  793. maxsize,
  794. block,
  795. headers,
  796. retries,
  797. _proxy,
  798. _proxy_headers,
  799. **conn_kw
  800. )
  801. self.key_file = key_file
  802. self.cert_file = cert_file
  803. self.cert_reqs = cert_reqs
  804. self.key_password = key_password
  805. self.ca_certs = ca_certs
  806. self.ca_cert_dir = ca_cert_dir
  807. self.ssl_version = ssl_version
  808. self.assert_hostname = assert_hostname
  809. self.assert_fingerprint = assert_fingerprint
  810. def _prepare_conn(self, conn):
  811. """
  812. Prepare the ``connection`` for :meth:`urllib3.util.ssl_wrap_socket`
  813. and establish the tunnel if proxy is used.
  814. """
  815. if isinstance(conn, VerifiedHTTPSConnection):
  816. conn.set_cert(
  817. key_file=self.key_file,
  818. key_password=self.key_password,
  819. cert_file=self.cert_file,
  820. cert_reqs=self.cert_reqs,
  821. ca_certs=self.ca_certs,
  822. ca_cert_dir=self.ca_cert_dir,
  823. assert_hostname=self.assert_hostname,
  824. assert_fingerprint=self.assert_fingerprint,
  825. )
  826. conn.ssl_version = self.ssl_version
  827. return conn
  828. def _prepare_proxy(self, conn):
  829. """
  830. Establishes a tunnel connection through HTTP CONNECT.
  831. Tunnel connection is established early because otherwise httplib would
  832. improperly set Host: header to proxy's IP:port.
  833. """
  834. conn.set_tunnel(self._proxy_host, self.port, self.proxy_headers)
  835. if self.proxy.scheme == "https":
  836. conn.tls_in_tls_required = True
  837. conn.connect()
  838. def _new_conn(self):
  839. """
  840. Return a fresh :class:`http.client.HTTPSConnection`.
  841. """
  842. self.num_connections += 1
  843. log.debug(
  844. "Starting new HTTPS connection (%d): %s:%s",
  845. self.num_connections,
  846. self.host,
  847. self.port or "443",
  848. )
  849. if not self.ConnectionCls or self.ConnectionCls is DummyConnection:
  850. raise SSLError(
  851. "Can't connect to HTTPS URL because the SSL module is not available."
  852. )
  853. actual_host = self.host
  854. actual_port = self.port
  855. if self.proxy is not None:
  856. actual_host = self.proxy.host
  857. actual_port = self.proxy.port
  858. conn = self.ConnectionCls(
  859. host=actual_host,
  860. port=actual_port,
  861. timeout=self.timeout.connect_timeout,
  862. strict=self.strict,
  863. cert_file=self.cert_file,
  864. key_file=self.key_file,
  865. key_password=self.key_password,
  866. **self.conn_kw
  867. )
  868. return self._prepare_conn(conn)
  869. def _validate_conn(self, conn):
  870. """
  871. Called right before a request is made, after the socket is created.
  872. """
  873. super(HTTPSConnectionPool, self)._validate_conn(conn)
  874. # Force connect early to allow us to validate the connection.
  875. if not getattr(conn, "sock", None): # AppEngine might not have `.sock`
  876. conn.connect()
  877. if not conn.is_verified:
  878. warnings.warn(
  879. (
  880. "Unverified HTTPS request is being made to host '%s'. "
  881. "Adding certificate verification is strongly advised. See: "
  882. "https://urllib3.readthedocs.io/en/1.26.x/advanced-usage.html"
  883. "#ssl-warnings" % conn.host
  884. ),
  885. InsecureRequestWarning,
  886. )
  887. if getattr(conn, "proxy_is_verified", None) is False:
  888. warnings.warn(
  889. (
  890. "Unverified HTTPS connection done to an HTTPS proxy. "
  891. "Adding certificate verification is strongly advised. See: "
  892. "https://urllib3.readthedocs.io/en/1.26.x/advanced-usage.html"
  893. "#ssl-warnings"
  894. ),
  895. InsecureRequestWarning,
  896. )
  897. def connection_from_url(url, **kw):
  898. """
  899. Given a url, return an :class:`.ConnectionPool` instance of its host.
  900. This is a shortcut for not having to parse out the scheme, host, and port
  901. of the url before creating an :class:`.ConnectionPool` instance.
  902. :param url:
  903. Absolute URL string that must include the scheme. Port is optional.
  904. :param \\**kw:
  905. Passes additional parameters to the constructor of the appropriate
  906. :class:`.ConnectionPool`. Useful for specifying things like
  907. timeout, maxsize, headers, etc.
  908. Example::
  909. >>> conn = connection_from_url('http://google.com/')
  910. >>> r = conn.request('GET', '/')
  911. """
  912. scheme, host, port = get_host(url)
  913. port = port or port_by_scheme.get(scheme, 80)
  914. if scheme == "https":
  915. return HTTPSConnectionPool(host, port=port, **kw)
  916. else:
  917. return HTTPConnectionPool(host, port=port, **kw)
  918. def _normalize_host(host, scheme):
  919. """
  920. Normalize hosts for comparisons and use with sockets.
  921. """
  922. host = normalize_host(host, scheme)
  923. # httplib doesn't like it when we include brackets in IPv6 addresses
  924. # Specifically, if we include brackets but also pass the port then
  925. # httplib crazily doubles up the square brackets on the Host header.
  926. # Instead, we need to make sure we never pass ``None`` as the port.
  927. # However, for backward compatibility reasons we can't actually
  928. # *assert* that. See http://bugs.python.org/issue28539
  929. if host.startswith("[") and host.endswith("]"):
  930. host = host[1:-1]
  931. return host