updatee chardet, urllib3
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Kenneth Reitz · committed by Kenneth Reitz · parent 53d0238 · Browse files · 17 files·+392 added−137 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
17 files+392 added−137 removed
- other:+392 added−137 removed
Provenance
- Commit
7aa6c62- Tree
48c0c30- Author
Kenneth Reitz <me@kennethreitz.com>- Committer
Kenneth Reitz <me@kennethreitz.com>- Parent
53d0238
17 files changed+392 added−137 removed
modified:requests/packages/chardet/__init__.py+1 added-1 removed
13 unmodified lines14 # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA15 # 02110-1301 USA16 ######################### END LICENSE BLOCK #########################17 18-__version__ = "2.2.1"18+__version__ = "2.3.0"19 from sys import version_info20 21 22 def detect(aBuf):10 unmodified linesmodified:requests/packages/chardet/chardetect.py+49 added-15 removed
10 unmodified lines11 12 If no paths are provided, it takes its input from stdin.13 14 """15+16+from __future__ import absolute_import, print_function, unicode_literals17+18+import argparse19+import sys20 from io import open16-from sys import argv, stdin21 22+from chardet import __version__23 from chardet.universaldetector import UniversalDetector24 25 21-def description_of(file, name='stdin'):22- """Return a string describing the probable encoding of a file."""26+def description_of(lines, name='stdin'):27+ """28+ Return a string describing the probable encoding of a file or29+ list of strings.30+31+ :param lines: The lines to get the encoding of.32+ :type lines: Iterable of bytes33+ :param name: Name of file or collection of lines34+ :type name: str35+ """36 u = UniversalDetector()24- for line in file:37+ for line in lines:38 u.feed(line)39 u.close()40 result = u.result41 if result['encoding']:29- return '%s: %s with confidence %s' % (name,30- result['encoding'],31- result['confidence'])42+ return '{0}: {1} with confidence {2}'.format(name, result['encoding'],43+ result['confidence'])44 else:33- return '%s: no result' % name45+ return '{0}: no result'.format(name)46 47 36-def main():37- if len(argv) <= 1:38- print(description_of(stdin))39- else:40- for path in argv[1:]:41- with open(path, 'rb') as f:42- print(description_of(f, path))48+def main(argv=None):49+ '''50+ Handles command line arguments and gets things started.51 52+ :param argv: List of arguments, as if specified on the command-line.53+ If None, ``sys.argv[1:]`` is used instead.54+ :type argv: list of str55+ '''56+ # Get command line arguments57+ parser = argparse.ArgumentParser(58+ description="Takes one or more file paths and reports their detected \59+ encodings",60+ formatter_class=argparse.ArgumentDefaultsHelpFormatter,61+ conflict_handler='resolve')62+ parser.add_argument('input',63+ help='File whose encoding we would like to determine.',64+ type=argparse.FileType('rb'), nargs='*',65+ default=[sys.stdin])66+ parser.add_argument('--version', action='version',67+ version='%(prog)s {0}'.format(__version__))68+ args = parser.parse_args(argv)69 70+ for f in args.input:71+ if f.isatty():72+ print("You are running chardetect interactively. Press " +73+ "CTRL-D twice at the start of a blank line to signal the " +74+ "end of your input. If you want help, run chardetect " +75+ "--help\n", file=sys.stderr)76+ print(description_of(f, f.name))77+78+79 if __name__ == '__main__':80 main()modified:requests/packages/chardet/jpcntx.py+8 added
175 unmodified lines176 def get_order(self, aBuf):177 return -1, 1178 179 class SJISContextAnalysis(JapaneseContextAnalysis):180+ def __init__(self):181+ self.charset_name = "SHIFT_JIS"182+183+ def get_charset_name(self):184+ return self.charset_name185+186 def get_order(self, aBuf):187 if not aBuf:188 return -1, 1189 # find out current char's byte length190 first_char = wrap_ord(aBuf[0])191 if ((0x81 <= first_char <= 0x9F) or (0xE0 <= first_char <= 0xFC)):192 charLen = 2193+ if (first_char == 0x87) or (0xFA <= first_char <= 0xFC):194+ self.charset_name = "CP932"195 else:196 charLen = 1197 198 # return its order if it is hiragana29 unmodified linesmodified:requests/packages/chardet/latin1prober.py+3 added-3 removed
127 unmodified lines128 total = sum(self._mFreqCounter)129 if total < 0.01:130 confidence = 0.0131 else:132- confidence = ((self._mFreqCounter[3] / total)133- - (self._mFreqCounter[1] * 20.0 / total))132+ confidence = ((self._mFreqCounter[3] - self._mFreqCounter[1] * 20.0)133+ / total)134 if confidence < 0.0:135 confidence = 0.0136 # lower the confidence of latin1 so that other more accurate137 # detector can take priority.138- confidence = confidence * 0.5138+ confidence = confidence * 0.73139 return confidencemodified:requests/packages/chardet/mbcssm.py+3 added-6 removed
351 unmodified lines352 2,2,2,2,2,2,2,2, # 60 - 67353 2,2,2,2,2,2,2,2, # 68 - 6f354 2,2,2,2,2,2,2,2, # 70 - 77355 2,2,2,2,2,2,2,1, # 78 - 7f356- 3,3,3,3,3,3,3,3, # 80 - 87356+ 3,3,3,3,3,2,2,3, # 80 - 87357 3,3,3,3,3,3,3,3, # 88 - 8f358 3,3,3,3,3,3,3,3, # 90 - 97359 3,3,3,3,3,3,3,3, # 98 - 9f360 #0xa0 is illegal in sjis encoding, but some pages does7 unmodified lines368 2,2,2,2,2,2,2,2, # d0 - d7369 2,2,2,2,2,2,2,2, # d8 - df370 3,3,3,3,3,3,3,3, # e0 - e7371 3,3,3,3,3,4,4,4, # e8 - ef372- 4,4,4,4,4,4,4,4, # f0 - f7373- 4,4,4,4,4,0,0,0 # f8 - ff374-)372+ 3,3,3,3,3,3,3,3, # f0 - f7373+ 3,3,3,3,3,0,0,0) # f8 - ff374 375 376 SJIS_st = (377 eError,eStart,eStart, 3,eError,eError,eError,eError,#00-07191 unmodified lines569 'classFactor': 16,570 'stateTable': UTF8_st,571 'charLenTable': UTF8CharLenTable,572 'name': 'UTF-8'}574-575-# flake8: noqamodified:requests/packages/chardet/sjisprober.py+1 added-1 removed
45 unmodified lines46 MultiByteCharSetProber.reset(self)47 self._mContextAnalyzer.reset()48 49 def get_charset_name(self):50- return "SHIFT_JIS"50+ return self._mContextAnalyzer.get_charset_name()51 52 def feed(self, aBuf):53 aLen = len(aBuf)54 for i in range(0, aLen):37 unmodified linesmodified:requests/packages/chardet/universaldetector.py+2 added-2 removed
69 unmodified lines70 return71 72 if not self._mGotData:73 # If the data starts with BOM, we know it is UTF74- if aBuf[:3] == codecs.BOM:74+ if aBuf[:3] == codecs.BOM_UTF8:75 # EF BB BF UTF-8 with BOM76- self.result = {'encoding': "UTF-8", 'confidence': 1.0}76+ self.result = {'encoding': "UTF-8-SIG", 'confidence': 1.0}77 elif aBuf[:4] == codecs.BOM_UTF32_LE:78 # FF FE 00 00 UTF-32, little-endian BOM79 self.result = {'encoding': "UTF-32LE", 'confidence': 1.0}80 elif aBuf[:4] == codecs.BOM_UTF32_BE:90 unmodified linesmodified:requests/packages/urllib3/contrib/pyopenssl.py+22 added-3 removed
27 unmodified lines28 Now you can use :mod:`urllib3` as you normally would, and it will support SNI29 when the required modules are installed.30 31 Activating this module also has the positive side effect of disabling SSL/TLS32-encryption in Python 2 (see `CRIME attack`_).32+compression in Python 2 (see `CRIME attack`_).33 34 If you want to configure the default list of supported cipher suites, you can35 set the ``urllib3.contrib.pyopenssl.DEFAULT_SSL_CIPHER_LIST`` variable.36 32 unmodified lines69 70 # Map from urllib3 to PyOpenSSL compatible parameter-values.71 _openssl_versions = {72 ssl.PROTOCOL_SSLv23: OpenSSL.SSL.SSLv23_METHOD,73- ssl.PROTOCOL_SSLv3: OpenSSL.SSL.SSLv3_METHOD,73 ssl.PROTOCOL_TLSv1: OpenSSL.SSL.TLSv1_METHOD,74 }75+76+try:77+ _openssl_versions.update({ssl.PROTOCOL_SSLv3: OpenSSL.SSL.SSLv3_METHOD})78+except AttributeError:79+ pass80+81 _openssl_verify = {82 ssl.CERT_NONE: OpenSSL.SSL.VERIFY_NONE,83 ssl.CERT_OPTIONAL: OpenSSL.SSL.VERIFY_PEER,84 ssl.CERT_REQUIRED: OpenSSL.SSL.VERIFY_PEER118 unmodified lines203 204 def settimeout(self, timeout):205 return self.socket.settimeout(timeout)206 207+ def _send_until_done(self, data):208+ while True:209+ try:210+ return self.connection.send(data)211+ except OpenSSL.SSL.WantWriteError:212+ _, wlist, _ = select.select([], [self.socket], [],213+ self.socket.gettimeout())214+ if not wlist:215+ raise timeout()216+ continue217+218 def sendall(self, data):203- return self.connection.sendall(data)219+ while len(data):220+ sent = self._send_until_done(data)221+ data = data[sent:]222 223 def close(self):224 if self._makefile_refs < 1:225 return self.connection.shutdown()39 unmodified lines265 ca_certs=None, server_hostname=None,266 ssl_version=None):267 ctx = OpenSSL.SSL.Context(_openssl_versions[ssl_version])268 if certfile:269+ keyfile = keyfile or certfile # Match behaviour of the normal python ssl library270 ctx.use_certificate_file(certfile)271 if keyfile:272 ctx.use_privatekey_file(keyfile)273 if cert_reqs != ssl.CERT_NONE:30 unmodified linesmodified:requests/packages/urllib3/util/retry.py+15 added-9 removed
1 import time2 import logging3 4 from ..exceptions import (5- ProtocolError,5 ConnectTimeoutError,7- ReadTimeoutError,6 MaxRetryError,7+ ProtocolError,8+ ReadTimeoutError,9+ ResponseError,10 )11 from ..packages import six12 13 22 unmodified lines36 37 Errors will be wrapped in :class:`~urllib3.exceptions.MaxRetryError` unless38 retries are disabled, in which case the causing exception will be raised.39 39-40 :param int total:41 Total number of retries to allow. Takes precedence over other counts.42 43 Set to ``None`` to remove this constraint and fall back on other139 unmodified lines183 """184 return isinstance(err, ConnectTimeoutError)185 186 def _is_read_error(self, err):187- """ Errors that occur after the request has been started, so we can't188- assume that the server did not process any of it.187+ """ Errors that occur after the request has been started, so we should188+ assume that the server began processing it.189 """190 return isinstance(err, (ReadTimeoutError, ProtocolError))191 192 def is_forced_retry(self, method, status_code):4 unmodified lines197 198 return self.status_forcelist and status_code in self.status_forcelist199 200 def is_exhausted(self):201- """ Are we out of retries?202- """201+ """ Are we out of retries? """202 retry_counts = (self.total, self.connect, self.read, self.redirect)203 retry_counts = list(filter(None, retry_counts))204 if not retry_counts:205 return False22 unmodified lines228 _observed_errors = self._observed_errors229 connect = self.connect230 read = self.read231 redirect = self.redirect232+ cause = 'unknown'233 234 if error and self._is_connection_error(error):235 # Connect retry?236 if connect is False:13 unmodified lines250 elif response and response.get_redirect_location():251 # Redirect retry?252 if redirect is not None:253 redirect -= 1254+ cause = 'too many redirects'255 256 else:256- # FIXME: Nothing changed, scenario doesn't make sense.257+ # Incrementing because of a server error like a 500 in258+ # status_forcelist and a the given method is in the whitelist259 _observed_errors += 1260+ cause = ResponseError.GENERIC_ERROR261+ if response and response.status:262+ cause = ResponseError.SPECIFIC_ERROR.format(263+ status_code=response.status)264 265 new_retry = self.new(266 total=total,267 connect=connect, read=read, redirect=redirect,268 _observed_errors=_observed_errors)269 270 if new_retry.is_exhausted():265- raise MaxRetryError(_pool, url, error)271+ raise MaxRetryError(_pool, url, error or ResponseError(cause))272 273 log.debug("Incremented Retry for (url='%s'): %r" % (url, new_retry))274 275 return new_retry10 unmodified linesmodified:requests/packages/urllib3/util/ssl_.py+162 added-40 removed
2 unmodified lines3 4 from ..exceptions import SSLError5 6 7-try: # Test for SSL features8- SSLContext = None9- HAS_SNI = False7+SSLContext = None8+HAS_SNI = False9+create_default_context = None10 11- import ssl11+import errno12+import ssl13+14+try: # Test for SSL features15 from ssl import wrap_socket, CERT_NONE, PROTOCOL_SSLv2313- from ssl import SSLContext # Modern SSL?16 from ssl import HAS_SNI # Has SNI?17 except ImportError:18 pass19 20 21+try:22+ from ssl import OP_NO_SSLv2, OP_NO_SSLv3, OP_NO_COMPRESSION23+except ImportError:24+ OP_NO_SSLv2, OP_NO_SSLv3 = 0x1000000, 0x200000025+ OP_NO_COMPRESSION = 0x2000026+27+try:28+ from ssl import _DEFAULT_CIPHERS29+except ImportError:30+ _DEFAULT_CIPHERS = (31+ 'ECDH+AESGCM:DH+AESGCM:ECDH+AES256:DH+AES256:ECDH+AES128:DH+AES:ECDH+HIGH:'32+ 'DH+HIGH:ECDH+3DES:DH+3DES:RSA+AESGCM:RSA+AES:RSA+HIGH:RSA+3DES:ECDH+RC4:'33+ 'DH+RC4:RSA+RC4:!aNULL:!eNULL:!MD5'34+ )35+36+try:37+ from ssl import SSLContext # Modern SSL?38+except ImportError:39+ import sys40+41+ class SSLContext(object): # Platform-specific: Python 2 & 3.142+ supports_set_ciphers = sys.version_info >= (2, 7)43+44+ def __init__(self, protocol_version):45+ self.protocol = protocol_version46+ # Use default values from a real SSLContext47+ self.check_hostname = False48+ self.verify_mode = ssl.CERT_NONE49+ self.ca_certs = None50+ self.options = 051+ self.certfile = None52+ self.keyfile = None53+ self.ciphers = None54+55+ def load_cert_chain(self, certfile, keyfile):56+ self.certfile = certfile57+ self.keyfile = keyfile58+59+ def load_verify_locations(self, location):60+ self.ca_certs = location61+62+ def set_ciphers(self, cipher_suite):63+ if not self.supports_set_ciphers:64+ raise TypeError(65+ 'Your version of Python does not support setting '66+ 'a custom cipher suite. Please upgrade to Python '67+ '2.7, 3.2, or later if you need this functionality.'68+ )69+ self.ciphers = cipher_suite70+71+ def wrap_socket(self, socket, server_hostname=None):72+ kwargs = {73+ 'keyfile': self.keyfile,74+ 'certfile': self.certfile,75+ 'ca_certs': self.ca_certs,76+ 'cert_reqs': self.verify_mode,77+ 'ssl_version': self.protocol,78+ }79+ if self.supports_set_ciphers: # Platform-specific: Python 2.7+80+ return wrap_socket(socket, ciphers=self.ciphers, **kwargs)81+ else: # Platform-specific: Python 2.682+ return wrap_socket(socket, **kwargs)83+84+85 def assert_fingerprint(cert, fingerprint):86 """87 Checks if given fingerprint matches the supplied certificate.88 67 unmodified lines156 157 return candidate158 159 94-if SSLContext is not None: # Python 3.2+95- def ssl_wrap_socket(sock, keyfile=None, certfile=None, cert_reqs=None,96- ca_certs=None, server_hostname=None,97- ssl_version=None):98- """99- All arguments except `server_hostname` have the same meaning as for100- :func:`ssl.wrap_socket`160+def create_urllib3_context(ssl_version=None, cert_reqs=ssl.CERT_REQUIRED,161+ options=None, ciphers=None):162+ """All arguments have the same meaning as ``ssl_wrap_socket``.163 102- :param server_hostname:103- Hostname of the expected certificate104- """105- context = SSLContext(ssl_version)106- context.verify_mode = cert_reqs164+ By default, this function does a lot of the same work that165+ ``ssl.create_default_context`` does on Python 3.4+. It:166 108- # Disable TLS compression to migitate CRIME attack (issue #309)109- OP_NO_COMPRESSION = 0x20000110- context.options |= OP_NO_COMPRESSION167+ - Disables SSLv2, SSLv3, and compression168+ - Sets a restricted set of server ciphers169 112- if ca_certs:113- try:114- context.load_verify_locations(ca_certs)115- # Py32 raises IOError116- # Py33 raises FileNotFoundError117- except Exception as e: # Reraise as SSLError118- raise SSLError(e)119- if certfile:120- # FIXME: This block needs a test.121- context.load_cert_chain(certfile, keyfile)122- if HAS_SNI: # Platform-specific: OpenSSL with enabled SNI123- return context.wrap_socket(sock, server_hostname=server_hostname)124- return context.wrap_socket(sock)170+ If you wish to enable SSLv3, you can do::171 126-else: # Python 3.1 and earlier127- def ssl_wrap_socket(sock, keyfile=None, certfile=None, cert_reqs=None,128- ca_certs=None, server_hostname=None,129- ssl_version=None):130- return wrap_socket(sock, keyfile=keyfile, certfile=certfile,131- ca_certs=ca_certs, cert_reqs=cert_reqs,132- ssl_version=ssl_version)172+ from urllib3.util import ssl_173+ context = ssl_.create_urllib3_context()174+ context.options &= ~ssl_.OP_NO_SSLv3175+176+ You can do the same to enable compression (substituting ``COMPRESSION``177+ for ``SSLv3`` in the last line above).178+179+ :param ssl_version:180+ The desired protocol version to use. This will default to181+ PROTOCOL_SSLv23 which will negotiate the highest protocol that both182+ the server and your installation of OpenSSL support.183+ :param cert_reqs:184+ Whether to require the certificate verification. This defaults to185+ ``ssl.CERT_REQUIRED``.186+ :param options:187+ Specific OpenSSL options. These default to ``ssl.OP_NO_SSLv2``,188+ ``ssl.OP_NO_SSLv3``, ``ssl.OP_NO_COMPRESSION``.189+ :param ciphers:190+ Which cipher suites to allow the server to select.191+ :returns:192+ Constructed SSLContext object with specified options193+ :rtype: SSLContext194+ """195+ context = SSLContext(ssl_version or ssl.PROTOCOL_SSLv23)196+197+ if options is None:198+ options = 0199+ # SSLv2 is easily broken and is considered harmful and dangerous200+ options |= OP_NO_SSLv2201+ # SSLv3 has several problems and is now dangerous202+ options |= OP_NO_SSLv3203+ # Disable compression to prevent CRIME attacks for OpenSSL 1.0+204+ # (issue #309)205+ options |= OP_NO_COMPRESSION206+207+ context.options |= options208+209+ if getattr(context, 'supports_set_ciphers', True): # Platform-specific: Python 2.6210+ context.set_ciphers(ciphers or _DEFAULT_CIPHERS)211+212+ context.verify_mode = cert_reqs213+ if getattr(context, 'check_hostname', None) is not None: # Platform-specific: Python 3.2214+ context.check_hostname = (context.verify_mode == ssl.CERT_REQUIRED)215+ return context216+217+218+def ssl_wrap_socket(sock, keyfile=None, certfile=None, cert_reqs=None,219+ ca_certs=None, server_hostname=None,220+ ssl_version=None, ciphers=None, ssl_context=None):221+ """222+ All arguments except for server_hostname and ssl_context have the same223+ meaning as they do when using :func:`ssl.wrap_socket`.224+225+ :param server_hostname:226+ When SNI is supported, the expected hostname of the certificate227+ :param ssl_context:228+ A pre-made :class:`SSLContext` object. If none is provided, one will229+ be created using :func:`create_urllib3_context`.230+ :param ciphers:231+ A string of ciphers we wish the client to support. This is not232+ supported on Python 2.6 as the ssl module does not support it.233+ """234+ context = ssl_context235+ if context is None:236+ context = create_urllib3_context(ssl_version, cert_reqs,237+ ciphers=ciphers)238+239+ if ca_certs:240+ try:241+ context.load_verify_locations(ca_certs)242+ except IOError as e: # Platform-specific: Python 2.6, 2.7, 3.2243+ raise SSLError(e)244+ # Py33 raises FileNotFoundError which subclasses OSError245+ # These are not equivalent unless we check the errno attribute246+ except OSError as e: # Platform-specific: Python 3.3 and beyond247+ if e.errno == errno.ENOENT:248+ raise SSLError(e)249+ raise250+ if certfile:251+ context.load_cert_chain(certfile, keyfile)252+ if HAS_SNI: # Platform-specific: OpenSSL with enabled SNI253+ return context.wrap_socket(sock, server_hostname=server_hostname)254+ return context.wrap_socket(sock)modified:requests/packages/urllib3/util/url.py+43 added-2 removed
38 unmodified lines39 if self.port:40 return '%s:%d' % (self.host, self.port)41 return self.host42 43+ @property44+ def url(self):45+ """46+ Convert self into a url47 48+ This function should more or less round-trip with :func:`.parse_url`. The49+ returned url may not be exactly the same as the url inputted to50+ :func:`.parse_url`, but it should be equivalent by the RFC (e.g., urls51+ with a blank port will have : removed).52+53+ Example: ::54+55+ >>> U = parse_url('http://google.com/mail/')56+ >>> U.url57+ 'http://google.com/mail/'58+ >>> Url('http', 'username:password', 'host.com', 80,59+ ... '/path', 'query', 'fragment').url60+ 'http://username:password@host.com:80/path?query#fragment'61+ """62+ scheme, auth, host, port, path, query, fragment = self63+ url = ''64+65+ # We use "is not None" we want things to happen with empty strings (or 0 port)66+ if scheme is not None:67+ url += scheme + '://'68+ if auth is not None:69+ url += auth + '@'70+ if host is not None:71+ url += host72+ if port is not None:73+ url += ':' + str(port)74+ if path is not None:75+ url += path76+ if query is not None:77+ url += '?' + query78+ if fragment is not None:79+ url += '#' + fragment80+81+ return url82+83+ def __str__(self):84+ return self.url85+86 def split_first(s, delims):87 """88 Given a string and an iterable of delimiters, split on the first found89 delimiter. Return two split parts and the matched delimiter.35 unmodified lines125 126 Example::127 128 >>> parse_url('http://google.com/mail/')87- Url(scheme='http', host='google.com', port=None, path='/', ...)129+ Url(scheme='http', host='google.com', port=None, path='/mail/', ...)130 >>> parse_url('google.com:80')131 Url(scheme=None, host='google.com', port=80, path=None, ...)132 >>> parse_url('/foo?bar')133 Url(scheme=None, host=None, port=None, path='/foo', query='bar', ...)69 unmodified lines203 path, query = path.split('?', 1)204 205 return Url(scheme, auth, host, port, path, query, fragment)206 165-207 def get_host(url):208 """209 Deprecated. Use :func:`.parse_url` instead.210 """2 unmodified linesmodified:requests/packages/urllib3/__init__.py+1 added-1 removed
55 unmodified lines56 57 58 # Set security warning to only go off once by default.59 import warnings60-warnings.simplefilter('module', exceptions.SecurityWarning)60+warnings.simplefilter('always', exceptions.SecurityWarning)61 62 def disable_warnings(category=exceptions.HTTPWarning):63 """64 Helper for quickly disabling all urllib3 warnings.2 unmodified linesmodified:requests/packages/urllib3/_collections.py+3 added-4 removed
12 unmodified lines13 try: # Python 2.7+14 from collections import OrderedDict15 except ImportError:16 from .packages.ordered_dict import OrderedDict17-from .packages.six import itervalues17+from .packages.six import iterkeys, itervalues18 19 20 __all__ = ['RecentlyUsedContainer', 'HTTPHeaderDict']21 62 unmodified lines84 85 def clear(self):86 with self.lock:87 # Copy pointers to all values, then wipe the mapping88- # under Python 2, this copies the list of values twice :-|89- values = list(self._container.values())88+ values = list(itervalues(self._container))89 self._container.clear()90 91 if self.dispose_func:92 for value in values:93 self.dispose_func(value)94 95 def keys(self):96 with self.lock:98- return self._container.keys()97+ return list(iterkeys(self._container))98 99 100 class HTTPHeaderDict(MutableMapping):101 """97 unmodified linesmodified:requests/packages/urllib3/connection.py+20 added-4 removed
1 unmodified line2 import sys3 import socket4 from socket import timeout as SocketTimeout5 import warnings6+from .packages import six7 8 try: # Python 39 from http.client import HTTPConnection as _HTTPConnection, HTTPException10 except ImportError:15 unmodified lines26 class BaseSSLError(BaseException):27 pass28 29 30+try: # Python 3:31+ # Not a no-op, we're adding this to the namespace so it can be imported.32+ ConnectionError = ConnectionError33+except NameError: # Python 2:34+ class ConnectionError(Exception):35+ pass36+37+38 from .exceptions import (39 ConnectTimeoutError,40 SystemTimeWarning,41+ SecurityWarning,42 )43 from .packages.ssl_match_hostname import match_hostname34-from .packages import six44 45 from .util.ssl_ import (46 resolve_cert_reqs,47 resolve_ssl_version,48 ssl_wrap_socket,49 assert_fingerprint,50 )51 52+53 from .util import connection54 45-55 port_by_scheme = {56 'http': 80,57 'https': 443,58 }182 unmodified lines241 assert_fingerprint(self.sock.getpeercert(binary_form=True),242 self.assert_fingerprint)243 elif resolved_cert_reqs != ssl.CERT_NONE \244 and self.assert_hostname is not False:236- match_hostname(self.sock.getpeercert(),237- self.assert_hostname or hostname)245+ cert = self.sock.getpeercert()246+ if not cert.get('subjectAltName', ()):247+ warnings.warn((248+ 'Certificate has no `subjectAltName`, falling back to check for a `commonName` for now. '249+ 'This feature is being removed by major browsers and deprecated by RFC 2818. '250+ '(See https://github.com/shazow/urllib3/issues/497 for details.)'),251+ SecurityWarning252+ )253+ match_hostname(cert, self.assert_hostname or hostname)254 255 self.is_verified = (resolved_cert_reqs == ssl.CERT_REQUIRED256 or self.assert_fingerprint is not None)257 5 unmodified linesmodified:requests/packages/urllib3/connectionpool.py+34 added-30 removed
30 unmodified lines31 from .connection import (32 port_by_scheme,33 DummyConnection,34 HTTPConnection, HTTPSConnection, VerifiedHTTPSConnection,35- HTTPException, BaseSSLError,35+ HTTPException, BaseSSLError, ConnectionError36 )37 from .request import RequestMethods38 from .response import HTTPResponse39 237 unmodified lines277 # User passed us an int/float. This is for backwards compatibility,278 # can be removed later279 return Timeout.from_float(timeout)280 281+ def _raise_timeout(self, err, url, timeout_value):282+ """Is the error actually a timeout? Will raise a ReadTimeout or pass"""283+284+ if isinstance(err, SocketTimeout):285+ raise ReadTimeoutError(self, url, "Read timed out. (read timeout=%s)" % timeout_value)286+287+ # See the above comment about EAGAIN in Python 3. In Python 2 we have288+ # to specifically catch it and throw the timeout error289+ if hasattr(err, 'errno') and err.errno in _blocking_errnos:290+ raise ReadTimeoutError(self, url, "Read timed out. (read timeout=%s)" % timeout_value)291+292+ # Catch possible read timeouts thrown as SSL errors. If not the293+ # case, rethrow the original. We need to do this because of:294+ # http://bugs.python.org/issue10272295+ if 'timed out' in str(err) or 'did not complete (read)' in str(err): # Python 2.6296+ raise ReadTimeoutError(self, url, "Read timed out. (read timeout=%s)" % timeout_value)297+298 def _make_request(self, conn, method, url, timeout=_Default,299 **httplib_request_kw):300 """301 Perform a request on a given urllib connection object taken from our15 unmodified lines317 timeout_obj.start_connect()318 conn.timeout = timeout_obj.connect_timeout319 320 # Trigger any extra validation we need to do.321+ try:304- self._validate_conn(conn)322+ self._validate_conn(conn)323+ except (SocketTimeout, BaseSSLError) as e:324+ # Py2 raises this as a BaseSSLError, Py3 raises it as socket timeout.325+ self._raise_timeout(err=e, url=url, timeout_value=conn.timeout)326+ raise327 328 # conn.request() calls httplib.*.request, not the method in329 # urllib3.request. It also calls makefile (recv) on the socket.330 conn.request(method, url, **httplib_request_kw)21 unmodified lines352 try: # Python 2.7+, use buffering of HTTP responses353 httplib_response = conn.getresponse(buffering=True)354 except TypeError: # Python 2.6 and older355 httplib_response = conn.getresponse()334- except SocketTimeout:335- raise ReadTimeoutError(336- self, url, "Read timed out. (read timeout=%s)" % read_timeout)337-338- except BaseSSLError as e:339- # Catch possible read timeouts thrown as SSL errors. If not the340- # case, rethrow the original. We need to do this because of:341- # http://bugs.python.org/issue10272342- if 'timed out' in str(e) or \343- 'did not complete (read)' in str(e): # Python 2.6344- raise ReadTimeoutError(345- self, url, "Read timed out. (read timeout=%s)" % read_timeout)346-356+ except (SocketTimeout, BaseSSLError, SocketError) as e:357+ self._raise_timeout(err=e, url=url, timeout_value=read_timeout)358 raise359 349- except SocketError as e: # Platform-specific: Python 2350- # See the above comment about EAGAIN in Python 3. In Python 2 we351- # have to specifically catch it and throw the timeout error352- if e.errno in _blocking_errnos:353- raise ReadTimeoutError(354- self, url, "Read timed out. (read timeout=%s)" % read_timeout)355-356- raise357-360 # AppEngine doesn't have a version attr.361 http_version = getattr(conn, '_http_vsn_str', 'HTTP/?')362 log.debug("\"%s %s %s\" %s %s" % (method, url, http_version,363 httplib_response.status,174 unmodified lines538 # Timed out by queue.539 raise EmptyPoolError(self, "No pool connections are available.")540 541 except (BaseSSLError, CertificateError) as e:540- # Release connection unconditionally because there is no way to541- # close it externally in case of exception.542- release_conn = True542+ # Close the connection. If a connection is reused on which there543+ # was a Certificate error, the next request will certainly raise544+ # another Certificate error.545+ if conn:546+ conn.close()547+ conn = None548 raise SSLError(e)549 545- except (TimeoutError, HTTPException, SocketError) as e:550+ except (TimeoutError, HTTPException, SocketError, ConnectionError) as e:551 if conn:552 # Discard the connection for these exceptions. It will be553 # be replaced during the next _get_conn() call.554 conn.close()174 unmodified lines729 if not conn.is_verified:730 warnings.warn((731 'Unverified HTTPS request is being made. '732 'Adding certificate verification is strongly advised. See: '728- 'https://urllib3.readthedocs.org/en/latest/security.html '729- '(This warning will only appear once by default.)'),733+ 'https://urllib3.readthedocs.org/en/latest/security.html'),734 InsecureRequestWarning)735 736 737 def connection_from_url(url, **kw):24 unmodified linesmodified:requests/packages/urllib3/exceptions.py+8 added-5 removed
70 unmodified lines71 72 def __init__(self, pool, url, reason=None):73 self.reason = reason74 75- message = "Max retries exceeded with url: %s" % url76- if reason:77- message += " (Caused by %r)" % reason78- else:79- message += " (Caused by redirect)"75+ message = "Max retries exceeded with url: %s (Caused by %r)" % (76+ url, reason)77 78 RequestError.__init__(self, pool, url, message)79 80 56 unmodified lines137 138 self.location = location139 140 141+class ResponseError(HTTPError):142+ "Used as a container for an error reason supplied in a MaxRetryError."143+ GENERIC_ERROR = 'too many error responses'144+ SPECIFIC_ERROR = 'too many {status_code} error responses'145+146+147 class SecurityWarning(HTTPWarning):148 "Warned when perfoming security reducing actions"149 pass150 9 unmodified linesmodified:requests/packages/urllib3/request.py+17 added-11 removed
116 unmodified lines117 be overwritten because it depends on the dynamic random boundary string118 which is used to compose the body of the request. The random boundary119 string can be explicitly set with the ``multipart_boundary`` parameter.120 """121- if encode_multipart:122- body, content_type = encode_multipart_formdata(123- fields or {}, boundary=multipart_boundary)124- else:125- body, content_type = (urlencode(fields or {}),126- 'application/x-www-form-urlencoded')127-121 if headers is None:122 headers = self.headers123 131- headers_ = {'Content-Type': content_type}132- headers_.update(headers)124+ extra_kw = {'headers': {}}125 134- return self.urlopen(method, url, body=body, headers=headers_,135- **urlopen_kw)126+ if fields:127+ if 'body' in urlopen_kw:128+ raise TypeError('request got values for both \'fields\' and \'body\', can only specify one.')129+130+ if encode_multipart:131+ body, content_type = encode_multipart_formdata(fields, boundary=multipart_boundary)132+ else:133+ body, content_type = urlencode(fields), 'application/x-www-form-urlencoded'134+135+ extra_kw['body'] = body136+ extra_kw['headers'] = {'Content-Type': content_type}137+138+ extra_kw['headers'].update(headers)139+ extra_kw.update(urlopen_kw)140+141+ return self.urlopen(method, url, **extra_kw)