Skip to content
Myr

Merge pull request #1726 from t-8ch/update_urllib3

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Update urllib3

authored by Kenneth Reitz · committed by Kenneth Reitz · parents 1ba83c4, c477242 · Browse files · 8 files+152 added−106 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

8 files+152 added−106 removed

  • other:+152 added−106 removed

8 files+152 added−106 removed

modified:requests/packages/urllib3/contrib/pyopenssl.py+4 added-4 removed
27 unmodified lines
28import ssl29import select30from cStringIO import StringIO3132from .. import connectionpool32from .. import connection33from .. import util3435__all__ = ['inject_into_urllib3', 'extract_from_urllib3']36
14 unmodified lines
51}525354orig_util_HAS_SNI = util.HAS_SNI55orig_connectionpool_ssl_wrap_socket = connectionpool.ssl_wrap_socket55orig_connection_ssl_wrap_socket = connection.ssl_wrap_socket565758def inject_into_urllib3():59 'Monkey-patch urllib3 with PyOpenSSL-backed SSL-support.'6061 connectionpool.ssl_wrap_socket = ssl_wrap_socket61 connection.ssl_wrap_socket = ssl_wrap_socket62 util.HAS_SNI = HAS_SNI636465def extract_from_urllib3():66 'Undo monkey-patching by :func:`inject_into_urllib3`.'6768 connectionpool.ssl_wrap_socket = orig_connectionpool_ssl_wrap_socket68 connection.ssl_wrap_socket = orig_connection_ssl_wrap_socket69 util.HAS_SNI = orig_util_HAS_SNI707172### Note: This is a slightly bug-fixed version of same from ndg-httpsclient.
274 unmodified lines
modified:requests/packages/urllib3/packages/ssl_match_hostname/__init__.py+12 added-97 removed
1"""The match_hostname() function from Python 3.2, essential when using SSL."""1try:2 # Python 3.2+3 from ssl import CertificateError, match_hostname4except ImportError:5 try:6 # Backport of the function from a pypi module7 from backports.ssl_match_hostname import CertificateError, match_hostname8 except ImportError:9 # Our vendored copy10 from _implementation import CertificateError, match_hostname113import re45__version__ = '3.2.2'67class CertificateError(ValueError):8 pass910def _dnsname_match(dn, hostname, max_wildcards=1):11 """Matching according to RFC 6125, section 6.4.31213 http://tools.ietf.org/html/rfc6125#section-6.4.314 """15 pats = []16 if not dn:17 return False1819 parts = dn.split(r'.')20 leftmost = parts[0]2122 wildcards = leftmost.count('*')23 if wildcards > max_wildcards:24 # Issue #17980: avoid denials of service by refusing more25 # than one wildcard per fragment. A survery of established26 # policy among SSL implementations showed it to be a27 # reasonable choice.28 raise CertificateError(29 "too many wildcards in certificate DNS name: " + repr(dn))3031 # speed up common case w/o wildcards32 if not wildcards:33 return dn.lower() == hostname.lower()3435 # RFC 6125, section 6.4.3, subitem 1.36 # The client SHOULD NOT attempt to match a presented identifier in which37 # the wildcard character comprises a label other than the left-most label.38 if leftmost == '*':39 # When '*' is a fragment by itself, it matches a non-empty dotless40 # fragment.41 pats.append('[^.]+')42 elif leftmost.startswith('xn--') or hostname.startswith('xn--'):43 # RFC 6125, section 6.4.3, subitem 3.44 # The client SHOULD NOT attempt to match a presented identifier45 # where the wildcard character is embedded within an A-label or46 # U-label of an internationalized domain name.47 pats.append(re.escape(leftmost))48 else:49 # Otherwise, '*' matches any dotless string, e.g. www*50 pats.append(re.escape(leftmost).replace(r'\*', '[^.]*'))5152 # add the remaining fragments, ignore any wildcards53 for frag in parts[1:]:54 pats.append(re.escape(frag))5556 pat = re.compile(r'\A' + r'\.'.join(pats) + r'\Z', re.IGNORECASE)57 return pat.match(hostname)585960def match_hostname(cert, hostname):61 """Verify that *cert* (in decoded format as returned by62 SSLSocket.getpeercert()) matches the *hostname*. RFC 2818 and RFC 612563 rules are followed, but IP addresses are not accepted for *hostname*.6465 CertificateError is raised on failure. On success, the function66 returns nothing.67 """68 if not cert:69 raise ValueError("empty or no certificate")70 dnsnames = []71 san = cert.get('subjectAltName', ())72 for key, value in san:73 if key == 'DNS':74 if _dnsname_match(value, hostname):75 return76 dnsnames.append(value)77 if not dnsnames:78 # The subject is only checked when there is no dNSName entry79 # in subjectAltName80 for sub in cert.get('subject', ()):81 for key, value in sub:82 # XXX according to RFC 2818, the most specific Common Name83 # must be used.84 if key == 'commonName':85 if _dnsname_match(value, hostname):86 return87 dnsnames.append(value)88 if len(dnsnames) > 1:89 raise CertificateError("hostname %r "90 "doesn't match either of %s"91 % (hostname, ', '.join(map(repr, dnsnames))))92 elif len(dnsnames) == 1:93 raise CertificateError("hostname %r "94 "doesn't match %r"95 % (hostname, dnsnames[0]))96 else:97 raise CertificateError("no appropriate commonName or "98 "subjectAltName fields were found")12# Not needed, but documenting what we provide.13__all__ = ('CertificateError', 'match_hostname')
added:requests/packages/urllib3/packages/ssl_match_hostname/_implementation.py+105 added
1"""The match_hostname() function from Python 3.3.3, essential when using SSL."""23# Note: This file is under the PSF license as the code comes from the python4# stdlib. http://docs.python.org/3/license.html56import re78__version__ = '3.4.0.2'910class CertificateError(ValueError):11 pass121314def _dnsname_match(dn, hostname, max_wildcards=1):15 """Matching according to RFC 6125, section 6.4.31617 http://tools.ietf.org/html/rfc6125#section-6.4.318 """19 pats = []20 if not dn:21 return False2223 # Ported from python3-syntax:24 # leftmost, *remainder = dn.split(r'.')25 parts = dn.split(r'.')26 leftmost = parts[0]27 remainder = parts[1:]2829 wildcards = leftmost.count('*')30 if wildcards > max_wildcards:31 # Issue #17980: avoid denials of service by refusing more32 # than one wildcard per fragment. A survey of established33 # policy among SSL implementations showed it to be a34 # reasonable choice.35 raise CertificateError(36 "too many wildcards in certificate DNS name: " + repr(dn))3738 # speed up common case w/o wildcards39 if not wildcards:40 return dn.lower() == hostname.lower()4142 # RFC 6125, section 6.4.3, subitem 1.43 # The client SHOULD NOT attempt to match a presented identifier in which44 # the wildcard character comprises a label other than the left-most label.45 if leftmost == '*':46 # When '*' is a fragment by itself, it matches a non-empty dotless47 # fragment.48 pats.append('[^.]+')49 elif leftmost.startswith('xn--') or hostname.startswith('xn--'):50 # RFC 6125, section 6.4.3, subitem 3.51 # The client SHOULD NOT attempt to match a presented identifier52 # where the wildcard character is embedded within an A-label or53 # U-label of an internationalized domain name.54 pats.append(re.escape(leftmost))55 else:56 # Otherwise, '*' matches any dotless string, e.g. www*57 pats.append(re.escape(leftmost).replace(r'\*', '[^.]*'))5859 # add the remaining fragments, ignore any wildcards60 for frag in remainder:61 pats.append(re.escape(frag))6263 pat = re.compile(r'\A' + r'\.'.join(pats) + r'\Z', re.IGNORECASE)64 return pat.match(hostname)656667def match_hostname(cert, hostname):68 """Verify that *cert* (in decoded format as returned by69 SSLSocket.getpeercert()) matches the *hostname*. RFC 2818 and RFC 612570 rules are followed, but IP addresses are not accepted for *hostname*.7172 CertificateError is raised on failure. On success, the function73 returns nothing.74 """75 if not cert:76 raise ValueError("empty or no certificate")77 dnsnames = []78 san = cert.get('subjectAltName', ())79 for key, value in san:80 if key == 'DNS':81 if _dnsname_match(value, hostname):82 return83 dnsnames.append(value)84 if not dnsnames:85 # The subject is only checked when there is no dNSName entry86 # in subjectAltName87 for sub in cert.get('subject', ()):88 for key, value in sub:89 # XXX according to RFC 2818, the most specific Common Name90 # must be used.91 if key == 'commonName':92 if _dnsname_match(value, hostname):93 return94 dnsnames.append(value)95 if len(dnsnames) > 1:96 raise CertificateError("hostname %r "97 "doesn't match either of %s"98 % (hostname, ', '.join(map(repr, dnsnames))))99 elif len(dnsnames) == 1:100 raise CertificateError("hostname %r "101 "doesn't match %r"102 % (hostname, dnsnames[0]))103 else:104 raise CertificateError("no appropriate commonName or "105 "subjectAltName fields were found")
modified:requests/packages/urllib3/connectionpool.py+7 added
459 unmodified lines
460 raise HostChangedError(self, url, retries - 1)461462 conn = None463464 # Merge the proxy headers. Only do this in HTTP. We have to copy the465 # headers dict so we can safely change it without those changes being466 # reflected in anyone else's copy.467 if self.scheme == 'http':468 headers = headers.copy()469 headers.update(self.proxy_headers)470471 try:472 # Request a connection from the queue473 conn = self._get_conn(timeout=pool_timeout)474
207 unmodified lines
modified:requests/packages/urllib3/poolmanager.py+3 added-4 removed
243 unmodified lines
244 "Same as HTTP(S)ConnectionPool.urlopen, ``url`` must be absolute."245 u = parse_url(url)246247 if u.scheme == "http":248 # It's too late to set proxy headers on per-request basis for249 # tunnelled HTTPS connections, should use250 # constructor's proxy_headers instead.248 # For proxied HTTPS requests, httplib sets the necessary headers249 # on the CONNECT to the proxy. For HTTP, we'll definitely250 # need to set 'Host' at the very least.251 kw['headers'] = self._set_proxy_headers(url, kw.get('headers',252 self.headers))253 kw['headers'].update(self.proxy_headers)253254 return super(ProxyManager, self).urlopen(method, url, redirect, **kw)255256
2 unmodified lines
modified:requests/packages/urllib3/response.py+11 added
88 unmodified lines
89 self._decoder = None90 self._body = body if body and isinstance(body, basestring) else None91 self._fp = None92 self._original_response = original_response93 self._fp_bytes_read = 09495 self._pool = pool96 self._connection = connection97
31 unmodified lines
129130 if self._fp:131 return self.read(cache_content=True)132133 def tell(self):134 """135 Obtain the number of bytes pulled over the wire so far. May differ from136 the amount of content returned by :meth:``HTTPResponse.read`` if bytes137 are encoded on the wire (e.g, compressed).138 """139 return self._fp_bytes_read140141 def read(self, amt=None, decode_content=None, cache_content=False):142 """143 Similar to :meth:`httplib.HTTPResponse.read`, but with two additional144 parameters: ``decode_content`` and ``cache_content``.
46 unmodified lines
191 # in redundantly calling close.192 self._fp.close()193 flush_decoder = True194195 self._fp_bytes_read += len(data)196197 try:198 if decode_content and self._decoder:199 data = self._decoder.decompress(data)200 except (IOError, zlib.error) as e:
112 unmodified lines
modified:requests/packages/urllib3/util.py+9 added-1 removed
424 unmodified lines
425 return p.scheme or 'http', p.hostname, p.port426427428def make_headers(keep_alive=None, accept_encoding=None, user_agent=None,429 basic_auth=None):429 basic_auth=None, proxy_basic_auth=None):430 """431 Shortcuts for generating request headers.432433 :param keep_alive:
12 unmodified lines
446 :param basic_auth:447 Colon-separated username:password string for 'authorization: basic ...'448 auth header.449450 :param proxy_basic_auth:451 Colon-separated username:password string for 'proxy-authorization: basic ...'452 auth header.453454 Example: ::455456 >>> make_headers(keep_alive=True, user_agent="Batman/1.0")457 {'connection': 'keep-alive', 'user-agent': 'Batman/1.0'}
19 unmodified lines
477 if basic_auth:478 headers['authorization'] = 'Basic ' + \479 b64encode(six.b(basic_auth)).decode('utf-8')480481 if proxy_basic_auth:482 headers['proxy-authorization'] = 'Basic ' + \483 b64encode(six.b(proxy_basic_auth)).decode('utf-8')484485 return headers486487488def is_connection_dropped(conn): # Platform-specific
155 unmodified lines
modified:AUTHORS.rst+1 added
138 unmodified lines
139- Park Ilsu <daftonshady@gmail.com> @daftshady140- Matt Spitz @mattspitz141- Vikram Oberoi @voberoi142- Can Ibanoglu <can.ibanoglu@gmail.com> @canibanoglu143- Thomas Weißschuh <thomas@t-8ch.de> @t-8ch