connectionpool.py 34 KB

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