connectionpool.py 36 KB

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