Merge pull request #2678 from sigmavirus24/proposed/2.8.0
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Proposed 2.8.0
authored by Cory Benfield · committed by Cory Benfield · parents f7a43e2, 5d7392f · Browse files · 18 files·+587 added−141 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
18 files+587 added−141 removed
- other:+587 added−141 removed
Provenance
- Commit
8963e15- Tree
f81a803- Author
Cory Benfield <lukasaoz@gmail.com>- Committer
Cory Benfield <lukasaoz@gmail.com>- Parent 1
f7a43e2- Parent 2
5d7392f
18 files changed+587 added−141 removed
added:requests/packages/urllib3/contrib/appengine.py+222 added
1+import logging2+import os3+import warnings4+5+from ..exceptions import (6+ HTTPError,7+ HTTPWarning,8+ MaxRetryError,9+ ProtocolError,10+ TimeoutError,11+ SSLError12+)13+14+from ..packages.six import BytesIO15+from ..request import RequestMethods16+from ..response import HTTPResponse17+from ..util.timeout import Timeout18+from ..util.retry import Retry19+20+try:21+ from google.appengine.api import urlfetch22+except ImportError:23+ urlfetch = None24+25+26+log = logging.getLogger(__name__)27+28+29+class AppEnginePlatformWarning(HTTPWarning):30+ pass31+32+33+class AppEnginePlatformError(HTTPError):34+ pass35+36+37+class AppEngineManager(RequestMethods):38+ """39+ Connection manager for Google App Engine sandbox applications.40+41+ This manager uses the URLFetch service directly instead of using the42+ emulated httplib, and is subject to URLFetch limitations as described in43+ the App Engine documentation here:44+45+ https://cloud.google.com/appengine/docs/python/urlfetch46+47+ Notably it will raise an AppEnginePlatformError if:48+ * URLFetch is not available.49+ * If you attempt to use this on GAEv2 (Managed VMs), as full socket50+ support is available.51+ * If a request size is more than 10 megabytes.52+ * If a response size is more than 32 megabtyes.53+ * If you use an unsupported request method such as OPTIONS.54+55+ Beyond those cases, it will raise normal urllib3 errors.56+ """57+58+ def __init__(self, headers=None, retries=None, validate_certificate=True):59+ if not urlfetch:60+ raise AppEnginePlatformError(61+ "URLFetch is not available in this environment.")62+63+ if is_prod_appengine_v2():64+ raise AppEnginePlatformError(65+ "Use normal urllib3.PoolManager instead of AppEngineManager"66+ "on Managed VMs, as using URLFetch is not necessary in "67+ "this environment.")68+69+ warnings.warn(70+ "urllib3 is using URLFetch on Google App Engine sandbox instead "71+ "of sockets. To use sockets directly instead of URLFetch see "72+ "https://urllib3.readthedocs.org/en/latest/contrib.html.",73+ AppEnginePlatformWarning)74+75+ RequestMethods.__init__(self, headers)76+ self.validate_certificate = validate_certificate77+78+ self.retries = retries or Retry.DEFAULT79+80+ def __enter__(self):81+ return self82+83+ def __exit__(self, exc_type, exc_val, exc_tb):84+ # Return False to re-raise any potential exceptions85+ return False86+87+ def urlopen(self, method, url, body=None, headers=None,88+ retries=None, redirect=True, timeout=Timeout.DEFAULT_TIMEOUT,89+ **response_kw):90+91+ retries = self._get_retries(retries, redirect)92+93+ try:94+ response = urlfetch.fetch(95+ url,96+ payload=body,97+ method=method,98+ headers=headers or {},99+ allow_truncated=False,100+ follow_redirects=(101+ redirect and102+ retries.redirect != 0 and103+ retries.total),104+ deadline=self._get_absolute_timeout(timeout),105+ validate_certificate=self.validate_certificate,106+ )107+ except urlfetch.DeadlineExceededError as e:108+ raise TimeoutError(self, e)109+110+ except urlfetch.InvalidURLError as e:111+ if 'too large' in e.message:112+ raise AppEnginePlatformError(113+ "URLFetch request too large, URLFetch only "114+ "supports requests up to 10mb in size.", e)115+ raise ProtocolError(e)116+117+ except urlfetch.DownloadError as e:118+ if 'Too many redirects' in e.message:119+ raise MaxRetryError(self, url, reason=e)120+ raise ProtocolError(e)121+122+ except urlfetch.ResponseTooLargeError as e:123+ raise AppEnginePlatformError(124+ "URLFetch response too large, URLFetch only supports"125+ "responses up to 32mb in size.", e)126+127+ except urlfetch.SSLCertificateError as e:128+ raise SSLError(e)129+130+ except urlfetch.InvalidMethodError as e:131+ raise AppEnginePlatformError(132+ "URLFetch does not support method: %s" % method, e)133+134+ http_response = self._urlfetch_response_to_http_response(135+ response, **response_kw)136+137+ # Check for redirect response138+ if (http_response.get_redirect_location() and139+ retries.raise_on_redirect and redirect):140+ raise MaxRetryError(self, url, "too many redirects")141+142+ # Check if we should retry the HTTP response.143+ if retries.is_forced_retry(method, status_code=http_response.status):144+ retries = retries.increment(145+ method, url, response=http_response, _pool=self)146+ log.info("Forced retry: %s" % url)147+ retries.sleep()148+ return self.urlopen(149+ method, url,150+ body=body, headers=headers,151+ retries=retries, redirect=redirect,152+ timeout=timeout, **response_kw)153+154+ return http_response155+156+ def _urlfetch_response_to_http_response(self, urlfetch_resp, **response_kw):157+158+ if is_prod_appengine_v1():159+ # Production GAE handles deflate encoding automatically, but does160+ # not remove the encoding header.161+ content_encoding = urlfetch_resp.headers.get('content-encoding')162+163+ if content_encoding == 'deflate':164+ del urlfetch_resp.headers['content-encoding']165+166+ return HTTPResponse(167+ # In order for decoding to work, we must present the content as168+ # a file-like object.169+ body=BytesIO(urlfetch_resp.content),170+ headers=urlfetch_resp.headers,171+ status=urlfetch_resp.status_code,172+ **response_kw173+ )174+175+ def _get_absolute_timeout(self, timeout):176+ if timeout is Timeout.DEFAULT_TIMEOUT:177+ return 5 # 5s is the default timeout for URLFetch.178+ if isinstance(timeout, Timeout):179+ if not timeout.read is timeout.connect:180+ warnings.warn(181+ "URLFetch does not support granular timeout settings, "182+ "reverting to total timeout.", AppEnginePlatformWarning)183+ return timeout.total184+ return timeout185+186+ def _get_retries(self, retries, redirect):187+ if not isinstance(retries, Retry):188+ retries = Retry.from_int(189+ retries, redirect=redirect, default=self.retries)190+191+ if retries.connect or retries.read or retries.redirect:192+ warnings.warn(193+ "URLFetch only supports total retries and does not "194+ "recognize connect, read, or redirect retry parameters.",195+ AppEnginePlatformWarning)196+197+ return retries198+199+200+def is_appengine():201+ return (is_local_appengine() or202+ is_prod_appengine_v1() or203+ is_prod_appengine_v2())204+205+206+def is_appengine_sandbox():207+ return is_appengine() and not is_prod_appengine_v2()208+209+210+def is_local_appengine():211+ return ('APPENGINE_RUNTIME' in os.environ and212+ 'Development/' in os.environ['SERVER_SOFTWARE'])213+214+215+def is_prod_appengine_v1():216+ return ('APPENGINE_RUNTIME' in os.environ and217+ 'Google App Engine/' in os.environ['SERVER_SOFTWARE'] and218+ not is_prod_appengine_v2())219+220+221+def is_prod_appengine_v2():222+ return os.environ.get('GAE_VM', False) == 'true'modified:requests/packages/urllib3/contrib/pyopenssl.py+21 added-5 removed
83 unmodified lines84 }85 86 DEFAULT_SSL_CIPHER_LIST = util.ssl_.DEFAULT_CIPHERS87 88+# OpenSSL will only write 16K at a time89+SSL_WRITE_BLOCKSIZE = 1638490 91+try:92+ _ = memoryview93+ has_memoryview = True94+except NameError:95+ has_memoryview = False96+97 orig_util_HAS_SNI = util.HAS_SNI98 orig_connection_ssl_wrap_socket = connection.ssl_wrap_socket99 100 110 unmodified lines211 raise timeout()212 continue213 214 def sendall(self, data):207- while len(data):208- sent = self._send_until_done(data)209- data = data[sent:]215+ if has_memoryview and not isinstance(data, memoryview):216+ data = memoryview(data)217 218+ total_sent = 0219+ while total_sent < len(data):220+ sent = self._send_until_done(data[total_sent:total_sent+SSL_WRITE_BLOCKSIZE])221+ total_sent += sent222+223+ def shutdown(self):224+ # FIXME rethrow compatible exceptions should we ever use this225+ self.connection.shutdown()226+227 def close(self):228 if self._makefile_refs < 1:213- return self.connection.shutdown()229+ return self.connection.close()230 else:231 self._makefile_refs -= 1232 233 def getpeercert(self, binary_form=False):68 unmodified lines302 if not rd:303 raise timeout('select timed out')304 continue305 except OpenSSL.SSL.Error as e:290- raise ssl.SSLError('bad handshake', e)306+ raise ssl.SSLError('bad handshake: %r' % e)307 break308 309 return WrappedSocket(cnx, sock)modified:requests/packages/urllib3/util/connection.py+2 added
58 unmodified lines59 An host of '' or port 0 tells the OS to use the default.60 """61 62 host, port = address63+ if host.startswith('['):64+ host = host.strip('[]')65 err = None66 for res in socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM):67 af, socktype, proto, canonname, sa = res68 sock = None32 unmodified linesmodified:requests/packages/urllib3/util/response.py+54 added
1+try:2+ import http.client as httplib3+except ImportError:4+ import httplib5+6+from ..exceptions import HeaderParsingError7+8+9 def is_fp_closed(obj):10 """11 Checks whether a given file-like object is closed.12 14 unmodified lines27 except AttributeError:28 pass29 30 raise ValueError("Unable to determine whether fp is closed.")31+32+33+def assert_header_parsing(headers):34+ """35+ Asserts whether all headers have been successfully parsed.36+ Extracts encountered errors from the result of parsing headers.37+38+ Only works on Python 3.39+40+ :param headers: Headers to verify.41+ :type headers: `httplib.HTTPMessage`.42+43+ :raises urllib3.exceptions.HeaderParsingError:44+ If parsing errors are found.45+ """46+47+ # This will fail silently if we pass in the wrong kind of parameter.48+ # To make debugging easier add an explicit check.49+ if not isinstance(headers, httplib.HTTPMessage):50+ raise TypeError('expected httplib.Message, got {}.'.format(51+ type(headers)))52+53+ defects = getattr(headers, 'defects', None)54+ get_payload = getattr(headers, 'get_payload', None)55+56+ unparsed_data = None57+ if get_payload: # Platform-specific: Python 3.58+ unparsed_data = get_payload()59+60+ if defects or unparsed_data:61+ raise HeaderParsingError(defects=defects, unparsed_data=unparsed_data)62+63+64+def is_response_to_head(response):65+ """66+ Checks, wether a the request of a response has been a HEAD-request.67+ Handles the quirks of AppEngine.68+69+ :param conn:70+ :type conn: :class:`httplib.HTTPResponse`71+ """72+ # FIXME: Can we do this somehow without accessing private httplib _method?73+ method = response._method74+ if isinstance(method, int): # Platform-specific: Appengine75+ return method == 376+ return method.upper() == 'HEAD'modified:requests/packages/urllib3/util/retry.py+1 added-1 removed
92 unmodified lines93 {backoff factor} * (2 ^ ({number of total retries} - 1))94 95 seconds. If the backoff_factor is 0.1, then :func:`.sleep` will sleep96 for [0.1s, 0.2s, 0.4s, ...] between retries. It will never be longer97- than :attr:`Retry.MAX_BACKOFF`.97+ than :attr:`Retry.BACKOFF_MAX`.98 99 By default, backoff is disabled (set to 0).100 101 :param bool raise_on_redirect: Whether, if the number of redirects is184 unmodified linesmodified:requests/packages/urllib3/util/ssl_.py+14 added-17 removed
6 unmodified lines7 SSLContext = None8 HAS_SNI = False9 create_default_context = None10 11+# Maps the length of a digest to a possible hash function producing this digest12+HASHFUNC_MAP = {13+ 32: md5,14+ 40: sha1,15+ 64: sha256,16+}17+18 import errno19 import warnings20 21 try: # Test for SSL features96 unmodified lines118 :param fingerprint:119 Fingerprint as string of hexdigits, can be interspersed by colons.120 """121 115- # Maps the length of a digest to a possible hash function producing116- # this digest.117- hashfunc_map = {118- 16: md5,119- 20: sha1,120- 32: sha256,121- }122-122 fingerprint = fingerprint.replace(':', '').lower()124- digest_length, odd = divmod(len(fingerprint), 2)123+ digest_length = len(fingerprint)124+ hashfunc = HASHFUNC_MAP.get(digest_length)125+ if not hashfunc:126+ raise SSLError(127+ 'Fingerprint of invalid length: {0}'.format(fingerprint))128 126- if odd or digest_length not in hashfunc_map:127- raise SSLError('Fingerprint is of invalid length.')128-129 # We need encode() here for py32; works on py2 and p33.130 fingerprint_bytes = unhexlify(fingerprint.encode())131 132- hashfunc = hashfunc_map[digest_length]133-132 cert_digest = hashfunc(cert).digest()133 136- if not cert_digest == fingerprint_bytes:134+ if cert_digest != fingerprint_bytes:135 raise SSLError('Fingerprints did not match. Expected "{0}", got "{1}".'138- .format(hexlify(fingerprint_bytes),139- hexlify(cert_digest)))136+ .format(fingerprint, hexlify(cert_digest)))137 138 139 def resolve_cert_reqs(candidate):140 """137 unmodified linesmodified:requests/packages/urllib3/__init__.py+3 added-1 removed
2 unmodified lines3 """4 5 __author__ = 'Andrey Petrov (andrey.petrov@shazow.net)'6 __license__ = 'MIT'7-__version__ = '1.10.4'7+__version__ = 'dev'8 9 10 from .connectionpool import (11 HTTPConnectionPool,45 unmodified lines57 58 import warnings59 # SecurityWarning's always go off by default.60 warnings.simplefilter('always', exceptions.SecurityWarning, append=True)61+# SubjectAltNameWarning's should go off once per host62+warnings.simplefilter('default', exceptions.SubjectAltNameWarning)63 # InsecurePlatformWarning's don't vary between requests, so we keep it default.64 warnings.simplefilter('default', exceptions.InsecurePlatformWarning,65 append=True)66 5 unmodified linesmodified:requests/packages/urllib3/connection.py+9 added-5 removed
36 unmodified lines37 38 from .exceptions import (39 ConnectTimeoutError,40 SystemTimeWarning,41- SecurityWarning,41+ SubjectAltNameWarning,42 )43 from .packages.ssl_match_hostname import match_hostname44 45 from .util.ssl_ import (145 unmodified lines191 def set_cert(self, key_file=None, cert_file=None,192 cert_reqs=None, ca_certs=None,193 assert_hostname=None, assert_fingerprint=None):194 195+ if ca_certs and cert_reqs is None:196+ cert_reqs = 'CERT_REQUIRED'197+198 self.key_file = key_file199 self.cert_file = cert_file200 self.cert_reqs = cert_reqs201 self.ca_certs = ca_certs45 unmodified lines247 and self.assert_hostname is not False:248 cert = self.sock.getpeercert()249 if not cert.get('subjectAltName', ()):250 warnings.warn((248- 'Certificate has no `subjectAltName`, falling back to check for a `commonName` for now. '249- 'This feature is being removed by major browsers and deprecated by RFC 2818. '250- '(See https://github.com/shazow/urllib3/issues/497 for details.)'),251- SecurityWarning251+ 'Certificate for {0} has no `subjectAltName`, falling back to check for a '252+ '`commonName` for now. This feature is being removed by major browsers and '253+ 'deprecated by RFC 2818. (See https://github.com/shazow/urllib3/issues/497 '254+ 'for details.)'.format(hostname)),255+ SubjectAltNameWarning256 )257 match_hostname(cert, self.assert_hostname or hostname)258 259 self.is_verified = (resolved_cert_reqs == ssl.CERT_REQUIRED9 unmodified linesmodified:requests/packages/urllib3/connectionpool.py+31 added-14 removed
15 unmodified lines16 from .exceptions import (17 ClosedPoolError,18 ProtocolError,19 EmptyPoolError,20+ HeaderParsingError,21 HostChangedError,22 LocationValueError,23 MaxRetryError,24 ProxyError,13 unmodified lines38 from .request import RequestMethods39 from .response import HTTPResponse40 41 from .util.connection import is_connection_dropped42+from .util.response import assert_header_parsing43 from .util.retry import Retry44 from .util.timeout import Timeout43-from .util.url import get_host45+from .util.url import get_host, Url46 47 48 xrange = six.moves.xrange49 71 unmodified lines121 been parsed, this is always a `urllib3.util.Timeout` object.122 123 :param maxsize:124 Number of connections to save that can be reused. More than 1 is useful123- in multithreaded situations. If ``block`` is set to false, more125+ in multithreaded situations. If ``block`` is set to False, more126 connections will be created but they will not be saved once they've127 been used.128 129 :param block:252 unmodified lines382 http_version = getattr(conn, '_http_vsn_str', 'HTTP/?')383 log.debug("\"%s %s %s\" %s %s" % (method, url, http_version,384 httplib_response.status,385 httplib_response.length))386+387+ try:388+ assert_header_parsing(httplib_response.msg)389+ except HeaderParsingError as hpe: # Platform-specific: Python 3390+ log.warning(391+ 'Failed to parse headers (url=%s): %s',392+ self._absolute_url(url), hpe, exc_info=True)393+394 return httplib_response395 396+ def _absolute_url(self, path):397+ return Url(scheme=self.scheme, host=self.host, port=self.port, path=path).url398+399 def close(self):400 """401 Close all pooled connections and disable the pool.402 """18 unmodified lines421 return True422 423 # TODO: Add optional support for socket.gethostbyname checking.424 scheme, host, port = get_host(url)412-425+ 426 # Use explicit default port for comparison when none is given427 if self.port and not port:428 port = port_by_scheme.get(scheme)429 elif not self.port and port == port_by_scheme.get(scheme):150 unmodified lines580 except (BaseSSLError, CertificateError) as e:581 # Close the connection. If a connection is reused on which there582 # was a Certificate error, the next request will certainly raise583 # another Certificate error.571- if conn:572- conn.close()573- conn = None584+ conn = conn and conn.close()585+ release_conn = True586 raise SSLError(e)587 588 except SSLError:589 # Treat SSLError separately from BaseSSLError to preserve590 # traceback.579- if conn:580- conn.close()581- conn = None591+ conn = conn and conn.close()592+ release_conn = True593 raise594 595 except (TimeoutError, HTTPException, SocketError, ConnectionError) as e:585- if conn:586- # Discard the connection for these exceptions. It will be587- # be replaced during the next _get_conn() call.588- conn.close()589- conn = None596+ # Discard the connection for these exceptions. It will be597+ # be replaced during the next _get_conn() call.598+ conn = conn and conn.close()599+ release_conn = True600 601 if isinstance(e, SocketError) and self.proxy:602 e = ProxyError('Cannot connect to proxy.', e)603 elif isinstance(e, (SocketError, HTTPException)):31 unmodified lines635 try:636 retries = retries.increment(method, url, response=response, _pool=self)637 except MaxRetryError:638 if retries.raise_on_redirect:639+ # Release the connection for this response, since we're not640+ # returning it to be released manually.641+ response.release_conn()642 raise643 return response644 645 log.info("Redirecting %s -> %s" % (url, redirect_location))49 unmodified lines695 696 HTTPConnectionPool.__init__(self, host, port, strict, timeout, maxsize,697 block, headers, retries, _proxy, _proxy_headers,698 **conn_kw)699+700+ if ca_certs and cert_reqs is None:701+ cert_reqs = 'CERT_REQUIRED'702+703 self.key_file = key_file704 self.cert_file = cert_file705 self.cert_reqs = cert_reqs706 self.ca_certs = ca_certs106 unmodified linesmodified:requests/packages/urllib3/exceptions.py+21 added
147 unmodified lines148 "Warned when perfoming security reducing actions"149 pass150 151 152+class SubjectAltNameWarning(SecurityWarning):153+ "Warned when connecting to a host with a certificate missing a SAN."154+ pass155+156+157 class InsecureRequestWarning(SecurityWarning):158 "Warned when making an unverified HTTPS request."159 pass160 10 unmodified lines171 172 class ResponseNotChunked(ProtocolError, ValueError):173 "Response needs to be chunked in order to read it as chunks."174 pass175+176+177+class ProxySchemeUnknown(AssertionError, ValueError):178+ "ProxyManager does not support the supplied scheme"179+ # TODO(t-8ch): Stop inheriting from AssertionError in v2.0.180+181+ def __init__(self, scheme):182+ message = "Not supported proxy scheme %s" % scheme183+ super(ProxySchemeUnknown, self).__init__(message)184+185+186+class HeaderParsingError(HTTPError):187+ "Raised by assert_header_parsing, but we convert it to a log.warning statement."188+ def __init__(self, defects, unparsed_data):189+ message = '%s, unparsed data: %r' % (defects or 'Unknown', unparsed_data)190+ super(HeaderParsingError, self).__init__(message)modified:requests/packages/urllib3/poolmanager.py+3 added-3 removed
6 unmodified lines7 8 from ._collections import RecentlyUsedContainer9 from .connectionpool import HTTPConnectionPool, HTTPSConnectionPool10 from .connectionpool import port_by_scheme11-from .exceptions import LocationValueError, MaxRetryError11+from .exceptions import LocationValueError, MaxRetryError, ProxySchemeUnknown12 from .request import RequestMethods13 from .util.url import parse_url14 from .util.retry import Retry15 210 unmodified lines226 if not proxy.port:227 port = port_by_scheme.get(proxy.scheme, 80)228 proxy = proxy._replace(port=port)229 230- assert proxy.scheme in ("http", "https"), \231- 'Not supported proxy scheme %s' % proxy.scheme230+ if proxy.scheme not in ("http", "https"):231+ raise ProxySchemeUnknown(proxy.scheme)232 233 self.proxy = proxy234 self.proxy_headers = proxy_headers or {}235 45 unmodified linesmodified:requests/packages/urllib3/request.py+10 added-2 removed
69 unmodified lines70 return self.request_encode_body(method, url, fields=fields,71 headers=headers,72 **urlopen_kw)73 74- def request_encode_url(self, method, url, fields=None, **urlopen_kw):74+ def request_encode_url(self, method, url, fields=None, headers=None,75+ **urlopen_kw):76 """77 Make a request using :meth:`urlopen` with the ``fields`` encoded in78 the url. This is useful for request methods like GET, HEAD, DELETE, etc.79 """80+ if headers is None:81+ headers = self.headers82+83+ extra_kw = {'headers': headers}84+ extra_kw.update(urlopen_kw)85+86 if fields:87 url += '?' + urlencode(fields)81- return self.urlopen(method, url, **urlopen_kw)88 89+ return self.urlopen(method, url, **extra_kw)90+91 def request_encode_body(self, method, url, fields=None, headers=None,92 encode_multipart=True, multipart_boundary=None,93 **urlopen_kw):94 """55 unmodified linesmodified:requests/packages/urllib3/response.py+85 added-63 removed
1 try:2 import http.client as httplib3 except ImportError:4 import httplib5+from contextlib import contextmanager6 import zlib7 import io8 from socket import timeout as SocketTimeout9 2 unmodified lines12 ProtocolError, DecodeError, ReadTimeoutError, ResponseNotChunked13 )14 from .packages.six import string_types as basestring, binary_type, PY315 from .connection import HTTPException, BaseSSLError15-from .util.response import is_fp_closed16+from .util.response import is_fp_closed, is_response_to_head17 18 19 class DeflateDecoder(object):20 181 unmodified lines202 data += buf + self._decoder.flush()203 204 return data205 206+ @contextmanager207+ def _error_catcher(self):208+ """209+ Catch low-level python exceptions, instead re-raising urllib3210+ variants, so that low-level exceptions are not leaked in the211+ high-level api.212+213+ On exit, release the connection back to the pool.214+ """215+ try:216+ try:217+ yield218+219+ except SocketTimeout:220+ # FIXME: Ideally we'd like to include the url in the ReadTimeoutError but221+ # there is yet no clean way to get at it from this context.222+ raise ReadTimeoutError(self._pool, None, 'Read timed out.')223+224+ except BaseSSLError as e:225+ # FIXME: Is there a better way to differentiate between SSLErrors?226+ if 'read operation timed out' not in str(e): # Defensive:227+ # This shouldn't happen but just in case we're missing an edge228+ # case, let's avoid swallowing SSL errors.229+ raise230+231+ raise ReadTimeoutError(self._pool, None, 'Read timed out.')232+233+ except HTTPException as e:234+ # This includes IncompleteRead.235+ raise ProtocolError('Connection broken: %r' % e, e)236+ except Exception:237+ # The response may not be closed but we're not going to use it anymore238+ # so close it now to ensure that the connection is released back to the pool.239+ if self._original_response and not self._original_response.isclosed():240+ self._original_response.close()241+242+ raise243+ finally:244+ if self._original_response and self._original_response.isclosed():245+ self.release_conn()246+247 def read(self, amt=None, decode_content=None, cache_content=False):248 """249 Similar to :meth:`httplib.HTTPResponse.read`, but with two additional250 parameters: ``decode_content`` and ``cache_content``.21 unmodified lines272 if self._fp is None:273 return274 275 flush_decoder = False276+ data = None277 235- try:236- try:237- if amt is None:238- # cStringIO doesn't like amt=None239- data = self._fp.read()278+ with self._error_catcher():279+ if amt is None:280+ # cStringIO doesn't like amt=None281+ data = self._fp.read()282+ flush_decoder = True283+ else:284+ cache_content = False285+ data = self._fp.read(amt)286+ if amt != 0 and not data: # Platform-specific: Buggy versions of Python.287+ # Close the connection when no data is returned288+ #289+ # This is redundant to what httplib/http.client _should_290+ # already do. However, versions of python released before291+ # December 15, 2012 (http://bugs.python.org/issue16298) do292+ # not properly close the connection in all cases. There is293+ # no harm in redundantly calling close.294+ self._fp.close()295 flush_decoder = True241- else:242- cache_content = False243- data = self._fp.read(amt)244- if amt != 0 and not data: # Platform-specific: Buggy versions of Python.245- # Close the connection when no data is returned246- #247- # This is redundant to what httplib/http.client _should_248- # already do. However, versions of python released before249- # December 15, 2012 (http://bugs.python.org/issue16298) do250- # not properly close the connection in all cases. There is251- # no harm in redundantly calling close.252- self._fp.close()253- flush_decoder = True296 255- except SocketTimeout:256- # FIXME: Ideally we'd like to include the url in the ReadTimeoutError but257- # there is yet no clean way to get at it from this context.258- raise ReadTimeoutError(self._pool, None, 'Read timed out.')259-260- except BaseSSLError as e:261- # FIXME: Is there a better way to differentiate between SSLErrors?262- if 'read operation timed out' not in str(e): # Defensive:263- # This shouldn't happen but just in case we're missing an edge264- # case, let's avoid swallowing SSL errors.265- raise266-267- raise ReadTimeoutError(self._pool, None, 'Read timed out.')268-269- except HTTPException as e:270- # This includes IncompleteRead.271- raise ProtocolError('Connection broken: %r' % e, e)272-297+ if data:298 self._fp_bytes_read += len(data)299 300 data = self._decode(data, decode_content, flush_decoder)301 302 if cache_content:303 self._body = data304 280- return data305+ return data306 282- finally:283- if self._original_response and self._original_response.isclosed():284- self.release_conn()307 308 def stream(self, amt=2**16, decode_content=None):309 """310 A generator wrapper for the read() method. A call will block until29 unmodified lines340 Remaining parameters are passed to the HTTPResponse constructor, along341 with ``original_response=r``.342 """343 headers = r.msg344+345 if not isinstance(headers, HTTPHeaderDict):346 if PY3: # Python 3347 headers = HTTPHeaderDict(headers.items())348 else: # Python 2110 unmodified lines459 if not self.chunked:460 raise ResponseNotChunked("Response is not chunked. "461 "Header 'transfer-encoding: chunked' is missing.")462 440- if self._original_response and self._original_response._method.upper() == 'HEAD':441- # Don't bother reading the body of a HEAD request.442- # FIXME: Can we do this somehow without accessing private httplib _method?463+ # Don't bother reading the body of a HEAD request.464+ if self._original_response and is_response_to_head(self._original_response):465 self._original_response.close()466 return467 468+ with self._error_catcher():446- while True:447- self._update_chunk_length()448- if self.chunk_left == 0:449- break450- chunk = self._handle_chunk(amt)451- yield self._decode(chunk, decode_content=decode_content,452- flush_decoder=True)469+ while True:470+ self._update_chunk_length()471+ if self.chunk_left == 0:472+ break473+ chunk = self._handle_chunk(amt)474+ yield self._decode(chunk, decode_content=decode_content,475+ flush_decoder=True)476 454- # Chunk content ends with \r\n: discard it.455- while True:456- line = self._fp.fp.readline()457- if not line:458- # Some sites may not end with '\r\n'.459- break460- if line == b'\r\n':461- break477+ # Chunk content ends with \r\n: discard it.478+ while True:479+ line = self._fp.fp.readline()480+ if not line:481+ # Some sites may not end with '\r\n'.482+ break483+ if line == b'\r\n':484+ break485 463- # We read everything; close the "file".464- if self._original_response:465- self._original_response.close()466- self.release_conn()486+ # We read everything; close the "file".487+ if self._original_response:488+ self._original_response.close()modified:requests/packages/__init__.py+34 added-1 removed
1+'''2+Debian and other distributions "unbundle" requests' vendored dependencies, and3+rewrite all imports to use the global versions of ``urllib3`` and ``chardet``.4+The problem with this is that not only requests itself imports those5+dependencies, but third-party code outside of the distros' control too.6+7+In reaction to these problems, the distro maintainers replaced8+``requests.packages`` with a magical "stub module" that imports the correct9+modules. The implementations were varying in quality and all had severe10+problems. For example, a symlink (or hardlink) that links the correct modules11+into place introduces problems regarding object identity, since you now have12+two modules in `sys.modules` with the same API, but different identities::13+14+ requests.packages.urllib3 is not urllib315+16+With version ``2.5.2``, requests started to maintain its own stub, so that17+distro-specific breakage would be reduced to a minimum, even though the whole18+issue is not requests' fault in the first place. See19+https://github.com/kennethreitz/requests/pull/2375 for the corresponding pull20+request.21+'''22+23 from __future__ import absolute_import24+import sys25 26+try:3-from . import urllib327+ from . import urllib328+except ImportError:29+ import urllib330+ sys.modules['%s.urllib3' % __name__] = urllib331+32+try:33+ from . import chardet34+except ImportError:35+ import chardet36+ sys.modules['%s.chardet' % __name__] = chardetmodified:requests/packages/README.rst+5 added-2 removed
1 If you are planning to submit a pull request to requests with any changes in 2-this library do not go any further. These are independent libraries which we 3-vendor into requests. Any changes necessary to these libraries must be made in 2+this library do not go any further. These are independent libraries which we3+vendor into requests. Any changes necessary to these libraries must be made in4 them and submitted as separate pull requests to those libraries.5 6 urllib3 pull requests go here: https://github.com/shazow/urllib37 8 chardet pull requests go here: https://github.com/chardet/chardet9+10+See https://github.com/kennethreitz/requests/pull/1812#issuecomment-3085431611+for the reasoning behind this.modified:requests/adapters.py+4 added
18 unmodified lines19 from .utils import (DEFAULT_CA_BUNDLE_PATH, get_encoding_from_headers,20 prepend_scheme_if_needed, get_auth_from_url, urldefragauth,21 select_proxy)22 from .structures import CaseInsensitiveDict23+from .packages.urllib3.exceptions import ClosedPoolError24 from .packages.urllib3.exceptions import ConnectTimeoutError25 from .packages.urllib3.exceptions import HTTPError as _HTTPError26 from .packages.urllib3.exceptions import MaxRetryError27 from .packages.urllib3.exceptions import ProxyError as _ProxyError390 unmodified lines418 raise RetryError(e, request=request)419 420 raise ConnectionError(e, request=request)421 422+ except ClosedPoolError as e:423+ raise ConnectionError(e, request=request)424+425 except _ProxyError as e:426 raise ProxyError(e)427 428 except (_SSLError, _HTTPError) as e:8 unmodified linesmodified:requests/auth.py+38 added-27 removed
9 unmodified lines10 import os11 import re12 import time13 import hashlib14+import threading15 16 from base64 import b64encode17 18 from .compat import urlparse, str44 unmodified lines63 """Attaches HTTP Digest Authentication to the given Request object."""64 def __init__(self, username, password):65 self.username = username66 self.password = password66- self.last_nonce = ''67- self.nonce_count = 068- self.chal = {}69- self.pos = None70- self.num_401_calls = 167+ # Keep state in per-thread local storage68+ self._thread_local = threading.local()69 70+ def init_per_thread_state(self):71+ # Ensure state is initialized just once per-thread72+ if not hasattr(self._thread_local, 'init'):73+ self._thread_local.init = True74+ self._thread_local.last_nonce = ''75+ self._thread_local.nonce_count = 076+ self._thread_local.chal = {}77+ self._thread_local.pos = None78+ self._thread_local.num_401_calls = None79+80 def build_digest_header(self, method, url):81 74- realm = self.chal['realm']75- nonce = self.chal['nonce']76- qop = self.chal.get('qop')77- algorithm = self.chal.get('algorithm')78- opaque = self.chal.get('opaque')82+ realm = self._thread_local.chal['realm']83+ nonce = self._thread_local.chal['nonce']84+ qop = self._thread_local.chal.get('qop')85+ algorithm = self._thread_local.chal.get('algorithm')86+ opaque = self._thread_local.chal.get('opaque')87 88 if algorithm is None:89 _algorithm = 'MD5'90 else:30 unmodified lines121 122 HA1 = hash_utf8(A1)123 HA2 = hash_utf8(A2)124 117- if nonce == self.last_nonce:118- self.nonce_count += 1125+ if nonce == self._thread_local.last_nonce:126+ self._thread_local.nonce_count += 1127 else:120- self.nonce_count = 1121- ncvalue = '%08x' % self.nonce_count122- s = str(self.nonce_count).encode('utf-8')128+ self._thread_local.nonce_count = 1129+ ncvalue = '%08x' % self._thread_local.nonce_count130+ s = str(self._thread_local.nonce_count).encode('utf-8')131 s += nonce.encode('utf-8')132 s += time.ctime().encode('utf-8')133 s += os.urandom(8)134 11 unmodified lines146 else:147 # XXX handle auth-int.148 return None149 142- self.last_nonce = nonce150+ self._thread_local.last_nonce = nonce151 152 # XXX should the partial digests be encoded too?153 base = 'username="%s", realm="%s", nonce="%s", uri="%s", ' \154 'response="%s"' % (self.username, realm, nonce, path, respdig)10 unmodified lines165 166 def handle_redirect(self, r, **kwargs):167 """Reset num_401_calls counter on redirects."""168 if r.is_redirect:161- self.num_401_calls = 1169+ self._thread_local.num_401_calls = 1170 171 def handle_401(self, r, **kwargs):172 """Takes the given response and tries digest-auth, if needed."""173 166- if self.pos is not None:174+ if self._thread_local.pos is not None:175 # Rewind the file position indicator of the body to where176 # it was to resend the request.169- r.request.body.seek(self.pos)170- num_401_calls = getattr(self, 'num_401_calls', 1)177+ r.request.body.seek(self._thread_local.pos)178 s_auth = r.headers.get('www-authenticate', '')179 173- if 'digest' in s_auth.lower() and num_401_calls < 2:180+ if 'digest' in s_auth.lower() and self._thread_local.num_401_calls < 2:181 175- self.num_401_calls += 1182+ self._thread_local.num_401_calls += 1183 pat = re.compile(r'digest ', flags=re.IGNORECASE)177- self.chal = parse_dict_header(pat.sub('', s_auth, count=1))184+ self._thread_local.chal = parse_dict_header(pat.sub('', s_auth, count=1))185 186 # Consume content and release the original connection187 # to allow our new request to reuse the same one.188 r.content9 unmodified lines198 _r.request = prep199 200 return _r201 195- self.num_401_calls = 1202+ self._thread_local.num_401_calls = 1203 return r204 205 def __call__(self, r):206+ # Initialize per-thread state, if needed207+ self.init_per_thread_state()208 # If we have a saved nonce, skip the 401200- if self.last_nonce:209+ if self._thread_local.last_nonce:210 r.headers['Authorization'] = self.build_digest_header(r.method, r.url)211 try:203- self.pos = r.body.tell()212+ self._thread_local.pos = r.body.tell()213 except AttributeError:214 # In the case of HTTPDigestAuth being reused and the body of215 # the previous request was a file-like object, pos has the216 # file position of the previous body. Ensure it's set to217 # None.209- self.pos = None218+ self._thread_local.pos = None219 r.register_hook('response', self.handle_401)220 r.register_hook('response', self.handle_redirect)221+ self._thread_local.num_401_calls = 1222+223 return rmodified:test_requests.py+30 added
33 unmodified lines34 import StringIO35 except ImportError:36 import io as StringIO37 38+try:39+ from multiprocessing.pool import ThreadPool40+except ImportError:41+ ThreadPool = None42+43 if is_py3:44 def u(s):45 return s46 else:378 unmodified lines425 426 r = requests.get(url, auth=auth)427 assert '"auth"' in r.request.headers['Authorization']428 429+ def test_DIGESTAUTH_THREADED(self):430+431+ auth = HTTPDigestAuth('user', 'pass')432+ url = httpbin('digest-auth', 'auth', 'user', 'pass')433+ session = requests.Session()434+ session.auth=auth435+436+ def do_request(i):437+ r = session.get(url)438+ assert '"auth"' in r.request.headers['Authorization']439+ return 1440+ if ThreadPool is not None:441+ pool = ThreadPool(processes=50)442+ pool.map(do_request, range(100))443+444 def test_POSTBIN_GET_POST_FILES(self):445 446 url = httpbin('post')447 post1 = requests.post(url).raise_for_status()1237 unmodified lines1685 1686 with pytest.raises(RetryError):1687 s.get(httpbin('status/500'))1688 1689+1690+def test_urllib3_pool_connection_closed():1691+ s = requests.Session()1692+ s.mount('http://', HTTPAdapter(pool_connections=0, pool_maxsize=0))1693+1694+ try:1695+ s.get(httpbin('status/200'))1696+ except ConnectionError as e:1697+ assert u"HTTPConnectionPool(host='httpbin.org', port=80): Pool is closed." in str(e)1698+1699 def test_vendor_aliases():1700 from requests.packages import urllib31701 from requests.packages import chardet1702 5 unmodified lines