connectionpool.py 39 KB

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