connectionpool.py 30 KB

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