Update urllib to 1.8.2
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by apr · committed by apr · parent 826425f · Browse files · 12 files·+738 added−678 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
12 files+738 added−678 removed
- other:+738 added−678 removed
Provenance
- Commit
36b0481- Tree
2aa2b04- Author
apr <alex@forallsecure.com>- Committer
apr <alex@forallsecure.com>- Parent
826425f
12 files changed+738 added−678 removed
modified:requests/packages/urllib3/contrib/pyopenssl.py+13 added-4 removed
1-'''SSL with SNI_-support for Python 2.1+'''SSL with SNI_-support for Python 2. Follow these instructions if you would2+like to verify SSL certificates in Python 2. Note, the default libraries do3+*not* do certificate checking; you need to do additional work to validate4+certificates yourself.5 6 This needs the following packages installed:7 8 * pyOpenSSL (tested with 0.13)9 * ndg-httpsclient (tested with 0.3.2)10 * pyasn1 (tested with 0.1.6)11 9-To activate it call :func:`~urllib3.contrib.pyopenssl.inject_into_urllib3`.10-This can be done in a ``sitecustomize`` module, or at any other time before11-your application begins using ``urllib3``, like this::12+You can install them with the following command:13 14+ pip install pyopenssl ndg-httpsclient pyasn115+16+To activate certificate checking, call17+:func:`~urllib3.contrib.pyopenssl.inject_into_urllib3` from your Python code18+before you begin making HTTP requests. This can be done in a ``sitecustomize``19+module, or at any other time before your application begins using ``urllib3``,20+like this::21+22 try:23 import urllib3.contrib.pyopenssl24 urllib3.contrib.pyopenssl.inject_into_urllib3()25 except ImportError:397 unmodified linesadded:requests/packages/urllib3/util/__init__.py+27 added
1+# urllib3/util/__init__.py2+# Copyright 2008-2014 Andrey Petrov and contributors (see CONTRIBUTORS.txt)3+#4+# This module is part of urllib3 and is released under5+# the MIT License: http://www.opensource.org/licenses/mit-license.php6+7+from .connection import is_connection_dropped8+from .request import make_headers9+from .response import is_fp_closed10+from .ssl_ import (11+ SSLContext,12+ HAS_SNI,13+ assert_fingerprint,14+ resolve_cert_reqs,15+ resolve_ssl_version,16+ ssl_wrap_socket,17+)18+from .timeout import (19+ current_time,20+ Timeout,21+)22+from .url import (23+ get_host,24+ parse_url,25+ split_first,26+ Url,27+)added:requests/packages/urllib3/util/connection.py+45 added
1+from socket import error as SocketError2+try:3+ from select import poll, POLLIN4+except ImportError: # `poll` doesn't exist on OSX and other platforms5+ poll = False6+ try:7+ from select import select8+ except ImportError: # `select` doesn't exist on AppEngine.9+ select = False10+11+def is_connection_dropped(conn): # Platform-specific12+ """13+ Returns True if the connection is dropped and should be closed.14+15+ :param conn:16+ :class:`httplib.HTTPConnection` object.17+18+ Note: For platforms like AppEngine, this will always return ``False`` to19+ let the platform handle connection recycling transparently for us.20+ """21+ sock = getattr(conn, 'sock', False)22+ if sock is False: # Platform-specific: AppEngine23+ return False24+ if sock is None: # Connection already closed (such as by httplib).25+ return False26+27+ if not poll:28+ if not select: # Platform-specific: AppEngine29+ return False30+31+ try:32+ return select([sock], [], [], 0.0)[0]33+ except SocketError:34+ return True35+36+ # This version is better on platforms that support it.37+ p = poll()38+ p.register(sock, POLLIN)39+ for (fno, ev) in p.poll(0.0):40+ if fno == sock.fileno():41+ # Either data is buffered (bad), or the connection is dropped.42+ return True43+44+45+added:requests/packages/urllib3/util/request.py+68 added
1+from base64 import b64encode2+3+from ..packages import six4+5+6+ACCEPT_ENCODING = 'gzip,deflate'7+8+9+def make_headers(keep_alive=None, accept_encoding=None, user_agent=None,10+ basic_auth=None, proxy_basic_auth=None):11+ """12+ Shortcuts for generating request headers.13+14+ :param keep_alive:15+ If ``True``, adds 'connection: keep-alive' header.16+17+ :param accept_encoding:18+ Can be a boolean, list, or string.19+ ``True`` translates to 'gzip,deflate'.20+ List will get joined by comma.21+ String will be used as provided.22+23+ :param user_agent:24+ String representing the user-agent you want, such as25+ "python-urllib3/0.6"26+27+ :param basic_auth:28+ Colon-separated username:password string for 'authorization: basic ...'29+ auth header.30+31+ :param proxy_basic_auth:32+ Colon-separated username:password string for 'proxy-authorization: basic ...'33+ auth header.34+35+ Example: ::36+37+ >>> make_headers(keep_alive=True, user_agent="Batman/1.0")38+ {'connection': 'keep-alive', 'user-agent': 'Batman/1.0'}39+ >>> make_headers(accept_encoding=True)40+ {'accept-encoding': 'gzip,deflate'}41+ """42+ headers = {}43+ if accept_encoding:44+ if isinstance(accept_encoding, str):45+ pass46+ elif isinstance(accept_encoding, list):47+ accept_encoding = ','.join(accept_encoding)48+ else:49+ accept_encoding = ACCEPT_ENCODING50+ headers['accept-encoding'] = accept_encoding51+52+ if user_agent:53+ headers['user-agent'] = user_agent54+55+ if keep_alive:56+ headers['connection'] = 'keep-alive'57+58+ if basic_auth:59+ headers['authorization'] = 'Basic ' + \60+ b64encode(six.b(basic_auth)).decode('utf-8')61+62+ if proxy_basic_auth:63+ headers['proxy-authorization'] = 'Basic ' + \64+ b64encode(six.b(proxy_basic_auth)).decode('utf-8')65+66+ return headers67+68+added:requests/packages/urllib3/util/response.py+13 added
1+def is_fp_closed(obj):2+ """3+ Checks whether a given file-like object is closed.4+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)11+ return obj.fp is None12+13+ return obj.closedadded:requests/packages/urllib3/util/ssl_.py+133 added
1+from binascii import hexlify, unhexlify2+from hashlib import md5, sha13+4+from ..exceptions import SSLError5+6+7+try: # Test for SSL features8+ SSLContext = None9+ HAS_SNI = False10+11+ import ssl12+ from ssl import wrap_socket, CERT_NONE, PROTOCOL_SSLv2313+ from ssl import SSLContext # Modern SSL?14+ from ssl import HAS_SNI # Has SNI?15+except ImportError:16+ pass17+18+19+def assert_fingerprint(cert, fingerprint):20+ """21+ Checks if given fingerprint matches the supplied certificate.22+23+ :param cert:24+ Certificate as bytes object.25+ :param fingerprint:26+ Fingerprint as string of hexdigits, can be interspersed by colons.27+ """28+29+ # Maps the length of a digest to a possible hash function producing30+ # this digest.31+ hashfunc_map = {32+ 16: md5,33+ 20: sha134+ }35+36+ fingerprint = fingerprint.replace(':', '').lower()37+38+ digest_length, rest = divmod(len(fingerprint), 2)39+40+ if rest or digest_length not in hashfunc_map:41+ raise SSLError('Fingerprint is of invalid length.')42+43+ # We need encode() here for py32; works on py2 and p33.44+ fingerprint_bytes = unhexlify(fingerprint.encode())45+46+ hashfunc = hashfunc_map[digest_length]47+48+ cert_digest = hashfunc(cert).digest()49+50+ if not cert_digest == fingerprint_bytes:51+ raise SSLError('Fingerprints did not match. Expected "{0}", got "{1}".'52+ .format(hexlify(fingerprint_bytes),53+ hexlify(cert_digest)))54+55+56+def resolve_cert_reqs(candidate):57+ """58+ Resolves the argument to a numeric constant, which can be passed to59+ the wrap_socket function/method from the ssl module.60+ Defaults to :data:`ssl.CERT_NONE`.61+ If given a string it is assumed to be the name of the constant in the62+ :mod:`ssl` module or its abbrevation.63+ (So you can specify `REQUIRED` instead of `CERT_REQUIRED`.64+ If it's neither `None` nor a string we assume it is already the numeric65+ constant which can directly be passed to wrap_socket.66+ """67+ if candidate is None:68+ return CERT_NONE69+70+ if isinstance(candidate, str):71+ res = getattr(ssl, candidate, None)72+ if res is None:73+ res = getattr(ssl, 'CERT_' + candidate)74+ return res75+76+ return candidate77+78+79+def resolve_ssl_version(candidate):80+ """81+ like resolve_cert_reqs82+ """83+ if candidate is None:84+ return PROTOCOL_SSLv2385+86+ if isinstance(candidate, str):87+ res = getattr(ssl, candidate, None)88+ if res is None:89+ res = getattr(ssl, 'PROTOCOL_' + candidate)90+ return res91+92+ return candidate93+94+95+if SSLContext is not None: # Python 3.2+96+ def ssl_wrap_socket(sock, keyfile=None, certfile=None, cert_reqs=None,97+ ca_certs=None, server_hostname=None,98+ ssl_version=None):99+ """100+ All arguments except `server_hostname` have the same meaning as for101+ :func:`ssl.wrap_socket`102+103+ :param server_hostname:104+ Hostname of the expected certificate105+ """106+ context = SSLContext(ssl_version)107+ context.verify_mode = cert_reqs108+109+ # Disable TLS compression to migitate CRIME attack (issue #309)110+ OP_NO_COMPRESSION = 0x20000111+ context.options |= OP_NO_COMPRESSION112+113+ if ca_certs:114+ try:115+ context.load_verify_locations(ca_certs)116+ # Py32 raises IOError117+ # Py33 raises FileNotFoundError118+ except Exception as e: # Reraise as SSLError119+ raise SSLError(e)120+ if certfile:121+ # FIXME: This block needs a test.122+ context.load_cert_chain(certfile, keyfile)123+ if HAS_SNI: # Platform-specific: OpenSSL with enabled SNI124+ return context.wrap_socket(sock, server_hostname=server_hostname)125+ return context.wrap_socket(sock)126+127+else: # Python 3.1 and earlier128+ def ssl_wrap_socket(sock, keyfile=None, certfile=None, cert_reqs=None,129+ ca_certs=None, server_hostname=None,130+ ssl_version=None):131+ return wrap_socket(sock, keyfile=keyfile, certfile=certfile,132+ ca_certs=ca_certs, cert_reqs=cert_reqs,133+ ssl_version=ssl_version)added:requests/packages/urllib3/util/timeout.py+234 added
1+from socket import _GLOBAL_DEFAULT_TIMEOUT2+import time3+4+from ..exceptions import TimeoutStateError5+6+7+def current_time():8+ """9+ Retrieve the current time, this function is mocked out in unit testing.10+ """11+ return time.time()12+13+14+_Default = object()15+# The default timeout to use for socket connections. This is the attribute used16+# by httplib to define the default timeout17+18+19+class Timeout(object):20+ """21+ Utility object for storing timeout values.22+23+ Example usage:24+25+ .. code-block:: python26+27+ timeout = urllib3.util.Timeout(connect=2.0, read=7.0)28+ pool = HTTPConnectionPool('www.google.com', 80, timeout=timeout)29+ pool.request(...) # Etc, etc30+31+ :param connect:32+ The maximum amount of time to wait for a connection attempt to a server33+ to succeed. Omitting the parameter will default the connect timeout to34+ the system default, probably `the global default timeout in socket.py35+ <http://hg.python.org/cpython/file/603b4d593758/Lib/socket.py#l535>`_.36+ None will set an infinite timeout for connection attempts.37+38+ :type connect: integer, float, or None39+40+ :param read:41+ The maximum amount of time to wait between consecutive42+ read operations for a response from the server. Omitting43+ the parameter will default the read timeout to the system44+ default, probably `the global default timeout in socket.py45+ <http://hg.python.org/cpython/file/603b4d593758/Lib/socket.py#l535>`_.46+ None will set an infinite timeout.47+48+ :type read: integer, float, or None49+50+ :param total:51+ This combines the connect and read timeouts into one; the read timeout52+ will be set to the time leftover from the connect attempt. In the53+ event that both a connect timeout and a total are specified, or a read54+ timeout and a total are specified, the shorter timeout will be applied.55+56+ Defaults to None.57+58+ :type total: integer, float, or None59+60+ .. note::61+62+ Many factors can affect the total amount of time for urllib3 to return63+ an HTTP response. Specifically, Python's DNS resolver does not obey the64+ timeout specified on the socket. Other factors that can affect total65+ request time include high CPU load, high swap, the program running at a66+ low priority level, or other behaviors. The observed running time for67+ urllib3 to return a response may be greater than the value passed to68+ `total`.69+70+ In addition, the read and total timeouts only measure the time between71+ read operations on the socket connecting the client and the server,72+ not the total amount of time for the request to return a complete73+ response. For most requests, the timeout is raised because the server74+ has not sent the first byte in the specified time. This is not always75+ the case; if a server streams one byte every fifteen seconds, a timeout76+ of 20 seconds will not ever trigger, even though the request will77+ take several minutes to complete.78+79+ If your goal is to cut off any request after a set amount of wall clock80+ time, consider having a second "watcher" thread to cut off a slow81+ request.82+ """83+84+ #: A sentinel object representing the default timeout value85+ DEFAULT_TIMEOUT = _GLOBAL_DEFAULT_TIMEOUT86+87+ def __init__(self, total=None, connect=_Default, read=_Default):88+ self._connect = self._validate_timeout(connect, 'connect')89+ self._read = self._validate_timeout(read, 'read')90+ self.total = self._validate_timeout(total, 'total')91+ self._start_connect = None92+93+ def __str__(self):94+ return '%s(connect=%r, read=%r, total=%r)' % (95+ type(self).__name__, self._connect, self._read, self.total)96+97+98+ @classmethod99+ def _validate_timeout(cls, value, name):100+ """ Check that a timeout attribute is valid101+102+ :param value: The timeout value to validate103+ :param name: The name of the timeout attribute to validate. This is used104+ for clear error messages105+ :return: the value106+ :raises ValueError: if the type is not an integer or a float, or if it107+ is a numeric value less than zero108+ """109+ if value is _Default:110+ return cls.DEFAULT_TIMEOUT111+112+ if value is None or value is cls.DEFAULT_TIMEOUT:113+ return value114+115+ try:116+ float(value)117+ except (TypeError, ValueError):118+ raise ValueError("Timeout value %s was %s, but it must be an "119+ "int or float." % (name, value))120+121+ try:122+ if value < 0:123+ raise ValueError("Attempted to set %s timeout to %s, but the "124+ "timeout cannot be set to a value less "125+ "than 0." % (name, value))126+ except TypeError: # Python 3127+ raise ValueError("Timeout value %s was %s, but it must be an "128+ "int or float." % (name, value))129+130+ return value131+132+ @classmethod133+ def from_float(cls, timeout):134+ """ Create a new Timeout from a legacy timeout value.135+136+ The timeout value used by httplib.py sets the same timeout on the137+ connect(), and recv() socket requests. This creates a :class:`Timeout`138+ object that sets the individual timeouts to the ``timeout`` value passed139+ to this function.140+141+ :param timeout: The legacy timeout value142+ :type timeout: integer, float, sentinel default object, or None143+ :return: a Timeout object144+ :rtype: :class:`Timeout`145+ """146+ return Timeout(read=timeout, connect=timeout)147+148+ def clone(self):149+ """ Create a copy of the timeout object150+151+ Timeout properties are stored per-pool but each request needs a fresh152+ Timeout object to ensure each one has its own start/stop configured.153+154+ :return: a copy of the timeout object155+ :rtype: :class:`Timeout`156+ """157+ # We can't use copy.deepcopy because that will also create a new object158+ # for _GLOBAL_DEFAULT_TIMEOUT, which socket.py uses as a sentinel to159+ # detect the user default.160+ return Timeout(connect=self._connect, read=self._read,161+ total=self.total)162+163+ def start_connect(self):164+ """ Start the timeout clock, used during a connect() attempt165+166+ :raises urllib3.exceptions.TimeoutStateError: if you attempt167+ to start a timer that has been started already.168+ """169+ if self._start_connect is not None:170+ raise TimeoutStateError("Timeout timer has already been started.")171+ self._start_connect = current_time()172+ return self._start_connect173+174+ def get_connect_duration(self):175+ """ Gets the time elapsed since the call to :meth:`start_connect`.176+177+ :return: the elapsed time178+ :rtype: float179+ :raises urllib3.exceptions.TimeoutStateError: if you attempt180+ to get duration for a timer that hasn't been started.181+ """182+ if self._start_connect is None:183+ raise TimeoutStateError("Can't get connect duration for timer "184+ "that has not started.")185+ return current_time() - self._start_connect186+187+ @property188+ def connect_timeout(self):189+ """ Get the value to use when setting a connection timeout.190+191+ This will be a positive float or integer, the value None192+ (never timeout), or the default system timeout.193+194+ :return: the connect timeout195+ :rtype: int, float, :attr:`Timeout.DEFAULT_TIMEOUT` or None196+ """197+ if self.total is None:198+ return self._connect199+200+ if self._connect is None or self._connect is self.DEFAULT_TIMEOUT:201+ return self.total202+203+ return min(self._connect, self.total)204+205+ @property206+ def read_timeout(self):207+ """ Get the value for the read timeout.208+209+ This assumes some time has elapsed in the connection timeout and210+ computes the read timeout appropriately.211+212+ If self.total is set, the read timeout is dependent on the amount of213+ time taken by the connect timeout. If the connection time has not been214+ established, a :exc:`~urllib3.exceptions.TimeoutStateError` will be215+ raised.216+217+ :return: the value to use for the read timeout218+ :rtype: int, float, :attr:`Timeout.DEFAULT_TIMEOUT` or None219+ :raises urllib3.exceptions.TimeoutStateError: If :meth:`start_connect`220+ has not yet been called on this object.221+ """222+ if (self.total is not None and223+ self.total is not self.DEFAULT_TIMEOUT and224+ self._read is not None and225+ self._read is not self.DEFAULT_TIMEOUT):226+ # in case the connect timeout has not yet been established.227+ if self._start_connect is None:228+ return self._read229+ return max(0, min(self.total - self.get_connect_duration(),230+ self._read))231+ elif self.total is not None and self.total is not self.DEFAULT_TIMEOUT:232+ return max(0, self.total - self.get_connect_duration())233+ else:234+ return self._readadded:requests/packages/urllib3/util/url.py+162 added
1+from collections import namedtuple2+3+from ..exceptions import LocationParseError4+5+6+class Url(namedtuple('Url', ['scheme', 'auth', 'host', 'port', 'path', 'query', 'fragment'])):7+ """8+ Datastructure for representing an HTTP URL. Used as a return value for9+ :func:`parse_url`.10+ """11+ slots = ()12+13+ def __new__(cls, scheme=None, auth=None, host=None, port=None, path=None, query=None, fragment=None):14+ return super(Url, cls).__new__(cls, scheme, auth, host, port, path, query, fragment)15+16+ @property17+ def hostname(self):18+ """For backwards-compatibility with urlparse. We're nice like that."""19+ return self.host20+21+ @property22+ def request_uri(self):23+ """Absolute path including the query string."""24+ uri = self.path or '/'25+26+ if self.query is not None:27+ uri += '?' + self.query28+29+ return uri30+31+ @property32+ def netloc(self):33+ """Network location including host and port"""34+ if self.port:35+ return '%s:%d' % (self.host, self.port)36+ return self.host37+38+39+def split_first(s, delims):40+ """41+ Given a string and an iterable of delimiters, split on the first found42+ delimiter. Return two split parts and the matched delimiter.43+44+ If not found, then the first part is the full input string.45+46+ Example: ::47+48+ >>> split_first('foo/bar?baz', '?/=')49+ ('foo', 'bar?baz', '/')50+ >>> split_first('foo/bar?baz', '123')51+ ('foo/bar?baz', '', None)52+53+ Scales linearly with number of delims. Not ideal for large number of delims.54+ """55+ min_idx = None56+ min_delim = None57+ for d in delims:58+ idx = s.find(d)59+ if idx < 0:60+ continue61+62+ if min_idx is None or idx < min_idx:63+ min_idx = idx64+ min_delim = d65+66+ if min_idx is None or min_idx < 0:67+ return s, '', None68+69+ return s[:min_idx], s[min_idx+1:], min_delim70+71+72+def parse_url(url):73+ """74+ Given a url, return a parsed :class:`.Url` namedtuple. Best-effort is75+ performed to parse incomplete urls. Fields not provided will be None.76+77+ Partly backwards-compatible with :mod:`urlparse`.78+79+ Example: ::80+81+ >>> parse_url('http://google.com/mail/')82+ Url(scheme='http', host='google.com', port=None, path='/', ...)83+ >>> parse_url('google.com:80')84+ Url(scheme=None, host='google.com', port=80, path=None, ...)85+ >>> parse_url('/foo?bar')86+ Url(scheme=None, host=None, port=None, path='/foo', query='bar', ...)87+ """88+89+ # While this code has overlap with stdlib's urlparse, it is much90+ # simplified for our needs and less annoying.91+ # Additionally, this implementations does silly things to be optimal92+ # on CPython.93+94+ scheme = None95+ auth = None96+ host = None97+ port = None98+ path = None99+ fragment = None100+ query = None101+102+ # Scheme103+ if '://' in url:104+ scheme, url = url.split('://', 1)105+106+ # Find the earliest Authority Terminator107+ # (http://tools.ietf.org/html/rfc3986#section-3.2)108+ url, path_, delim = split_first(url, ['/', '?', '#'])109+110+ if delim:111+ # Reassemble the path112+ path = delim + path_113+114+ # Auth115+ if '@' in url:116+ # Last '@' denotes end of auth part117+ auth, url = url.rsplit('@', 1)118+119+ # IPv6120+ if url and url[0] == '[':121+ host, url = url.split(']', 1)122+ host += ']'123+124+ # Port125+ if ':' in url:126+ _host, port = url.split(':', 1)127+128+ if not host:129+ host = _host130+131+ if port:132+ # If given, ports must be integers.133+ if not port.isdigit():134+ raise LocationParseError(url)135+ port = int(port)136+ else:137+ # Blank ports are cool, too. (rfc3986#section-3.2.3)138+ port = None139+140+ elif not host and url:141+ host = url142+143+ if not path:144+ return Url(scheme, auth, host, port, path, query, fragment)145+146+ # Fragment147+ if '#' in path:148+ path, fragment = path.split('#', 1)149+150+ # Query151+ if '?' in path:152+ path, query = path.split('?', 1)153+154+ return Url(scheme, auth, host, port, path, query, fragment)155+156+157+def get_host(url):158+ """159+ Deprecated. Use :func:`.parse_url` instead.160+ """161+ p = parse_url(url)162+ return p.scheme or 'http', p.hostname, p.portmodified: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__ = '1.8'13+__version__ = '1.8.2'14 15 16 from .connectionpool import (17 HTTPConnectionPool,41 unmodified linesmodified:requests/packages/urllib3/connection.py+22 added-20 removed
66 unmodified lines67 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 earlier71+ if sys.version_info < (2, 7): # Python 2.6 and older72 kw.pop('source_address', None)74- self.source_address = None73 76- _HTTPConnection.__init__(self, *args, **kw)74+ # Pre-set source_address in case we have an older Python like 2.6.75+ self.source_address = kw.get('source_address')76 77+ # Superclass also sets self.source_address in Python 2.7+.78+ _HTTPConnection.__init__(self, *args, **kw) 79+80 def _new_conn(self):79- """ Establish a socket connection and set nodelay settings on it81+ """ Establish a socket connection and set nodelay settings on it.82 83 :return: a new socket connection84 """85 extra_args = []86 if self.source_address: # Python 2.7+87 extra_args.append(self.source_address)88 89 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)90+ (self.host, self.port), self.timeout, *extra_args)91+ conn.setsockopt(92+ socket.IPPROTO_TCP, socket.TCP_NODELAY, self.tcp_nodelay)93+94 return conn95 96 def _prepare_conn(self, conn):97 self.sock = conn9 unmodified lines107 class HTTPSConnection(HTTPConnection):108 default_port = port_by_scheme['https']109 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):111+ strict=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT, **kw):112 114- HTTPConnection.__init__(self, host, port,115- strict=strict,116- timeout=timeout,117- source_address=source_address)113+ HTTPConnection.__init__(self, host, port, strict=strict,114+ timeout=timeout, **kw)115 116 self.key_file = key_file117 self.cert_file = cert_file118 119+ # Required property for Google AppEngine 1.9.0 which otherwise causes120+ # HTTPS requests to go out as HTTP. (See Issue #356)121+ self._protocol = 'https'122+123 def connect(self):124 conn = self._new_conn()125 self._prepare_conn(conn)126 self.sock = ssl.wrap_socket(conn, self.key_file, self.cert_file)6 unmodified lines133 """134 cert_reqs = None135 ca_certs = None136 ssl_version = None137+ conn_kw = {}138 139 def set_cert(self, key_file=None, cert_file=None,140 cert_reqs=None, ca_certs=None,141 assert_hostname=None, assert_fingerprint=None):6 unmodified lines148 self.assert_fingerprint = assert_fingerprint149 150 def connect(self):151 # Add certificate verification152+153 try:154 sock = socket.create_connection(152- address=(self.host, self.port),153- timeout=self.timeout,154- )155+ address=(self.host, self.port), timeout=self.timeout,156+ **self.conn_kw)157 except SocketTimeout:158 raise ConnectTimeoutError(159 self, "Connection to %s timed out. (connect timeout=%s)" %160 (self.host, self.timeout))37 unmodified linesmodified:requests/packages/urllib3/connectionpool.py+20 added-5 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 errno9 import logging10 11 from socket import error as SocketError, timeout as SocketTimeout11 unmodified lines23 ConnectionError,24 ConnectTimeoutError,25 EmptyPoolError,26 HostChangedError,27+ LocationParseError,28 MaxRetryError,29 SSLError,30 TimeoutError,31 ReadTimeoutError,9 unmodified lines41 )42 from .request import RequestMethods43 from .response import HTTPResponse44 from .util import (43- assert_fingerprint,45 get_host,46 is_connection_dropped,47 Timeout,48 )16 unmodified lines65 scheme = None66 QueueCls = LifoQueue67 68 def __init__(self, host, port=None):69+ if host is None:70+ raise LocationParseError(host)71+72 # httplib doesn't like it when we include brackets in ipv6 addresses73 host = host.strip('[]')74 75 self.host = host63 unmodified lines139 ConnectionCls = HTTPConnection140 141 def __init__(self, host, port=None, strict=False,142 timeout=Timeout.DEFAULT_TIMEOUT, maxsize=1, block=False,139- headers=None, _proxy=None, _proxy_headers=None):143+ headers=None, _proxy=None, _proxy_headers=None, **conn_kw):144 ConnectionPool.__init__(self, host, port)145 RequestMethods.__init__(self, headers)146 147 self.strict = strict18 unmodified lines166 # These are mostly for testing and debugging purposes.167 self.num_connections = 0168 self.num_requests = 0169 170+ if sys.version_info < (2, 7): # Python 2.6 and older171+ conn_kw.pop('source_address', None)172+ self.conn_kw = conn_kw173+174 def _new_conn(self):175 """176 Return a fresh :class:`HTTPConnection`.177 """2 unmodified lines180 (self.num_connections, self.host))181 182 conn = self.ConnectionCls(host=self.host, port=self.port,183 timeout=self.timeout.connect_timeout,176- strict=self.strict)184+ strict=self.strict, **self.conn_kw)185 if self.proxy is not None:186 # Enable Nagle's algorithm for proxies, to avoid packet187 # fragmentation.188 conn.tcp_nodelay = 0412 unmodified lines601 block=False, headers=None,602 _proxy=None, _proxy_headers=None,603 key_file=None, cert_file=None, cert_reqs=None,604 ca_certs=None, ssl_version=None,597- assert_hostname=None, assert_fingerprint=None):605+ assert_hostname=None, assert_fingerprint=None,606+ **conn_kw):607 608+ if sys.version_info < (2, 7): # Python 2.6 or older609+ conn_kw.pop('source_address', None)610+611 HTTPConnectionPool.__init__(self, host, port, strict, timeout, maxsize,600- block, headers, _proxy, _proxy_headers)612+ block, headers, _proxy, _proxy_headers, **conn_kw)613 self.key_file = key_file614 self.cert_file = cert_file615 self.cert_reqs = cert_reqs616 self.ca_certs = ca_certs617 self.ssl_version = ssl_version618 self.assert_hostname = assert_hostname619 self.assert_fingerprint = assert_fingerprint620+ self.conn_kw = conn_kw621 622 def _prepare_conn(self, conn):623 """624 Prepare the ``connection`` for :meth:`urllib3.util.ssl_wrap_socket`7 unmodified lines632 ca_certs=self.ca_certs,633 assert_hostname=self.assert_hostname,634 assert_fingerprint=self.assert_fingerprint)635 conn.ssl_version = self.ssl_version636+ conn.conn_kw = self.conn_kw637 638 if self.proxy is not None:639 # Python 2.7+640 try:28 unmodified lines669 670 extra_params = {}671 if not six.PY3: # Python 2672 extra_params['strict'] = self.strict673+ extra_params.update(self.conn_kw)674 675 conn = self.ConnectionCls(host=actual_host, port=actual_port,676 timeout=self.timeout.connect_timeout,677 **extra_params)33 unmodified linesdeleted:requests/packages/urllib3/util.py-648 removed
1-# urllib3/util.py2-# Copyright 2008-2013 Andrey Petrov and contributors (see CONTRIBUTORS.txt)3-#4-# This module is part of urllib3 and is released under5-# the MIT License: http://www.opensource.org/licenses/mit-license.php6-7-8-from base64 import b64encode9-from binascii import hexlify, unhexlify10-from collections import namedtuple11-from hashlib import md5, sha112-from socket import error as SocketError, _GLOBAL_DEFAULT_TIMEOUT13-import time14-15-try:16- from select import poll, POLLIN17-except ImportError: # `poll` doesn't exist on OSX and other platforms18- poll = False19- try:20- from select import select21- except ImportError: # `select` doesn't exist on AppEngine.22- select = False23-24-try: # Test for SSL features25- SSLContext = None26- HAS_SNI = False27-28- import ssl29- from ssl import wrap_socket, CERT_NONE, PROTOCOL_SSLv2330- from ssl import SSLContext # Modern SSL?31- from ssl import HAS_SNI # Has SNI?32-except ImportError:33- pass34-35-from .packages import six36-from .exceptions import LocationParseError, SSLError, TimeoutStateError37-38-39-_Default = object()40-# The default timeout to use for socket connections. This is the attribute used41-# by httplib to define the default timeout42-43-44-def current_time():45- """46- Retrieve the current time, this function is mocked out in unit testing.47- """48- return time.time()49-50-51-class Timeout(object):52- """53- Utility object for storing timeout values.54-55- Example usage:56-57- .. code-block:: python58-59- timeout = urllib3.util.Timeout(connect=2.0, read=7.0)60- pool = HTTPConnectionPool('www.google.com', 80, timeout=timeout)61- pool.request(...) # Etc, etc62-63- :param connect:64- The maximum amount of time to wait for a connection attempt to a server65- to succeed. Omitting the parameter will default the connect timeout to66- the system default, probably `the global default timeout in socket.py67- <http://hg.python.org/cpython/file/603b4d593758/Lib/socket.py#l535>`_.68- None will set an infinite timeout for connection attempts.69-70- :type connect: integer, float, or None71-72- :param read:73- The maximum amount of time to wait between consecutive74- read operations for a response from the server. Omitting75- the parameter will default the read timeout to the system76- default, probably `the global default timeout in socket.py77- <http://hg.python.org/cpython/file/603b4d593758/Lib/socket.py#l535>`_.78- None will set an infinite timeout.79-80- :type read: integer, float, or None81-82- :param total:83- This combines the connect and read timeouts into one; the read timeout84- will be set to the time leftover from the connect attempt. In the85- event that both a connect timeout and a total are specified, or a read86- timeout and a total are specified, the shorter timeout will be applied.87-88- Defaults to None.89-90- :type total: integer, float, or None91-92- .. note::93-94- Many factors can affect the total amount of time for urllib3 to return95- an HTTP response. Specifically, Python's DNS resolver does not obey the96- timeout specified on the socket. Other factors that can affect total97- request time include high CPU load, high swap, the program running at a98- low priority level, or other behaviors. The observed running time for99- urllib3 to return a response may be greater than the value passed to100- `total`.101-102- In addition, the read and total timeouts only measure the time between103- read operations on the socket connecting the client and the server,104- not the total amount of time for the request to return a complete105- response. For most requests, the timeout is raised because the server106- has not sent the first byte in the specified time. This is not always107- the case; if a server streams one byte every fifteen seconds, a timeout108- of 20 seconds will not ever trigger, even though the request will109- take several minutes to complete.110-111- If your goal is to cut off any request after a set amount of wall clock112- time, consider having a second "watcher" thread to cut off a slow113- request.114- """115-116- #: A sentinel object representing the default timeout value117- DEFAULT_TIMEOUT = _GLOBAL_DEFAULT_TIMEOUT118-119- def __init__(self, total=None, connect=_Default, read=_Default):120- self._connect = self._validate_timeout(connect, 'connect')121- self._read = self._validate_timeout(read, 'read')122- self.total = self._validate_timeout(total, 'total')123- self._start_connect = None124-125- def __str__(self):126- return '%s(connect=%r, read=%r, total=%r)' % (127- type(self).__name__, self._connect, self._read, self.total)128-129-130- @classmethod131- def _validate_timeout(cls, value, name):132- """ Check that a timeout attribute is valid133-134- :param value: The timeout value to validate135- :param name: The name of the timeout attribute to validate. This is used136- for clear error messages137- :return: the value138- :raises ValueError: if the type is not an integer or a float, or if it139- is a numeric value less than zero140- """141- if value is _Default:142- return cls.DEFAULT_TIMEOUT143-144- if value is None or value is cls.DEFAULT_TIMEOUT:145- return value146-147- try:148- float(value)149- except (TypeError, ValueError):150- raise ValueError("Timeout value %s was %s, but it must be an "151- "int or float." % (name, value))152-153- try:154- if value < 0:155- raise ValueError("Attempted to set %s timeout to %s, but the "156- "timeout cannot be set to a value less "157- "than 0." % (name, value))158- except TypeError: # Python 3159- raise ValueError("Timeout value %s was %s, but it must be an "160- "int or float." % (name, value))161-162- return value163-164- @classmethod165- def from_float(cls, timeout):166- """ Create a new Timeout from a legacy timeout value.167-168- The timeout value used by httplib.py sets the same timeout on the169- connect(), and recv() socket requests. This creates a :class:`Timeout`170- object that sets the individual timeouts to the ``timeout`` value passed171- to this function.172-173- :param timeout: The legacy timeout value174- :type timeout: integer, float, sentinel default object, or None175- :return: a Timeout object176- :rtype: :class:`Timeout`177- """178- return Timeout(read=timeout, connect=timeout)179-180- def clone(self):181- """ Create a copy of the timeout object182-183- Timeout properties are stored per-pool but each request needs a fresh184- Timeout object to ensure each one has its own start/stop configured.185-186- :return: a copy of the timeout object187- :rtype: :class:`Timeout`188- """189- # We can't use copy.deepcopy because that will also create a new object190- # for _GLOBAL_DEFAULT_TIMEOUT, which socket.py uses as a sentinel to191- # detect the user default.192- return Timeout(connect=self._connect, read=self._read,193- total=self.total)194-195- def start_connect(self):196- """ Start the timeout clock, used during a connect() attempt197-198- :raises urllib3.exceptions.TimeoutStateError: if you attempt199- to start a timer that has been started already.200- """201- if self._start_connect is not None:202- raise TimeoutStateError("Timeout timer has already been started.")203- self._start_connect = current_time()204- return self._start_connect205-206- def get_connect_duration(self):207- """ Gets the time elapsed since the call to :meth:`start_connect`.208-209- :return: the elapsed time210- :rtype: float211- :raises urllib3.exceptions.TimeoutStateError: if you attempt212- to get duration for a timer that hasn't been started.213- """214- if self._start_connect is None:215- raise TimeoutStateError("Can't get connect duration for timer "216- "that has not started.")217- return current_time() - self._start_connect218-219- @property220- def connect_timeout(self):221- """ Get the value to use when setting a connection timeout.222-223- This will be a positive float or integer, the value None224- (never timeout), or the default system timeout.225-226- :return: the connect timeout227- :rtype: int, float, :attr:`Timeout.DEFAULT_TIMEOUT` or None228- """229- if self.total is None:230- return self._connect231-232- if self._connect is None or self._connect is self.DEFAULT_TIMEOUT:233- return self.total234-235- return min(self._connect, self.total)236-237- @property238- def read_timeout(self):239- """ Get the value for the read timeout.240-241- This assumes some time has elapsed in the connection timeout and242- computes the read timeout appropriately.243-244- If self.total is set, the read timeout is dependent on the amount of245- time taken by the connect timeout. If the connection time has not been246- established, a :exc:`~urllib3.exceptions.TimeoutStateError` will be247- raised.248-249- :return: the value to use for the read timeout250- :rtype: int, float, :attr:`Timeout.DEFAULT_TIMEOUT` or None251- :raises urllib3.exceptions.TimeoutStateError: If :meth:`start_connect`252- has not yet been called on this object.253- """254- if (self.total is not None and255- self.total is not self.DEFAULT_TIMEOUT and256- self._read is not None and257- self._read is not self.DEFAULT_TIMEOUT):258- # in case the connect timeout has not yet been established.259- if self._start_connect is None:260- return self._read261- return max(0, min(self.total - self.get_connect_duration(),262- self._read))263- elif self.total is not None and self.total is not self.DEFAULT_TIMEOUT:264- return max(0, self.total - self.get_connect_duration())265- else:266- return self._read267-268-269-class Url(namedtuple('Url', ['scheme', 'auth', 'host', 'port', 'path', 'query', 'fragment'])):270- """271- Datastructure for representing an HTTP URL. Used as a return value for272- :func:`parse_url`.273- """274- slots = ()275-276- def __new__(cls, scheme=None, auth=None, host=None, port=None, path=None, query=None, fragment=None):277- return super(Url, cls).__new__(cls, scheme, auth, host, port, path, query, fragment)278-279- @property280- def hostname(self):281- """For backwards-compatibility with urlparse. We're nice like that."""282- return self.host283-284- @property285- def request_uri(self):286- """Absolute path including the query string."""287- uri = self.path or '/'288-289- if self.query is not None:290- uri += '?' + self.query291-292- return uri293-294- @property295- def netloc(self):296- """Network location including host and port"""297- if self.port:298- return '%s:%d' % (self.host, self.port)299- return self.host300-301-302-def split_first(s, delims):303- """304- Given a string and an iterable of delimiters, split on the first found305- delimiter. Return two split parts and the matched delimiter.306-307- If not found, then the first part is the full input string.308-309- Example: ::310-311- >>> split_first('foo/bar?baz', '?/=')312- ('foo', 'bar?baz', '/')313- >>> split_first('foo/bar?baz', '123')314- ('foo/bar?baz', '', None)315-316- Scales linearly with number of delims. Not ideal for large number of delims.317- """318- min_idx = None319- min_delim = None320- for d in delims:321- idx = s.find(d)322- if idx < 0:323- continue324-325- if min_idx is None or idx < min_idx:326- min_idx = idx327- min_delim = d328-329- if min_idx is None or min_idx < 0:330- return s, '', None331-332- return s[:min_idx], s[min_idx+1:], min_delim333-334-335-def parse_url(url):336- """337- Given a url, return a parsed :class:`.Url` namedtuple. Best-effort is338- performed to parse incomplete urls. Fields not provided will be None.339-340- Partly backwards-compatible with :mod:`urlparse`.341-342- Example: ::343-344- >>> parse_url('http://google.com/mail/')345- Url(scheme='http', host='google.com', port=None, path='/', ...)346- >>> parse_url('google.com:80')347- Url(scheme=None, host='google.com', port=80, path=None, ...)348- >>> parse_url('/foo?bar')349- Url(scheme=None, host=None, port=None, path='/foo', query='bar', ...)350- """351-352- # While this code has overlap with stdlib's urlparse, it is much353- # simplified for our needs and less annoying.354- # Additionally, this implementations does silly things to be optimal355- # on CPython.356-357- scheme = None358- auth = None359- host = None360- port = None361- path = None362- fragment = None363- query = None364-365- # Scheme366- if '://' in url:367- scheme, url = url.split('://', 1)368-369- # Find the earliest Authority Terminator370- # (http://tools.ietf.org/html/rfc3986#section-3.2)371- url, path_, delim = split_first(url, ['/', '?', '#'])372-373- if delim:374- # Reassemble the path375- path = delim + path_376-377- # Auth378- if '@' in url:379- # Last '@' denotes end of auth part380- auth, url = url.rsplit('@', 1)381-382- # IPv6383- if url and url[0] == '[':384- host, url = url.split(']', 1)385- host += ']'386-387- # Port388- if ':' in url:389- _host, port = url.split(':', 1)390-391- if not host:392- host = _host393-394- if port:395- # If given, ports must be integers.396- if not port.isdigit():397- raise LocationParseError("Failed to parse: %s" % url)398- port = int(port)399- else:400- # Blank ports are cool, too. (rfc3986#section-3.2.3)401- port = None402-403- elif not host and url:404- host = url405-406- if not path:407- return Url(scheme, auth, host, port, path, query, fragment)408-409- # Fragment410- if '#' in path:411- path, fragment = path.split('#', 1)412-413- # Query414- if '?' in path:415- path, query = path.split('?', 1)416-417- return Url(scheme, auth, host, port, path, query, fragment)418-419-420-def get_host(url):421- """422- Deprecated. Use :func:`.parse_url` instead.423- """424- p = parse_url(url)425- return p.scheme or 'http', p.hostname, p.port426-427-428-def make_headers(keep_alive=None, accept_encoding=None, user_agent=None,429- basic_auth=None, proxy_basic_auth=None):430- """431- Shortcuts for generating request headers.432-433- :param keep_alive:434- If ``True``, adds 'connection: keep-alive' header.435-436- :param accept_encoding:437- Can be a boolean, list, or string.438- ``True`` translates to 'gzip,deflate'.439- List will get joined by comma.440- String will be used as provided.441-442- :param user_agent:443- String representing the user-agent you want, such as444- "python-urllib3/0.6"445-446- :param basic_auth:447- Colon-separated username:password string for 'authorization: basic ...'448- auth header.449-450- :param proxy_basic_auth:451- Colon-separated username:password string for 'proxy-authorization: basic ...'452- auth header.453-454- Example: ::455-456- >>> make_headers(keep_alive=True, user_agent="Batman/1.0")457- {'connection': 'keep-alive', 'user-agent': 'Batman/1.0'}458- >>> make_headers(accept_encoding=True)459- {'accept-encoding': 'gzip,deflate'}460- """461- headers = {}462- if accept_encoding:463- if isinstance(accept_encoding, str):464- pass465- elif isinstance(accept_encoding, list):466- accept_encoding = ','.join(accept_encoding)467- else:468- accept_encoding = 'gzip,deflate'469- headers['accept-encoding'] = accept_encoding470-471- if user_agent:472- headers['user-agent'] = user_agent473-474- if keep_alive:475- headers['connection'] = 'keep-alive'476-477- if basic_auth:478- headers['authorization'] = 'Basic ' + \479- b64encode(six.b(basic_auth)).decode('utf-8')480-481- if proxy_basic_auth:482- headers['proxy-authorization'] = 'Basic ' + \483- b64encode(six.b(proxy_basic_auth)).decode('utf-8')484-485- return headers486-487-488-def is_connection_dropped(conn): # Platform-specific489- """490- Returns True if the connection is dropped and should be closed.491-492- :param conn:493- :class:`httplib.HTTPConnection` object.494-495- Note: For platforms like AppEngine, this will always return ``False`` to496- let the platform handle connection recycling transparently for us.497- """498- sock = getattr(conn, 'sock', False)499- if not sock: # Platform-specific: AppEngine500- return False501-502- if not poll:503- if not select: # Platform-specific: AppEngine504- return False505-506- try:507- return select([sock], [], [], 0.0)[0]508- except SocketError:509- return True510-511- # This version is better on platforms that support it.512- p = poll()513- p.register(sock, POLLIN)514- for (fno, ev) in p.poll(0.0):515- if fno == sock.fileno():516- # Either data is buffered (bad), or the connection is dropped.517- return True518-519-520-def resolve_cert_reqs(candidate):521- """522- Resolves the argument to a numeric constant, which can be passed to523- the wrap_socket function/method from the ssl module.524- Defaults to :data:`ssl.CERT_NONE`.525- If given a string it is assumed to be the name of the constant in the526- :mod:`ssl` module or its abbrevation.527- (So you can specify `REQUIRED` instead of `CERT_REQUIRED`.528- If it's neither `None` nor a string we assume it is already the numeric529- constant which can directly be passed to wrap_socket.530- """531- if candidate is None:532- return CERT_NONE533-534- if isinstance(candidate, str):535- res = getattr(ssl, candidate, None)536- if res is None:537- res = getattr(ssl, 'CERT_' + candidate)538- return res539-540- return candidate541-542-543-def resolve_ssl_version(candidate):544- """545- like resolve_cert_reqs546- """547- if candidate is None:548- return PROTOCOL_SSLv23549-550- if isinstance(candidate, str):551- res = getattr(ssl, candidate, None)552- if res is None:553- res = getattr(ssl, 'PROTOCOL_' + candidate)554- return res555-556- return candidate557-558-559-def assert_fingerprint(cert, fingerprint):560- """561- Checks if given fingerprint matches the supplied certificate.562-563- :param cert:564- Certificate as bytes object.565- :param fingerprint:566- Fingerprint as string of hexdigits, can be interspersed by colons.567- """568-569- # Maps the length of a digest to a possible hash function producing570- # this digest.571- hashfunc_map = {572- 16: md5,573- 20: sha1574- }575-576- fingerprint = fingerprint.replace(':', '').lower()577-578- digest_length, rest = divmod(len(fingerprint), 2)579-580- if rest or digest_length not in hashfunc_map:581- raise SSLError('Fingerprint is of invalid length.')582-583- # We need encode() here for py32; works on py2 and p33.584- fingerprint_bytes = unhexlify(fingerprint.encode())585-586- hashfunc = hashfunc_map[digest_length]587-588- cert_digest = hashfunc(cert).digest()589-590- if not cert_digest == fingerprint_bytes:591- raise SSLError('Fingerprints did not match. Expected "{0}", got "{1}".'592- .format(hexlify(fingerprint_bytes),593- hexlify(cert_digest)))594-595-def is_fp_closed(obj):596- """597- Checks whether a given file-like object is closed.598-599- :param obj:600- The file-like object to check.601- """602- if hasattr(obj, 'fp'):603- # Object is a container for another file-like object that gets released604- # on exhaustion (e.g. HTTPResponse)605- return obj.fp is None606-607- return obj.closed608-609-610-if SSLContext is not None: # Python 3.2+611- def ssl_wrap_socket(sock, keyfile=None, certfile=None, cert_reqs=None,612- ca_certs=None, server_hostname=None,613- ssl_version=None):614- """615- All arguments except `server_hostname` have the same meaning as for616- :func:`ssl.wrap_socket`617-618- :param server_hostname:619- Hostname of the expected certificate620- """621- context = SSLContext(ssl_version)622- context.verify_mode = cert_reqs623-624- # Disable TLS compression to migitate CRIME attack (issue #309)625- OP_NO_COMPRESSION = 0x20000626- context.options |= OP_NO_COMPRESSION627-628- if ca_certs:629- try:630- context.load_verify_locations(ca_certs)631- # Py32 raises IOError632- # Py33 raises FileNotFoundError633- except Exception as e: # Reraise as SSLError634- raise SSLError(e)635- if certfile:636- # FIXME: This block needs a test.637- context.load_cert_chain(certfile, keyfile)638- if HAS_SNI: # Platform-specific: OpenSSL with enabled SNI639- return context.wrap_socket(sock, server_hostname=server_hostname)640- return context.wrap_socket(sock)641-642-else: # Python 3.1 and earlier643- def ssl_wrap_socket(sock, keyfile=None, certfile=None, cert_reqs=None,644- ca_certs=None, server_hostname=None,645- ssl_version=None):646- return wrap_socket(sock, keyfile=keyfile, certfile=certfile,647- ca_certs=ca_certs, cert_reqs=cert_reqs,648- ssl_version=ssl_version)