Updates urllib3 to 528ad3c
Before adoption: this commit came in with the history the project adopted, so no landing records it.
This includes fixes for openssl running with Pypy, so SSL connections can be made if ndg-httpsclient, pyopenssl and pyasn1 are installed. see also: - https://github.com/shazow/urllib3/issues/449 - https://github.com/pypa/pip/issues/1988
authored by Kevin Burke · committed by Kevin Burke · parent c0322e4 · Browse files · 8 files·+100 added−24 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+100 added−24 removed
- other:+100 added−24 removed
Provenance
- Commit
8bbc4fc- Tree
905c2c0- Author
Kevin Burke <kev@inburke.com>- Committer
Kevin Burke <kev@inburke.com>- Parent
c0322e4
8 files changed+100 added−24 removed
modified:requests/packages/urllib3/contrib/pyopenssl.py+28 added-6 removed
44 unmodified lines45 .. _crime attack: https://en.wikipedia.org/wiki/CRIME_(security_exploit)46 47 '''48 49+try:49-from ndg.httpsclient.ssl_peer_verification import SUBJ_ALT_NAME_SUPPORT50-from ndg.httpsclient.subj_alt_name import SubjectAltName as BaseSubjectAltName50+ from ndg.httpsclient.ssl_peer_verification import SUBJ_ALT_NAME_SUPPORT51+ from ndg.httpsclient.subj_alt_name import SubjectAltName as BaseSubjectAltName52+except SyntaxError as e:53+ raise ImportError(e)54+55 import OpenSSL.SSL56 from pyasn1.codec.der import decoder as der_decoder57 from pyasn1.type import univ, constraint58 from socket import _fileobject, timeout99 unmodified lines158 return dns_name159 160 161 class WrappedSocket(object):158- '''API-compatibility wrapper for Python OpenSSL's Connection-class.'''162+ '''API-compatibility wrapper for Python OpenSSL's Connection-class.163 164+ Note: _makefile_refs, _drop() and _reuse() are needed for the garbage165+ collector of pypy.166+ '''167+168 def __init__(self, connection, socket, suppress_ragged_eofs=True):169 self.connection = connection170 self.socket = socket171 self.suppress_ragged_eofs = suppress_ragged_eofs172+ self._makefile_refs = 0173 174 def fileno(self):175 return self.socket.fileno()176 177 def makefile(self, mode, bufsize=-1):178+ self._makefile_refs += 1169- return _fileobject(self, mode, bufsize)179+ return _fileobject(self, mode, bufsize, close=True)180 181 def recv(self, *args, **kwargs):182 try:183 data = self.connection.recv(*args, **kwargs)5 unmodified lines189 except OpenSSL.SSL.WantReadError:190 rd, wd, ed = select.select(191 [self.socket], [], [], self.socket.gettimeout())192 if not rd:183- raise timeout()193+ raise timeout('The read operation timed out')194 else:195 return self.recv(*args, **kwargs)196 else:197 return data4 unmodified lines202 def sendall(self, data):203 return self.connection.sendall(data)204 205 def close(self):206+ if self._makefile_refs < 1:196- return self.connection.shutdown()207+ return self.connection.shutdown()208+ else:209+ self._makefile_refs -= 1210 211 def getpeercert(self, binary_form=False):212 x509 = self.connection.get_peer_certificate()213 14 unmodified lines228 for value in get_subj_alt_name(x509)229 ]230 }231 232+ def _reuse(self):233+ self._makefile_refs += 1234 235+ def _drop(self):236+ if self._makefile_refs < 1:237+ self.close()238+ else:239+ self._makefile_refs -= 1240+241+242 def _verify_callback(cnx, x509, err_no, err_depth, return_code):243 return err_no == 0244 245 39 unmodified linesmodified:requests/packages/urllib3/util/response.py+13 added-4 removed
3 unmodified lines4 5 :param obj:6 The file-like object to check.7 """8- if hasattr(obj, 'fp'):9- # Object is a container for another file-like object that gets released10- # on exhaustion (e.g. HTTPResponse)8+9+ try:10+ # Check via the official file-like-object way.11+ return obj.closed12+ except AttributeError:13+ pass14+15+ try:16+ # Check if the object is a container for another file-like object that17+ # gets released on exhaustion (e.g. HTTPResponse).18 return obj.fp is None19+ except AttributeError:20+ pass21 13- return obj.closed22+ raise ValueError("Unable to determine whether fp is closed.")modified:requests/packages/urllib3/util/retry.py+1 added-1 removed
81 unmodified lines82 indempotent (multiple requests with the same parameters end with the83 same state). See :attr:`Retry.DEFAULT_METHOD_WHITELIST`.84 85 :param iterable status_forcelist:86- A set of HTTP status codes that we should force a retry on. 86+ A set of HTTP status codes that we should force a retry on.87 88 By default, this is disabled with ``None``.89 90 :param float backoff_factor:189 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.InsecureRequestWarning)60+warnings.simplefilter('module', 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/connection.py+23 added-8 removed
1+import datetime2 import sys3 import socket4 from socket import timeout as SocketTimeout5+import warnings6 7 try: # Python 38 from http.client import HTTPConnection as _HTTPConnection, HTTPException9 except ImportError:17 unmodified lines27 28 29 from .exceptions import (30 ConnectTimeoutError,31+ SystemTimeWarning,32 )33 from .packages.ssl_match_hostname import match_hostname34 from .packages import six35 11 unmodified lines47 'http': 80,48 'https': 443,49 }50 51+RECENT_DATE = datetime.date(2014, 1, 1)52 53+54 class HTTPConnection(_HTTPConnection, object):55 """56 Based on httplib.HTTPConnection but provides an extra constructor57 backwards-compatibility layer between older and newer Pythons.118 unmodified lines176 """177 cert_reqs = None178 ca_certs = None179 ssl_version = None180+ assert_fingerprint = None181 182 def set_cert(self, key_file=None, cert_file=None,183 cert_reqs=None, ca_certs=None,184 assert_hostname=None, assert_fingerprint=None):26 unmodified lines211 212 # Override the host with the one we're requesting data from.213 hostname = self._tunnel_host214 215+ is_time_off = datetime.date.today() < RECENT_DATE216+ if is_time_off:217+ warnings.warn((218+ 'System time is way off (before {0}). This will probably '219+ 'lead to SSL verification errors').format(RECENT_DATE),220+ SystemTimeWarning221+ )222+223 # Wrap socket using verification with the root certs in224 # trusted_root_certs225 self.sock = ssl_wrap_socket(conn, self.key_file, self.cert_file,226 cert_reqs=resolved_cert_reqs,227 ca_certs=self.ca_certs,228 server_hostname=hostname,229 ssl_version=resolved_ssl_version)230 217- if resolved_cert_reqs != ssl.CERT_NONE:218- if self.assert_fingerprint:219- assert_fingerprint(self.sock.getpeercert(binary_form=True),220- self.assert_fingerprint)221- elif self.assert_hostname is not False:222- match_hostname(self.sock.getpeercert(),223- self.assert_hostname or hostname)231+ if self.assert_fingerprint:232+ assert_fingerprint(self.sock.getpeercert(binary_form=True),233+ self.assert_fingerprint)234+ elif resolved_cert_reqs != ssl.CERT_NONE \235+ and self.assert_hostname is not False:236+ match_hostname(self.sock.getpeercert(),237+ self.assert_hostname or hostname)238 225- self.is_verified = resolved_cert_reqs == ssl.CERT_REQUIRED239+ self.is_verified = (resolved_cert_reqs == ssl.CERT_REQUIRED240+ or self.assert_fingerprint is not None)241 242 243 if ssl:244 # Make a copy for testing.2 unmodified linesmodified:requests/packages/urllib3/connectionpool.py+1 added-1 removed
716 unmodified lines717 """718 super(HTTPSConnectionPool, self)._validate_conn(conn)719 720 # Force connect early to allow us to validate the connection.721- if not conn.sock:721+ if not getattr(conn, 'sock', None): # AppEngine might not have `.sock`722 conn.connect()723 724 if not conn.is_verified:725 warnings.warn((32 unmodified linesmodified:requests/packages/urllib3/exceptions.py+19 added-2 removed
58 unmodified lines59 60 ## Leaf Exceptions61 62 class MaxRetryError(RequestError):63- "Raised when the maximum number of retries is exceeded."63+ """Raised when the maximum number of retries is exceeded.64 65+ :param pool: The connection pool66+ :type pool: :class:`~urllib3.connectionpool.HTTPConnectionPool`67+ :param string url: The requested Url68+ :param exceptions.Exception reason: The underlying error69+70+ """71+72 def __init__(self, pool, url, reason=None):73 self.reason = reason74 75 message = "Max retries exceeded with url: %s" % url64 unmodified lines140 141 self.location = location142 143 137-class InsecureRequestWarning(HTTPWarning):144+class SecurityWarning(HTTPWarning):145+ "Warned when perfoming security reducing actions"146+ pass147+148+149+class InsecureRequestWarning(SecurityWarning):150 "Warned when making an unverified HTTPS request."151 pass152+153+154+class SystemTimeWarning(SecurityWarning):155+ "Warned when system time is suspected to be wrong"156+ passmodified:requests/packages/urllib3/response.py+14 added-1 removed
46 unmodified lines47 """48 HTTP Response container.49 50 Backwards-compatible to httplib's HTTPResponse but the response ``body`` is51- loaded and decoded on-demand when the ``data`` property is accessed.51+ loaded and decoded on-demand when the ``data`` property is accessed. This52+ class is also compatible with the Python standard library's :mod:`io`53+ module, and can hence be treated as a readable object in the context of that54+ framework.55 56 Extra parameters for behaviour not present in httplib.HTTPResponse:57 58 :param preload_content:260 unmodified lines319 if self._fp is not None and hasattr(self._fp, 'flush'):320 return self._fp.flush()321 322 def readable(self):323+ # This method is required for `io` module compatibility.324 return True325+326+ def readinto(self, b):327+ # This method is required for `io` module compatibility.328+ temp = self.read(len(b))329+ if len(temp) == 0:330+ return 0331+ else:332+ b[:len(temp)] = temp333+ return len(temp)