Plex plugin to to play various online streams (mostly Latvian).

connectionpool.py 33KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866
  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. try: # Python 3
  9. from queue import LifoQueue, Empty, Full
  10. except ImportError:
  11. from Queue import LifoQueue, Empty, Full
  12. # Queue is imported for side effects on MS Windows
  13. import Queue as _unused_module_Queue # noqa: unused
  14. from .exceptions import (
  15. ClosedPoolError,
  16. ProtocolError,
  17. EmptyPoolError,
  18. HeaderParsingError,
  19. HostChangedError,
  20. LocationValueError,
  21. MaxRetryError,
  22. ProxyError,
  23. ReadTimeoutError,
  24. SSLError,
  25. TimeoutError,
  26. InsecureRequestWarning,
  27. NewConnectionError,
  28. )
  29. from .packages.ssl_match_hostname import CertificateError
  30. from .packages import six
  31. from .connection import (
  32. port_by_scheme,
  33. DummyConnection,
  34. HTTPConnection, HTTPSConnection, VerifiedHTTPSConnection,
  35. HTTPException, BaseSSLError,
  36. )
  37. from .request import RequestMethods
  38. from .response import HTTPResponse
  39. from .util.connection import is_connection_dropped
  40. from .util.response import assert_header_parsing
  41. from .util.retry import Retry
  42. from .util.timeout import Timeout
  43. from .util.url import get_host, Url
  44. xrange = six.moves.xrange
  45. log = logging.getLogger(__name__)
  46. _Default = object()
  47. # Pool objects
  48. class ConnectionPool(object):
  49. """
  50. Base class for all connection pools, such as
  51. :class:`.HTTPConnectionPool` and :class:`.HTTPSConnectionPool`.
  52. """
  53. scheme = None
  54. QueueCls = LifoQueue
  55. def __init__(self, host, port=None):
  56. if not host:
  57. raise LocationValueError("No host specified.")
  58. # httplib doesn't like it when we include brackets in ipv6 addresses
  59. # Specifically, if we include brackets but also pass the port then
  60. # httplib crazily doubles up the square brackets on the Host header.
  61. # Instead, we need to make sure we never pass ``None`` as the port.
  62. # However, for backward compatibility reasons we can't actually
  63. # *assert* that.
  64. self.host = host.strip('[]')
  65. self.port = port
  66. def __str__(self):
  67. return '%s(host=%r, port=%r)' % (type(self).__name__,
  68. 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 = set([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__(self, host, port=None, strict=False,
  133. timeout=Timeout.DEFAULT_TIMEOUT, maxsize=1, block=False,
  134. headers=None, retries=None,
  135. _proxy=None, _proxy_headers=None,
  136. **conn_kw):
  137. ConnectionPool.__init__(self, host, port)
  138. RequestMethods.__init__(self, headers)
  139. self.strict = strict
  140. if not isinstance(timeout, Timeout):
  141. timeout = Timeout.from_float(timeout)
  142. if retries is None:
  143. retries = Retry.DEFAULT
  144. self.timeout = timeout
  145. self.retries = retries
  146. self.pool = self.QueueCls(maxsize)
  147. self.block = block
  148. self.proxy = _proxy
  149. self.proxy_headers = _proxy_headers or {}
  150. # Fill the queue up so that doing get() on it will block properly
  151. for _ in xrange(maxsize):
  152. self.pool.put(None)
  153. # These are mostly for testing and debugging purposes.
  154. self.num_connections = 0
  155. self.num_requests = 0
  156. self.conn_kw = conn_kw
  157. if self.proxy:
  158. # Enable Nagle's algorithm for proxies, to avoid packet fragmentation.
  159. # We cannot know if the user has added default socket options, so we cannot replace the
  160. # list.
  161. self.conn_kw.setdefault('socket_options', [])
  162. def _new_conn(self):
  163. """
  164. Return a fresh :class:`HTTPConnection`.
  165. """
  166. self.num_connections += 1
  167. log.info("Starting new HTTP connection (%d): %s",
  168. self.num_connections, self.host)
  169. conn = self.ConnectionCls(host=self.host, port=self.port,
  170. timeout=self.timeout.connect_timeout,
  171. strict=self.strict, **self.conn_kw)
  172. return conn
  173. def _get_conn(self, timeout=None):
  174. """
  175. Get a connection. Will return a pooled connection if one is available.
  176. If no connections are available and :prop:`.block` is ``False``, then a
  177. fresh connection is returned.
  178. :param timeout:
  179. Seconds to wait before giving up and raising
  180. :class:`urllib3.exceptions.EmptyPoolError` if the pool is empty and
  181. :prop:`.block` is ``True``.
  182. """
  183. conn = None
  184. try:
  185. conn = self.pool.get(block=self.block, timeout=timeout)
  186. except AttributeError: # self.pool is None
  187. raise ClosedPoolError(self, "Pool is closed.")
  188. except Empty:
  189. if self.block:
  190. raise EmptyPoolError(self,
  191. "Pool reached maximum size and no more "
  192. "connections are allowed.")
  193. pass # Oh well, we'll create a new connection then
  194. # If this is a persistent connection, check if it got disconnected
  195. if conn and is_connection_dropped(conn):
  196. log.info("Resetting dropped connection: %s", self.host)
  197. conn.close()
  198. if getattr(conn, 'auto_open', 1) == 0:
  199. # This is a proxied connection that has been mutated by
  200. # httplib._tunnel() and cannot be reused (since it would
  201. # attempt to bypass the proxy)
  202. conn = None
  203. return conn or self._new_conn()
  204. def _put_conn(self, conn):
  205. """
  206. Put a connection back into the pool.
  207. :param conn:
  208. Connection object for the current host and port as returned by
  209. :meth:`._new_conn` or :meth:`._get_conn`.
  210. If the pool is already full, the connection is closed and discarded
  211. because we exceeded maxsize. If connections are discarded frequently,
  212. then maxsize should be increased.
  213. If the pool is closed, then the connection will be closed and discarded.
  214. """
  215. try:
  216. self.pool.put(conn, block=False)
  217. return # Everything is dandy, done.
  218. except AttributeError:
  219. # self.pool is None.
  220. pass
  221. except Full:
  222. # This should never happen if self.block == True
  223. log.warning(
  224. "Connection pool is full, discarding connection: %s",
  225. self.host)
  226. # Connection never got put back into the pool, close it.
  227. if conn:
  228. conn.close()
  229. def _validate_conn(self, conn):
  230. """
  231. Called right before a request is made, after the socket is created.
  232. """
  233. pass
  234. def _prepare_proxy(self, conn):
  235. # Nothing to do for HTTP connections.
  236. pass
  237. def _get_timeout(self, timeout):
  238. """ Helper that always returns a :class:`urllib3.util.Timeout` """
  239. if timeout is _Default:
  240. return self.timeout.clone()
  241. if isinstance(timeout, Timeout):
  242. return timeout.clone()
  243. else:
  244. # User passed us an int/float. This is for backwards compatibility,
  245. # can be removed later
  246. return Timeout.from_float(timeout)
  247. def _raise_timeout(self, err, url, timeout_value):
  248. """Is the error actually a timeout? Will raise a ReadTimeout or pass"""
  249. if isinstance(err, SocketTimeout):
  250. raise ReadTimeoutError(self, url, "Read timed out. (read timeout=%s)" % timeout_value)
  251. # See the above comment about EAGAIN in Python 3. In Python 2 we have
  252. # to specifically catch it and throw the timeout error
  253. if hasattr(err, 'errno') and err.errno in _blocking_errnos:
  254. raise ReadTimeoutError(self, url, "Read timed out. (read timeout=%s)" % timeout_value)
  255. # Catch possible read timeouts thrown as SSL errors. If not the
  256. # case, rethrow the original. We need to do this because of:
  257. # http://bugs.python.org/issue10272
  258. if 'timed out' in str(err) or 'did not complete (read)' in str(err): # Python 2.6
  259. raise ReadTimeoutError(self, url, "Read timed out. (read timeout=%s)" % timeout_value)
  260. def _make_request(self, conn, method, url, timeout=_Default, chunked=False,
  261. **httplib_request_kw):
  262. """
  263. Perform a request on a given urllib connection object taken from our
  264. pool.
  265. :param conn:
  266. a connection from one of our connection pools
  267. :param timeout:
  268. Socket timeout in seconds for the request. This can be a
  269. float or integer, which will set the same timeout value for
  270. the socket connect and the socket read, or an instance of
  271. :class:`urllib3.util.Timeout`, which gives you more fine-grained
  272. control over your timeouts.
  273. """
  274. self.num_requests += 1
  275. timeout_obj = self._get_timeout(timeout)
  276. timeout_obj.start_connect()
  277. conn.timeout = timeout_obj.connect_timeout
  278. # Trigger any extra validation we need to do.
  279. try:
  280. self._validate_conn(conn)
  281. except (SocketTimeout, BaseSSLError) as e:
  282. # Py2 raises this as a BaseSSLError, Py3 raises it as socket timeout.
  283. self._raise_timeout(err=e, url=url, timeout_value=conn.timeout)
  284. raise
  285. # conn.request() calls httplib.*.request, not the method in
  286. # urllib3.request. It also calls makefile (recv) on the socket.
  287. if chunked:
  288. conn.request_chunked(method, url, **httplib_request_kw)
  289. else:
  290. conn.request(method, url, **httplib_request_kw)
  291. # Reset the timeout for the recv() on the socket
  292. read_timeout = timeout_obj.read_timeout
  293. # App Engine doesn't have a sock attr
  294. if getattr(conn, 'sock', None):
  295. # In Python 3 socket.py will catch EAGAIN and return None when you
  296. # try and read into the file pointer created by http.client, which
  297. # instead raises a BadStatusLine exception. Instead of catching
  298. # the exception and assuming all BadStatusLine exceptions are read
  299. # timeouts, check for a zero timeout before making the request.
  300. if read_timeout == 0:
  301. raise ReadTimeoutError(
  302. self, url, "Read timed out. (read timeout=%s)" % read_timeout)
  303. if read_timeout is Timeout.DEFAULT_TIMEOUT:
  304. conn.sock.settimeout(socket.getdefaulttimeout())
  305. else: # None or a value
  306. conn.sock.settimeout(read_timeout)
  307. # Receive the response from the server
  308. try:
  309. try: # Python 2.7, use buffering of HTTP responses
  310. httplib_response = conn.getresponse(buffering=True)
  311. except TypeError: # Python 2.6 and older, Python 3
  312. try:
  313. httplib_response = conn.getresponse()
  314. except Exception as e:
  315. # Remove the TypeError from the exception chain in Python 3;
  316. # otherwise it looks like a programming error was the cause.
  317. six.raise_from(e, None)
  318. except (SocketTimeout, BaseSSLError, SocketError) as e:
  319. self._raise_timeout(err=e, url=url, timeout_value=read_timeout)
  320. raise
  321. # AppEngine doesn't have a version attr.
  322. http_version = getattr(conn, '_http_vsn_str', 'HTTP/?')
  323. log.debug("\"%s %s %s\" %s %s", method, url, http_version,
  324. httplib_response.status, httplib_response.length)
  325. try:
  326. assert_header_parsing(httplib_response.msg)
  327. except HeaderParsingError as hpe: # Platform-specific: Python 3
  328. log.warning(
  329. 'Failed to parse headers (url=%s): %s',
  330. self._absolute_url(url), hpe, exc_info=True)
  331. return httplib_response
  332. def _absolute_url(self, path):
  333. return Url(scheme=self.scheme, host=self.host, port=self.port, path=path).url
  334. def close(self):
  335. """
  336. Close all pooled connections and disable the pool.
  337. """
  338. # Disable access to the pool
  339. old_pool, self.pool = self.pool, None
  340. try:
  341. while True:
  342. conn = old_pool.get(block=False)
  343. if conn:
  344. conn.close()
  345. except Empty:
  346. pass # Done.
  347. def is_same_host(self, url):
  348. """
  349. Check if the given ``url`` is a member of the same host as this
  350. connection pool.
  351. """
  352. if url.startswith('/'):
  353. return True
  354. # TODO: Add optional support for socket.gethostbyname checking.
  355. scheme, host, port = get_host(url)
  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. **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 \**response_kw:
  430. Additional parameters are passed to
  431. :meth:`urllib3.response.HTTPResponse.from_httplib`
  432. """
  433. if headers is None:
  434. headers = self.headers
  435. if not isinstance(retries, Retry):
  436. retries = Retry.from_int(retries, redirect=redirect, default=self.retries)
  437. if release_conn is None:
  438. release_conn = response_kw.get('preload_content', True)
  439. # Check host
  440. if assert_same_host and not self.is_same_host(url):
  441. raise HostChangedError(self, url, retries)
  442. conn = None
  443. # Track whether `conn` needs to be released before
  444. # returning/raising/recursing. Update this variable if necessary, and
  445. # leave `release_conn` constant throughout the function. That way, if
  446. # the function recurses, the original value of `release_conn` will be
  447. # passed down into the recursive call, and its value will be respected.
  448. #
  449. # See issue #651 [1] for details.
  450. #
  451. # [1] <https://github.com/shazow/urllib3/issues/651>
  452. release_this_conn = release_conn
  453. # Merge the proxy headers. Only do this in HTTP. We have to copy the
  454. # headers dict so we can safely change it without those changes being
  455. # reflected in anyone else's copy.
  456. if self.scheme == 'http':
  457. headers = headers.copy()
  458. headers.update(self.proxy_headers)
  459. # Must keep the exception bound to a separate variable or else Python 3
  460. # complains about UnboundLocalError.
  461. err = None
  462. # Keep track of whether we cleanly exited the except block. This
  463. # ensures we do proper cleanup in finally.
  464. clean_exit = False
  465. try:
  466. # Request a connection from the queue.
  467. timeout_obj = self._get_timeout(timeout)
  468. conn = self._get_conn(timeout=pool_timeout)
  469. conn.timeout = timeout_obj.connect_timeout
  470. is_new_proxy_conn = self.proxy is not None and not getattr(conn, 'sock', None)
  471. if is_new_proxy_conn:
  472. self._prepare_proxy(conn)
  473. # Make the request on the httplib connection object.
  474. httplib_response = self._make_request(conn, method, url,
  475. timeout=timeout_obj,
  476. body=body, headers=headers,
  477. chunked=chunked)
  478. # If we're going to release the connection in ``finally:``, then
  479. # the response doesn't need to know about the connection. Otherwise
  480. # it will also try to release it and we'll have a double-release
  481. # mess.
  482. response_conn = conn if not release_conn else None
  483. # Import httplib's response into our own wrapper object
  484. response = self.ResponseCls.from_httplib(httplib_response,
  485. pool=self,
  486. connection=response_conn,
  487. **response_kw)
  488. # Everything went great!
  489. clean_exit = True
  490. except Empty:
  491. # Timed out by queue.
  492. raise EmptyPoolError(self, "No pool connections are available.")
  493. except (BaseSSLError, CertificateError) as e:
  494. # Close the connection. If a connection is reused on which there
  495. # was a Certificate error, the next request will certainly raise
  496. # another Certificate error.
  497. clean_exit = False
  498. raise SSLError(e)
  499. except SSLError:
  500. # Treat SSLError separately from BaseSSLError to preserve
  501. # traceback.
  502. clean_exit = False
  503. raise
  504. except (TimeoutError, HTTPException, SocketError, ProtocolError) as e:
  505. # Discard the connection for these exceptions. It will be
  506. # be replaced during the next _get_conn() call.
  507. clean_exit = False
  508. if isinstance(e, (SocketError, NewConnectionError)) and self.proxy:
  509. e = ProxyError('Cannot connect to proxy.', e)
  510. elif isinstance(e, (SocketError, HTTPException)):
  511. e = ProtocolError('Connection aborted.', e)
  512. retries = retries.increment(method, url, error=e, _pool=self,
  513. _stacktrace=sys.exc_info()[2])
  514. retries.sleep()
  515. # Keep track of the error for the retry warning.
  516. err = e
  517. finally:
  518. if not clean_exit:
  519. # We hit some kind of exception, handled or otherwise. We need
  520. # to throw the connection away unless explicitly told not to.
  521. # Close the connection, set the variable to None, and make sure
  522. # we put the None back in the pool to avoid leaking it.
  523. conn = conn and conn.close()
  524. release_this_conn = True
  525. if release_this_conn:
  526. # Put the connection back to be reused. If the connection is
  527. # expired then it will be None, which will get replaced with a
  528. # fresh connection during _get_conn.
  529. self._put_conn(conn)
  530. if not conn:
  531. # Try again
  532. log.warning("Retrying (%r) after connection "
  533. "broken by '%r': %s", retries, err, url)
  534. return self.urlopen(method, url, body, headers, retries,
  535. redirect, assert_same_host,
  536. timeout=timeout, pool_timeout=pool_timeout,
  537. release_conn=release_conn, **response_kw)
  538. # Handle redirect?
  539. redirect_location = redirect and response.get_redirect_location()
  540. if redirect_location:
  541. if response.status == 303:
  542. method = 'GET'
  543. try:
  544. retries = retries.increment(method, url, response=response, _pool=self)
  545. except MaxRetryError:
  546. if retries.raise_on_redirect:
  547. # Release the connection for this response, since we're not
  548. # returning it to be released manually.
  549. response.release_conn()
  550. raise
  551. return response
  552. log.info("Redirecting %s -> %s", url, redirect_location)
  553. return self.urlopen(
  554. method, redirect_location, body, headers,
  555. retries=retries, redirect=redirect,
  556. assert_same_host=assert_same_host,
  557. timeout=timeout, pool_timeout=pool_timeout,
  558. release_conn=release_conn, **response_kw)
  559. # Check if we should retry the HTTP response.
  560. if retries.is_forced_retry(method, status_code=response.status):
  561. try:
  562. retries = retries.increment(method, url, response=response, _pool=self)
  563. except MaxRetryError:
  564. if retries.raise_on_status:
  565. # Release the connection for this response, since we're not
  566. # returning it to be released manually.
  567. response.release_conn()
  568. raise
  569. return response
  570. retries.sleep()
  571. log.info("Forced retry: %s", url)
  572. return self.urlopen(
  573. method, url, body, headers,
  574. retries=retries, redirect=redirect,
  575. assert_same_host=assert_same_host,
  576. timeout=timeout, pool_timeout=pool_timeout,
  577. release_conn=release_conn, **response_kw)
  578. return response
  579. class HTTPSConnectionPool(HTTPConnectionPool):
  580. """
  581. Same as :class:`.HTTPConnectionPool`, but HTTPS.
  582. When Python is compiled with the :mod:`ssl` module, then
  583. :class:`.VerifiedHTTPSConnection` is used, which *can* verify certificates,
  584. instead of :class:`.HTTPSConnection`.
  585. :class:`.VerifiedHTTPSConnection` uses one of ``assert_fingerprint``,
  586. ``assert_hostname`` and ``host`` in this order to verify connections.
  587. If ``assert_hostname`` is False, no verification is done.
  588. The ``key_file``, ``cert_file``, ``cert_reqs``, ``ca_certs``,
  589. ``ca_cert_dir``, and ``ssl_version`` are only used if :mod:`ssl` is
  590. available and are fed into :meth:`urllib3.util.ssl_wrap_socket` to upgrade
  591. the connection socket into an SSL socket.
  592. """
  593. scheme = 'https'
  594. ConnectionCls = HTTPSConnection
  595. def __init__(self, host, port=None,
  596. strict=False, timeout=Timeout.DEFAULT_TIMEOUT, maxsize=1,
  597. block=False, headers=None, retries=None,
  598. _proxy=None, _proxy_headers=None,
  599. key_file=None, cert_file=None, cert_reqs=None,
  600. ca_certs=None, ssl_version=None,
  601. assert_hostname=None, assert_fingerprint=None,
  602. ca_cert_dir=None, **conn_kw):
  603. HTTPConnectionPool.__init__(self, host, port, strict, timeout, maxsize,
  604. block, headers, retries, _proxy, _proxy_headers,
  605. **conn_kw)
  606. if ca_certs and cert_reqs is None:
  607. cert_reqs = 'CERT_REQUIRED'
  608. self.key_file = key_file
  609. self.cert_file = cert_file
  610. self.cert_reqs = cert_reqs
  611. self.ca_certs = ca_certs
  612. self.ca_cert_dir = ca_cert_dir
  613. self.ssl_version = ssl_version
  614. self.assert_hostname = assert_hostname
  615. self.assert_fingerprint = assert_fingerprint
  616. def _prepare_conn(self, conn):
  617. """
  618. Prepare the ``connection`` for :meth:`urllib3.util.ssl_wrap_socket`
  619. and establish the tunnel if proxy is used.
  620. """
  621. if isinstance(conn, VerifiedHTTPSConnection):
  622. conn.set_cert(key_file=self.key_file,
  623. cert_file=self.cert_file,
  624. cert_reqs=self.cert_reqs,
  625. ca_certs=self.ca_certs,
  626. ca_cert_dir=self.ca_cert_dir,
  627. assert_hostname=self.assert_hostname,
  628. assert_fingerprint=self.assert_fingerprint)
  629. conn.ssl_version = self.ssl_version
  630. return conn
  631. def _prepare_proxy(self, conn):
  632. """
  633. Establish tunnel connection early, because otherwise httplib
  634. would improperly set Host: header to proxy's IP:port.
  635. """
  636. # Python 2.7+
  637. try:
  638. set_tunnel = conn.set_tunnel
  639. except AttributeError: # Platform-specific: Python 2.6
  640. set_tunnel = conn._set_tunnel
  641. if sys.version_info <= (2, 6, 4) and not self.proxy_headers: # Python 2.6.4 and older
  642. set_tunnel(self.host, self.port)
  643. else:
  644. set_tunnel(self.host, self.port, self.proxy_headers)
  645. conn.connect()
  646. def _new_conn(self):
  647. """
  648. Return a fresh :class:`httplib.HTTPSConnection`.
  649. """
  650. self.num_connections += 1
  651. log.info("Starting new HTTPS connection (%d): %s",
  652. self.num_connections, self.host)
  653. if not self.ConnectionCls or self.ConnectionCls is DummyConnection:
  654. raise SSLError("Can't connect to HTTPS URL because the SSL "
  655. "module is not available.")
  656. actual_host = self.host
  657. actual_port = self.port
  658. if self.proxy is not None:
  659. actual_host = self.proxy.host
  660. actual_port = self.proxy.port
  661. conn = self.ConnectionCls(host=actual_host, port=actual_port,
  662. timeout=self.timeout.connect_timeout,
  663. strict=self.strict, **self.conn_kw)
  664. return self._prepare_conn(conn)
  665. def _validate_conn(self, conn):
  666. """
  667. Called right before a request is made, after the socket is created.
  668. """
  669. super(HTTPSConnectionPool, self)._validate_conn(conn)
  670. # Force connect early to allow us to validate the connection.
  671. if not getattr(conn, 'sock', None): # AppEngine might not have `.sock`
  672. conn.connect()
  673. if not conn.is_verified:
  674. warnings.warn((
  675. 'Unverified HTTPS request is being made. '
  676. 'Adding certificate verification is strongly advised. See: '
  677. 'https://urllib3.readthedocs.io/en/latest/security.html'),
  678. InsecureRequestWarning)
  679. def connection_from_url(url, **kw):
  680. """
  681. Given a url, return an :class:`.ConnectionPool` instance of its host.
  682. This is a shortcut for not having to parse out the scheme, host, and port
  683. of the url before creating an :class:`.ConnectionPool` instance.
  684. :param url:
  685. Absolute URL string that must include the scheme. Port is optional.
  686. :param \**kw:
  687. Passes additional parameters to the constructor of the appropriate
  688. :class:`.ConnectionPool`. Useful for specifying things like
  689. timeout, maxsize, headers, etc.
  690. Example::
  691. >>> conn = connection_from_url('http://google.com/')
  692. >>> r = conn.request('GET', '/')
  693. """
  694. scheme, host, port = get_host(url)
  695. port = port or port_by_scheme.get(scheme, 80)
  696. if scheme == 'https':
  697. return HTTPSConnectionPool(host, port=port, **kw)
  698. else:
  699. return HTTPConnectionPool(host, port=port, **kw)