Skip to content
Myr

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

21 files+713 added−250 removed

modified:requests/packages/urllib3/contrib/appengine.py+86 added-21 removed
1"""2This module provides a pool manager that uses Google App Engine's3`URLFetch Service <https://cloud.google.com/appengine/docs/python/urlfetch>`_.45Example usage::67 from urllib3 import PoolManager8 from urllib3.contrib.appengine import AppEngineManager, is_appengine_sandbox910 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()1617 r = http.request('GET', 'https://google.com/')1819There are `limitations <https://cloud.google.com/appengine/docs/python/\20urlfetch/#Python_Quotas_and_limits>`_ to the URLFetch service and it may not be21the best choice for your application. There are three options for using22urllib3 on Google App Engine:23241. You can use :class:`AppEngineManager` with URLFetch. URLFetch is25 cost-effective in many circumstances as long as your usage is within the26 limitations.272. 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``::3233 env_variables:34 GAE_USE_SOCKETS_HTTPLIB : 'true'35363. 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"""4041from __future__ import absolute_import42import logging43import os44import warnings45from urlparse import urljoin4647from ..exceptions import (48 HTTPError,49 HTTPWarning,
31 unmodified lines
81 Connection manager for Google App Engine sandbox applications.8283 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>`_.8746 https://cloud.google.com/appengine/docs/python/urlfetch4748 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.9596 Beyond those cases, it will raise normal urllib3 errors.97 """9859 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 lines
115 AppEnginePlatformWarning)116117 RequestMethods.__init__(self, headers)118 self.validate_certificate = validate_certificate119 self.urlfetch_retries = urlfetch_retries120121 self.retries = retries or Retry.DEFAULT122123 def __enter__(self):
9 unmodified lines
133134 retries = self._get_retries(retries, redirect)135136 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 lines
175 raise AppEnginePlatformError(176 "URLFetch does not support method: %s" % method, e)177178 http_response = self._urlfetch_response_to_http_response(136 response, **response_kw)179 response, retries=retries, **response_kw)180138 # 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'190191 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_response197198 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)205206 # 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 lines
246 )247248 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 timeout259260 def _get_retries(self, retries, redirect):
36 unmodified lines
modified:requests/packages/urllib3/contrib/ntlmpool.py+2 added-5 removed
3 unmodified lines
4Issue #10, see: http://code.google.com/p/urllib3/issues/detail?id=105"""6from __future__ import absolute_import78try:9 from http.client import HTTPSConnection10except ImportError:11 from httplib import HTTPSConnection8from logging import getLogger9from ntlm import ntlm1015from urllib3 import HTTPSConnectionPool11from .. import HTTPSConnectionPool12from ..packages.six.moves.http_client import HTTPSConnection131415log = getLogger(__name__)16
96 unmodified lines
modified:requests/packages/urllib3/contrib/pyopenssl.py+182 added-109 removed
1"""1'''SSL with SNI_-support for Python 2. Follow these instructions if you would2SSL with SNI_-support for Python 2. Follow these instructions if you would3like to verify SSL certificates in Python 2. Note, the default libraries do4*not* do certificate checking; you need to do additional work to validate5certificates yourself.67This needs the following packages installed:88* 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)1213However, pyopenssl depends on cryptography, which depends on idna, so while we14use all three directly here we end up having relatively few packages required.1516You can install them with the following command:1714 pip install pyopenssl ndg-httpsclient pyasn118 pip install pyopenssl cryptography idna1920To activate certificate checking, call21:func:`~urllib3.contrib.pyopenssl.inject_into_urllib3` from your Python code22before you begin making HTTP requests. This can be done in a ``sitecustomize``
14 unmodified lines
3738If you want to configure the default list of supported cipher suites, you can39set the ``urllib3.contrib.pyopenssl.DEFAULT_SSL_CIPHER_LIST`` variable.4037Module Variables38----------------3940:var DEFAULT_SSL_CIPHER_LIST: The list of supported SSL/TLS cipher suites.4141.. _sni: https://en.wikipedia.org/wiki/Server_Name_Indication42.. _crime attack: https://en.wikipedia.org/wiki/CRIME_(security_exploit)4445'''43"""44from __future__ import absolute_import4548try:49 from ndg.httpsclient.ssl_peer_verification import SUBJ_ALT_NAME_SUPPORT50 from ndg.httpsclient.subj_alt_name import SubjectAltName as BaseSubjectAltName51except SyntaxError as e:52 raise ImportError(e)5346import idna47import OpenSSL.SSL55from pyasn1.codec.der import decoder as der_decoder56from pyasn1.type import univ, constraint48from cryptography import x50949from cryptography.hazmat.backends.openssl import backend as openssl_backend50from cryptography.hazmat.backends.openssl.x509 import _Certificate5152from socket import timeout, error as SocketError53from io import BytesIO5455try: # Platform-specific: Python 256 from socket import _fileobject57except ImportError: # Platform-specific: Python 358 _fileobject = None63 from urllib3.packages.backports.makefile import backport_makefile59 from ..packages.backports.makefile import backport_makefile6061import logging62import ssl63import select64import six65import sys6669from .. import connection67from .. import util6869__all__ = ['inject_into_urllib3', 'extract_from_urllib3']7074# SNI only *really* works if we can read the subjectAltName of certificates.75HAS_SNI = SUBJ_ALT_NAME_SUPPORT71# SNI always works.72HAS_SNI = True7374# Map from urllib3 to PyOpenSSL compatible parameter-values.75_openssl_versions = {76 ssl.PROTOCOL_SSLv23: OpenSSL.SSL.SSLv23_METHOD,
10 unmodified lines
87 _openssl_versions.update({ssl.PROTOCOL_SSLv3: OpenSSL.SSL.SSLv3_METHOD})88except AttributeError:89 pass9094_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)100101DEFAULT_SSL_CIPHER_LIST = util.ssl_.DEFAULT_CIPHERS.encode('ascii')102101# OpenSSL will only write 16K at a time102SSL_WRITE_BLOCKSIZE = 16384103104orig_util_HAS_SNI = util.HAS_SNI107orig_connection_ssl_wrap_socket = connection.ssl_wrap_socket105orig_util_SSLContext = util.ssl_.SSLContext106107108log = logging.getLogger(__name__)109110111def inject_into_urllib3():112 'Monkey-patch urllib3 with PyOpenSSL-backed SSL-support.'113113 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 = True119120121def extract_from_urllib3():122 'Undo monkey-patching by :func:`inject_into_urllib3`.'123121 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 = False129130126# Note: This is a slightly bug-fixed version of same from ndg-httpsclient.127class SubjectAltName(BaseSubjectAltName):128 '''ASN.1 implementation for subjectAltNames support'''131def _dnsname_to_stdlib(name):132 """133 Converts a dNSName SubjectAlternativeName field to the form used by the134 standard library on the given Python version.135130 # 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)152153 name = idna_encode(name)154 if sys.version_info >= (3, 0):155 name = name.decode('utf-8')156 return name157137# Note: This is a slightly bug-fixed version of same from ndg-httpsclient.158159def 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)167144 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 []188151 # 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 )203156 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 names205165 return dns_name206167207class WrappedSocket(object):208 '''API-compatibility wrapper for Python OpenSSL's Connection-class.209210 Note: _makefile_refs, _drop() and _reuse() are needed for the garbage
109 unmodified lines
320 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 }326327 def _reuse(self):328 self._makefile_refs += 1
14 unmodified lines
343344WrappedSocket.makefile = makefile345346311def _verify_callback(cnx, x509, err_no, err_depth, return_code):312 return err_no == 0347class 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 = False358359 @property360 def options(self):361 return self._options362315def 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)367334 # 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()]371338 # 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 )378341 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()381382 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)386387 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))395396 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)401402 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)406407 if isinstance(server_hostname, six.text_type): # Platform-specific: Python 3408 server_hostname = server_hostname.encode('utf-8')409410 if server_hostname is not None:411 cnx.set_tlsext_host_name(server_hostname)412413 cnx.set_connect_state()414415 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 break426358 return WrappedSocket(cnx, sock)427 return WrappedSocket(cnx, sock)428429430def _verify_callback(cnx, x509, err_no, err_depth, return_code):431 return err_no == 0
modified:requests/packages/urllib3/contrib/socks.py+11 added-5 removed
1# -*- coding: utf-8 -*-2"""3SOCKS support for urllib34~~~~~~~~~~~~~~~~~~~~~~~~~56This contrib module contains provisional support for SOCKS proxies from within3This module contains provisional support for SOCKS proxies from within4urllib3. This module supports SOCKS4 (specifically the SOCKS4A variant) and5SOCKS5. To enable its functionality, either install PySocks or install this6module with the ``socks`` extra.78The SOCKS implementation supports the full range of urllib3 features. It also9supports the following SOCKS features:1011- SOCKS412- SOCKS4a13- SOCKS514- Usernames and passwords for the SOCKS proxy1516Known Limitations:1718- 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"""24from __future__ import absolute_import
154 unmodified lines
modified:requests/packages/urllib3/packages/ssl_match_hostname/__init__.py+7 added-1 removed
1import sys23try: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")89 from ssl import CertificateError, match_hostname10except ImportError:11 try:12 # Backport of the function from a pypi module
7 unmodified lines
modified:requests/packages/urllib3/packages/ssl_match_hostname/_implementation.py+55 added-3 removed
2 unmodified lines
3# Note: This file is under the PSF license as the code comes from the python4# stdlib. http://docs.python.org/3/license.html56import re7import sys88__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.14try:15 import ipaddress16except ImportError:17 ipaddress = None1819__version__ = '3.5.0.1'202122class CertificateError(ValueError):23 pass2425
49 unmodified lines
75 pat = re.compile(r'\A' + r'\.'.join(pats) + r'\Z', re.IGNORECASE)76 return pat.match(hostname)777879def _to_unicode(obj):80 if isinstance(obj, str) and sys.version_info < (3,):81 obj = unicode(obj, encoding='ascii', errors='strict')82 return obj8384def _ipaddress_match(ipname, host_ip):85 """Exact matching of IP addresses.8687 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_ip949596def 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 line
101 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 lines
deleted:requests/packages/urllib3/packages/ssl_match_hostname/.gitignore-1 removed
1env
modified:requests/packages/urllib3/util/response.py+7 added
11 unmodified lines
12 The file-like object to check.13 """1415 try:16 # Check `isclosed()` first, in case Python3 doesn't set `closed`.17 # GH Issue #92818 return obj.isclosed()19 except AttributeError:20 pass2122 try:23 # Check via the official file-like-object way.24 return obj.closed25 except AttributeError:26 pass
55 unmodified lines
modified:requests/packages/urllib3/util/retry.py+93 added-17 removed
1from __future__ import absolute_import2import time3import logging4from collections import namedtuple5from itertools import takewhile6import email7import re89from ..exceptions import (10 ConnectTimeoutError,11 MaxRetryError,12 ProtocolError,13 ReadTimeoutError,14 ResponseError,15 InvalidHeader,16)17from ..packages import six181920log = logging.getLogger(__name__)2122# Data structure for representing the metadata of requests that result in a retry.23RequestHistory = namedtuple('RequestHistory', ["method", "url", "error",24 "status", "redirect_location"])252627class Retry(object):28 """ Retry configuration.2930 Each retry attempt will create a new Retry object with updated values, so
90 unmodified lines
121 :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.125126 :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`.129130 :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.133134 """135136 DEFAULT_METHOD_WHITELIST = frozenset([137 'HEAD', 'GET', 'PUT', 'DELETE', 'OPTIONS', 'TRACE'])138139 RETRY_AFTER_STATUS_CODES = frozenset([413, 429, 503])140141 #: Maximum backoff time.142 BACKOFF_MAX = 120143144 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):148149 self.total = total150 self.connect = connect151 self.read = read
7 unmodified lines
159 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_header165166 def new(self, **kw):167 params = dict(168 total=self.total,
2 unmodified lines
171 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 lines
195 """ Formula for computing the current backoff196197 :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 0204181 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)207184 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()218187 By default, the backoff factor is 0 and this method will return188 immediately.189 """219 if seconds < 0:220 seconds = 0221222 return seconds223224 def get_retry_after(self, response):225 """ Get the value of Retry-After in seconds. """226227 retry_after = response.getheader("Retry-After")228229 if retry_after is None:230 return None231232 return self.parse_retry_after(retry_after)233234 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 True239240 return False241242 def _sleep_backoff(self):243 backoff = self.get_backoff_time()244 if backoff <= 0:245 return246 time.sleep(backoff)247248 def sleep(self, response=None):249 """ Sleep between retry attempts.250251 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 """256257 if response:258 slept = self.sleep_for_retry(response)259 if slept:260 return261262 self._sleep_backoff()263264 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 lines
272 assume that the server began processing it.273 """274 return isinstance(err, (ReadTimeoutError, ProtocolError))275207 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 False281213 return self.status_forcelist and status_code in self.status_forcelist282 if self.status_forcelist and status_code in self.status_forcelist:283 return True284285 return (self.total and self.respect_retry_after_header and286 has_retry_after and (status_code in self.RETRY_AFTER_STATUS_CODES))287288 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 lines
313 total = self.total314 if total is not None:315 total -= 1316244 _observed_errors = self._observed_errors317 connect = self.connect318 read = self.read319 redirect = self.redirect320 cause = 'unknown'321 status = None322 redirect_location = None323324 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 += 1330331 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 += 1337338 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.status345346 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.status354355 history = self.history + (RequestHistory(method, url, error, status, redirect_location),)356357 new_retry = self.new(358 total=total,359 connect=connect, read=read, redirect=redirect,284 _observed_errors=_observed_errors)360 history=history)361362 if new_retry.is_exhausted():363 raise MaxRetryError(_pool, url, error or ResponseError(cause))364
12 unmodified lines
modified:requests/packages/urllib3/util/ssl_.py+28 added-12 removed
9 unmodified lines
101112SSLContext = None13HAS_SNI = False14create_default_context = None14IS_PYOPENSSL = False1516# Maps the length of a digest to a possible hash function producing this digest17HASHFUNC_MAP = {
43 unmodified lines
61#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.69DEFAULT_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)69DEFAULT_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])8485try:86 from ssl import SSLContext # Modern SSL?87except ImportError:
38 unmodified lines
126 '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 lines
296 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)305306 if ca_certs or ca_cert_dir:
6 unmodified lines
313 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()320321 if certfile:322 context.load_cert_chain(certfile, keyfile)323 if HAS_SNI: # Platform-specific: OpenSSL with enabled SNI
4 unmodified lines
328 '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 lines
110 :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_TIMEOUT119120 if value is None or value is cls.DEFAULT_TIMEOUT:121 return value122123 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))131132 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))140141 return value142143 @classmethod
102 unmodified lines
modified:requests/packages/urllib3/util/url.py+14 added-5 removed
8 unmodified lines
910class 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__ = ()1718 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)2829 @property
158 unmodified lines
188 if not host:189 host = _host190191 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 lines
219220221def 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.port
modified:requests/packages/urllib3/__init__.py+1 added-1 removed
30 unmodified lines
31 pass3233__author__ = 'Andrey Petrov (andrey.petrov@shazow.net)'34__license__ = 'MIT'35__version__ = '1.16'35__version__ = '1.19'3637__all__ = (38 'HTTPConnectionPool',39 'HTTPSConnectionPool',
57 unmodified lines
modified:requests/packages/urllib3/connection.py+62 added-26 removed
5 unmodified lines
6import socket7from socket import error as SocketError, timeout as SocketTimeout8import warnings9from .packages import six10from .packages.six.moves.http_client import HTTPConnection as _HTTPConnection11from .packages.six.moves.http_client import HTTPException # noqa: F4011211try: # Python 312 from http.client import HTTPConnection as _HTTPConnection13 from http.client import HTTPException # noqa: unused in this module14except ImportError:15 from httplib import HTTPConnection as _HTTPConnection16 from httplib import HTTPException # noqa: unused in this module1713try: # Compiled with SSL?14 import ssl15 BaseSSLError = ssl.SSLError16except (ImportError, AttributeError): # Platform-specific: No SSL.
21 unmodified lines
3839from .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)464748from .util import connection
120 unmodified lines
169 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 lines
204205class HTTPSConnection(HTTPConnection):206 default_port = port_by_scheme['https']207208 ssl_version = None209210 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):213214 HTTPConnection.__init__(self, host, port, strict=strict,215 timeout=timeout, **kw)216217 self.key_file = key_file218 self.cert_file = cert_file219 self.ssl_context = ssl_context220221 # 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'224225 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)228229 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 )234235 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 )241242243class VerifiedHTTPSConnection(HTTPSConnection):244 """245 Based on httplib.HTTPSConnection but wraps the socket with246 SSL certification.
7 unmodified lines
254 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_mode270241 if (ca_certs or ca_cert_dir) and cert_reqs is None:242 cert_reqs = 'CERT_REQUIRED'243271 self.key_file = key_file272 self.cert_file = cert_file273 self.cert_reqs = cert_reqs274 self.assert_hostname = assert_hostname
4 unmodified lines
279 def connect(self):280 # Add certificate verification281 conn = self._new_conn()282256 resolved_cert_reqs = resolve_cert_reqs(self.cert_reqs)257 resolved_ssl_version = resolve_ssl_version(self.ssl_version)258283 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 lines
304 )305306 # 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 )313314 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)324325 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 lines
337 SubjectAltNameWarning338 )339 _match_hostname(cert, self.assert_hostname or hostname)340341 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 )345346347def _match_hostname(cert, asserted_hostname):348 try:
18 unmodified lines
modified:requests/packages/urllib3/connectionpool.py+25 added-20 removed
5 unmodified lines
67from socket import error as SocketError, timeout as SocketTimeout8import socket910try: # Python 311 from queue import LifoQueue, Empty, Full12except ImportError:13 from Queue import LifoQueue, Empty, Full14 # Queue is imported for side effects on MS Windows15 import Queue as _unused_module_Queue # noqa: unused101711from .exceptions import (12 ClosedPoolError,13 ProtocolError,14 EmptyPoolError,
9 unmodified lines
24 NewConnectionError,25)26from .packages.ssl_match_hostname import CertificateError27from .packages import six28from .packages.six.moves.queue import LifoQueue, Empty, Full29from .connection import (30 port_by_scheme,31 DummyConnection,32 HTTPConnection, HTTPSConnection, VerifiedHTTPSConnection,
8 unmodified lines
41from .util.timeout import Timeout42from .util.url import get_host, Url434445if six.PY2:46 # Queue is imported for side effects on MS Windows47 import Queue as _unused_module_Queue # noqa: F4014849xrange = six.moves.xrange5051log = logging.getLogger(__name__)52
154 unmodified lines
207 """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)213214 conn = self.ConnectionCls(host=self.host, port=self.port,215 timeout=self.timeout.connect_timeout,216 strict=self.strict, **self.conn_kw)
26 unmodified lines
243 pass # Oh well, we'll create a new connection then244245 # 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 would
142 unmodified lines
394 raise395396 # 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)401402 try:403 assert_header_parsing(httplib_response.msg)404 except HeaderParsingError as hpe: # Platform-specific: Python 3
193 unmodified lines
598 # it will also try to release it and we'll have a double-release599 # mess.600 response_conn = conn if not release_conn else None601602 # Pass method to Response for length checking603 response_kw['request_method'] = method604605 # 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)611612 # Everything went great!613 clean_exit = True
71 unmodified lines
685 response.release_conn()686 raise687 return response688689 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)697698 # 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 line
706 # 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 lines
779 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_version778783 return conn784785 def _prepare_proxy(self, conn):786 """
17 unmodified lines
804 """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)810811 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 lines
837 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)844845846def connection_from_url(url, **kw):
25 unmodified lines
modified:requests/packages/urllib3/exceptions.py+32 added
1from __future__ import absolute_import2from .packages.six.moves.http_client import (3 IncompleteRead as httplib_IncompleteRead4)5# Base Exceptions678class HTTPError(Exception):
186 unmodified lines
195 "Response needs to be chunked in order to read it as chunks."196 pass197198199class BodyNotHttplibCompatible(HTTPError):200 """201 Body should be httplib.HTTPResponse like (have an fp attribute which202 returns raw chunks) for read_chunked().203 """204 pass205206207class IncompleteRead(HTTPError, httplib_IncompleteRead):208 """209 Response length doesn't match expected Content-Length210211 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)217218 def __repr__(self):219 return ('IncompleteRead(%i bytes read, '220 '%i more expected)' % (self.partial, self.expected))221222223class InvalidHeader(HTTPError):224 "The header provided was somehow invalid."225 pass226227228class 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 lines
modified:requests/packages/urllib3/fields.py+1 added-1 removed
128 unmodified lines
129 if isinstance(header_parts, dict):130 iterable = header_parts.items()131132 for name, value in iterable:133 if value:133 if value is not None:134 parts.append(self._render_part(name, value))135136 return '; '.join(parts)137
41 unmodified lines
modified:requests/packages/urllib3/filepost.py+1 added-1 removed
11 unmodified lines
121314def 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().hex1920
74 unmodified lines
modified:requests/packages/urllib3/poolmanager.py+2 added-6 removed
1 unmodified line
2import collections3import functools4import logging56try: # Python 37 from urllib.parse import urljoin8except ImportError:9 from urlparse import urljoin106from ._collections import RecentlyUsedContainer7from .connectionpool import HTTPConnectionPool, HTTPSConnectionPool8from .connectionpool import port_by_scheme9from .exceptions import LocationValueError, MaxRetryError, ProxySchemeUnknown10from .packages.six.moves.urllib.parse import urljoin11from .request import RequestMethods12from .util.url import parse_url13from .util.retry import Retry14
3 unmodified lines
1819log = logging.getLogger(__name__)2021SSL_KEYWORDS = ('key_file', 'cert_file', 'cert_reqs', 'ca_certs',26 'ssl_version', 'ca_cert_dir')22 'ssl_version', 'ca_cert_dir', 'ssl_context')2324# 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 lines
modified:requests/packages/urllib3/request.py+1 added-4 removed
1from __future__ import absolute_import2try:3 from urllib.parse import urlencode4except ImportError:5 from urllib import urlencode23from .filepost import encode_multipart_formdata4from .packages.six.moves.urllib.parse import urlencode567__all__ = ['RequestMethods']8
140 unmodified lines
modified:requests/packages/urllib3/response.py+94 added-6 removed
1from __future__ import absolute_import2from contextlib import contextmanager3import zlib4import io5import logging6from socket import timeout as SocketTimeout7from socket import error as SocketError89from ._collections import HTTPHeaderDict10from .exceptions import (10 ProtocolError, DecodeError, ReadTimeoutError, ResponseNotChunked11 BodyNotHttplibCompatible, ProtocolError, DecodeError, ReadTimeoutError,12 ResponseNotChunked, IncompleteRead, InvalidHeader13)14from .packages.six import string_types as basestring, binary_type, PY315from .packages.six.moves import http_client as httplib16from .connection import HTTPException, BaseSSLError17from .util.response import is_fp_closed, is_response_to_head1819log = logging.getLogger(__name__)202122class DeflateDecoder(object):2324 def __init__(self):25 self._first_try = True
66 unmodified lines
92 :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.9697 :param retries:98 The retries contains the last :class:`~urllib3.util.retry.Retry` that99 was used during the request.100101 :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 """105106 CONTENT_DECODERS = ['gzip', 'deflate']107 REDIRECT_STATUSES = [301, 302, 303, 307, 308]108109 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):113114 if isinstance(headers, HTTPHeaderDict):115 self.headers = headers116 else:
2 unmodified lines
119 self.version = version120 self.reason = reason121 self.strict = strict122 self.decode_content = decode_content123 self.retries = retries124 self.enforce_content_length = enforce_content_length125126 self._decoder = None127 self._body = None128 self._fp = None
17 unmodified lines
146 encodings = (enc.strip() for enc in tr_enc.split(","))147 if "chunked" in encodings:148 self.chunked = True149150 # Determine length of response151 self.length_remaining = self._init_length(request_method)152153 # 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 lines
194 are encoded on the wire (e.g, compressed).195 """196 return self._fp_bytes_read197198 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')203204 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 None214215 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 = None232233 # 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 = 0239240 # Check for responses that shouldn't include a body241 if status in (204, 304) or 100 <= status < 200 or request_method == 'HEAD':242 length = 0243244 return length245246 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 lines
387 # 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)398399 if data:400 self._fp_bytes_read += len(data)401 if self.length_remaining is not None:402 self.length_remaining -= len(data)403404 data = self._decode(data, decode_content, flush_decoder)405406 if cache_content:
16 unmodified lines
423 :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 lines
481 @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 True491492 def fileno(self):
21 unmodified lines
514 else:515 b[:len(temp)] = temp516 return len(temp)517518 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')526527 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 lines
574 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.")582583 # 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