Merge pull request #2556 from sigmavirus24/release/2.6.1
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Prepare v2.6.1
authored by Ian Cordasco · committed by Ian Cordasco · parents 1f0e577, ae7c28e · Browse files · 11 files·+172 added−169 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
11 files+172 added−169 removed
- other:+172 added−169 removed
Provenance
- Commit
3880cf1- Tree
932d6b3- Author
Ian Cordasco <sigmavirus24@users.noreply.github.com>- Committer
Ian Cordasco <sigmavirus24@users.noreply.github.com>- Parent 1
1f0e577- Parent 2
ae7c28e
11 files changed+172 added−169 removed
modified:requests/packages/urllib3/contrib/pyopenssl.py+4 added-19 removed
36 unmodified lines37 Module Variables38 ----------------39 40 :var DEFAULT_SSL_CIPHER_LIST: The list of supported SSL/TLS cipher suites.41- Default: ``ECDH+AESGCM:DH+AESGCM:ECDH+AES256:DH+AES256:ECDH+AES128:DH+AES:42- ECDH+3DES:DH+3DES:RSA+AESGCM:RSA+AES:RSA+3DES:!aNULL:!MD5:!DSS``41 42 .. _sni: https://en.wikipedia.org/wiki/Server_Name_Indication43 .. _crime attack: https://en.wikipedia.org/wiki/CRIME_(security_exploit)44 37 unmodified lines82 ssl.CERT_REQUIRED: OpenSSL.SSL.VERIFY_PEER83 + OpenSSL.SSL.VERIFY_FAIL_IF_NO_PEER_CERT,84 }85 88-# A secure default.89-# Sources for more information on TLS ciphers:90-#91-# - https://wiki.mozilla.org/Security/Server_Side_TLS92-# - https://www.ssllabs.com/projects/best-practices/index.html93-# - https://hynek.me/articles/hardening-your-web-servers-ssl-ciphers/94-#95-# The general intent is:96-# - Prefer cipher suites that offer perfect forward secrecy (DHE/ECDHE),97-# - prefer ECDHE over DHE for better performance,98-# - prefer any AES-GCM over any AES-CBC for better performance and security,99-# - use 3DES as fallback which is secure but slow,100-# - disable NULL authentication, MD5 MACs and DSS for security reasons.101-DEFAULT_SSL_CIPHER_LIST = "ECDH+AESGCM:DH+AESGCM:ECDH+AES256:DH+AES256:" + \102- "ECDH+AES128:DH+AES:ECDH+3DES:DH+3DES:RSA+AESGCM:RSA+AES:RSA+3DES:" + \103- "!aNULL:!MD5:!DSS"86+DEFAULT_SSL_CIPHER_LIST = util.ssl_.DEFAULT_CIPHERS87 88 89 orig_util_HAS_SNI = util.HAS_SNI90 orig_connection_ssl_wrap_socket = connection.ssl_wrap_socket190 unmodified lines281 while True:282 try:283 cnx.do_handshake()284 except OpenSSL.SSL.WantReadError:302- select.select([sock], [], [])285+ rd, _, _ = select.select([sock], [], [], sock.gettimeout())286+ if not rd:287+ raise timeout('select timed out')288 continue289 except OpenSSL.SSL.Error as e:290 raise ssl.SSLError('bad handshake', e)291 break2 unmodified linesmodified:requests/packages/urllib3/util/ssl_.py+26 added-12 removed
7 unmodified lines8 HAS_SNI = False9 create_default_context = None10 11 import errno12-import ssl12 import warnings13 14 try: # Test for SSL features15+ import ssl16 from ssl import wrap_socket, CERT_NONE, PROTOCOL_SSLv2317 from ssl import HAS_SNI # Has SNI?18 except ImportError:19 pass4 unmodified lines24 except ImportError:25 OP_NO_SSLv2, OP_NO_SSLv3 = 0x1000000, 0x200000026 OP_NO_COMPRESSION = 0x2000027 28+# A secure default.29+# Sources for more information on TLS ciphers:30+#31+# - https://wiki.mozilla.org/Security/Server_Side_TLS32+# - https://www.ssllabs.com/projects/best-practices/index.html33+# - https://hynek.me/articles/hardening-your-web-servers-ssl-ciphers/34+#35+# The general intent is:36+# - Prefer cipher suites that offer perfect forward secrecy (DHE/ECDHE),37+# - prefer ECDHE over DHE for better performance,28-try:29- from ssl import _DEFAULT_CIPHERS30-except ImportError:31- _DEFAULT_CIPHERS = (32- 'ECDH+AESGCM:DH+AESGCM:ECDH+AES256:DH+AES256:ECDH+AES128:DH+AES:ECDH+HIGH:'33- 'DH+HIGH:ECDH+3DES:DH+3DES:RSA+AESGCM:RSA+AES:RSA+HIGH:RSA+3DES:!aNULL:'34- '!eNULL:!MD5'35- )38+# - prefer any AES-GCM over any AES-CBC for better performance and security,39+# - use 3DES as fallback which is secure but slow,40+# - disable NULL authentication, MD5 MACs and DSS for security reasons.41+DEFAULT_CIPHERS = (42+ 'ECDH+AESGCM:DH+AESGCM:ECDH+AES256:DH+AES256:ECDH+AES128:DH+AES:ECDH+HIGH:'43+ 'DH+HIGH:ECDH+3DES:DH+3DES:RSA+AESGCM:RSA+AES:RSA+HIGH:RSA+3DES:!aNULL:'44+ '!eNULL:!MD5'45+)46 47 try:48 from ssl import SSLContext # Modern SSL?49 except ImportError:50 import sys51 52 class SSLContext(object): # Platform-specific: Python 2 & 3.143- supports_set_ciphers = sys.version_info >= (2, 7)53+ supports_set_ciphers = ((2, 7) <= sys.version_info < (3,) or54+ (3, 2) <= sys.version_info)55 56 def __init__(self, protocol_version):57 self.protocol = protocol_version58 # Use default values from a real SSLContext118 unmodified lines177 178 return candidate179 180 170-def create_urllib3_context(ssl_version=None, cert_reqs=ssl.CERT_REQUIRED,181+def create_urllib3_context(ssl_version=None, cert_reqs=None,182 options=None, ciphers=None):183 """All arguments have the same meaning as ``ssl_wrap_socket``.184 185 By default, this function does a lot of the same work that28 unmodified lines214 :rtype: SSLContext215 """216 context = SSLContext(ssl_version or ssl.PROTOCOL_SSLv23)217 218+ # Setting the default here, as we may have no ssl module on import219+ cert_reqs = ssl.CERT_REQUIRED if cert_reqs is None else cert_reqs220+221 if options is None:222 options = 0223 # SSLv2 is easily broken and is considered harmful and dangerous224 options |= OP_NO_SSLv25 unmodified lines230 231 context.options |= options232 233 if getattr(context, 'supports_set_ciphers', True): # Platform-specific: Python 2.6220- context.set_ciphers(ciphers or _DEFAULT_CIPHERS)234+ context.set_ciphers(ciphers or DEFAULT_CIPHERS)235 236 context.verify_mode = cert_reqs237 if getattr(context, 'check_hostname', None) is not None: # Platform-specific: Python 3.2238 # We do our own verification, including fingerprints and alternative42 unmodified linesmodified:requests/packages/urllib3/__init__.py+4 added-2 removed
2 unmodified lines3 """4 5 __author__ = 'Andrey Petrov (andrey.petrov@shazow.net)'6 __license__ = 'MIT'7-__version__ = '1.10.2'7+__version__ = '1.10.3'8 9 10 from .connectionpool import (11 HTTPConnectionPool,42 unmodified lines54 # ... Clean up.55 del NullHandler56 57 58-# Set security warning to always go off by default.58 import warnings59+# SecurityWarning's always go off by default.60 warnings.simplefilter('always', exceptions.SecurityWarning)61+# InsecurePlatformWarning's don't vary between requests, so we keep it default.62+warnings.simplefilter('default', exceptions.InsecurePlatformWarning)63 64 def disable_warnings(category=exceptions.HTTPWarning):65 """66 Helper for quickly disabling all urllib3 warnings.2 unmodified linesmodified:requests/packages/urllib3/_collections.py+24 added-21 removed
225 unmodified lines226 # vals should be a tuple then, i.e. only one item so far227 # Need to convert the tuple to list for further extension228 _dict_setitem(self, key_lower, [vals[0], vals[1], val])229 230- def extend(*args, **kwargs):230+ def extend(self, *args, **kwargs):231 """Generic import function for any type of header-like object.232 Adapted version of MutableMapping.update in order to insert items233 with self.add instead of self.__setitem__234 """235- if len(args) > 2:236- raise TypeError("update() takes at most 2 positional "235+ if len(args) > 1:236+ raise TypeError("extend() takes at most 1 positional "237 "arguments ({} given)".format(len(args)))238- elif not args:239- raise TypeError("update() takes at least 1 argument (0 given)")240- self = args[0]241- other = args[1] if len(args) >= 2 else ()238+ other = args[0] if len(args) >= 1 else ()239 243- if isinstance(other, Mapping):240+ if isinstance(other, HTTPHeaderDict):241+ for key, val in other.iteritems():242+ self.add(key, val)243+ elif isinstance(other, Mapping):244 for key in other:245 self.add(key, other[key])246 elif hasattr(other, "keys"):247 for key in other.keys():55 unmodified lines303 def items(self):304 return list(self.iteritems())305 306 @classmethod307- def from_httplib(cls, message, duplicates=('set-cookie',)): # Python 2307+ def from_httplib(cls, message): # Python 2308 """Read headers from a Python 2 httplib message object."""309- ret = cls(message.items())310- # ret now contains only the last header line for each duplicate.311- # Importing with all duplicates would be nice, but this would312- # mean to repeat most of the raw parsing already done, when the313- # message object was created. Extracting only the headers of interest 314- # separately, the cookies, should be faster and requires less315- # extra code.316- for key in duplicates:317- ret.discard(key)318- for val in message.getheaders(key):319- ret.add(key, val)320- return ret309+ # python2.7 does not expose a proper API for exporting multiheaders310+ # efficiently. This function re-reads raw lines from the message 311+ # object and extracts the multiheaders properly.312+ headers = []313+ 314+ for line in message.headers:315+ if line.startswith((' ', '\t')):316+ key, value = headers[-1]317+ headers[-1] = (key, value + '\r\n' + line.rstrip())318+ continue319+ 320+ key, value = line.split(':', 1)321+ headers.append((key, value.strip()))322+323+ return cls(headers)modified:requests/packages/urllib3/connection.py+2 added
258 unmodified lines259 if ssl:260 # Make a copy for testing.261 UnverifiedHTTPSConnection = HTTPSConnection262 HTTPSConnection = VerifiedHTTPSConnection263+else:264+ HTTPSConnection = DummyConnectionmodified:requests/packages/urllib3/connectionpool.py-1 removed
733 unmodified lines734 log.info("Starting new HTTPS connection (%d): %s"735 % (self.num_connections, self.host))736 737 if not self.ConnectionCls or self.ConnectionCls is DummyConnection:738- # Platform-specific: Python without ssl738 raise SSLError("Can't connect to HTTPS URL because the SSL "739 "module is not available.")740 741 actual_host = self.host54 unmodified linesmodified:requests/packages/urllib3/exceptions.py+5 added
160 unmodified lines161 162 class InsecurePlatformWarning(SecurityWarning):163 "Warned when certain SSL configuration is not available on a platform."164 pass165+166+167+class ResponseNotChunked(ProtocolError, ValueError):168+ "Response needs to be chunked in order to read it as chunks."169+ passmodified:requests/packages/urllib3/response.py+82 added-7 removed
1+try:2+ import http.client as httplib3+except ImportError:4+ import httplib5 import zlib6 import io7 from socket import timeout as SocketTimeout8 9 from ._collections import HTTPHeaderDict6-from .exceptions import ProtocolError, DecodeError, ReadTimeoutError10+from .exceptions import (11+ ProtocolError, DecodeError, ReadTimeoutError, ResponseNotChunked12+)13 from .packages.six import string_types as basestring, binary_type, PY314 from .connection import HTTPException, BaseSSLError15 from .util.response import is_fp_closed16 105 unmodified lines122 123 if hasattr(body, 'read'):124 self._fp = body125 120- if preload_content and not self._body:121- self._body = self.read(decode_content=decode_content)126+ # Are we using the chunked-style of transfer encoding?127+ self.chunked = False128+ self.chunk_left = None129+ tr_enc = self.headers.get('transfer-encoding', '')130+ if tr_enc.lower() == "chunked":131+ self.chunked = True132 133+ # We certainly don't want to preload content when the response is chunked.134+ if not self.chunked:135+ if preload_content and not self._body:136+ self._body = self.read(decode_content=decode_content)137+138 def get_redirect_location(self):139 """140 Should we redirect and where to?141 141 unmodified lines283 :param decode_content:284 If True, will attempt to decode the body based on the285 'content-encoding' header.286 """287+ if self.chunked:288+ for line in self.read_chunked(amt):289+ yield line290+ else:272- while not is_fp_closed(self._fp):273- data = self.read(amt=amt, decode_content=decode_content)291+ while not is_fp_closed(self._fp):292+ data = self.read(amt=amt, decode_content=decode_content)293 275- if data:276- yield data294+ if data:295+ yield data296 297 @classmethod298 def from_httplib(ResponseCls, r, **response_kw):299 """69 unmodified lines369 return 0370 else:371 b[:len(temp)] = temp372 return len(temp)373+374+ def read_chunked(self, amt=None):375+ # FIXME: Rewrite this method and make it a class with376+ # a better structured logic.377+ if not self.chunked:378+ raise ResponseNotChunked("Response is not chunked. "379+ "Header 'transfer-encoding: chunked' is missing.")380+ while True:381+ # First, we'll figure out length of a chunk and then382+ # we'll try to read it from socket.383+ if self.chunk_left is None:384+ line = self._fp.fp.readline()385+ line = line.decode()386+ # See RFC 7230: Chunked Transfer Coding.387+ i = line.find(';')388+ if i >= 0:389+ line = line[:i] # Strip chunk-extensions.390+ try:391+ self.chunk_left = int(line, 16)392+ except ValueError:393+ # Invalid chunked protocol response, abort.394+ self.close()395+ raise httplib.IncompleteRead(''.join(line))396+ if self.chunk_left == 0:397+ break398+ if amt is None:399+ chunk = self._fp._safe_read(self.chunk_left)400+ yield chunk401+ self._fp._safe_read(2) # Toss the CRLF at the end of the chunk.402+ self.chunk_left = None403+ elif amt < self.chunk_left:404+ value = self._fp._safe_read(amt)405+ self.chunk_left = self.chunk_left - amt406+ yield value407+ elif amt == self.chunk_left:408+ value = self._fp._safe_read(amt)409+ self._fp._safe_read(2) # Toss the CRLF at the end of the chunk.410+ self.chunk_left = None411+ yield value412+ else: # amt > self.chunk_left413+ yield self._fp._safe_read(self.chunk_left)414+ self._fp._safe_read(2) # Toss the CRLF at the end of the chunk.415+ self.chunk_left = None416+417+ # Chunk content ends with \r\n: discard it.418+ while True:419+ line = self._fp.fp.readline()420+ if not line:421+ # Some sites may not end with '\r\n'.422+ break423+ if line == b'\r\n':424+ break425+426+ # We read everything; close the "file".427+ self.release_conn()428+modified:requests/packages/__init__.py+1 added-105 removed
1-"""2-Copyright (c) Donald Stufft, pip, and individual contributors3-4-Permission is hereby granted, free of charge, to any person obtaining5-a copy of this software and associated documentation files (the6-"Software"), to deal in the Software without restriction, including7-without limitation the rights to use, copy, modify, merge, publish,8-distribute, sublicense, and/or sell copies of the Software, and to9-permit persons to whom the Software is furnished to do so, subject to10-the following conditions:11-12-The above copyright notice and this permission notice shall be13-included in all copies or substantial portions of the Software.14-15-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,16-EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF17-MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND18-NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE19-LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION20-OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION21-WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.22-"""1 from __future__ import absolute_import2 25-import sys26-27-28-class VendorAlias(object):29-30- def __init__(self, package_names):31- self._package_names = package_names32- self._vendor_name = __name__33- self._vendor_pkg = self._vendor_name + "."34- self._vendor_pkgs = [35- self._vendor_pkg + name for name in self._package_names36- ]37-38- def find_module(self, fullname, path=None):39- if fullname.startswith(self._vendor_pkg):40- return self41-42- def load_module(self, name):43- # Ensure that this only works for the vendored name44- if not name.startswith(self._vendor_pkg):45- raise ImportError(46- "Cannot import %s, must be a subpackage of '%s'." % (47- name, self._vendor_name,48- )49- )50-51- if not (name == self._vendor_name or52- any(name.startswith(pkg) for pkg in self._vendor_pkgs)):53- raise ImportError(54- "Cannot import %s, must be one of %s." % (55- name, self._vendor_pkgs56- )57- )58-59- # Check to see if we already have this item in sys.modules, if we do60- # then simply return that.61- if name in sys.modules:62- return sys.modules[name]63-64- # Check to see if we can import the vendor name65- try:66- # We do this dance here because we want to try and import this67- # module without hitting a recursion error because of a bunch of68- # VendorAlias instances on sys.meta_path69- real_meta_path = sys.meta_path[:]70- try:71- sys.meta_path = [72- m for m in sys.meta_path73- if not isinstance(m, VendorAlias)74- ]75- __import__(name)76- module = sys.modules[name]77- finally:78- # Re-add any additions to sys.meta_path that were made while79- # during the import we just did, otherwise things like80- # requests.packages.urllib3.poolmanager will fail.81- for m in sys.meta_path:82- if m not in real_meta_path:83- real_meta_path.append(m)84-85- # Restore sys.meta_path with any new items.86- sys.meta_path = real_meta_path87- except ImportError:88- # We can't import the vendor name, so we'll try to import the89- # "real" name.90- real_name = name[len(self._vendor_pkg):]91- try:92- __import__(real_name)93- module = sys.modules[real_name]94- except ImportError:95- raise ImportError("No module named '%s'" % (name,))96-97- # If we've gotten here we've found the module we're looking for, either98- # as part of our vendored package, or as the real name, so we'll add99- # it to sys.modules as the vendored name so that we don't have to do100- # the lookup again.101- sys.modules[name] = module102-103- # Finally, return the loaded module104- return module105-106-107-sys.meta_path.insert(0, VendorAlias(["urllib3", "chardet"]))3+from . import urllib3modified:requests/__init__.py+2 added-2 removed
40 unmodified lines41 42 """43 44 __title__ = 'requests'45-__version__ = '2.6.0'46-__build__ = 0x02060045+__version__ = '2.6.1'46+__build__ = 0x02060147 __author__ = 'Kenneth Reitz'48 __license__ = 'Apache 2.0'49 __copyright__ = 'Copyright 2015 Kenneth Reitz'50 27 unmodified linesmodified:HISTORY.rst+22 added
1 unmodified line2 3 Release History4 ---------------5 6+2.6.1 (2015-04-22)7+++++++++++++++++++8+9+**Bugfixes**10+11+- Remove VendorAlias import machinery introduced in v2.5.2.12+13+- Simplify the PreparedRequest.prepare API: We no longer require the user to14+ pass an empty list to the hooks keyword argument. (c.f. #2552)15+16+- Resolve redirects now receives and forwards all of the original arguments to17+ the adapter. (#2503)18+19+- Handle UnicodeDecodeErrors when trying to deal with a unicode URL that20+ cannot be encoded in ASCII. (#2540)21+22+- Populate the parsed path of the URI field when performing Digest23+ Authentication. (#2426)24+25+- Copy a PreparedRequest's CookieJar more reliably when it is not an instance26+ of RequestsCookieJar. (#2527)27+28 2.6.0 (2015-03-14)29 ++++++++++++++++++30 31 **Bugfixes**980 unmodified lines