Update urllib to 1.8 (8a8c601bee)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Stan Hu · committed by Stan Hu · parent 0303e9b · Browse files · 8 files·+227 added−76 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+227 added−76 removed
- other:+227 added−76 removed
Provenance
- Commit
6c83998- Tree
91df41b- Author
Stan Hu <stanhu@gmail.com>- Committer
Stan Hu <stanhu@gmail.com>- Parent
0303e9b
8 files changed+227 added−76 removed
modified:requests/packages/urllib3/contrib/pyopenssl.py+34 added-11 removed
27 unmodified lines28 Module Variables29 ----------------30 31 :var DEFAULT_SSL_CIPHER_LIST: The list of supported SSL/TLS cipher suites.32- Default: ``EECDH+ECDSA+AESGCM EECDH+aRSA+AESGCM EECDH+ECDSA+SHA25633- EECDH+aRSA+SHA256 EECDH+aRSA+RC4 EDH+aRSA EECDH RC4 !aNULL !eNULL !LOW !3DES34- !MD5 !EXP !PSK !SRP !DSS'``32+ Default: ``ECDH+AESGCM:DH+AESGCM:ECDH+AES256:DH+AES256:ECDH+AES128:DH+AES:33+ ECDH+3DES:DH+3DES:RSA+AESGCM:RSA+AES:RSA+3DES:!aNULL:!MD5:!DSS``34 35 .. _sni: https://en.wikipedia.org/wiki/Server_Name_Indication36 .. _crime attack: https://en.wikipedia.org/wiki/CRIME_(security_exploit)37 3 unmodified lines41 from ndg.httpsclient.subj_alt_name import SubjectAltName as BaseSubjectAltName42 import OpenSSL.SSL43 from pyasn1.codec.der import decoder as der_decoder44 from pyasn1.type import univ, constraint46-from socket import _fileobject45+from socket import _fileobject, timeout46 import ssl47 import select48 from cStringIO import StringIO49 17 unmodified lines67 ssl.CERT_REQUIRED: OpenSSL.SSL.VERIFY_PEER68 + OpenSSL.SSL.VERIFY_FAIL_IF_NO_PEER_CERT,69 }70 72-# Default SSL/TLS cipher list.73-# Recommendation by https://community.qualys.com/blogs/securitylabs/2013/08/05/74-# configuring-apache-nginx-and-openssl-for-forward-secrecy75-DEFAULT_SSL_CIPHER_LIST = 'EECDH+ECDSA+AESGCM EECDH+aRSA+AESGCM ' + \76- 'EECDH+ECDSA+SHA256 EECDH+aRSA+SHA256 EECDH+aRSA+RC4 EDH+aRSA ' + \77- 'EECDH RC4 !aNULL !eNULL !LOW !3DES !MD5 !EXP !PSK !SRP !DSS'71+# A secure default.72+# Sources for more information on TLS ciphers:73+#74+# - https://wiki.mozilla.org/Security/Server_Side_TLS75+# - https://www.ssllabs.com/projects/best-practices/index.html76+# - https://hynek.me/articles/hardening-your-web-servers-ssl-ciphers/77+#78+# The general intent is:79+# - Prefer cipher suites that offer perfect forward secrecy (DHE/ECDHE),80+# - prefer ECDHE over DHE for better performance,81+# - prefer any AES-GCM over any AES-CBC for better performance and security,82+# - use 3DES as fallback which is secure but slow,83+# - disable NULL authentication, MD5 MACs and DSS for security reasons.84+DEFAULT_SSL_CIPHER_LIST = "ECDH+AESGCM:DH+AESGCM:ECDH+AES256:DH+AES256:" + \85+ "ECDH+AES128:DH+AES:ECDH+3DES:DH+3DES:RSA+AESGCM:RSA+AES:RSA+3DES:" + \86+ "!aNULL:!MD5:!DSS"87 88 89 orig_util_HAS_SNI = util.HAS_SNI90 orig_connection_ssl_wrap_socket = connection.ssl_wrap_socket56 unmodified lines147 148 149 class fileobject(_fileobject):150 151+ def _wait_for_sock(self):152+ rd, wd, ed = select.select([self._sock], [], [],153+ self._sock.gettimeout())154+ if not rd:155+ raise timeout()156+157+158 def read(self, size=-1):159 # Use max, disallow tiny reads in a loop as they are very inefficient.160 # We never leave read() with any leftover data from a new recv() call161 # in our internal buffer.9 unmodified lines171 while True:172 try:173 data = self._sock.recv(rbufsize)174 except OpenSSL.SSL.WantReadError:175+ self._wait_for_sock()176 continue177 if not data:178 break179 buf.write(data)19 unmodified lines199 # fragmentation issues on many platforms.200 try:201 data = self._sock.recv(left)202 except OpenSSL.SSL.WantReadError:203+ self._wait_for_sock()204 continue205 if not data:206 break207 n = len(data)43 unmodified lines251 if not data:252 break253 buffers.append(data)254 except OpenSSL.SSL.WantReadError:255+ self._wait_for_sock()256 continue257 break258 return "".join(buffers)259 2 unmodified lines262 while True:263 try:264 data = self._sock.recv(self._rbufsize)265 except OpenSSL.SSL.WantReadError:266+ self._wait_for_sock()267 continue268 if not data:269 break270 nl = data.find('\n')19 unmodified lines290 while True:291 try:292 data = self._sock.recv(self._rbufsize)293 except OpenSSL.SSL.WantReadError:294+ self._wait_for_sock()274- continue295+ continue296 if not data:297 break298 left = size - buf_len299 # did we just receive a newline?86 unmodified lines386 try:387 ctx.load_verify_locations(ca_certs, None)388 except OpenSSL.SSL.Error as e:389 raise ssl.SSLError('bad ca_certs: %r' % ca_certs, e)390+ else:391+ ctx.set_default_verify_paths()392 393 # Disable TLS compression to migitate CRIME attack (issue #309)394 OP_NO_COMPRESSION = 0x20000395 ctx.set_options(OP_NO_COMPRESSION)18 unmodified linesmodified:requests/packages/urllib3/packages/ssl_match_hostname/__init__.py+1 added-1 removed
5 unmodified lines6 # 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_hostname10+ from ._implementation import CertificateError, match_hostname11 12 # Not needed, but documenting what we provide.13 __all__ = ('CertificateError', 'match_hostname')modified:requests/packages/urllib3/__init__.py+1 added-1 removed
8 unmodified lines9 """10 11 __author__ = 'Andrey Petrov (andrey.petrov@shazow.net)'12 __license__ = 'MIT'13-__version__ = 'dev'13+__version__ = '1.8'14 15 16 from .connectionpool import (17 HTTPConnectionPool,41 unmodified linesmodified:requests/packages/urllib3/_collections.py+104 added-2 removed
2 unmodified lines3 #4 # This module is part of urllib3 and is released under5 # the MIT License: http://www.opensource.org/licenses/mit-license.php6 7-from collections import MutableMapping7+from collections import Mapping, MutableMapping8 try:9 from threading import RLock10 except ImportError: # Platform-specific: No threads available11 class RLock:7 unmodified lines19 try: # Python 2.7+20 from collections import OrderedDict21 except ImportError:22 from .packages.ordered_dict import OrderedDict23+from .packages.six import itervalues24 25 25-__all__ = ['RecentlyUsedContainer']26+__all__ = ['RecentlyUsedContainer', 'HTTPHeaderDict']27 28 29 _Null = object()30 70 unmodified lines101 102 def keys(self):103 with self.lock:104 return self._container.keys()105+106+107+class HTTPHeaderDict(MutableMapping):108+ """109+ :param headers:110+ An iterable of field-value pairs. Must not contain multiple field names111+ when compared case-insensitively.112+113+ :param kwargs:114+ Additional field-value pairs to pass in to ``dict.update``.115+116+ A ``dict`` like container for storing HTTP Headers.117+118+ Field names are stored and compared case-insensitively in compliance with119+ RFC 2616. Iteration provides the first case-sensitive key seen for each120+ case-insensitive pair.121+122+ Using ``__setitem__`` syntax overwrites fields that compare equal123+ case-insensitively in order to maintain ``dict``'s api. For fields that124+ compare equal, instead create a new ``HTTPHeaderDict`` and use ``.add``125+ in a loop.126+127+ If multiple fields that are equal case-insensitively are passed to the128+ constructor or ``.update``, the behavior is undefined and some will be129+ lost.130+131+ >>> headers = HTTPHeaderDict()132+ >>> headers.add('Set-Cookie', 'foo=bar')133+ >>> headers.add('set-cookie', 'baz=quxx')134+ >>> headers['content-length'] = '7'135+ >>> headers['SET-cookie']136+ 'foo=bar, baz=quxx'137+ >>> headers['Content-Length']138+ '7'139+140+ If you want to access the raw headers with their original casing141+ for debugging purposes you can access the private ``._data`` attribute142+ which is a normal python ``dict`` that maps the case-insensitive key to a143+ list of tuples stored as (case-sensitive-original-name, value). Using the144+ structure from above as our example:145+146+ >>> headers._data147+ {'set-cookie': [('Set-Cookie', 'foo=bar'), ('set-cookie', 'baz=quxx')],148+ 'content-length': [('content-length', '7')]}149+ """150+151+ def __init__(self, headers=None, **kwargs):152+ self._data = {}153+ if headers is None:154+ headers = {}155+ self.update(headers, **kwargs)156+157+ def add(self, key, value):158+ """Adds a (name, value) pair, doesn't overwrite the value if it already159+ exists.160+161+ >>> headers = HTTPHeaderDict(foo='bar')162+ >>> headers.add('Foo', 'baz')163+ >>> headers['foo']164+ 'bar, baz'165+ """166+ self._data.setdefault(key.lower(), []).append((key, value))167+168+ def getlist(self, key):169+ """Returns a list of all the values for the named field. Returns an170+ empty list if the key doesn't exist."""171+ return self[key].split(', ') if key in self else []172+173+ def copy(self):174+ h = HTTPHeaderDict()175+ for key in self._data:176+ for rawkey, value in self._data[key]:177+ h.add(rawkey, value)178+ return h179+180+ def __eq__(self, other):181+ if not isinstance(other, Mapping):182+ return False183+ other = HTTPHeaderDict(other)184+ return dict((k1, self[k1]) for k1 in self._data) == \185+ dict((k2, other[k2]) for k2 in other._data)186+187+ def __getitem__(self, key):188+ values = self._data[key.lower()]189+ return ', '.join(value[1] for value in values)190+191+ def __setitem__(self, key, value):192+ self._data[key.lower()] = [(key, value)]193+194+ def __delitem__(self, key):195+ del self._data[key.lower()]196+197+ def __len__(self):198+ return len(self._data)199+200+ def __iter__(self):201+ for headers in itervalues(self._data):202+ yield headers[0][0]203+204+ def __repr__(self):205+ return '%s(%r)' % (self.__class__.__name__, dict(self.items()))modified:requests/packages/urllib3/connection.py+32 added-15 removed
2 unmodified lines3 #4 # This module is part of urllib3 and is released under5 # the MIT License: http://www.opensource.org/licenses/mit-license.php6 7+import sys8 import socket9 from socket import timeout as SocketTimeout10 11 try: # Python 326 unmodified lines38 from .exceptions import (39 ConnectTimeoutError,40 )41 from .packages.ssl_match_hostname import match_hostname42+from .packages import six43 from .util import (44 assert_fingerprint,45 resolve_cert_reqs,46 resolve_ssl_version,7 unmodified lines54 }55 56 57 class HTTPConnection(_HTTPConnection, object):58+ """59+ Based on httplib.HTTPConnection but provides an extra constructor60+ backwards-compatibility layer between older and newer Pythons.61+ """62+63 default_port = port_by_scheme['http']64 65 # By default, disable Nagle's Algorithm.66 tcp_nodelay = 167 68+ def __init__(self, *args, **kw):69+ if six.PY3: # Python 370+ kw.pop('strict', None)71+72+ if sys.version_info < (2, 7): # Python 2.6 and earlier73+ kw.pop('source_address', None)74+ self.source_address = None75+76+ _HTTPConnection.__init__(self, *args, **kw)77+78 def _new_conn(self):79 """ Establish a socket connection and set nodelay settings on it80 81 :return: a new socket connection82 """66- try:67- conn = socket.create_connection(68- (self.host, self.port),69- self.timeout,70- self.source_address,71- )72- except AttributeError: # Python 2.673- conn = socket.create_connection(74- (self.host, self.port),75- self.timeout,76- )83+ extra_args = []84+ if self.source_address: # Python 2.7+85+ extra_args.append(self.source_address)86+87+ conn = socket.create_connection(88+ (self.host, self.port),89+ self.timeout,90+ *extra_args91+ )92 conn.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY,93 self.tcp_nodelay)94 return conn95 13 unmodified lines109 110 def __init__(self, host, port=None, key_file=None, cert_file=None,111 strict=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT,112 source_address=None):98- try:99- HTTPConnection.__init__(self, host, port, strict, timeout, source_address)100- except TypeError: # Python 2.6101- HTTPConnection.__init__(self, host, port, strict, timeout)113+114+ HTTPConnection.__init__(self, host, port,115+ strict=strict,116+ timeout=timeout,117+ source_address=source_address)118+119 self.key_file = key_file120 self.cert_file = cert_file121 122 def connect(self):73 unmodified linesmodified:requests/packages/urllib3/connectionpool.py+43 added-35 removed
17 unmodified lines18 19 20 from .exceptions import (21 ClosedPoolError,22+ ConnectionError,23 ConnectTimeoutError,24 EmptyPoolError,25 HostChangedError,26 MaxRetryError,143 unmodified lines170 self.num_connections += 1171 log.info("Starting new HTTP connection (%d): %s" %172 (self.num_connections, self.host))173 173- extra_params = {}174- if not six.PY3: # Python 2175- extra_params['strict'] = self.strict176-174 conn = self.ConnectionCls(host=self.host, port=self.port,175 timeout=self.timeout.connect_timeout,179- **extra_params)176+ strict=self.strict)177 if self.proxy is not None:178 # Enable Nagle's algorithm for proxies, to avoid packet179 # fragmentation.180 conn.tcp_nodelay = 053 unmodified lines234 # self.pool is None.235 pass236 except Full:237 # This should never happen if self.block == True241- log.warning("HttpConnectionPool is full, discarding connection: %s"242- % self.host)238+ log.warning(239+ "Connection pool is full, discarding connection: %s" %240+ self.host)241 242 # Connection never got put back into the pool, close it.243 if conn:244 conn.close()166 unmodified lines411 these headers completely replace any pool-specific headers.412 413 :param retries:414 Number of retries to allow before raising a MaxRetryError exception.415+ If `False`, then retries are disabled and any exception is raised416+ immediately.417 418 :param redirect:419 If True, automatically handle redirects (status codes 301, 302,420- 303, 307, 308). Each redirect counts as a retry.420+ 303, 307, 308). Each redirect counts as a retry. Disabling retries421+ will disable redirect, too.422 423 :param assert_same_host:424 If ``True``, will make sure that the host of the pool requests is425 consistent else will raise HostChangedError. When False, you can25 unmodified lines451 """452 if headers is None:453 headers = self.headers454 454- if retries < 0:455+ if retries < 0 and retries is not False:456 raise MaxRetryError(self, url)457 458 if release_conn is None:459 release_conn = response_kw.get('preload_content', True)10 unmodified lines470 if self.scheme == 'http':471 headers = headers.copy()472 headers.update(self.proxy_headers)473 474+ # Must keep the exception bound to a separate variable or else Python 3475+ # complains about UnboundLocalError.476+ err = None477+478 try:479 # Request a connection from the queue480 conn = self._get_conn(timeout=pool_timeout)481 19 unmodified lines501 # ``response.release_conn()`` is called (implicitly by502 # ``response.read()``)503 504 except Empty:500- # Timed out by queue505+ # Timed out by queue.506 raise EmptyPoolError(self, "No pool connections are available.")507 503- except BaseSSLError as e:508+ except (BaseSSLError, CertificateError) as e:509+ # Release connection unconditionally because there is no way to510+ # close it externally in case of exception.511+ release_conn = True512 raise SSLError(e)513 506- except CertificateError as e:507- # Name mismatch508- raise SSLError(e)514+ except (TimeoutError, HTTPException, SocketError) as e:515+ if conn:516+ # Discard the connection for these exceptions. It will be517+ # be replaced during the next _get_conn() call.518+ conn.close()519+ conn = None520 510- except TimeoutError as e:511- # Connection broken, discard.512- conn = None513- # Save the error off for retry logic.514- err = e521+ if not retries:522+ if isinstance(e, TimeoutError):523+ # TimeoutError is exempt from MaxRetryError-wrapping.524+ # FIXME: ... Not sure why. Add a reason here.525+ raise526 516- if retries == 0:517- raise527+ # Wrap unexpected exceptions with the most appropriate528+ # module-level exception and re-raise.529+ if isinstance(e, SocketError) and self.proxy:530+ raise ProxyError('Cannot connect to proxy.', e)531 519- except (HTTPException, SocketError) as e:520- # Connection broken, discard. It will be replaced next _get_conn().521- conn = None522- # This is necessary so we can access e below523- err = e532+ if retries is False:533+ raise ConnectionError('Connection failed.', e)534 525- if retries == 0:526- if isinstance(e, SocketError) and self.proxy is not None:527- raise ProxyError('Cannot connect to proxy. '528- 'Socket error: %s.' % e)529- else:530- raise MaxRetryError(self, url, e)535+ raise MaxRetryError(self, url, e)536 537+ # Keep track of the error for the retry warning.538+ err = e539+540 finally:541 if release_conn:542 # Put the connection back to be reused. If the connection is543 # expired then it will be None, which will get replaced with a1 unmodified line545 self._put_conn(conn)546 547 if not conn:548 # Try again541- log.warn("Retrying (%d attempts remain) after connection "542- "broken by '%r': %s" % (retries, err, url))549+ log.warning("Retrying (%d attempts remain) after connection "550+ "broken by '%r': %s" % (retries, err, url))551 return self.urlopen(method, url, body, headers, retries - 1,552 redirect, assert_same_host,553 timeout=timeout, pool_timeout=pool_timeout,554 release_conn=release_conn, **response_kw)555 556 # Handle redirect?557 redirect_location = redirect and response.get_redirect_location()550- if redirect_location:558+ if redirect_location and retries is not False:559 if response.status == 303:560 method = 'GET'561 log.info("Redirecting %s -> %s" % (url, redirect_location))562 return self.urlopen(method, redirect_location, body, headers,133 unmodified linesmodified:requests/packages/urllib3/exceptions.py+5 added
42 unmodified lines43 "Raised when the connection to a proxy fails."44 pass45 46 47+class ConnectionError(HTTPError):48+ "Raised when a normal connection fails."49+ pass50+51+52 class DecodeError(HTTPError):53 "Raised when automatic decoding based on Content-Type fails."54 pass55 71 unmodified linesmodified:requests/packages/urllib3/response.py+7 added-11 removed
7 unmodified lines8 import logging9 import zlib10 import io11 12+from ._collections import HTTPHeaderDict13 from .exceptions import DecodeError14 from .packages.six import string_types as basestring, binary_type15 from .util import is_fp_closed16 62 unmodified lines79 80 def __init__(self, body='', headers=None, status=0, version=0, reason=None,81 strict=0, preload_content=True, decode_content=True,82 original_response=None, pool=None, connection=None):82- self.headers = headers or {}83+84+ self.headers = HTTPHeaderDict()85+ if headers:86+ self.headers.update(headers)87 self.status = status88 self.version = version89 self.reason = reason90 self.strict = strict161 unmodified lines252 Remaining parameters are passed to the HTTPResponse constructor, along253 with ``original_response=r``.254 """255 252- # Normalize headers between different versions of Python253- headers = {}256+ headers = HTTPHeaderDict()257 for k, v in r.getheaders():255- # Python 3: Header keys are returned capitalised256- k = k.lower()258+ headers.add(k, v)259 258- has_value = headers.get(k)259- if has_value: # Python 3: Repeating header keys are unmerged.260- v = ', '.join([has_value, v])261-262- headers[k] = v263-260 # HTTPResponse objects in Python 3 don't have a .strict attribute261 strict = getattr(r, 'strict', 0)262 return ResponseCls(body=r,263 headers=headers,45 unmodified lines