upate urllib3 to a0c986a24d
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Thomas Weißschuh · committed by Thomas Weißschuh · parent 1ba83c4 · Browse files · 7 files·+151 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
7 files+151 added−106 removed
- other:+151 added−106 removed
Provenance
- Commit
3ef4115- Tree
5990729- Author
Thomas Weißschuh <thomas@t-8ch.de>- Committer
Thomas Weißschuh <thomas@t-8ch.de>- Parent
1ba83c4
7 files changed+151 added−106 removed
modified:requests/packages/urllib3/contrib/pyopenssl.py+4 added-4 removed
27 unmodified lines28 import ssl29 import select30 from cStringIO import StringIO31 32-from .. import connectionpool32+from .. import connection33 from .. import util34 35 __all__ = ['inject_into_urllib3', 'extract_from_urllib3']36 14 unmodified lines51 }52 53 54 orig_util_HAS_SNI = util.HAS_SNI55-orig_connectionpool_ssl_wrap_socket = connectionpool.ssl_wrap_socket55+orig_connection_ssl_wrap_socket = connection.ssl_wrap_socket56 57 58 def inject_into_urllib3():59 'Monkey-patch urllib3 with PyOpenSSL-backed SSL-support.'60 61- connectionpool.ssl_wrap_socket = ssl_wrap_socket61+ connection.ssl_wrap_socket = ssl_wrap_socket62 util.HAS_SNI = HAS_SNI63 64 65 def extract_from_urllib3():66 'Undo monkey-patching by :func:`inject_into_urllib3`.'67 68- connectionpool.ssl_wrap_socket = orig_connectionpool_ssl_wrap_socket68+ connection.ssl_wrap_socket = orig_connection_ssl_wrap_socket69 util.HAS_SNI = orig_util_HAS_SNI70 71 72 ### Note: This is a slightly bug-fixed version of same from ndg-httpsclient.274 unmodified linesmodified: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."""1+try:2+ # Python 3.2+3+ from ssl import CertificateError, match_hostname4+except 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_hostname11 3-import re4-5-__version__ = '3.2.2'6-7-class CertificateError(ValueError):8- pass9-10-def _dnsname_match(dn, hostname, max_wildcards=1):11- """Matching according to RFC 6125, section 6.4.312-13- http://tools.ietf.org/html/rfc6125#section-6.4.314- """15- pats = []16- if not dn:17- return False18-19- parts = dn.split(r'.')20- leftmost = parts[0]21-22- 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))30-31- # speed up common case w/o wildcards32- if not wildcards:33- return dn.lower() == hostname.lower()34-35- # 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'\*', '[^.]*'))51-52- # add the remaining fragments, ignore any wildcards53- for frag in parts[1:]:54- pats.append(re.escape(frag))55-56- pat = re.compile(r'\A' + r'\.'.join(pats) + r'\Z', re.IGNORECASE)57- return pat.match(hostname)58-59-60-def 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*.64-65- 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."""2+3+# 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+8+__version__ = '3.4.0.2'9+10+class CertificateError(ValueError):11+ pass12+13+14+def _dnsname_match(dn, hostname, max_wildcards=1):15+ """Matching according to RFC 6125, section 6.4.316+17+ http://tools.ietf.org/html/rfc6125#section-6.4.318+ """19+ pats = []20+ if not dn:21+ return False22+23+ # Ported from python3-syntax:24+ # leftmost, *remainder = dn.split(r'.')25+ parts = dn.split(r'.')26+ leftmost = parts[0]27+ remainder = parts[1:]28+29+ 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))37+38+ # speed up common case w/o wildcards39+ if not wildcards:40+ return dn.lower() == hostname.lower()41+42+ # 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'\*', '[^.]*'))58+59+ # add the remaining fragments, ignore any wildcards60+ for frag in remainder:61+ pats.append(re.escape(frag))62+63+ pat = re.compile(r'\A' + r'\.'.join(pats) + r'\Z', re.IGNORECASE)64+ return pat.match(hostname)65+66+67+def 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*.71+72+ 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 lines460 raise HostChangedError(self, url, retries - 1)461 462 conn = None463 464+ # 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)470+471 try:472 # Request a connection from the queue473 conn = self._get_conn(timeout=pool_timeout)474 207 unmodified linesmodified:requests/packages/urllib3/poolmanager.py+3 added-4 removed
243 unmodified lines244 "Same as HTTP(S)ConnectionPool.urlopen, ``url`` must be absolute."245 u = parse_url(url)246 247 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)253 254 return super(ProxyManager, self).urlopen(method, url, redirect, **kw)255 256 2 unmodified linesmodified:requests/packages/urllib3/response.py+11 added
88 unmodified lines89 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 = 094 95 self._pool = pool96 self._connection = connection97 31 unmodified lines129 130 if self._fp:131 return self.read(cache_content=True)132 133+ 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_read140+141 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 lines191 # in redundantly calling close.192 self._fp.close()193 flush_decoder = True194 195+ self._fp_bytes_read += len(data)196+197 try:198 if decode_content and self._decoder:199 data = self._decoder.decompress(data)200 except (IOError, zlib.error) as e:112 unmodified linesmodified:requests/packages/urllib3/util.py+9 added-1 removed
424 unmodified lines425 return p.scheme or 'http', p.hostname, p.port426 427 428 def 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.432 433 :param keep_alive:12 unmodified lines446 :param basic_auth:447 Colon-separated username:password string for 'authorization: basic ...'448 auth header.449 450+ :param proxy_basic_auth:451+ Colon-separated username:password string for 'proxy-authorization: basic ...'452+ auth header.453+454 Example: ::455 456 >>> make_headers(keep_alive=True, user_agent="Batman/1.0")457 {'connection': 'keep-alive', 'user-agent': 'Batman/1.0'}19 unmodified lines477 if basic_auth:478 headers['authorization'] = 'Basic ' + \479 b64encode(six.b(basic_auth)).decode('utf-8')480 481+ if proxy_basic_auth:482+ headers['proxy-authorization'] = 'Basic ' + \483+ b64encode(six.b(proxy_basic_auth)).decode('utf-8')484+485 return headers486 487 488 def is_connection_dropped(conn): # Platform-specific155 unmodified lines