connectionpool.py 36 KB

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