Skip to content
Myr

Merge pull request #1981 from stanhu/master

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

Update urllib to 1.8 (8a8c601bee)

authored by Kenneth Reitz · committed by Kenneth Reitz · parents 0303e9b, 6c83998 · 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

8 files+227 added−76 removed

modified:requests/packages/urllib3/contrib/pyopenssl.py+34 added-11 removed
27 unmodified lines
28Module Variables29----------------3031: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``3435.. _sni: https://en.wikipedia.org/wiki/Server_Name_Indication36.. _crime attack: https://en.wikipedia.org/wiki/CRIME_(security_exploit)37
3 unmodified lines
41from ndg.httpsclient.subj_alt_name import SubjectAltName as BaseSubjectAltName42import OpenSSL.SSL43from pyasn1.codec.der import decoder as der_decoder44from pyasn1.type import univ, constraint46from socket import _fileobject45from socket import _fileobject, timeout46import ssl47import select48from cStringIO import StringIO49
17 unmodified lines
67 ssl.CERT_REQUIRED: OpenSSL.SSL.VERIFY_PEER68 + OpenSSL.SSL.VERIFY_FAIL_IF_NO_PEER_CERT,69}7072# 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-secrecy75DEFAULT_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.84DEFAULT_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"878889orig_util_HAS_SNI = util.HAS_SNI90orig_connection_ssl_wrap_socket = connection.ssl_wrap_socket
56 unmodified lines
147148149class fileobject(_fileobject):150151 def _wait_for_sock(self):152 rd, wd, ed = select.select([self._sock], [], [],153 self._sock.gettimeout())154 if not rd:155 raise timeout()156157158 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 lines
171 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 lines
199 # 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 lines
251 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 lines
262 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 lines
290 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 lines
386 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()392393 # Disable TLS compression to migitate CRIME attack (issue #309)394 OP_NO_COMPRESSION = 0x20000395 ctx.set_options(OP_NO_COMPRESSION)
18 unmodified lines
modified:requests/packages/urllib3/packages/ssl_match_hostname/__init__.py+1 added-1 removed
5 unmodified lines
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_hostname10 from ._implementation import CertificateError, match_hostname1112# Not needed, but documenting what we provide.13__all__ = ('CertificateError', 'match_hostname')
modified:requests/packages/urllib3/__init__.py+1 added-1 removed
8 unmodified lines
9"""1011__author__ = 'Andrey Petrov (andrey.petrov@shazow.net)'12__license__ = 'MIT'13__version__ = 'dev'13__version__ = '1.8'141516from .connectionpool import (17 HTTPConnectionPool,
41 unmodified lines
modified:requests/packages/urllib3/_collections.py+104 added-2 removed
2 unmodified lines
3#4# This module is part of urllib3 and is released under5# the MIT License: http://www.opensource.org/licenses/mit-license.php67from collections import MutableMapping7from collections import Mapping, MutableMapping8try:9 from threading import RLock10except ImportError: # Platform-specific: No threads available11 class RLock:
7 unmodified lines
19try: # Python 2.7+20 from collections import OrderedDict21except ImportError:22 from .packages.ordered_dict import OrderedDict23from .packages.six import itervalues242525__all__ = ['RecentlyUsedContainer']26__all__ = ['RecentlyUsedContainer', 'HTTPHeaderDict']272829_Null = object()30
70 unmodified lines
101102 def keys(self):103 with self.lock:104 return self._container.keys()105106107class HTTPHeaderDict(MutableMapping):108 """109 :param headers:110 An iterable of field-value pairs. Must not contain multiple field names111 when compared case-insensitively.112113 :param kwargs:114 Additional field-value pairs to pass in to ``dict.update``.115116 A ``dict`` like container for storing HTTP Headers.117118 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.121122 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.126127 If multiple fields that are equal case-insensitively are passed to the128 constructor or ``.update``, the behavior is undefined and some will be129 lost.130131 >>> 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'139140 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:145146 >>> headers._data147 {'set-cookie': [('Set-Cookie', 'foo=bar'), ('set-cookie', 'baz=quxx')],148 'content-length': [('content-length', '7')]}149 """150151 def __init__(self, headers=None, **kwargs):152 self._data = {}153 if headers is None:154 headers = {}155 self.update(headers, **kwargs)156157 def add(self, key, value):158 """Adds a (name, value) pair, doesn't overwrite the value if it already159 exists.160161 >>> 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))167168 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 []172173 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 h179180 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)186187 def __getitem__(self, key):188 values = self._data[key.lower()]189 return ', '.join(value[1] for value in values)190191 def __setitem__(self, key, value):192 self._data[key.lower()] = [(key, value)]193194 def __delitem__(self, key):195 del self._data[key.lower()]196197 def __len__(self):198 return len(self._data)199200 def __iter__(self):201 for headers in itervalues(self._data):202 yield headers[0][0]203204 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 lines
3#4# This module is part of urllib3 and is released under5# the MIT License: http://www.opensource.org/licenses/mit-license.php67import sys8import socket9from socket import timeout as SocketTimeout1011try: # Python 3
26 unmodified lines
38from .exceptions import (39 ConnectTimeoutError,40)41from .packages.ssl_match_hostname import match_hostname42from .packages import six43from .util import (44 assert_fingerprint,45 resolve_cert_reqs,46 resolve_ssl_version,
7 unmodified lines
54}555657class HTTPConnection(_HTTPConnection, object):58 """59 Based on httplib.HTTPConnection but provides an extra constructor60 backwards-compatibility layer between older and newer Pythons.61 """6263 default_port = port_by_scheme['http']6465 # By default, disable Nagle's Algorithm.66 tcp_nodelay = 16768 def __init__(self, *args, **kw):69 if six.PY3: # Python 370 kw.pop('strict', None)7172 if sys.version_info < (2, 7): # Python 2.6 and earlier73 kw.pop('source_address', None)74 self.source_address = None7576 _HTTPConnection.__init__(self, *args, **kw)7778 def _new_conn(self):79 """ Establish a socket connection and set nodelay settings on it8081 :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)8687 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 lines
109110 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)113114 HTTPConnection.__init__(self, host, port,115 strict=strict,116 timeout=timeout,117 source_address=source_address)118119 self.key_file = key_file120 self.cert_file = cert_file121122 def connect(self):
73 unmodified lines
modified:requests/packages/urllib3/connectionpool.py+43 added-35 removed
17 unmodified lines
181920from .exceptions import (21 ClosedPoolError,22 ConnectionError,23 ConnectTimeoutError,24 EmptyPoolError,25 HostChangedError,26 MaxRetryError,
143 unmodified lines
170 self.num_connections += 1171 log.info("Starting new HTTP connection (%d): %s" %172 (self.num_connections, self.host))173173 extra_params = {}174 if not six.PY3: # Python 2175 extra_params['strict'] = self.strict176174 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 = 0
53 unmodified lines
234 # 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)241242 # Connection never got put back into the pool, close it.243 if conn:244 conn.close()
166 unmodified lines
411 these headers completely replace any pool-specific headers.412413 :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.417418 :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.422423 :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 can
25 unmodified lines
451 """452 if headers is None:453 headers = self.headers454454 if retries < 0:455 if retries < 0 and retries is not False:456 raise MaxRetryError(self, url)457458 if release_conn is None:459 release_conn = response_kw.get('preload_content', True)
10 unmodified lines
470 if self.scheme == 'http':471 headers = headers.copy()472 headers.update(self.proxy_headers)473474 # Must keep the exception bound to a separate variable or else Python 3475 # complains about UnboundLocalError.476 err = None477478 try:479 # Request a connection from the queue480 conn = self._get_conn(timeout=pool_timeout)481
19 unmodified lines
501 # ``response.release_conn()`` is called (implicitly by502 # ``response.read()``)503504 except Empty:500 # Timed out by queue505 # Timed out by queue.506 raise EmptyPoolError(self, "No pool connections are available.")507503 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)513506 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 = None520510 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 raise526516 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)531519 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)534525 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)536537 # Keep track of the error for the retry warning.538 err = e539540 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 a
1 unmodified line
545 self._put_conn(conn)546547 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)555556 # 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 lines
modified:requests/packages/urllib3/exceptions.py+5 added
42 unmodified lines
43 "Raised when the connection to a proxy fails."44 pass454647class ConnectionError(HTTPError):48 "Raised when a normal connection fails."49 pass505152class DecodeError(HTTPError):53 "Raised when automatic decoding based on Content-Type fails."54 pass55
71 unmodified lines
modified:requests/packages/urllib3/response.py+7 added-11 removed
7 unmodified lines
8import logging9import zlib10import io1112from ._collections import HTTPHeaderDict13from .exceptions import DecodeError14from .packages.six import string_types as basestring, binary_type15from .util import is_fp_closed16
62 unmodified lines
7980 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 {}8384 self.headers = HTTPHeaderDict()85 if headers:86 self.headers.update(headers)87 self.status = status88 self.version = version89 self.reason = reason90 self.strict = strict
161 unmodified lines
252 Remaining parameters are passed to the HTTPResponse constructor, along253 with ``original_response=r``.254 """255252 # 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)259258 has_value = headers.get(k)259 if has_value: # Python 3: Repeating header keys are unmerged.260 v = ', '.join([has_value, v])261262 headers[k] = v263260 # 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