Update urllib3 to 1.19
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Cory Benfield · committed by Cory Benfield · parent e2408fc · Browse files · 21 files·+713 added−250 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
21 files+713 added−250 removed
- other:+713 added−250 removed
Provenance
- Commit
99fa7be- Tree
48fe0bf- Author
Cory Benfield <lukasaoz@gmail.com>- Committer
Cory Benfield <lukasaoz@gmail.com>- Parent
e2408fc
21 files changed+713 added−250 removed
modified:requests/packages/urllib3/contrib/appengine.py+86 added-21 removed
1+"""2+This module provides a pool manager that uses Google App Engine's3+`URLFetch Service <https://cloud.google.com/appengine/docs/python/urlfetch>`_.4+5+Example usage::6+7+ from urllib3 import PoolManager8+ from urllib3.contrib.appengine import AppEngineManager, is_appengine_sandbox9+10+ if is_appengine_sandbox():11+ # AppEngineManager uses AppEngine's URLFetch API behind the scenes12+ http = AppEngineManager()13+ else:14+ # PoolManager uses a socket-level API behind the scenes15+ http = PoolManager()16+17+ r = http.request('GET', 'https://google.com/')18+19+There are `limitations <https://cloud.google.com/appengine/docs/python/\20+urlfetch/#Python_Quotas_and_limits>`_ to the URLFetch service and it may not be21+the best choice for your application. There are three options for using22+urllib3 on Google App Engine:23+24+1. You can use :class:`AppEngineManager` with URLFetch. URLFetch is25+ cost-effective in many circumstances as long as your usage is within the26+ limitations.27+2. You can use a normal :class:`~urllib3.PoolManager` by enabling sockets.28+ Sockets also have `limitations and restrictions29+ <https://cloud.google.com/appengine/docs/python/sockets/\30+ #limitations-and-restrictions>`_ and have a lower free quota than URLFetch.31+ To use sockets, be sure to specify the following in your ``app.yaml``::32+33+ env_variables:34+ GAE_USE_SOCKETS_HTTPLIB : 'true'35+36+3. If you are using `App Engine Flexible37+<https://cloud.google.com/appengine/docs/flexible/>`_, you can use the standard38+:class:`PoolManager` without any configuration or special environment variables.39+"""40+41 from __future__ import absolute_import42 import logging43 import os44 import warnings45+from urlparse import urljoin46 47 from ..exceptions import (48 HTTPError,49 HTTPWarning,31 unmodified lines81 Connection manager for Google App Engine sandbox applications.82 83 This manager uses the URLFetch service directly instead of using the84 emulated httplib, and is subject to URLFetch limitations as described in44- the App Engine documentation here:85+ the App Engine documentation `here86+ <https://cloud.google.com/appengine/docs/python/urlfetch>`_.87 46- https://cloud.google.com/appengine/docs/python/urlfetch47-48- Notably it will raise an AppEnginePlatformError if:88+ Notably it will raise an :class:`AppEnginePlatformError` if:89 * URLFetch is not available.50- * If you attempt to use this on GAEv2 (Managed VMs), as full socket90+ * If you attempt to use this on App Engine Flexible, as full socket91 support is available.92 * If a request size is more than 10 megabytes.93 * If a response size is more than 32 megabtyes.94 * If you use an unsupported request method such as OPTIONS.95 96 Beyond those cases, it will raise normal urllib3 errors.97 """98 59- def __init__(self, headers=None, retries=None, validate_certificate=True):99+ def __init__(self, headers=None, retries=None, validate_certificate=True,100+ urlfetch_retries=True):101 if not urlfetch:102 raise AppEnginePlatformError(103 "URLFetch is not available in this environment.")104 10 unmodified lines115 AppEnginePlatformWarning)116 117 RequestMethods.__init__(self, headers)118 self.validate_certificate = validate_certificate119+ self.urlfetch_retries = urlfetch_retries120 121 self.retries = retries or Retry.DEFAULT122 123 def __enter__(self):9 unmodified lines133 134 retries = self._get_retries(retries, redirect)135 136 try:137+ follow_redirects = (138+ redirect and139+ retries.redirect != 0 and140+ retries.total)141 response = urlfetch.fetch(142 url,143 payload=body,144 method=method,145 headers=headers or {},146 allow_truncated=False,101- follow_redirects=(102- redirect and103- retries.redirect != 0 and104- retries.total),147+ follow_redirects=self.urlfetch_retries and follow_redirects,148 deadline=self._get_absolute_timeout(timeout),149 validate_certificate=self.validate_certificate,150 )151 except urlfetch.DeadlineExceededError as e:23 unmodified lines175 raise AppEnginePlatformError(176 "URLFetch does not support method: %s" % method, e)177 178 http_response = self._urlfetch_response_to_http_response(136- response, **response_kw)179+ response, retries=retries, **response_kw)180 138- # Check for redirect response139- if (http_response.get_redirect_location() and140- retries.raise_on_redirect and redirect):141- raise MaxRetryError(self, url, "too many redirects")181+ # Handle redirect?182+ redirect_location = redirect and http_response.get_redirect_location()183+ if redirect_location:184+ # Check for redirect response185+ if (self.urlfetch_retries and retries.raise_on_redirect):186+ raise MaxRetryError(self, url, "too many redirects")187+ else:188+ if http_response.status == 303:189+ method = 'GET'190 191+ try:192+ retries = retries.increment(method, url, response=http_response, _pool=self)193+ except MaxRetryError:194+ if retries.raise_on_redirect:195+ raise MaxRetryError(self, url, "too many redirects")196+ return http_response197+198+ retries.sleep_for_retry(http_response)199+ log.debug("Redirecting %s -> %s", url, redirect_location)200+ redirect_url = urljoin(url, redirect_location)201+ return self.urlopen(202+ method, redirect_url, body, headers,203+ retries=retries, redirect=redirect,204+ timeout=timeout, **response_kw)205+206 # Check if we should retry the HTTP response.144- if retries.is_forced_retry(method, status_code=http_response.status):207+ has_retry_after = bool(http_response.getheader('Retry-After'))208+ if retries.is_retry(method, http_response.status, has_retry_after):209 retries = retries.increment(210 method, url, response=http_response, _pool=self)147- log.info("Forced retry: %s", url)148- retries.sleep()211+ log.debug("Retry: %s", url)212+ retries.sleep(http_response)213 return self.urlopen(214 method, url,215 body=body, headers=headers,216 retries=retries, redirect=redirect,29 unmodified lines246 )247 248 def _get_absolute_timeout(self, timeout):249 if timeout is Timeout.DEFAULT_TIMEOUT:186- return 5 # 5s is the default timeout for URLFetch.250+ return None # Defer to URLFetch's default.251 if isinstance(timeout, Timeout):188- if timeout._read is not timeout._connect:252+ if timeout._read is not None or timeout._connect is not None:253 warnings.warn(254 "URLFetch does not support granular timeout settings, "191- "reverting to total timeout.", AppEnginePlatformWarning)255+ "reverting to total or default URLFetch timeout.",256+ AppEnginePlatformWarning)257 return timeout.total258 return timeout259 260 def _get_retries(self, retries, redirect):36 unmodified linesmodified:requests/packages/urllib3/contrib/ntlmpool.py+2 added-5 removed
3 unmodified lines4 Issue #10, see: http://code.google.com/p/urllib3/issues/detail?id=105 """6 from __future__ import absolute_import7 8-try:9- from http.client import HTTPSConnection10-except ImportError:11- from httplib import HTTPSConnection8 from logging import getLogger9 from ntlm import ntlm10 15-from urllib3 import HTTPSConnectionPool11+from .. import HTTPSConnectionPool12+from ..packages.six.moves.http_client import HTTPSConnection13 14 15 log = getLogger(__name__)16 96 unmodified linesmodified:requests/packages/urllib3/contrib/pyopenssl.py+182 added-109 removed
1+"""1-'''SSL with SNI_-support for Python 2. Follow these instructions if you would2+SSL with SNI_-support for Python 2. Follow these instructions if you would3 like to verify SSL certificates in Python 2. Note, the default libraries do4 *not* do certificate checking; you need to do additional work to validate5 certificates yourself.6 7 This needs the following packages installed:8 8-* pyOpenSSL (tested with 0.13)9-* ndg-httpsclient (tested with 0.3.2)10-* pyasn1 (tested with 0.1.6)9+* pyOpenSSL (tested with 16.0.0)10+* cryptography (minimum 1.3.4, from pyopenssl)11+* idna (minimum 2.0, from cryptography)12 13+However, pyopenssl depends on cryptography, which depends on idna, so while we14+use all three directly here we end up having relatively few packages required.15+16 You can install them with the following command:17 14- pip install pyopenssl ndg-httpsclient pyasn118+ pip install pyopenssl cryptography idna19 20 To activate certificate checking, call21 :func:`~urllib3.contrib.pyopenssl.inject_into_urllib3` from your Python code22 before you begin making HTTP requests. This can be done in a ``sitecustomize``14 unmodified lines37 38 If you want to configure the default list of supported cipher suites, you can39 set the ``urllib3.contrib.pyopenssl.DEFAULT_SSL_CIPHER_LIST`` variable.40 37-Module Variables38-----------------39-40-:var DEFAULT_SSL_CIPHER_LIST: The list of supported SSL/TLS cipher suites.41-41 .. _sni: https://en.wikipedia.org/wiki/Server_Name_Indication42 .. _crime attack: https://en.wikipedia.org/wiki/CRIME_(security_exploit)44-45-'''43+"""44 from __future__ import absolute_import45 48-try:49- from ndg.httpsclient.ssl_peer_verification import SUBJ_ALT_NAME_SUPPORT50- from ndg.httpsclient.subj_alt_name import SubjectAltName as BaseSubjectAltName51-except SyntaxError as e:52- raise ImportError(e)53-46+import idna47 import OpenSSL.SSL55-from pyasn1.codec.der import decoder as der_decoder56-from pyasn1.type import univ, constraint48+from cryptography import x50949+from cryptography.hazmat.backends.openssl import backend as openssl_backend50+from cryptography.hazmat.backends.openssl.x509 import _Certificate51+52 from socket import timeout, error as SocketError53+from io import BytesIO54 55 try: # Platform-specific: Python 256 from socket import _fileobject57 except ImportError: # Platform-specific: Python 358 _fileobject = None63- from urllib3.packages.backports.makefile import backport_makefile59+ from ..packages.backports.makefile import backport_makefile60 61+import logging62 import ssl63 import select64 import six65+import sys66 69-from .. import connection67 from .. import util68 69 __all__ = ['inject_into_urllib3', 'extract_from_urllib3']70 74-# SNI only *really* works if we can read the subjectAltName of certificates.75-HAS_SNI = SUBJ_ALT_NAME_SUPPORT71+# SNI always works.72+HAS_SNI = True73 74 # Map from urllib3 to PyOpenSSL compatible parameter-values.75 _openssl_versions = {76 ssl.PROTOCOL_SSLv23: OpenSSL.SSL.SSLv23_METHOD,10 unmodified lines87 _openssl_versions.update({ssl.PROTOCOL_SSLv3: OpenSSL.SSL.SSLv3_METHOD})88 except AttributeError:89 pass90 94-_openssl_verify = {91+_stdlib_to_openssl_verify = {92 ssl.CERT_NONE: OpenSSL.SSL.VERIFY_NONE,93 ssl.CERT_OPTIONAL: OpenSSL.SSL.VERIFY_PEER,94 ssl.CERT_REQUIRED:95 OpenSSL.SSL.VERIFY_PEER + OpenSSL.SSL.VERIFY_FAIL_IF_NO_PEER_CERT,96 }97+_openssl_to_stdlib_verify = dict(98+ (v, k) for k, v in _stdlib_to_openssl_verify.items()99+)100 101-DEFAULT_SSL_CIPHER_LIST = util.ssl_.DEFAULT_CIPHERS.encode('ascii')102-101 # OpenSSL will only write 16K at a time102 SSL_WRITE_BLOCKSIZE = 16384103 104 orig_util_HAS_SNI = util.HAS_SNI107-orig_connection_ssl_wrap_socket = connection.ssl_wrap_socket105+orig_util_SSLContext = util.ssl_.SSLContext106 107 108+log = logging.getLogger(__name__)109+110+111 def inject_into_urllib3():112 'Monkey-patch urllib3 with PyOpenSSL-backed SSL-support.'113 113- connection.ssl_wrap_socket = ssl_wrap_socket114+ util.ssl_.SSLContext = PyOpenSSLContext115 util.HAS_SNI = HAS_SNI116+ util.ssl_.HAS_SNI = HAS_SNI117 util.IS_PYOPENSSL = True118+ util.ssl_.IS_PYOPENSSL = True119 120 121 def extract_from_urllib3():122 'Undo monkey-patching by :func:`inject_into_urllib3`.'123 121- connection.ssl_wrap_socket = orig_connection_ssl_wrap_socket124+ util.ssl_.SSLContext = orig_util_SSLContext125 util.HAS_SNI = orig_util_HAS_SNI126+ util.ssl_.HAS_SNI = orig_util_HAS_SNI127 util.IS_PYOPENSSL = False128+ util.ssl_.IS_PYOPENSSL = False129 130 126-# Note: This is a slightly bug-fixed version of same from ndg-httpsclient.127-class SubjectAltName(BaseSubjectAltName):128- '''ASN.1 implementation for subjectAltNames support'''131+def _dnsname_to_stdlib(name):132+ """133+ Converts a dNSName SubjectAlternativeName field to the form used by the134+ standard library on the given Python version.135 130- # There is no limit to how many SAN certificates a certificate may have,131- # however this needs to have some limit so we'll set an arbitrarily high132- # limit.133- sizeSpec = univ.SequenceOf.sizeSpec + \134- constraint.ValueSizeConstraint(1, 1024)136+ Cryptography produces a dNSName as a unicode string that was idna-decoded137+ from ASCII bytes. We need to idna-encode that string to get it back, and138+ then on Python 3 we also need to convert to unicode via UTF-8 (the stdlib139+ uses PyUnicode_FromStringAndSize on it, which decodes via UTF-8).140+ """141+ def idna_encode(name):142+ """143+ Borrowed wholesale from the Python Cryptography Project. It turns out144+ that we can't just safely call `idna.encode`: it can explode for145+ wildcard names. This avoids that problem.146+ """147+ for prefix in [u'*.', u'.']:148+ if name.startswith(prefix):149+ name = name[len(prefix):]150+ return prefix.encode('ascii') + idna.encode(name)151+ return idna.encode(name)152 153+ name = idna_encode(name)154+ if sys.version_info >= (3, 0):155+ name = name.decode('utf-8')156+ return name157 137-# Note: This is a slightly bug-fixed version of same from ndg-httpsclient.158+159 def get_subj_alt_name(peer_cert):139- # Search through extensions140- dns_name = []141- if not SUBJ_ALT_NAME_SUPPORT:142- return dns_name160+ """161+ Given an PyOpenSSL certificate, provides all the subject alternative names.162+ """163+ # Pass the cert to cryptography, which has much better APIs for this.164+ # This is technically using private APIs, but should work across all165+ # relevant versions until PyOpenSSL gets something proper for this.166+ cert = _Certificate(openssl_backend, peer_cert._x509)167 144- general_names = SubjectAltName()145- for i in range(peer_cert.get_extension_count()):146- ext = peer_cert.get_extension(i)147- ext_name = ext.get_short_name()148- if ext_name != b'subjectAltName':149- continue168+ # We want to find the SAN extension. Ask Cryptography to locate it (it's169+ # faster than looping in Python)170+ try:171+ ext = cert.extensions.get_extension_for_class(172+ x509.SubjectAlternativeName173+ ).value174+ except x509.ExtensionNotFound:175+ # No such extension, return the empty list.176+ return []177+ except (x509.DuplicateExtension, x509.UnsupportedExtension,178+ x509.UnsupportedGeneralNameType, UnicodeError) as e:179+ # A problem has been found with the quality of the certificate. Assume180+ # no SAN field is present.181+ log.warning(182+ "A problem was encountered with the certificate that prevented "183+ "urllib3 from finding the SubjectAlternativeName field. This can "184+ "affect certificate validation. The error was %s",185+ e,186+ )187+ return []188 151- # PyOpenSSL returns extension data in ASN.1 encoded form152- ext_dat = ext.get_data()153- decoded_dat = der_decoder.decode(ext_dat,154- asn1Spec=general_names)189+ # We want to return dNSName and iPAddress fields. We need to cast the IPs190+ # back to strings because the match_hostname function wants them as191+ # strings.192+ # Sadly the DNS names need to be idna encoded and then, on Python 3, UTF-8193+ # decoded. This is pretty frustrating, but that's what the standard library194+ # does with certificates, and so we need to attempt to do the same.195+ names = [196+ ('DNS', _dnsname_to_stdlib(name))197+ for name in ext.get_values_for_type(x509.DNSName)198+ ]199+ names.extend(200+ ('IP Address', str(name))201+ for name in ext.get_values_for_type(x509.IPAddress)202+ )203 156- for name in decoded_dat:157- if not isinstance(name, SubjectAltName):158- continue159- for entry in range(len(name)):160- component = name.getComponentByPosition(entry)161- if component.getName() != 'dNSName':162- continue163- dns_name.append(str(component.getComponent()))204+ return names205 165- return dns_name206 167-207 class WrappedSocket(object):208 '''API-compatibility wrapper for Python OpenSSL's Connection-class.209 210 Note: _makefile_refs, _drop() and _reuse() are needed for the garbage109 unmodified lines320 return {321 'subject': (322 (('commonName', x509.get_subject().CN),),323 ),285- 'subjectAltName': [286- ('DNS', value)287- for value in get_subj_alt_name(x509)288- ]324+ 'subjectAltName': get_subj_alt_name(x509)325 }326 327 def _reuse(self):328 self._makefile_refs += 114 unmodified lines343 344 WrappedSocket.makefile = makefile345 346 311-def _verify_callback(cnx, x509, err_no, err_depth, return_code):312- return err_no == 0347+class PyOpenSSLContext(object):348+ """349+ I am a wrapper class for the PyOpenSSL ``Context`` object. I am responsible350+ for translating the interface of the standard library ``SSLContext`` object351+ to calls into PyOpenSSL.352+ """353+ def __init__(self, protocol):354+ self.protocol = _openssl_versions[protocol]355+ self._ctx = OpenSSL.SSL.Context(self.protocol)356+ self._options = 0357+ self.check_hostname = False358 359+ @property360+ def options(self):361+ return self._options362 315-def ssl_wrap_socket(sock, keyfile=None, certfile=None, cert_reqs=None,316- ca_certs=None, server_hostname=None,317- ssl_version=None, ca_cert_dir=None):318- ctx = OpenSSL.SSL.Context(_openssl_versions[ssl_version])319- if certfile:320- keyfile = keyfile or certfile # Match behaviour of the normal python ssl library321- ctx.use_certificate_file(certfile)322- if keyfile:323- ctx.use_privatekey_file(keyfile)324- if cert_reqs != ssl.CERT_NONE:325- ctx.set_verify(_openssl_verify[cert_reqs], _verify_callback)326- if ca_certs or ca_cert_dir:327- try:328- ctx.load_verify_locations(ca_certs, ca_cert_dir)329- except OpenSSL.SSL.Error as e:330- raise ssl.SSLError('bad ca_certs: %r' % ca_certs, e)331- else:332- ctx.set_default_verify_paths()363+ @options.setter364+ def options(self, value):365+ self._options = value366+ self._ctx.set_options(value)367 334- # Disable TLS compression to mitigate CRIME attack (issue #309)335- OP_NO_COMPRESSION = 0x20000336- ctx.set_options(OP_NO_COMPRESSION)368+ @property369+ def verify_mode(self):370+ return _openssl_to_stdlib_verify[self._ctx.get_verify_mode()]371 338- # Set list of supported ciphersuites.339- ctx.set_cipher_list(DEFAULT_SSL_CIPHER_LIST)372+ @verify_mode.setter373+ def verify_mode(self, value):374+ self._ctx.set_verify(375+ _stdlib_to_openssl_verify[value],376+ _verify_callback377+ )378 341- cnx = OpenSSL.SSL.Connection(ctx, sock)342- if isinstance(server_hostname, six.text_type): # Platform-specific: Python 3343- server_hostname = server_hostname.encode('utf-8')344- cnx.set_tlsext_host_name(server_hostname)345- cnx.set_connect_state()346- while True:347- try:348- cnx.do_handshake()349- except OpenSSL.SSL.WantReadError:350- rd, _, _ = select.select([sock], [], [], sock.gettimeout())351- if not rd:352- raise timeout('select timed out')353- continue354- except OpenSSL.SSL.Error as e:355- raise ssl.SSLError('bad handshake: %r' % e)356- break379+ def set_default_verify_paths(self):380+ self._ctx.set_default_verify_paths()381 382+ def set_ciphers(self, ciphers):383+ if isinstance(ciphers, six.text_type):384+ ciphers = ciphers.encode('utf-8')385+ self._ctx.set_cipher_list(ciphers)386+387+ def load_verify_locations(self, cafile=None, capath=None, cadata=None):388+ if cafile is not None:389+ cafile = cafile.encode('utf-8')390+ if capath is not None:391+ capath = capath.encode('utf-8')392+ self._ctx.load_verify_locations(cafile, capath)393+ if cadata is not None:394+ self._ctx.load_verify_locations(BytesIO(cadata))395+396+ def load_cert_chain(self, certfile, keyfile=None, password=None):397+ self._ctx.use_certificate_file(certfile)398+ if password is not None:399+ self._ctx.set_passwd_cb(lambda max_length, prompt_twice, userdata: password)400+ self._ctx.use_privatekey_file(keyfile or certfile)401+402+ def wrap_socket(self, sock, server_side=False,403+ do_handshake_on_connect=True, suppress_ragged_eofs=True,404+ server_hostname=None):405+ cnx = OpenSSL.SSL.Connection(self._ctx, sock)406+407+ if isinstance(server_hostname, six.text_type): # Platform-specific: Python 3408+ server_hostname = server_hostname.encode('utf-8')409+410+ if server_hostname is not None:411+ cnx.set_tlsext_host_name(server_hostname)412+413+ cnx.set_connect_state()414+415+ while True:416+ try:417+ cnx.do_handshake()418+ except OpenSSL.SSL.WantReadError:419+ rd, _, _ = select.select([sock], [], [], sock.gettimeout())420+ if not rd:421+ raise timeout('select timed out')422+ continue423+ except OpenSSL.SSL.Error as e:424+ raise ssl.SSLError('bad handshake: %r' % e)425+ break426+358- return WrappedSocket(cnx, sock)427+ return WrappedSocket(cnx, sock)428+429+430+def _verify_callback(cnx, x509, err_no, err_depth, return_code):431+ return err_no == 0modified:requests/packages/urllib3/contrib/socks.py+11 added-5 removed
1 # -*- coding: utf-8 -*-2 """3-SOCKS support for urllib34-~~~~~~~~~~~~~~~~~~~~~~~~~5-6-This contrib module contains provisional support for SOCKS proxies from within3+This module contains provisional support for SOCKS proxies from within4 urllib3. This module supports SOCKS4 (specifically the SOCKS4A variant) and5 SOCKS5. To enable its functionality, either install PySocks or install this6 module with the ``socks`` extra.7 8+The SOCKS implementation supports the full range of urllib3 features. It also9+supports the following SOCKS features:10+11+- SOCKS412+- SOCKS4a13+- SOCKS514+- Usernames and passwords for the SOCKS proxy15+16 Known Limitations:17 18 - Currently PySocks does not support contacting remote websites via literal14- IPv6 addresses. Any such connection attempt will fail.19+ IPv6 addresses. Any such connection attempt will fail. You must use a domain20+ name.21 - Currently PySocks does not support IPv6 connections to the SOCKS proxy. Any22 such connection attempt will fail.23 """24 from __future__ import absolute_import154 unmodified linesmodified:requests/packages/urllib3/packages/ssl_match_hostname/__init__.py+7 added-1 removed
1+import sys2+3 try:2- # Python 3.2+4+ # Our match_hostname function is the same as 3.5's, so we only want to5+ # import the match_hostname function if it's at least that good.6+ if sys.version_info < (3, 5):7+ raise ImportError("Fallback to vendored code")8+9 from ssl import CertificateError, match_hostname10 except ImportError:11 try:12 # Backport of the function from a pypi module7 unmodified linesmodified:requests/packages/urllib3/packages/ssl_match_hostname/_implementation.py+55 added-3 removed
2 unmodified lines3 # Note: This file is under the PSF license as the code comes from the python4 # stdlib. http://docs.python.org/3/license.html5 6 import re7+import sys8 8-__version__ = '3.4.0.2'9+# ipaddress has been backported to 2.6+ in pypi. If it is installed on the10+# system, use it to handle IPAddress ServerAltnames (this was added in11+# python-3.5) otherwise only do DNS matching. This allows12+# backports.ssl_match_hostname to continue to be used all the way back to13+# python-2.4.14+try:15+ import ipaddress16+except ImportError:17+ ipaddress = None18 19+__version__ = '3.5.0.1'20+21+22 class CertificateError(ValueError):23 pass24 25 49 unmodified lines75 pat = re.compile(r'\A' + r'\.'.join(pats) + r'\Z', re.IGNORECASE)76 return pat.match(hostname)77 78 79+def _to_unicode(obj):80+ if isinstance(obj, str) and sys.version_info < (3,):81+ obj = unicode(obj, encoding='ascii', errors='strict')82+ return obj83+84+def _ipaddress_match(ipname, host_ip):85+ """Exact matching of IP addresses.86+87+ RFC 6125 explicitly doesn't define an algorithm for this88+ (section 1.7.2 - "Out of Scope").89+ """90+ # OpenSSL may add a trailing newline to a subjectAltName's IP address91+ # Divergence from upstream: ipaddress can't handle byte str92+ ip = ipaddress.ip_address(_to_unicode(ipname).rstrip())93+ return ip == host_ip94+95+96 def match_hostname(cert, hostname):97 """Verify that *cert* (in decoded format as returned by98 SSLSocket.getpeercert()) matches the *hostname*. RFC 2818 and RFC 612599 rules are followed, but IP addresses are not accepted for *hostname*.1 unmodified line101 CertificateError is raised on failure. On success, the function102 returns nothing.103 """104 if not cert:76- raise ValueError("empty or no certificate")105+ raise ValueError("empty or no certificate, match_hostname needs a "106+ "SSL socket or SSL context with either "107+ "CERT_OPTIONAL or CERT_REQUIRED")108+ try:109+ # Divergence from upstream: ipaddress can't handle byte str110+ host_ip = ipaddress.ip_address(_to_unicode(hostname))111+ except ValueError:112+ # Not an IP address (common case)113+ host_ip = None114+ except UnicodeError:115+ # Divergence from upstream: Have to deal with ipaddress not taking116+ # byte strings. addresses should be all ascii, so we consider it not117+ # an ipaddress in this case118+ host_ip = None119+ except AttributeError:120+ # Divergence from upstream: Make ipaddress library optional121+ if ipaddress is None:122+ host_ip = None123+ else:124+ raise125 dnsnames = []126 san = cert.get('subjectAltName', ())127 for key, value in san:128 if key == 'DNS':81- if _dnsname_match(value, hostname):129+ if host_ip is None and _dnsname_match(value, hostname):130 return131 dnsnames.append(value)132+ elif key == 'IP Address':133+ if host_ip is not None and _ipaddress_match(value, host_ip):134+ return135+ dnsnames.append(value)136 if not dnsnames:137 # The subject is only checked when there is no dNSName entry138 # in subjectAltName139 for sub in cert.get('subject', ()):18 unmodified linesdeleted:requests/packages/urllib3/packages/ssl_match_hostname/.gitignore-1 removed
1-envmodified:requests/packages/urllib3/util/response.py+7 added
11 unmodified lines12 The file-like object to check.13 """14 15 try:16+ # Check `isclosed()` first, in case Python3 doesn't set `closed`.17+ # GH Issue #92818+ return obj.isclosed()19+ except AttributeError:20+ pass21+22+ try:23 # Check via the official file-like-object way.24 return obj.closed25 except AttributeError:26 pass55 unmodified linesmodified:requests/packages/urllib3/util/retry.py+93 added-17 removed
1 from __future__ import absolute_import2 import time3 import logging4+from collections import namedtuple5+from itertools import takewhile6+import email7+import re8 9 from ..exceptions import (10 ConnectTimeoutError,11 MaxRetryError,12 ProtocolError,13 ReadTimeoutError,14 ResponseError,15+ InvalidHeader,16 )17 from ..packages import six18 19 20 log = logging.getLogger(__name__)21 22+# Data structure for representing the metadata of requests that result in a retry.23+RequestHistory = namedtuple('RequestHistory', ["method", "url", "error",24+ "status", "redirect_location"])25 26+27 class Retry(object):28 """ Retry configuration.29 30 Each retry attempt will create a new Retry object with updated values, so90 unmodified lines121 :param bool raise_on_status: Similar meaning to ``raise_on_redirect``:122 whether we should raise an exception, or return a response,123 if status falls in ``status_forcelist`` range and retries have124 been exhausted.125+126+ :param tuple history: The history of the request encountered during127+ each call to :meth:`~Retry.increment`. The list is in the order128+ the requests occurred. Each list item is of class :class:`RequestHistory`.129+130+ :param bool respect_retry_after_header:131+ Whether to respect Retry-After header on status codes defined as132+ :attr:`Retry.RETRY_AFTER_STATUS_CODES` or not.133+134 """135 136 DEFAULT_METHOD_WHITELIST = frozenset([137 'HEAD', 'GET', 'PUT', 'DELETE', 'OPTIONS', 'TRACE'])138 139+ RETRY_AFTER_STATUS_CODES = frozenset([413, 429, 503])140+141 #: Maximum backoff time.142 BACKOFF_MAX = 120143 144 def __init__(self, total=10, connect=None, read=None, redirect=None,145 method_whitelist=DEFAULT_METHOD_WHITELIST, status_forcelist=None,146 backoff_factor=0, raise_on_redirect=True, raise_on_status=True,127- _observed_errors=0):147+ history=None, respect_retry_after_header=True):148 149 self.total = total150 self.connect = connect151 self.read = read7 unmodified lines159 self.method_whitelist = method_whitelist160 self.backoff_factor = backoff_factor161 self.raise_on_redirect = raise_on_redirect162 self.raise_on_status = raise_on_status143- self._observed_errors = _observed_errors # TODO: use .history instead?163+ self.history = history or tuple()164+ self.respect_retry_after_header = respect_retry_after_header165 166 def new(self, **kw):167 params = dict(168 total=self.total,2 unmodified lines171 status_forcelist=self.status_forcelist,172 backoff_factor=self.backoff_factor,173 raise_on_redirect=self.raise_on_redirect,174 raise_on_status=self.raise_on_status,154- _observed_errors=self._observed_errors,175+ history=self.history,176 )177 params.update(kw)178 return type(self)(**params)179 15 unmodified lines195 """ Formula for computing the current backoff196 197 :rtype: float198 """178- if self._observed_errors <= 1:199+ # We want to consider only the last consecutive errors sequence (Ignore redirects).200+ consecutive_errors_len = len(list(takewhile(lambda x: x.redirect_location is None,201+ reversed(self.history))))202+ if consecutive_errors_len <= 1:203 return 0204 181- backoff_value = self.backoff_factor * (2 ** (self._observed_errors - 1))205+ backoff_value = self.backoff_factor * (2 ** (consecutive_errors_len - 1))206 return min(self.BACKOFF_MAX, backoff_value)207 184- def sleep(self):185- """ Sleep between retry attempts using an exponential backoff.208+ def parse_retry_after(self, retry_after):209+ # Whitespace: https://tools.ietf.org/html/rfc7230#section-3.2.4210+ if re.match(r"^\s*[0-9]+\s*$", retry_after):211+ seconds = int(retry_after)212+ else:213+ retry_date_tuple = email.utils.parsedate(retry_after)214+ if retry_date_tuple is None:215+ raise InvalidHeader("Invalid Retry-After header: %s" % retry_after)216+ retry_date = time.mktime(retry_date_tuple)217+ seconds = retry_date - time.time()218 187- By default, the backoff factor is 0 and this method will return188- immediately.189- """219+ if seconds < 0:220+ seconds = 0221+222+ return seconds223+224+ def get_retry_after(self, response):225+ """ Get the value of Retry-After in seconds. """226+227+ retry_after = response.getheader("Retry-After")228+229+ if retry_after is None:230+ return None231+232+ return self.parse_retry_after(retry_after)233+234+ def sleep_for_retry(self, response=None):235+ retry_after = self.get_retry_after(response)236+ if retry_after:237+ time.sleep(retry_after)238+ return True239+240+ return False241+242+ def _sleep_backoff(self):243 backoff = self.get_backoff_time()244 if backoff <= 0:245 return246 time.sleep(backoff)247 248+ def sleep(self, response=None):249+ """ Sleep between retry attempts.250+251+ This method will respect a server's ``Retry-After`` response header252+ and sleep the duration of the time requested. If that is not present, it253+ will use an exponential backoff. By default, the backoff factor is 0 and254+ this method will return immediately.255+ """256+257+ if response:258+ slept = self.sleep_for_retry(response)259+ if slept:260+ return261+262+ self._sleep_backoff()263+264 def _is_connection_error(self, err):265 """ Errors when we're fairly sure that the server did not receive the266 request, so it should be safe to retry.267 """4 unmodified lines272 assume that the server began processing it.273 """274 return isinstance(err, (ReadTimeoutError, ProtocolError))275 207- def is_forced_retry(self, method, status_code):276+ def is_retry(self, method, status_code, has_retry_after=False):277 """ Is this method/status code retryable? (Based on method/codes whitelists)278 """279 if self.method_whitelist and method.upper() not in self.method_whitelist:280 return False281 213- return self.status_forcelist and status_code in self.status_forcelist282+ if self.status_forcelist and status_code in self.status_forcelist:283+ return True284 285+ return (self.total and self.respect_retry_after_header and286+ has_retry_after and (status_code in self.RETRY_AFTER_STATUS_CODES))287+288 def is_exhausted(self):289 """ Are we out of retries? """290 retry_counts = (self.total, self.connect, self.read, self.redirect)291 retry_counts = list(filter(None, retry_counts))21 unmodified lines313 total = self.total314 if total is not None:315 total -= 1316 244- _observed_errors = self._observed_errors317 connect = self.connect318 read = self.read319 redirect = self.redirect320 cause = 'unknown'321+ status = None322+ redirect_location = None323 324 if error and self._is_connection_error(error):325 # Connect retry?326 if connect is False:327 raise six.reraise(type(error), error, _stacktrace)328 elif connect is not None:329 connect -= 1256- _observed_errors += 1330 331 elif error and self._is_read_error(error):332 # Read retry?333 if read is False:334 raise six.reraise(type(error), error, _stacktrace)335 elif read is not None:336 read -= 1264- _observed_errors += 1337 338 elif response and response.get_redirect_location():339 # Redirect retry?340 if redirect is not None:341 redirect -= 1342 cause = 'too many redirects'343+ redirect_location = response.get_redirect_location()344+ status = response.status345 346 else:347 # Incrementing because of a server error like a 500 in348 # status_forcelist and a the given method is in the whitelist275- _observed_errors += 1349 cause = ResponseError.GENERIC_ERROR350 if response and response.status:351 cause = ResponseError.SPECIFIC_ERROR.format(352 status_code=response.status)353+ status = response.status354 355+ history = self.history + (RequestHistory(method, url, error, status, redirect_location),)356+357 new_retry = self.new(358 total=total,359 connect=connect, read=read, redirect=redirect,284- _observed_errors=_observed_errors)360+ history=history)361 362 if new_retry.is_exhausted():363 raise MaxRetryError(_pool, url, error or ResponseError(cause))364 12 unmodified linesmodified:requests/packages/urllib3/util/ssl_.py+28 added-12 removed
9 unmodified lines10 11 12 SSLContext = None13 HAS_SNI = False14-create_default_context = None14 IS_PYOPENSSL = False15 16 # Maps the length of a digest to a possible hash function producing this digest17 HASHFUNC_MAP = {43 unmodified lines61 #62 # The general intent is:63 # - Prefer cipher suites that offer perfect forward secrecy (DHE/ECDHE),64 # - prefer ECDHE over DHE for better performance,66-# - prefer any AES-GCM over any AES-CBC for better performance and security,67-# - use 3DES as fallback which is secure but slow,65+# - prefer any AES-GCM and ChaCha20 over any AES-CBC for better performance and66+# security,67+# - prefer AES-GCM over ChaCha20 because hardware-accelerated AES is common,68 # - disable NULL authentication, MD5 MACs and DSS for security reasons.69-DEFAULT_CIPHERS = (70- 'ECDH+AESGCM:DH+AESGCM:ECDH+AES256:DH+AES256:ECDH+AES128:DH+AES:ECDH+HIGH:'71- 'DH+HIGH:ECDH+3DES:DH+3DES:RSA+AESGCM:RSA+AES:RSA+HIGH:RSA+3DES:!aNULL:'72- '!eNULL:!MD5'73-)69+DEFAULT_CIPHERS = ':'.join([70+ 'ECDH+AESGCM',71+ 'ECDH+CHACHA20',72+ 'DH+AESGCM',73+ 'DH+CHACHA20',74+ 'ECDH+AES256',75+ 'DH+AES256',76+ 'ECDH+AES128',77+ 'DH+AES',78+ 'RSA+AESGCM',79+ 'RSA+AES',80+ '!aNULL',81+ '!eNULL',82+ '!MD5',83+])84 85 try:86 from ssl import SSLContext # Modern SSL?87 except ImportError:38 unmodified lines126 'A true SSLContext object is not available. This prevents '127 'urllib3 from configuring SSL appropriately and may cause '128 'certain SSL connections to fail. You can upgrade to a newer '129 'version of Python to solve this. For more information, see '120- 'https://urllib3.readthedocs.io/en/latest/security.html'121- '#insecureplatformwarning.',130+ 'https://urllib3.readthedocs.io/en/latest/advanced-usage.html'131+ '#ssl-warnings',132 InsecurePlatformWarning133 )134 kwargs = {135 'keyfile': self.keyfile,160 unmodified lines296 SSLContext.load_verify_locations().297 """298 context = ssl_context299 if context is None:300+ # Note: This branch of code and all the variables in it are no longer301+ # used by urllib3 itself. We should consider deprecating and removing302+ # this code.303 context = create_urllib3_context(ssl_version, cert_reqs,304 ciphers=ciphers)305 306 if ca_certs or ca_cert_dir:6 unmodified lines313 except OSError as e: # Platform-specific: Python 3.3 and beyond314 if e.errno == errno.ENOENT:315 raise SSLError(e)316 raise317+ elif getattr(context, 'load_default_certs', None) is not None:318+ # try to load OS default certs; works well on Windows (require Python3.4+)319+ context.load_default_certs()320 321 if certfile:322 context.load_cert_chain(certfile, keyfile)323 if HAS_SNI: # Platform-specific: OpenSSL with enabled SNI4 unmodified lines328 'Indication) extension to TLS is not available on this platform. '329 'This may cause the server to present an incorrect TLS '330 'certificate, which can cause validation failures. You can upgrade to '331 'a newer version of Python to solve this. For more information, see '316- 'https://urllib3.readthedocs.io/en/latest/security.html'317- '#snimissingwarning.',332+ 'https://urllib3.readthedocs.io/en/latest/advanced-usage.html'333+ '#ssl-warnings',334 SNIMissingWarning335 )336 return context.wrap_socket(sock)modified:requests/packages/urllib3/util/timeout.py+9 added-6 removed
109 unmodified lines110 :param value: The timeout value to validate111 :param name: The name of the timeout attribute to validate. This is112 used to specify in error messages.113 :return: The validated and casted version of the given value.114- :raises ValueError: If the type is not an integer or a float, or if it115- is a numeric value less than zero.114+ :raises ValueError: If it is a numeric value less than or equal to115+ zero, or the type is not an integer, float, or None.116 """117 if value is _Default:118 return cls.DEFAULT_TIMEOUT119 120 if value is None or value is cls.DEFAULT_TIMEOUT:121 return value122 123+ if isinstance(value, bool):124+ raise ValueError("Timeout cannot be a boolean value. It must "125+ "be an int, float or None.")126 try:127 float(value)128 except (TypeError, ValueError):129 raise ValueError("Timeout value %s was %s, but it must be an "127- "int or float." % (name, value))130+ "int, float or None." % (name, value))131 132 try:130- if value < 0:133+ if value <= 0:134 raise ValueError("Attempted to set %s timeout to %s, but the "135 "timeout cannot be set to a value less "133- "than 0." % (name, value))136+ "than or equal to 0." % (name, value))137 except TypeError: # Python 3138 raise ValueError("Timeout value %s was %s, but it must be an "136- "int or float." % (name, value))139+ "int, float or None." % (name, value))140 141 return value142 143 @classmethod102 unmodified linesmodified:requests/packages/urllib3/util/url.py+14 added-5 removed
8 unmodified lines9 10 class Url(namedtuple('Url', url_attrs)):11 """12 Datastructure for representing an HTTP URL. Used as a return value for13- :func:`parse_url`.13+ :func:`parse_url`. Both the scheme and host are normalized as they are14+ both case-insensitive according to RFC 3986.15 """15- slots = ()16+ __slots__ = ()17 18 def __new__(cls, scheme=None, auth=None, host=None, port=None, path=None,19 query=None, fragment=None):20 if path and not path.startswith('/'):21 path = '/' + path22+ if scheme:23+ scheme = scheme.lower()24+ if host:25+ host = host.lower()26 return super(Url, cls).__new__(cls, scheme, auth, host, port, path,27 query, fragment)28 29 @property158 unmodified lines188 if not host:189 host = _host190 191 if port:187- # If given, ports must be integers.192+ # If given, ports must be integers. No whitespace, no plus or193+ # minus prefixes, no non-integer digits such as ^2 (superscript).194 if not port.isdigit():195 raise LocationParseError(url)196+ try:190- port = int(port)197+ port = int(port)198+ except ValueError:199+ raise LocationParseError(url)200 else:201 # Blank ports are cool, too. (rfc3986#section-3.2.3)202 port = None203 15 unmodified lines219 220 221 def get_host(url):222 """214- Deprecated. Use :func:`.parse_url` instead.223+ Deprecated. Use :func:`parse_url` instead.224 """225 p = parse_url(url)226 return p.scheme or 'http', p.hostname, p.portmodified:requests/packages/urllib3/__init__.py+1 added-1 removed
30 unmodified lines31 pass32 33 __author__ = 'Andrey Petrov (andrey.petrov@shazow.net)'34 __license__ = 'MIT'35-__version__ = '1.16'35+__version__ = '1.19'36 37 __all__ = (38 'HTTPConnectionPool',39 'HTTPSConnectionPool',57 unmodified linesmodified:requests/packages/urllib3/connection.py+62 added-26 removed
5 unmodified lines6 import socket7 from socket import error as SocketError, timeout as SocketTimeout8 import warnings9 from .packages import six10+from .packages.six.moves.http_client import HTTPConnection as _HTTPConnection11+from .packages.six.moves.http_client import HTTPException # noqa: F40112 11-try: # Python 312- from http.client import HTTPConnection as _HTTPConnection13- from http.client import HTTPException # noqa: unused in this module14-except ImportError:15- from httplib import HTTPConnection as _HTTPConnection16- from httplib import HTTPException # noqa: unused in this module17-13 try: # Compiled with SSL?14 import ssl15 BaseSSLError = ssl.SSLError16 except (ImportError, AttributeError): # Platform-specific: No SSL.21 unmodified lines38 39 from .util.ssl_ import (40 resolve_cert_reqs,41 resolve_ssl_version,47- ssl_wrap_socket,42 assert_fingerprint,43+ create_urllib3_context,44+ ssl_wrap_socket45 )46 47 48 from .util import connection120 unmodified lines169 body with chunked encoding and not as one block170 """171 headers = HTTPHeaderDict(headers if headers is not None else {})172 skip_accept_encoding = 'accept-encoding' in headers177- self.putrequest(method, url, skip_accept_encoding=skip_accept_encoding)173+ skip_host = 'host' in headers174+ self.putrequest(175+ method,176+ url,177+ skip_accept_encoding=skip_accept_encoding,178+ skip_host=skip_host179+ )180 for header, value in headers.items():181 self.putheader(header, value)182 if 'transfer-encoding' not in headers:183 self.putheader('Transfer-Encoding', 'chunked')20 unmodified lines204 205 class HTTPSConnection(HTTPConnection):206 default_port = port_by_scheme['https']207 208+ ssl_version = None209+210 def __init__(self, host, port=None, key_file=None, cert_file=None,207- strict=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT, **kw):211+ strict=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT,212+ ssl_context=None, **kw):213 214 HTTPConnection.__init__(self, host, port, strict=strict,215 timeout=timeout, **kw)216 217 self.key_file = key_file218 self.cert_file = cert_file219+ self.ssl_context = ssl_context220 221 # Required property for Google AppEngine 1.9.0 which otherwise causes222 # HTTPS requests to go out as HTTP. (See Issue #356)223 self._protocol = 'https'224 225 def connect(self):226 conn = self._new_conn()227 self._prepare_conn(conn)222- self.sock = ssl.wrap_socket(conn, self.key_file, self.cert_file)228 229+ if self.ssl_context is None:230+ self.ssl_context = create_urllib3_context(231+ ssl_version=resolve_ssl_version(None),232+ cert_reqs=resolve_cert_reqs(None),233+ )234 235+ self.sock = ssl_wrap_socket(236+ sock=conn,237+ keyfile=self.key_file,238+ certfile=self.cert_file,239+ ssl_context=self.ssl_context,240+ )241+242+243 class VerifiedHTTPSConnection(HTTPSConnection):244 """245 Based on httplib.HTTPSConnection but wraps the socket with246 SSL certification.7 unmodified lines254 def set_cert(self, key_file=None, cert_file=None,255 cert_reqs=None, ca_certs=None,256 assert_hostname=None, assert_fingerprint=None,257 ca_cert_dir=None):258+ """259+ This method should only be called once, before the connection is used.260+ """261+ # If cert_reqs is not provided, we can try to guess. If the user gave262+ # us a cert database, we assume they want to use it: otherwise, if263+ # they gave us an SSL Context object we should use whatever is set for264+ # it.265+ if cert_reqs is None:266+ if ca_certs or ca_cert_dir:267+ cert_reqs = 'CERT_REQUIRED'268+ elif self.ssl_context is not None:269+ cert_reqs = self.ssl_context.verify_mode270 241- if (ca_certs or ca_cert_dir) and cert_reqs is None:242- cert_reqs = 'CERT_REQUIRED'243-271 self.key_file = key_file272 self.cert_file = cert_file273 self.cert_reqs = cert_reqs274 self.assert_hostname = assert_hostname4 unmodified lines279 def connect(self):280 # Add certificate verification281 conn = self._new_conn()282 256- resolved_cert_reqs = resolve_cert_reqs(self.cert_reqs)257- resolved_ssl_version = resolve_ssl_version(self.ssl_version)258-283 hostname = self.host284 if getattr(self, '_tunnel_host', None):285 # _tunnel_host was added in Python 2.6.3286 # (See: http://hg.python.org/cpython/rev/0f57b30a152f)17 unmodified lines304 )305 306 # Wrap socket using verification with the root certs in307 # trusted_root_certs284- self.sock = ssl_wrap_socket(conn, self.key_file, self.cert_file,285- cert_reqs=resolved_cert_reqs,286- ca_certs=self.ca_certs,287- ca_cert_dir=self.ca_cert_dir,288- server_hostname=hostname,289- ssl_version=resolved_ssl_version)308+ if self.ssl_context is None:309+ self.ssl_context = create_urllib3_context(310+ ssl_version=resolve_ssl_version(self.ssl_version),311+ cert_reqs=resolve_cert_reqs(self.cert_reqs),312+ )313 314+ context = self.ssl_context315+ context.verify_mode = resolve_cert_reqs(self.cert_reqs)316+ self.sock = ssl_wrap_socket(317+ sock=conn,318+ keyfile=self.key_file,319+ certfile=self.cert_file,320+ ca_certs=self.ca_certs,321+ ca_cert_dir=self.ca_cert_dir,322+ server_hostname=hostname,323+ ssl_context=context)324+325 if self.assert_fingerprint:326 assert_fingerprint(self.sock.getpeercert(binary_form=True),327 self.assert_fingerprint)294- elif resolved_cert_reqs != ssl.CERT_NONE \328+ elif context.verify_mode != ssl.CERT_NONE \329 and self.assert_hostname is not False:330 cert = self.sock.getpeercert()331 if not cert.get('subjectAltName', ()):332 warnings.warn((4 unmodified lines337 SubjectAltNameWarning338 )339 _match_hostname(cert, self.assert_hostname or hostname)340 341+ self.is_verified = (307- self.is_verified = (resolved_cert_reqs == ssl.CERT_REQUIRED or308- self.assert_fingerprint is not None)342+ context.verify_mode == ssl.CERT_REQUIRED or343+ self.assert_fingerprint is not None344+ )345 346 347 def _match_hostname(cert, asserted_hostname):348 try:18 unmodified linesmodified:requests/packages/urllib3/connectionpool.py+25 added-20 removed
5 unmodified lines6 7 from socket import error as SocketError, timeout as SocketTimeout8 import socket9 10-try: # Python 311- from queue import LifoQueue, Empty, Full12-except ImportError:13- from Queue import LifoQueue, Empty, Full14- # Queue is imported for side effects on MS Windows15- import Queue as _unused_module_Queue # noqa: unused10 17-11 from .exceptions import (12 ClosedPoolError,13 ProtocolError,14 EmptyPoolError,9 unmodified lines24 NewConnectionError,25 )26 from .packages.ssl_match_hostname import CertificateError27 from .packages import six28+from .packages.six.moves.queue import LifoQueue, Empty, Full29 from .connection import (30 port_by_scheme,31 DummyConnection,32 HTTPConnection, HTTPSConnection, VerifiedHTTPSConnection,8 unmodified lines41 from .util.timeout import Timeout42 from .util.url import get_host, Url43 44 45+if six.PY2:46+ # Queue is imported for side effects on MS Windows47+ import Queue as _unused_module_Queue # noqa: F40148+49 xrange = six.moves.xrange50 51 log = logging.getLogger(__name__)52 154 unmodified lines207 """208 Return a fresh :class:`HTTPConnection`.209 """210 self.num_connections += 1213- log.info("Starting new HTTP connection (%d): %s",214- self.num_connections, self.host)211+ log.debug("Starting new HTTP connection (%d): %s",212+ self.num_connections, self.host)213 214 conn = self.ConnectionCls(host=self.host, port=self.port,215 timeout=self.timeout.connect_timeout,216 strict=self.strict, **self.conn_kw)26 unmodified lines243 pass # Oh well, we'll create a new connection then244 245 # If this is a persistent connection, check if it got disconnected246 if conn and is_connection_dropped(conn):249- log.info("Resetting dropped connection: %s", self.host)247+ log.debug("Resetting dropped connection: %s", self.host)248 conn.close()249 if getattr(conn, 'auto_open', 1) == 0:250 # This is a proxied connection that has been mutated by251 # httplib._tunnel() and cannot be reused (since it would142 unmodified lines394 raise395 396 # AppEngine doesn't have a version attr.397 http_version = getattr(conn, '_http_vsn_str', 'HTTP/?')400- log.debug("\"%s %s %s\" %s %s", method, url, http_version,401- httplib_response.status, httplib_response.length)398+ log.debug("%s://%s:%s \"%s %s %s\" %s %s", self.scheme, self.host, self.port,399+ method, url, http_version, httplib_response.status,400+ httplib_response.length)401 402 try:403 assert_header_parsing(httplib_response.msg)404 except HeaderParsingError as hpe: # Platform-specific: Python 3193 unmodified lines598 # it will also try to release it and we'll have a double-release599 # mess.600 response_conn = conn if not release_conn else None601 602+ # Pass method to Response for length checking603+ response_kw['request_method'] = method604+605 # Import httplib's response into our own wrapper object606 response = self.ResponseCls.from_httplib(httplib_response,607 pool=self,608 connection=response_conn,609+ retries=retries,610 **response_kw)611 612 # Everything went great!613 clean_exit = True71 unmodified lines685 response.release_conn()686 raise687 return response688 689+ retries.sleep_for_retry(response)686- log.info("Redirecting %s -> %s", url, redirect_location)690+ log.debug("Redirecting %s -> %s", url, redirect_location)691 return self.urlopen(692 method, redirect_location, body, headers,693 retries=retries, redirect=redirect,694 assert_same_host=assert_same_host,695 timeout=timeout, pool_timeout=pool_timeout,696 release_conn=release_conn, **response_kw)697 698 # Check if we should retry the HTTP response.695- if retries.is_forced_retry(method, status_code=response.status):699+ has_retry_after = bool(response.getheader('Retry-After'))700+ if retries.is_retry(method, response.status, has_retry_after):701 try:702 retries = retries.increment(method, url, response=response, _pool=self)703 except MaxRetryError:704 if retries.raise_on_status:1 unmodified line706 # returning it to be released manually.707 response.release_conn()708 raise709 return response705- retries.sleep()706- log.info("Forced retry: %s", url)710+ retries.sleep(response)711+ log.debug("Retry: %s", url)712 return self.urlopen(713 method, url, body, headers,714 retries=retries, redirect=redirect,715 assert_same_host=assert_same_host,63 unmodified lines779 ca_cert_dir=self.ca_cert_dir,780 assert_hostname=self.assert_hostname,781 assert_fingerprint=self.assert_fingerprint)782 conn.ssl_version = self.ssl_version778-783 return conn784 785 def _prepare_proxy(self, conn):786 """17 unmodified lines804 """805 Return a fresh :class:`httplib.HTTPSConnection`.806 """807 self.num_connections += 1804- log.info("Starting new HTTPS connection (%d): %s",805- self.num_connections, self.host)808+ log.debug("Starting new HTTPS connection (%d): %s",809+ self.num_connections, self.host)810 811 if not self.ConnectionCls or self.ConnectionCls is DummyConnection:812 raise SSLError("Can't connect to HTTPS URL because the SSL "813 "module is not available.")23 unmodified lines837 if not conn.is_verified:838 warnings.warn((839 'Unverified HTTPS request is being made. '840 'Adding certificate verification is strongly advised. See: '837- 'https://urllib3.readthedocs.io/en/latest/security.html'),841+ 'https://urllib3.readthedocs.io/en/latest/advanced-usage.html'842+ '#ssl-warnings'),843 InsecureRequestWarning)844 845 846 def connection_from_url(url, **kw):25 unmodified linesmodified:requests/packages/urllib3/exceptions.py+32 added
1 from __future__ import absolute_import2+from .packages.six.moves.http_client import (3+ IncompleteRead as httplib_IncompleteRead4+)5 # Base Exceptions6 7 8 class HTTPError(Exception):186 unmodified lines195 "Response needs to be chunked in order to read it as chunks."196 pass197 198 199+class BodyNotHttplibCompatible(HTTPError):200+ """201+ Body should be httplib.HTTPResponse like (have an fp attribute which202+ returns raw chunks) for read_chunked().203+ """204+ pass205+206+207+class IncompleteRead(HTTPError, httplib_IncompleteRead):208+ """209+ Response length doesn't match expected Content-Length210+211+ Subclass of http_client.IncompleteRead to allow int value212+ for `partial` to avoid creating large objects on streamed213+ reads.214+ """215+ def __init__(self, partial, expected):216+ super(IncompleteRead, self).__init__(partial, expected)217+218+ def __repr__(self):219+ return ('IncompleteRead(%i bytes read, '220+ '%i more expected)' % (self.partial, self.expected))221+222+223+class InvalidHeader(HTTPError):224+ "The header provided was somehow invalid."225+ pass226+227+228 class ProxySchemeUnknown(AssertionError, ValueError):229 "ProxyManager does not support the supplied scheme"230 # TODO(t-8ch): Stop inheriting from AssertionError in v2.0.231 10 unmodified linesmodified:requests/packages/urllib3/fields.py+1 added-1 removed
128 unmodified lines129 if isinstance(header_parts, dict):130 iterable = header_parts.items()131 132 for name, value in iterable:133- if value:133+ if value is not None:134 parts.append(self._render_part(name, value))135 136 return '; '.join(parts)137 41 unmodified linesmodified:requests/packages/urllib3/filepost.py+1 added-1 removed
11 unmodified lines12 13 14 def choose_boundary():15 """16- Our embarassingly-simple replacement for mimetools.choose_boundary.16+ Our embarrassingly-simple replacement for mimetools.choose_boundary.17 """18 return uuid4().hex19 20 74 unmodified linesmodified:requests/packages/urllib3/poolmanager.py+2 added-6 removed
1 unmodified line2 import collections3 import functools4 import logging5 6-try: # Python 37- from urllib.parse import urljoin8-except ImportError:9- from urlparse import urljoin10-6 from ._collections import RecentlyUsedContainer7 from .connectionpool import HTTPConnectionPool, HTTPSConnectionPool8 from .connectionpool import port_by_scheme9 from .exceptions import LocationValueError, MaxRetryError, ProxySchemeUnknown10+from .packages.six.moves.urllib.parse import urljoin11 from .request import RequestMethods12 from .util.url import parse_url13 from .util.retry import Retry14 3 unmodified lines18 19 log = logging.getLogger(__name__)20 21 SSL_KEYWORDS = ('key_file', 'cert_file', 'cert_reqs', 'ca_certs',26- 'ssl_version', 'ca_cert_dir')22+ 'ssl_version', 'ca_cert_dir', 'ssl_context')23 24 # The base fields to use when determining what pool to get a connection from;25 # these do not rely on the ``connection_pool_kw`` and can be determined by the26 # URL and potentially the ``urllib3.connection.port_by_scheme`` dictionary.337 unmodified linesmodified:requests/packages/urllib3/request.py+1 added-4 removed
1 from __future__ import absolute_import2-try:3- from urllib.parse import urlencode4-except ImportError:5- from urllib import urlencode2 3 from .filepost import encode_multipart_formdata4+from .packages.six.moves.urllib.parse import urlencode5 6 7 __all__ = ['RequestMethods']8 140 unmodified linesmodified:requests/packages/urllib3/response.py+94 added-6 removed
1 from __future__ import absolute_import2 from contextlib import contextmanager3 import zlib4 import io5+import logging6 from socket import timeout as SocketTimeout7 from socket import error as SocketError8 9 from ._collections import HTTPHeaderDict10 from .exceptions import (10- ProtocolError, DecodeError, ReadTimeoutError, ResponseNotChunked11+ BodyNotHttplibCompatible, ProtocolError, DecodeError, ReadTimeoutError,12+ ResponseNotChunked, IncompleteRead, InvalidHeader13 )14 from .packages.six import string_types as basestring, binary_type, PY315 from .packages.six.moves import http_client as httplib16 from .connection import HTTPException, BaseSSLError17 from .util.response import is_fp_closed, is_response_to_head18 19+log = logging.getLogger(__name__)20 21+22 class DeflateDecoder(object):23 24 def __init__(self):25 self._first_try = True66 unmodified lines92 :param original_response:93 When this HTTPResponse wrapper is generated from an httplib.HTTPResponse94 object, it's convenient to include the original for debug purposes. It's95 otherwise unused.96+97+ :param retries:98+ The retries contains the last :class:`~urllib3.util.retry.Retry` that99+ was used during the request.100+101+ :param enforce_content_length:102+ Enforce content length checking. Body returned by server must match103+ value of Content-Length header, if present. Otherwise, raise error.104 """105 106 CONTENT_DECODERS = ['gzip', 'deflate']107 REDIRECT_STATUSES = [301, 302, 303, 307, 308]108 109 def __init__(self, body='', headers=None, status=0, version=0, reason=None,110 strict=0, preload_content=True, decode_content=True,99- original_response=None, pool=None, connection=None):111+ original_response=None, pool=None, connection=None,112+ retries=None, enforce_content_length=False, request_method=None):113 114 if isinstance(headers, HTTPHeaderDict):115 self.headers = headers116 else:2 unmodified lines119 self.version = version120 self.reason = reason121 self.strict = strict122 self.decode_content = decode_content123+ self.retries = retries124+ self.enforce_content_length = enforce_content_length125 126 self._decoder = None127 self._body = None128 self._fp = None17 unmodified lines146 encodings = (enc.strip() for enc in tr_enc.split(","))147 if "chunked" in encodings:148 self.chunked = True149 150+ # Determine length of response151+ self.length_remaining = self._init_length(request_method)152+153 # If requested, preload the body.154 if preload_content and not self._body:155 self._body = self.read(decode_content=decode_content)156 37 unmodified lines194 are encoded on the wire (e.g, compressed).195 """196 return self._fp_bytes_read197 198+ def _init_length(self, request_method):199+ """200+ Set initial length value for Response content if available.201+ """202+ length = self.headers.get('content-length')203+204+ if length is not None and self.chunked:205+ # This Response will fail with an IncompleteRead if it can't be206+ # received as chunked. This method falls back to attempt reading207+ # the response before raising an exception.208+ log.warning("Received response with both Content-Length and "209+ "Transfer-Encoding set. This is expressly forbidden "210+ "by RFC 7230 sec 3.3.2. Ignoring Content-Length and "211+ "attempting to process response as Transfer-Encoding: "212+ "chunked.")213+ return None214+215+ elif length is not None:216+ try:217+ # RFC 7230 section 3.3.2 specifies multiple content lengths can218+ # be sent in a single Content-Length header219+ # (e.g. Content-Length: 42, 42). This line ensures the values220+ # are all valid ints and that as long as the `set` length is 1,221+ # all values are the same. Otherwise, the header is invalid.222+ lengths = set([int(val) for val in length.split(',')])223+ if len(lengths) > 1:224+ raise InvalidHeader("Content-Length contained multiple "225+ "unmatching values (%s)" % length)226+ length = lengths.pop()227+ except ValueError:228+ length = None229+ else:230+ if length < 0:231+ length = None232+233+ # Convert status to int for comparison234+ # In some cases, httplib returns a status of "_UNKNOWN"235+ try:236+ status = int(self.status)237+ except ValueError:238+ status = 0239+240+ # Check for responses that shouldn't include a body241+ if status in (204, 304) or 100 <= status < 200 or request_method == 'HEAD':242+ length = 0243+244+ return length245+246 def _init_decoder(self):247 """182- Set-up the _decoder attribute if necessar.248+ Set-up the _decoder attribute if necessary.249 """250 # Note: content-encoding value should be case-insensitive, per RFC 7230251 # Section 3.2252 content_encoding = self.headers.get('content-encoding', '').lower()134 unmodified lines387 # not properly close the connection in all cases. There is388 # no harm in redundantly calling close.389 self._fp.close()390 flush_decoder = True391+ if self.enforce_content_length and self.length_remaining not in (0, None):392+ # This is an edge case that httplib failed to cover due393+ # to concerns of backward compatibility. We're394+ # addressing it here to make sure IncompleteRead is395+ # raised during streaming, so all calls with incorrect396+ # Content-Length are caught.397+ raise IncompleteRead(self._fp_bytes_read, self.length_remaining)398 399 if data:400 self._fp_bytes_read += len(data)401+ if self.length_remaining is not None:402+ self.length_remaining -= len(data)403 404 data = self._decode(data, decode_content, flush_decoder)405 406 if cache_content:16 unmodified lines423 :param decode_content:424 If True, will attempt to decode the body based on the425 'content-encoding' header.426 """352- if self.chunked:427+ if self.chunked and self.supports_chunked_reads():428 for line in self.read_chunked(amt, decode_content=decode_content):429 yield line430 else:431 while not is_fp_closed(self._fp):49 unmodified lines481 @property482 def closed(self):483 if self._fp is None:484 return True485+ elif hasattr(self._fp, 'isclosed'):486+ return self._fp.isclosed()487 elif hasattr(self._fp, 'closed'):488 return self._fp.closed412- elif hasattr(self._fp, 'isclosed'): # Python 2413- return self._fp.isclosed()489 else:490 return True491 492 def fileno(self):21 unmodified lines514 else:515 b[:len(temp)] = temp516 return len(temp)517 518+ def supports_chunked_reads(self):519+ """520+ Checks if the underlying file-like object looks like a521+ httplib.HTTPResponse object. We do this by testing for the fp522+ attribute. If it is present we assume it returns raw chunks as523+ processed by read_chunked().524+ """525+ return hasattr(self._fp, 'fp')526+527 def _update_chunk_length(self):528 # First, we'll figure out length of a chunk and then529 # we'll try to read it from socket.530 if self.chunk_left is not None:43 unmodified lines574 if not self.chunked:575 raise ResponseNotChunked(576 "Response is not chunked. "577 "Header 'transfer-encoding: chunked' is missing.")578+ if not self.supports_chunked_reads():579+ raise BodyNotHttplibCompatible(580+ "Body should be httplib.HTTPResponse like. "581+ "It should have have an fp attribute which returns raw chunks.")582 583 # Don't bother reading the body of a HEAD request.584 if self._original_response and is_response_to_head(self._original_response):585 self._original_response.close()33 unmodified lines