Skip to content
Myr

Merge pull request #2017 from Ayper/master

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

Update urllib to 1.8.2

authored by Kenneth Reitz · committed by Kenneth Reitz · parents 826425f, 36b0481 · 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

12 files+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 would2like to verify SSL certificates in Python 2. Note, the default libraries do3*not* do certificate checking; you need to do additional work to validate4certificates yourself.56This needs the following packages installed:78* pyOpenSSL (tested with 0.13)9* ndg-httpsclient (tested with 0.3.2)10* pyasn1 (tested with 0.1.6)119To activate it call :func:`~urllib3.contrib.pyopenssl.inject_into_urllib3`.10This can be done in a ``sitecustomize`` module, or at any other time before11your application begins using ``urllib3``, like this::12You can install them with the following command:1314 pip install pyopenssl ndg-httpsclient pyasn11516To activate certificate checking, call17:func:`~urllib3.contrib.pyopenssl.inject_into_urllib3` from your Python code18before you begin making HTTP requests. This can be done in a ``sitecustomize``19module, or at any other time before your application begins using ``urllib3``,20like this::2122 try:23 import urllib3.contrib.pyopenssl24 urllib3.contrib.pyopenssl.inject_into_urllib3()25 except ImportError:
397 unmodified lines
added: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.php67from .connection import is_connection_dropped8from .request import make_headers9from .response import is_fp_closed10from .ssl_ import (11 SSLContext,12 HAS_SNI,13 assert_fingerprint,14 resolve_cert_reqs,15 resolve_ssl_version,16 ssl_wrap_socket,17)18from .timeout import (19 current_time,20 Timeout,21)22from .url import (23 get_host,24 parse_url,25 split_first,26 Url,27)
added:requests/packages/urllib3/util/connection.py+45 added
1from socket import error as SocketError2try:3 from select import poll, POLLIN4except 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 = False1011def is_connection_dropped(conn): # Platform-specific12 """13 Returns True if the connection is dropped and should be closed.1415 :param conn:16 :class:`httplib.HTTPConnection` object.1718 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 False2627 if not poll:28 if not select: # Platform-specific: AppEngine29 return False3031 try:32 return select([sock], [], [], 0.0)[0]33 except SocketError:34 return True3536 # 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 True434445
added:requests/packages/urllib3/util/request.py+68 added
1from base64 import b64encode23from ..packages import six456ACCEPT_ENCODING = 'gzip,deflate'789def 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.1314 :param keep_alive:15 If ``True``, adds 'connection: keep-alive' header.1617 :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.2223 :param user_agent:24 String representing the user-agent you want, such as25 "python-urllib3/0.6"2627 :param basic_auth:28 Colon-separated username:password string for 'authorization: basic ...'29 auth header.3031 :param proxy_basic_auth:32 Colon-separated username:password string for 'proxy-authorization: basic ...'33 auth header.3435 Example: ::3637 >>> 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_encoding5152 if user_agent:53 headers['user-agent'] = user_agent5455 if keep_alive:56 headers['connection'] = 'keep-alive'5758 if basic_auth:59 headers['authorization'] = 'Basic ' + \60 b64encode(six.b(basic_auth)).decode('utf-8')6162 if proxy_basic_auth:63 headers['proxy-authorization'] = 'Basic ' + \64 b64encode(six.b(proxy_basic_auth)).decode('utf-8')6566 return headers6768
added:requests/packages/urllib3/util/response.py+13 added
1def is_fp_closed(obj):2 """3 Checks whether a given file-like object is closed.45 :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 None1213 return obj.closed
added:requests/packages/urllib3/util/ssl_.py+133 added
1from binascii import hexlify, unhexlify2from hashlib import md5, sha134from ..exceptions import SSLError567try: # Test for SSL features8 SSLContext = None9 HAS_SNI = False1011 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?15except ImportError:16 pass171819def assert_fingerprint(cert, fingerprint):20 """21 Checks if given fingerprint matches the supplied certificate.2223 :param cert:24 Certificate as bytes object.25 :param fingerprint:26 Fingerprint as string of hexdigits, can be interspersed by colons.27 """2829 # Maps the length of a digest to a possible hash function producing30 # this digest.31 hashfunc_map = {32 16: md5,33 20: sha134 }3536 fingerprint = fingerprint.replace(':', '').lower()3738 digest_length, rest = divmod(len(fingerprint), 2)3940 if rest or digest_length not in hashfunc_map:41 raise SSLError('Fingerprint is of invalid length.')4243 # We need encode() here for py32; works on py2 and p33.44 fingerprint_bytes = unhexlify(fingerprint.encode())4546 hashfunc = hashfunc_map[digest_length]4748 cert_digest = hashfunc(cert).digest()4950 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)))545556def 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_NONE6970 if isinstance(candidate, str):71 res = getattr(ssl, candidate, None)72 if res is None:73 res = getattr(ssl, 'CERT_' + candidate)74 return res7576 return candidate777879def resolve_ssl_version(candidate):80 """81 like resolve_cert_reqs82 """83 if candidate is None:84 return PROTOCOL_SSLv238586 if isinstance(candidate, str):87 res = getattr(ssl, candidate, None)88 if res is None:89 res = getattr(ssl, 'PROTOCOL_' + candidate)90 return res9192 return candidate939495if 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`102103 :param server_hostname:104 Hostname of the expected certificate105 """106 context = SSLContext(ssl_version)107 context.verify_mode = cert_reqs108109 # Disable TLS compression to migitate CRIME attack (issue #309)110 OP_NO_COMPRESSION = 0x20000111 context.options |= OP_NO_COMPRESSION112113 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)126127else: # 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
1from socket import _GLOBAL_DEFAULT_TIMEOUT2import time34from ..exceptions import TimeoutStateError567def current_time():8 """9 Retrieve the current time, this function is mocked out in unit testing.10 """11 return time.time()121314_Default = object()15# The default timeout to use for socket connections. This is the attribute used16# by httplib to define the default timeout171819class Timeout(object):20 """21 Utility object for storing timeout values.2223 Example usage:2425 .. code-block:: python2627 timeout = urllib3.util.Timeout(connect=2.0, read=7.0)28 pool = HTTPConnectionPool('www.google.com', 80, timeout=timeout)29 pool.request(...) # Etc, etc3031 :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.3738 :type connect: integer, float, or None3940 :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.4748 :type read: integer, float, or None4950 :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.5556 Defaults to None.5758 :type total: integer, float, or None5960 .. note::6162 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`.6970 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.7879 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 """8384 #: A sentinel object representing the default timeout value85 DEFAULT_TIMEOUT = _GLOBAL_DEFAULT_TIMEOUT8687 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 = None9293 def __str__(self):94 return '%s(connect=%r, read=%r, total=%r)' % (95 type(self).__name__, self._connect, self._read, self.total)969798 @classmethod99 def _validate_timeout(cls, value, name):100 """ Check that a timeout attribute is valid101102 :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_TIMEOUT111112 if value is None or value is cls.DEFAULT_TIMEOUT:113 return value114115 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))120121 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))129130 return value131132 @classmethod133 def from_float(cls, timeout):134 """ Create a new Timeout from a legacy timeout value.135136 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.140141 :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)147148 def clone(self):149 """ Create a copy of the timeout object150151 Timeout properties are stored per-pool but each request needs a fresh152 Timeout object to ensure each one has its own start/stop configured.153154 :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)162163 def start_connect(self):164 """ Start the timeout clock, used during a connect() attempt165166 :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_connect173174 def get_connect_duration(self):175 """ Gets the time elapsed since the call to :meth:`start_connect`.176177 :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_connect186187 @property188 def connect_timeout(self):189 """ Get the value to use when setting a connection timeout.190191 This will be a positive float or integer, the value None192 (never timeout), or the default system timeout.193194 :return: the connect timeout195 :rtype: int, float, :attr:`Timeout.DEFAULT_TIMEOUT` or None196 """197 if self.total is None:198 return self._connect199200 if self._connect is None or self._connect is self.DEFAULT_TIMEOUT:201 return self.total202203 return min(self._connect, self.total)204205 @property206 def read_timeout(self):207 """ Get the value for the read timeout.208209 This assumes some time has elapsed in the connection timeout and210 computes the read timeout appropriately.211212 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.216217 :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._read
added:requests/packages/urllib3/util/url.py+162 added
1from collections import namedtuple23from ..exceptions import LocationParseError456class 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 = ()1213 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)1516 @property17 def hostname(self):18 """For backwards-compatibility with urlparse. We're nice like that."""19 return self.host2021 @property22 def request_uri(self):23 """Absolute path including the query string."""24 uri = self.path or '/'2526 if self.query is not None:27 uri += '?' + self.query2829 return uri3031 @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.host373839def 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.4344 If not found, then the first part is the full input string.4546 Example: ::4748 >>> split_first('foo/bar?baz', '?/=')49 ('foo', 'bar?baz', '/')50 >>> split_first('foo/bar?baz', '123')51 ('foo/bar?baz', '', None)5253 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 continue6162 if min_idx is None or idx < min_idx:63 min_idx = idx64 min_delim = d6566 if min_idx is None or min_idx < 0:67 return s, '', None6869 return s[:min_idx], s[min_idx+1:], min_delim707172def 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.7677 Partly backwards-compatible with :mod:`urlparse`.7879 Example: ::8081 >>> 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 """8889 # 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.9394 scheme = None95 auth = None96 host = None97 port = None98 path = None99 fragment = None100 query = None101102 # Scheme103 if '://' in url:104 scheme, url = url.split('://', 1)105106 # Find the earliest Authority Terminator107 # (http://tools.ietf.org/html/rfc3986#section-3.2)108 url, path_, delim = split_first(url, ['/', '?', '#'])109110 if delim:111 # Reassemble the path112 path = delim + path_113114 # Auth115 if '@' in url:116 # Last '@' denotes end of auth part117 auth, url = url.rsplit('@', 1)118119 # IPv6120 if url and url[0] == '[':121 host, url = url.split(']', 1)122 host += ']'123124 # Port125 if ':' in url:126 _host, port = url.split(':', 1)127128 if not host:129 host = _host130131 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 = None139140 elif not host and url:141 host = url142143 if not path:144 return Url(scheme, auth, host, port, path, query, fragment)145146 # Fragment147 if '#' in path:148 path, fragment = path.split('#', 1)149150 # Query151 if '?' in path:152 path, query = path.split('?', 1)153154 return Url(scheme, auth, host, port, path, query, fragment)155156157def 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.port
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__ = '1.8'13__version__ = '1.8.2'141516from .connectionpool import (17 HTTPConnectionPool,
41 unmodified lines
modified:requests/packages/urllib3/connection.py+22 added-20 removed
66 unmodified lines
6768 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 earlier71 if sys.version_info < (2, 7): # Python 2.6 and older72 kw.pop('source_address', None)74 self.source_address = None7376 _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')7677 # Superclass also sets self.source_address in Python 2.7+.78 _HTTPConnection.__init__(self, *args, **kw) 7980 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.8283 :return: a new socket connection84 """85 extra_args = []86 if self.source_address: # Python 2.7+87 extra_args.append(self.source_address)8889 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)9394 return conn9596 def _prepare_conn(self, conn):97 self.sock = conn
9 unmodified lines
107class HTTPSConnection(HTTPConnection):108 default_port = port_by_scheme['https']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):111 strict=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT, **kw):112114 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)115116 self.key_file = key_file117 self.cert_file = cert_file118119 # 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'122123 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 lines
133 """134 cert_reqs = None135 ca_certs = None136 ssl_version = None137 conn_kw = {}138139 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 lines
148 self.assert_fingerprint = assert_fingerprint149150 def connect(self):151 # Add certificate verification152153 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 lines
modified:requests/packages/urllib3/connectionpool.py+20 added-5 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 errno9import logging1011from socket import error as SocketError, timeout as SocketTimeout
11 unmodified lines
23 ConnectionError,24 ConnectTimeoutError,25 EmptyPoolError,26 HostChangedError,27 LocationParseError,28 MaxRetryError,29 SSLError,30 TimeoutError,31 ReadTimeoutError,
9 unmodified lines
41)42from .request import RequestMethods43from .response import HTTPResponse44from .util import (43 assert_fingerprint,45 get_host,46 is_connection_dropped,47 Timeout,48)
16 unmodified lines
65 scheme = None66 QueueCls = LifoQueue6768 def __init__(self, host, port=None):69 if host is None:70 raise LocationParseError(host)7172 # httplib doesn't like it when we include brackets in ipv6 addresses73 host = host.strip('[]')7475 self.host = host
63 unmodified lines
139 ConnectionCls = HTTPConnection140141 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)146147 self.strict = strict
18 unmodified lines
166 # These are mostly for testing and debugging purposes.167 self.num_connections = 0168 self.num_requests = 0169170 if sys.version_info < (2, 7): # Python 2.6 and older171 conn_kw.pop('source_address', None)172 self.conn_kw = conn_kw173174 def _new_conn(self):175 """176 Return a fresh :class:`HTTPConnection`.177 """
2 unmodified lines
180 (self.num_connections, self.host))181182 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 = 0
412 unmodified lines
601 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):607608 if sys.version_info < (2, 7): # Python 2.6 or older609 conn_kw.pop('source_address', None)610611 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_kw621622 def _prepare_conn(self, conn):623 """624 Prepare the ``connection`` for :meth:`urllib3.util.ssl_wrap_socket`
7 unmodified lines
632 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_kw637638 if self.proxy is not None:639 # Python 2.7+640 try:
28 unmodified lines
669670 extra_params = {}671 if not six.PY3: # Python 2672 extra_params['strict'] = self.strict673 extra_params.update(self.conn_kw)674675 conn = self.ConnectionCls(host=actual_host, port=actual_port,676 timeout=self.timeout.connect_timeout,677 **extra_params)
33 unmodified lines
deleted: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.php678from base64 import b64encode9from binascii import hexlify, unhexlify10from collections import namedtuple11from hashlib import md5, sha112from socket import error as SocketError, _GLOBAL_DEFAULT_TIMEOUT13import time1415try:16 from select import poll, POLLIN17except 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 = False2324try: # Test for SSL features25 SSLContext = None26 HAS_SNI = False2728 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?32except ImportError:33 pass3435from .packages import six36from .exceptions import LocationParseError, SSLError, TimeoutStateError373839_Default = object()40# The default timeout to use for socket connections. This is the attribute used41# by httplib to define the default timeout424344def current_time():45 """46 Retrieve the current time, this function is mocked out in unit testing.47 """48 return time.time()495051class Timeout(object):52 """53 Utility object for storing timeout values.5455 Example usage:5657 .. code-block:: python5859 timeout = urllib3.util.Timeout(connect=2.0, read=7.0)60 pool = HTTPConnectionPool('www.google.com', 80, timeout=timeout)61 pool.request(...) # Etc, etc6263 :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.6970 :type connect: integer, float, or None7172 :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.7980 :type read: integer, float, or None8182 :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.8788 Defaults to None.8990 :type total: integer, float, or None9192 .. note::9394 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`.101102 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.110111 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 """115116 #: A sentinel object representing the default timeout value117 DEFAULT_TIMEOUT = _GLOBAL_DEFAULT_TIMEOUT118119 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 = None124125 def __str__(self):126 return '%s(connect=%r, read=%r, total=%r)' % (127 type(self).__name__, self._connect, self._read, self.total)128129130 @classmethod131 def _validate_timeout(cls, value, name):132 """ Check that a timeout attribute is valid133134 :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_TIMEOUT143144 if value is None or value is cls.DEFAULT_TIMEOUT:145 return value146147 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))152153 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))161162 return value163164 @classmethod165 def from_float(cls, timeout):166 """ Create a new Timeout from a legacy timeout value.167168 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.172173 :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)179180 def clone(self):181 """ Create a copy of the timeout object182183 Timeout properties are stored per-pool but each request needs a fresh184 Timeout object to ensure each one has its own start/stop configured.185186 :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)194195 def start_connect(self):196 """ Start the timeout clock, used during a connect() attempt197198 :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_connect205206 def get_connect_duration(self):207 """ Gets the time elapsed since the call to :meth:`start_connect`.208209 :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_connect218219 @property220 def connect_timeout(self):221 """ Get the value to use when setting a connection timeout.222223 This will be a positive float or integer, the value None224 (never timeout), or the default system timeout.225226 :return: the connect timeout227 :rtype: int, float, :attr:`Timeout.DEFAULT_TIMEOUT` or None228 """229 if self.total is None:230 return self._connect231232 if self._connect is None or self._connect is self.DEFAULT_TIMEOUT:233 return self.total234235 return min(self._connect, self.total)236237 @property238 def read_timeout(self):239 """ Get the value for the read timeout.240241 This assumes some time has elapsed in the connection timeout and242 computes the read timeout appropriately.243244 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.248249 :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._read267268269class 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 = ()275276 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)278279 @property280 def hostname(self):281 """For backwards-compatibility with urlparse. We're nice like that."""282 return self.host283284 @property285 def request_uri(self):286 """Absolute path including the query string."""287 uri = self.path or '/'288289 if self.query is not None:290 uri += '?' + self.query291292 return uri293294 @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.host300301302def 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.306307 If not found, then the first part is the full input string.308309 Example: ::310311 >>> split_first('foo/bar?baz', '?/=')312 ('foo', 'bar?baz', '/')313 >>> split_first('foo/bar?baz', '123')314 ('foo/bar?baz', '', None)315316 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 continue324325 if min_idx is None or idx < min_idx:326 min_idx = idx327 min_delim = d328329 if min_idx is None or min_idx < 0:330 return s, '', None331332 return s[:min_idx], s[min_idx+1:], min_delim333334335def 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.339340 Partly backwards-compatible with :mod:`urlparse`.341342 Example: ::343344 >>> 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 """351352 # 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.356357 scheme = None358 auth = None359 host = None360 port = None361 path = None362 fragment = None363 query = None364365 # Scheme366 if '://' in url:367 scheme, url = url.split('://', 1)368369 # Find the earliest Authority Terminator370 # (http://tools.ietf.org/html/rfc3986#section-3.2)371 url, path_, delim = split_first(url, ['/', '?', '#'])372373 if delim:374 # Reassemble the path375 path = delim + path_376377 # Auth378 if '@' in url:379 # Last '@' denotes end of auth part380 auth, url = url.rsplit('@', 1)381382 # IPv6383 if url and url[0] == '[':384 host, url = url.split(']', 1)385 host += ']'386387 # Port388 if ':' in url:389 _host, port = url.split(':', 1)390391 if not host:392 host = _host393394 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 = None402403 elif not host and url:404 host = url405406 if not path:407 return Url(scheme, auth, host, port, path, query, fragment)408409 # Fragment410 if '#' in path:411 path, fragment = path.split('#', 1)412413 # Query414 if '?' in path:415 path, query = path.split('?', 1)416417 return Url(scheme, auth, host, port, path, query, fragment)418419420def 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.port426427428def 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.432433 :param keep_alive:434 If ``True``, adds 'connection: keep-alive' header.435436 :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.441442 :param user_agent:443 String representing the user-agent you want, such as444 "python-urllib3/0.6"445446 :param basic_auth:447 Colon-separated username:password string for 'authorization: basic ...'448 auth header.449450 :param proxy_basic_auth:451 Colon-separated username:password string for 'proxy-authorization: basic ...'452 auth header.453454 Example: ::455456 >>> 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_encoding470471 if user_agent:472 headers['user-agent'] = user_agent473474 if keep_alive:475 headers['connection'] = 'keep-alive'476477 if basic_auth:478 headers['authorization'] = 'Basic ' + \479 b64encode(six.b(basic_auth)).decode('utf-8')480481 if proxy_basic_auth:482 headers['proxy-authorization'] = 'Basic ' + \483 b64encode(six.b(proxy_basic_auth)).decode('utf-8')484485 return headers486487488def is_connection_dropped(conn): # Platform-specific489 """490 Returns True if the connection is dropped and should be closed.491492 :param conn:493 :class:`httplib.HTTPConnection` object.494495 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 False501502 if not poll:503 if not select: # Platform-specific: AppEngine504 return False505506 try:507 return select([sock], [], [], 0.0)[0]508 except SocketError:509 return True510511 # 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 True518519520def 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_NONE533534 if isinstance(candidate, str):535 res = getattr(ssl, candidate, None)536 if res is None:537 res = getattr(ssl, 'CERT_' + candidate)538 return res539540 return candidate541542543def resolve_ssl_version(candidate):544 """545 like resolve_cert_reqs546 """547 if candidate is None:548 return PROTOCOL_SSLv23549550 if isinstance(candidate, str):551 res = getattr(ssl, candidate, None)552 if res is None:553 res = getattr(ssl, 'PROTOCOL_' + candidate)554 return res555556 return candidate557558559def assert_fingerprint(cert, fingerprint):560 """561 Checks if given fingerprint matches the supplied certificate.562563 :param cert:564 Certificate as bytes object.565 :param fingerprint:566 Fingerprint as string of hexdigits, can be interspersed by colons.567 """568569 # Maps the length of a digest to a possible hash function producing570 # this digest.571 hashfunc_map = {572 16: md5,573 20: sha1574 }575576 fingerprint = fingerprint.replace(':', '').lower()577578 digest_length, rest = divmod(len(fingerprint), 2)579580 if rest or digest_length not in hashfunc_map:581 raise SSLError('Fingerprint is of invalid length.')582583 # We need encode() here for py32; works on py2 and p33.584 fingerprint_bytes = unhexlify(fingerprint.encode())585586 hashfunc = hashfunc_map[digest_length]587588 cert_digest = hashfunc(cert).digest()589590 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)))594595def is_fp_closed(obj):596 """597 Checks whether a given file-like object is closed.598599 :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 None606607 return obj.closed608609610if 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`617618 :param server_hostname:619 Hostname of the expected certificate620 """621 context = SSLContext(ssl_version)622 context.verify_mode = cert_reqs623624 # Disable TLS compression to migitate CRIME attack (issue #309)625 OP_NO_COMPRESSION = 0x20000626 context.options |= OP_NO_COMPRESSION627628 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)641642else: # 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)