Skip to content
Myr

new urllib3

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

authored by Kenneth Reitz · committed by Kenneth Reitz · parent 2affd63 · Browse files · 9 files+850 added−105 removed
This commit

State

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

Diff stats

9 files+850 added−105 removed

  • other:+850 added−105 removed

9 files+850 added−105 removed

modified:requests/packages/urllib3/contrib/pyopenssl.py+179 added-8 removed
18 unmodified lines
19Now you can use :mod:`urllib3` as you normally would, and it will support SNI20when the required modules are installed.21'''2223from ndg.httpsclient.ssl_peer_verification import (ServerSSLCertVerification,24 SUBJ_ALT_NAME_SUPPORT)23from ndg.httpsclient.ssl_peer_verification import SUBJ_ALT_NAME_SUPPORT24from ndg.httpsclient.subj_alt_name import SubjectAltName25import OpenSSL.SSL26from pyasn1.codec.der import decoder as der_decoder27from socket import _fileobject28import ssl29from cStringIO import StringIO3031from .. import connectionpool32from .. import util33
64 unmodified lines
9899 return dns_name100101102class fileobject(_fileobject):103104 def read(self, size=-1):105 # Use max, disallow tiny reads in a loop as they are very inefficient.106 # We never leave read() with any leftover data from a new recv() call107 # in our internal buffer.108 rbufsize = max(self._rbufsize, self.default_bufsize)109 # Our use of StringIO rather than lists of string objects returned by110 # recv() minimizes memory usage and fragmentation that occurs when111 # rbufsize is large compared to the typical return value of recv().112 buf = self._rbuf113 buf.seek(0, 2) # seek end114 if size < 0:115 # Read until EOF116 self._rbuf = StringIO() # reset _rbuf. we consume it via buf.117 while True:118 try:119 data = self._sock.recv(rbufsize)120 except OpenSSL.SSL.WantReadError:121 continue122 if not data:123 break124 buf.write(data)125 return buf.getvalue()126 else:127 # Read until size bytes or EOF seen, whichever comes first128 buf_len = buf.tell()129 if buf_len >= size:130 # Already have size bytes in our buffer? Extract and return.131 buf.seek(0)132 rv = buf.read(size)133 self._rbuf = StringIO()134 self._rbuf.write(buf.read())135 return rv136137 self._rbuf = StringIO() # reset _rbuf. we consume it via buf.138 while True:139 left = size - buf_len140 # recv() will malloc the amount of memory given as its141 # parameter even though it often returns much less data142 # than that. The returned data string is short lived143 # as we copy it into a StringIO and free it. This avoids144 # fragmentation issues on many platforms.145 try:146 data = self._sock.recv(left)147 except OpenSSL.SSL.WantReadError:148 continue149 if not data:150 break151 n = len(data)152 if n == size and not buf_len:153 # Shortcut. Avoid buffer data copies when:154 # - We have no data in our buffer.155 # AND156 # - Our call to recv returned exactly the157 # number of bytes we were asked to read.158 return data159 if n == left:160 buf.write(data)161 del data # explicit free162 break163 assert n <= left, "recv(%d) returned %d bytes" % (left, n)164 buf.write(data)165 buf_len += n166 del data # explicit free167 #assert buf_len == buf.tell()168 return buf.getvalue()169170 def readline(self, size=-1):171 buf = self._rbuf172 buf.seek(0, 2) # seek end173 if buf.tell() > 0:174 # check if we already have it in our buffer175 buf.seek(0)176 bline = buf.readline(size)177 if bline.endswith('\n') or len(bline) == size:178 self._rbuf = StringIO()179 self._rbuf.write(buf.read())180 return bline181 del bline182 if size < 0:183 # Read until \n or EOF, whichever comes first184 if self._rbufsize <= 1:185 # Speed up unbuffered case186 buf.seek(0)187 buffers = [buf.read()]188 self._rbuf = StringIO() # reset _rbuf. we consume it via buf.189 data = None190 recv = self._sock.recv191 while True:192 try:193 while data != "\n":194 data = recv(1)195 if not data:196 break197 buffers.append(data)198 except OpenSSL.SSL.WantReadError:199 continue200 break201 return "".join(buffers)202203 buf.seek(0, 2) # seek end204 self._rbuf = StringIO() # reset _rbuf. we consume it via buf.205 while True:206 try:207 data = self._sock.recv(self._rbufsize)208 except OpenSSL.SSL.WantReadError:209 continue210 if not data:211 break212 nl = data.find('\n')213 if nl >= 0:214 nl += 1215 buf.write(data[:nl])216 self._rbuf.write(data[nl:])217 del data218 break219 buf.write(data)220 return buf.getvalue()221 else:222 # Read until size bytes or \n or EOF seen, whichever comes first223 buf.seek(0, 2) # seek end224 buf_len = buf.tell()225 if buf_len >= size:226 buf.seek(0)227 rv = buf.read(size)228 self._rbuf = StringIO()229 self._rbuf.write(buf.read())230 return rv231 self._rbuf = StringIO() # reset _rbuf. we consume it via buf.232 while True:233 try:234 data = self._sock.recv(self._rbufsize)235 except OpenSSL.SSL.WantReadError:236 continue237 if not data:238 break239 left = size - buf_len240 # did we just receive a newline?241 nl = data.find('\n', 0, left)242 if nl >= 0:243 nl += 1244 # save the excess data to _rbuf245 self._rbuf.write(data[nl:])246 if buf_len:247 buf.write(data[:nl])248 break249 else:250 # Shortcut. Avoid data copy through buf when returning251 # a substring of our first recv().252 return data[:nl]253 n = len(data)254 if n == size and not buf_len:255 # Shortcut. Avoid data copy through buf when256 # returning exactly all of our first recv().257 return data258 if n >= left:259 buf.write(data[:left])260 self._rbuf.write(data[left:])261 break262 buf.write(data)263 buf_len += n264 #assert buf_len == buf.tell()265 return buf.getvalue()266267268class WrappedSocket(object):269 '''API-compatibility wrapper for Python OpenSSL's Connection-class.'''270271 def __init__(self, connection, socket):
3 unmodified lines
275 def fileno(self):276 return self.socket.fileno()277278 def makefile(self, mode, bufsize=-1):113 return _fileobject(self.connection, mode, bufsize)279 return fileobject(self.connection, mode, bufsize)280281 def settimeout(self, timeout):282 return self.socket.settimeout(timeout)283
4 unmodified lines
288 return self.connection.shutdown()289290 def getpeercert(self, binary_form=False):291 x509 = self.connection.get_peer_certificate()292293 if not x509:127 raise ssl.SSLError('')294 return x509295296 if binary_form:297 return OpenSSL.crypto.dump_certificate(298 OpenSSL.crypto.FILETYPE_ASN1,
32 unmodified lines
331332 cnx = OpenSSL.SSL.Connection(ctx, sock)333 cnx.set_tlsext_host_name(server_hostname)334 cnx.set_connect_state()335 while True:168 try:169 cnx.do_handshake()170 except OpenSSL.SSL.Error as e:171 raise ssl.SSLError('bad handshake', e)336 try:337 cnx.do_handshake()338 except OpenSSL.SSL.WantReadError:339 continue340 except OpenSSL.SSL.Error as e:341 raise ssl.SSLError('bad handshake', e)342 break343344 return WrappedSocket(cnx, sock)
modified:requests/packages/urllib3/packages/ssl_match_hostname/__init__.py+52 added-15 removed
5 unmodified lines
67class CertificateError(ValueError):8 pass910def _dnsname_to_pat(dn):10def _dnsname_match(dn, hostname, max_wildcards=1):11 """Matching according to RFC 6125, section 6.4.31213 http://tools.ietf.org/html/rfc6125#section-6.4.314 """15 pats = []12 for frag in dn.split(r'.'):13 if frag == '*':14 # When '*' is a fragment by itself, it matches a non-empty dotless15 # fragment.16 pats.append('[^.]+')17 else:18 # Otherwise, '*' matches any dotless fragment.19 frag = re.escape(frag)20 pats.append(frag.replace(r'\*', '[^.]*'))21 return re.compile(r'\A' + r'\.'.join(pats) + r'\Z', re.IGNORECASE)16 if not dn:17 return False1819 parts = dn.split(r'.')20 leftmost = parts[0]2122 wildcards = leftmost.count('*')23 if wildcards > max_wildcards:24 # Issue #17980: avoid denials of service by refusing more25 # than one wildcard per fragment. A survery of established26 # policy among SSL implementations showed it to be a27 # reasonable choice.28 raise CertificateError(29 "too many wildcards in certificate DNS name: " + repr(dn))3031 # speed up common case w/o wildcards32 if not wildcards:33 return dn.lower() == hostname.lower()3435 # RFC 6125, section 6.4.3, subitem 1.36 # The client SHOULD NOT attempt to match a presented identifier in which37 # the wildcard character comprises a label other than the left-most label.38 if leftmost == '*':39 # When '*' is a fragment by itself, it matches a non-empty dotless40 # fragment.41 pats.append('[^.]+')42 elif leftmost.startswith('xn--') or hostname.startswith('xn--'):43 # RFC 6125, section 6.4.3, subitem 3.44 # The client SHOULD NOT attempt to match a presented identifier45 # where the wildcard character is embedded within an A-label or46 # U-label of an internationalized domain name.47 pats.append(re.escape(leftmost))48 else:49 # Otherwise, '*' matches any dotless string, e.g. www*50 pats.append(re.escape(leftmost).replace(r'\*', '[^.]*'))5152 # add the remaining fragments, ignore any wildcards53 for frag in parts[1:]:54 pats.append(re.escape(frag))5556 pat = re.compile(r'\A' + r'\.'.join(pats) + r'\Z', re.IGNORECASE)57 return pat.match(hostname)585960def match_hostname(cert, hostname):61 """Verify that *cert* (in decoded format as returned by25 SSLSocket.getpeercert()) matches the *hostname*. RFC 2818 rules26 are mostly followed, but IP addresses are not accepted for *hostname*.62 SSLSocket.getpeercert()) matches the *hostname*. RFC 2818 and RFC 612563 rules are followed, but IP addresses are not accepted for *hostname*.6465 CertificateError is raised on failure. On success, the function66 returns nothing.67 """
2 unmodified lines
70 dnsnames = []71 san = cert.get('subjectAltName', ())72 for key, value in san:73 if key == 'DNS':37 if _dnsname_to_pat(value).match(hostname):74 if _dnsname_match(value, hostname):75 return76 dnsnames.append(value)77 if not dnsnames:78 # The subject is only checked when there is no dNSName entry
2 unmodified lines
81 for key, value in sub:82 # XXX according to RFC 2818, the most specific Common Name83 # must be used.84 if key == 'commonName':48 if _dnsname_to_pat(value).match(hostname):85 if _dnsname_match(value, hostname):86 return87 dnsnames.append(value)88 if len(dnsnames) > 1:89 raise CertificateError("hostname %r "
9 unmodified lines
modified:requests/packages/urllib3/__init__.py+1 added-1 removed
21 unmodified lines
22from . import exceptions23from .filepost import encode_multipart_formdata24from .poolmanager import PoolManager, ProxyManager, proxy_from_url25from .response import HTTPResponse26from .util import make_headers, get_host26from .util import make_headers, get_host, Timeout272829# Set default logging handler to avoid "No handler found" warnings.30import logging
28 unmodified lines
modified:requests/packages/urllib3/connectionpool.py+151 added-48 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 logging8import socket7import errno8import logging910from socket import error as SocketError, timeout as SocketTimeout12from .util import resolve_cert_reqs, resolve_ssl_version, assert_fingerprint11import socket1213try: # Python 314 from http.client import HTTPConnection, HTTPException15 from http.client import HTTP_PORT, HTTPS_PORT
4 unmodified lines
20try: # Python 321 from queue import LifoQueue, Empty, Full22except ImportError:23 from Queue import LifoQueue, Empty, Full24 import Queue as _ # Platform-specific: Windows252627try: # Compiled with SSL?28 HTTPSConnection = object
14 unmodified lines
43except (ImportError, AttributeError): # Platform-specific: No SSL.44 pass454647from .request import RequestMethods48from .response import HTTPResponse49from .util import get_host, is_connection_dropped, ssl_wrap_socket47from .exceptions import (48 ClosedPoolError,49 ConnectTimeoutError,50 EmptyPoolError,51 HostChangedError,52 MaxRetryError,53 SSLError,56 TimeoutError,54 ReadTimeoutError,55 ProxyError,56)5859from .packages.ssl_match_hostname import match_hostname, CertificateError57from .packages.ssl_match_hostname import CertificateError, match_hostname58from .packages import six59from .request import RequestMethods60from .response import HTTPResponse61from .util import (62 assert_fingerprint,63 get_host,64 is_connection_dropped,65 resolve_cert_reqs,66 resolve_ssl_version,67 ssl_wrap_socket,68 Timeout,69)706271xrange = six.moves.xrange7273log = logging.getLogger(__name__)74
28 unmodified lines
103 self.assert_fingerprint = assert_fingerprint104105 def connect(self):106 # Add certificate verification99 sock = socket.create_connection((self.host, self.port), self.timeout)107 try:108 sock = socket.create_connection(109 address=(self.host, self.port),110 timeout=self.timeout)111 except SocketTimeout:112 raise ConnectTimeoutError(113 self, "Connection to %s timed out. (connect timeout=%s)" %114 (self.host, self.timeout))115116 resolved_cert_reqs = resolve_cert_reqs(self.cert_reqs)117 resolved_ssl_version = resolve_ssl_version(self.ssl_version)118
18 unmodified lines
137 elif self.assert_hostname is not False:138 match_hostname(self.sock.getpeercert(),139 self.assert_hostname or self.host)140141142## Pool objects143144class ConnectionPool(object):145 """
4 unmodified lines
150 scheme = None151 QueueCls = LifoQueue152153 def __init__(self, host, port=None):154 # httplib doesn't like it when we include brackets in ipv6 addresses155 host = host.strip('[]')156157 self.host = host158 self.port = port159160 def __str__(self):161 return '%s(host=%r, port=%r)' % (type(self).__name__,162 self.host, self.port)163164# This is taken from http://hg.python.org/cpython/file/7aaba721ebc0/Lib/socket.py#l252165_blocking_errnos = set([errno.EAGAIN, errno.EWOULDBLOCK])166167class HTTPConnectionPool(ConnectionPool, RequestMethods):168 """169 Thread-safe connection pool for one host.
10 unmodified lines
180 Causes BadStatusLine to be raised if the status line can't be parsed181 as a valid HTTP/1.0 or 1.1 status line, passed into182 :class:`httplib.HTTPConnection`.183184 .. note::185 Only works in Python 2. This parameter is ignored in Python 3.186187 :param timeout:164 Socket timeout in seconds for each individual connection, can be165 a float. None disables timeout.188 Socket timeout in seconds for each individual connection. This can189 be a float or integer, which sets the timeout for the HTTP request,190 or an instance of :class:`urllib3.util.Timeout` which gives you more191 fine-grained control over request timeouts. After the constructor has192 been parsed, this is always a `urllib3.util.Timeout` object.193194 :param maxsize:195 Number of connections to save that can be reused. More than 1 is useful196 in multithreaded situations. If ``block`` is set to false, more
21 unmodified lines
218 """219220 scheme = 'http'221195 def __init__(self, host, port=None, strict=False, timeout=None, maxsize=1,196 block=False, headers=None, _proxy=None, _proxy_headers=None):222 def __init__(self, host, port=None, strict=False,223 timeout=Timeout.DEFAULT_TIMEOUT, maxsize=1, block=False,224 headers=None, _proxy=None, _proxy_headers=None):225 ConnectionPool.__init__(self, host, port)226 RequestMethods.__init__(self, headers)227228 self.strict = strict229230 # This is for backwards compatibility and can be removed once a timeout231 # can only be set to a Timeout object232 if not isinstance(timeout, Timeout):233 timeout = Timeout.from_float(timeout)234235 self.timeout = timeout236237 self.pool = self.QueueCls(maxsize)238 self.block = block239240 self.proxy = _proxy
13 unmodified lines
254 """255 self.num_connections += 1256 log.info("Starting new HTTP connection (%d): %s" %257 (self.num_connections, self.host))223 return HTTPConnection(host=self.host,224 port=self.port,225 strict=self.strict)258 extra_params = {}259 if not six.PY3: # Python 2260 extra_params['strict'] = self.strict261262 return HTTPConnection(host=self.host, port=self.port,263 timeout=self.timeout.connect_timeout,264 **extra_params)265266267 def _get_conn(self, timeout=None):268 """269 Get a connection. Will return a pooled connection if one is available.270
51 unmodified lines
322 log.warning("HttpConnectionPool is full, discarding connection: %s"323 % self.host)324325 # Connection never got put back into the pool, close it.326 if conn:286 conn.close()327 conn.close()328329 def _get_timeout(self, timeout):330 """ Helper that always returns a :class:`urllib3.util.Timeout` """331 if timeout is _Default:332 return self.timeout.clone()333334 if isinstance(timeout, Timeout):335 return timeout.clone()336 else:337 # User passed us an int/float. This is for backwards compatibility,338 # can be removed later339 return Timeout.from_float(timeout)340341 def _make_request(self, conn, method, url, timeout=_Default,342 **httplib_request_kw):343 """344 Perform a request on a given httplib connection object taken from our345 pool.346347 :param conn:348 a connection from one of our connection pools349350 :param timeout:351 Socket timeout in seconds for the request. This can be a352 float or integer, which will set the same timeout value for353 the socket connect and the socket read, or an instance of354 :class:`urllib3.util.Timeout`, which gives you more fine-grained355 control over your timeouts.356 """357 self.num_requests += 1358296 if timeout is _Default:297 timeout = self.timeout359 timeout_obj = self._get_timeout(timeout)360299 conn.timeout = timeout # This only does anything in Py26+300 conn.request(method, url, **httplib_request_kw)361 try:362 timeout_obj.start_connect()363 conn.timeout = timeout_obj.connect_timeout364 # conn.request() calls httplib.*.request, not the method in365 # request.py. It also calls makefile (recv) on the socket366 conn.request(method, url, **httplib_request_kw)367 except SocketTimeout:368 raise ConnectTimeoutError(369 self, "Connection to %s timed out. (connect timeout=%s)" %370 (self.host, timeout_obj.connect_timeout))371302 # Set timeout303 sock = getattr(conn, 'sock', False) # AppEngine doesn't have sock attr.304 if sock:305 sock.settimeout(timeout)372 # Reset the timeout for the recv() on the socket373 read_timeout = timeout_obj.read_timeout374 log.debug("Setting read timeout to %s" % read_timeout)375 # App Engine doesn't have a sock attr376 if hasattr(conn, 'sock') and \377 read_timeout is not None and \378 read_timeout is not Timeout.DEFAULT_TIMEOUT:379 # In Python 3 socket.py will catch EAGAIN and return None when you380 # try and read into the file pointer created by http.client, which381 # instead raises a BadStatusLine exception. Instead of catching382 # the exception and assuming all BadStatusLine exceptions are read383 # timeouts, check for a zero timeout before making the request.384 if read_timeout == 0:385 raise ReadTimeoutError(386 self, url,387 "Read timed out. (read timeout=%s)" % read_timeout)388 conn.sock.settimeout(read_timeout)389390 # Receive the response from the server391 try:307 try: # Python 2.7+, use buffering of HTTP responses308 httplib_response = conn.getresponse(buffering=True)309 except TypeError: # Python 2.6 and older310 httplib_response = conn.getresponse()392 try: # Python 2.7+, use buffering of HTTP responses393 httplib_response = conn.getresponse(buffering=True)394 except TypeError: # Python 2.6 and older395 httplib_response = conn.getresponse()396 except SocketTimeout:397 raise ReadTimeoutError(398 self, url, "Read timed out. (read timeout=%s)" % read_timeout)399400 except SocketError as e: # Platform-specific: Python 2401 # See the above comment about EAGAIN in Python 3. In Python 2 we402 # have to specifically catch it and throw the timeout error403 if e.errno in _blocking_errnos:404 raise ReadTimeoutError(405 self, url,406 "Read timed out. (read timeout=%s)" % read_timeout)407 raise408409410 # AppEngine doesn't have a version attr.411 http_version = getattr(conn, '_http_vsn_str', 'HTTP/?')412 log.debug("\"%s %s %s\" %s %s" % (method, url, http_version,413 httplib_response.status,
70 unmodified lines
484 Number of retries to allow before raising a MaxRetryError exception.485486 :param redirect:487 If True, automatically handle redirects (status codes 301, 302,390 303, 307). Each redirect counts as a retry.488 303, 307, 308). Each redirect counts as a retry.489490 :param assert_same_host:491 If ``True``, will make sure that the host of the pool requests is492 consistent else will raise HostChangedError. When False, you can493 use the pool on an HTTP proxy and request foreign hosts.494495 :param timeout:398 If specified, overrides the default timeout for this one request.399 It may be a float (in seconds).496 If specified, overrides the default timeout for this one497 request. It may be a float (in seconds) or an instance of498 :class:`urllib3.util.Timeout`.499500 :param pool_timeout:501 If set and the pool is set to block=True, then this method will502 block for ``pool_timeout`` seconds and raise EmptyPoolError if no
18 unmodified lines
521522 if retries < 0:523 raise MaxRetryError(self, url)524426 if timeout is _Default:427 timeout = self.timeout428525 if release_conn is None:526 release_conn = response_kw.get('preload_content', True)527528 # Check host
27 unmodified lines
556 # The connection will be put back into the pool when557 # ``response.release_conn()`` is called (implicitly by558 # ``response.read()``)559464 except Empty as e:560 except Empty:561 # Timed out by queue466 raise TimeoutError(self, url,467 "Request timed out. (pool_timeout=%s)" %468 pool_timeout)562 raise ReadTimeoutError(563 self, url, "Read timed out, no pool connections are available.")564470 except SocketTimeout as e:565 except SocketTimeout:566 # Timed out by socket472 raise TimeoutError(self, url,473 "Request timed out. (timeout=%s)" %474 timeout)567 raise ReadTimeoutError(self, url, "Read timed out.")568569 except BaseSSLError as e:570 # SSL certificate error571 if 'timed out' in str(e) or \572 'did not complete (read)' in str(e): # Platform-specific: Python 2.6573 raise ReadTimeoutError(self, url, "Read timed out.")574 raise SSLError(e)575576 except CertificateError as e:577 # Name mismatch578 raise SSLError(e)579580 except (HTTPException, SocketError) as e:581 if isinstance(e, SocketError) and self.proxy is not None:582 raise ProxyError('Cannot connect to proxy. '583 'Socket error: %s.' % e)584585 # Connection broken, discard. It will be replaced next _get_conn().586 conn = None587 # This is necessary so we can access e below588 err = e
58 unmodified lines
647 key_file=None, cert_file=None, cert_reqs=None,648 ca_certs=None, ssl_version=None,649 assert_hostname=None, assert_fingerprint=None):650551 HTTPConnectionPool.__init__(self, host, port,552 strict, timeout, maxsize,651 HTTPConnectionPool.__init__(self, host, port, strict, timeout, maxsize,652 block, headers, _proxy, _proxy_headers)653 self.key_file = key_file654 self.cert_file = cert_file655 self.cert_reqs = cert_reqs
51 unmodified lines
707 connection_class = HTTPSConnection708 else:709 connection_class = VerifiedHTTPSConnection710711 extra_params = {}712 if not six.PY3: # Python 2713 extra_params['strict'] = self.strict714 connection = connection_class(host=actual_host, port=actual_port,613 strict=self.strict)715 timeout=self.timeout.connect_timeout,716 **extra_params)717718 return self._prepare_conn(connection)719720
25 unmodified lines
modified:requests/packages/urllib3/exceptions.py+28 added-2 removed
37 unmodified lines
38 "Raised when SSL certificate fails in an HTTPS connection."39 pass404142class ProxyError(HTTPError):43 "Raised when the connection to a proxy fails."44 pass454647class DecodeError(HTTPError):48 "Raised when automatic decoding based on Content-Type fails."49 pass50
23 unmodified lines
74 RequestError.__init__(self, pool, url, message)75 self.retries = retries767773class TimeoutError(RequestError):74 "Raised when a socket timeout occurs."78class TimeoutStateError(HTTPError):79 """ Raised when passing an invalid state to a timeout """80 pass818283class TimeoutError(HTTPError):84 """ Raised when a socket timeout error occurs.8586 Catching this error will catch both :exc:`ReadTimeoutErrors87 <ReadTimeoutError>` and :exc:`ConnectTimeoutErrors <ConnectTimeoutError>`.88 """89 pass909192class ReadTimeoutError(TimeoutError, RequestError):93 "Raised when a socket timeout occurs while receiving data from a server"94 pass959697# This timeout error does not have a URL attached and needs to inherit from the98# base HTTPError99class ConnectTimeoutError(TimeoutError):100 "Raised when a socket timeout occurs while connecting to a server"101 pass102103104class EmptyPoolError(PoolError):105 "Raised when a pool runs out of connections and no more are allowed."106 pass107
14 unmodified lines
added:requests/packages/urllib3/fields.py+177 added
1# urllib3/fields.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.php67import email.utils8import mimetypes910from .packages import six111213def guess_content_type(filename, default='application/octet-stream'):14 """15 Guess the "Content-Type" of a file.1617 :param filename:18 The filename to guess the "Content-Type" of using :mod:`mimetimes`.19 :param default:20 If no "Content-Type" can be guessed, default to `default`.21 """22 if filename:23 return mimetypes.guess_type(filename)[0] or default24 return default252627def format_header_param(name, value):28 """29 Helper function to format and quote a single header parameter.3031 Particularly useful for header parameters which might contain32 non-ASCII values, like file names. This follows RFC 2231, as33 suggested by RFC 2388 Section 4.4.3435 :param name:36 The name of the parameter, a string expected to be ASCII only.37 :param value:38 The value of the parameter, provided as a unicode string.39 """40 if not any(ch in value for ch in '"\\\r\n'):41 result = '%s="%s"' % (name, value)42 try:43 result.encode('ascii')44 except UnicodeEncodeError:45 pass46 else:47 return result48 if not six.PY3: # Python 2:49 value = value.encode('utf-8')50 value = email.utils.encode_rfc2231(value, 'utf-8')51 value = '%s*=%s' % (name, value)52 return value535455class RequestField(object):56 """57 A data container for request body parameters.5859 :param name:60 The name of this request field.61 :param data:62 The data/value body.63 :param filename:64 An optional filename of the request field.65 :param headers:66 An optional dict-like object of headers to initially use for the field.67 """68 def __init__(self, name, data, filename=None, headers=None):69 self._name = name70 self._filename = filename71 self.data = data72 self.headers = {}73 if headers:74 self.headers = dict(headers)7576 @classmethod77 def from_tuples(cls, fieldname, value):78 """79 A :class:`~urllib3.fields.RequestField` factory from old-style tuple parameters.8081 Supports constructing :class:`~urllib3.fields.RequestField` from parameter82 of key/value strings AND key/filetuple. A filetuple is a (filename, data, MIME type)83 tuple where the MIME type is optional. For example: ::8485 'foo': 'bar',86 'fakefile': ('foofile.txt', 'contents of foofile'),87 'realfile': ('barfile.txt', open('realfile').read()),88 'typedfile': ('bazfile.bin', open('bazfile').read(), 'image/jpeg'),89 'nonamefile': 'contents of nonamefile field',9091 Field names and filenames must be unicode.92 """93 if isinstance(value, tuple):94 if len(value) == 3:95 filename, data, content_type = value96 else:97 filename, data = value98 content_type = guess_content_type(filename)99 else:100 filename = None101 content_type = None102 data = value103104 request_param = cls(fieldname, data, filename=filename)105 request_param.make_multipart(content_type=content_type)106107 return request_param108109 def _render_part(self, name, value):110 """111 Overridable helper function to format a single header parameter.112113 :param name:114 The name of the parameter, a string expected to be ASCII only.115 :param value:116 The value of the parameter, provided as a unicode string.117 """118 return format_header_param(name, value)119120 def _render_parts(self, header_parts):121 """122 Helper function to format and quote a single header.123124 Useful for single headers that are composed of multiple items. E.g.,125 'Content-Disposition' fields.126127 :param header_parts:128 A sequence of (k, v) typles or a :class:`dict` of (k, v) to format as129 `k1="v1"; k2="v2"; ...`.130 """131 parts = []132 iterable = header_parts133 if isinstance(header_parts, dict):134 iterable = header_parts.items()135136 for name, value in iterable:137 if value:138 parts.append(self._render_part(name, value))139140 return '; '.join(parts)141142 def render_headers(self):143 """144 Renders the headers for this request field.145 """146 lines = []147148 sort_keys = ['Content-Disposition', 'Content-Type', 'Content-Location']149 for sort_key in sort_keys:150 if self.headers.get(sort_key, False):151 lines.append('%s: %s' % (sort_key, self.headers[sort_key]))152153 for header_name, header_value in self.headers.items():154 if header_name not in sort_keys:155 if header_value:156 lines.append('%s: %s' % (header_name, header_value))157158 lines.append('\r\n')159 return '\r\n'.join(lines)160161 def make_multipart(self, content_disposition=None, content_type=None, content_location=None):162 """163 Makes this request field into a multipart request field.164165 This method overrides "Content-Disposition", "Content-Type" and166 "Content-Location" headers to the request parameter.167168 :param content_type:169 The 'Content-Type' of the request body.170 :param content_location:171 The 'Content-Location' of the request body.172173 """174 self.headers['Content-Disposition'] = content_disposition or 'form-data'175 self.headers['Content-Disposition'] += '; '.join(['', self._render_parts((('name', self._name), ('filename', self._filename)))])176 self.headers['Content-Type'] = content_type177 self.headers['Content-Location'] = content_location
modified:requests/packages/urllib3/filepost.py+30 added-27 removed
10 unmodified lines
11from io import BytesIO1213from .packages import six14from .packages.six import b15from .fields import RequestField1617writer = codecs.lookup('utf-8')[3]1819
3 unmodified lines
23 """24 return uuid4().hex252626def get_content_type(filename):27 return mimetypes.guess_type(filename)[0] or 'application/octet-stream'27def iter_field_objects(fields):28 """29 Iterate over fields.3031 Supports list of (k, v) tuples and dicts, and lists of32 :class:`~urllib3.fields.RequestField`.3334 """35 if isinstance(fields, dict):36 i = six.iteritems(fields)37 else:38 i = iter(fields)3940 for field in i:41 if isinstance(field, RequestField):42 yield field43 else:44 yield RequestField.from_tuples(*field)454647def iter_fields(fields):48 """49 Iterate over fields.5051 .. deprecated ::5253 The addition of `~urllib3.fields.RequestField` makes this function54 obsolete. Instead, use :func:`iter_field_objects`, which returns55 `~urllib3.fields.RequestField` objects, instead.5657 Supports list of (k, v) tuples and dicts.5859 """60 if isinstance(fields, dict):61 return ((k, v) for k, v in six.iteritems(fields))62
4 unmodified lines
67 """68 Encode a dictionary of ``fields`` using the multipart/form-data MIME format.6970 :param fields:47 Dictionary of fields or list of (key, value) or (key, value, MIME type)48 field tuples. The key is treated as the field name, and the value as49 the body of the form-data bytes. If the value is a tuple of two50 elements, then the first element is treated as the filename of the51 form-data section and a suitable MIME type is guessed based on the52 filename. If the value is a tuple of three elements, then the third53 element is treated as an explicit MIME type of the form-data section.71 Dictionary of fields or list of (key, :class:`~urllib3.fields.RequestField`).7255 Field names and filenames must be unicode.5673 :param boundary:74 If not specified, then a random boundary will be generated using75 :func:`mimetools.choose_boundary`.76 """77 body = BytesIO()78 if boundary is None:79 boundary = choose_boundary()8065 for fieldname, value in iter_fields(fields):81 for field in iter_field_objects(fields):82 body.write(b('--%s\r\n' % (boundary)))8368 if isinstance(value, tuple):69 if len(value) == 3:70 filename, data, content_type = value71 else:72 filename, data = value73 content_type = get_content_type(filename)74 writer(body).write('Content-Disposition: form-data; name="%s"; '75 'filename="%s"\r\n' % (fieldname, filename))76 body.write(b('Content-Type: %s\r\n\r\n' %77 (content_type,)))78 else:79 data = value80 writer(body).write('Content-Disposition: form-data; name="%s"\r\n'81 % (fieldname))82 body.write(b'\r\n')84 writer(body).write(field.render_headers())85 data = field.data8687 if isinstance(data, int):88 data = str(data) # Backwards compatibility89
12 unmodified lines
modified:requests/packages/urllib3/response.py+2 added-1 removed
72 unmodified lines
73 otherwise unused.74 """7576 CONTENT_DECODERS = ['gzip', 'deflate']77 REDIRECT_STATUSES = [301, 302, 303, 307, 308]7879 def __init__(self, body='', headers=None, status=0, version=0, reason=None,80 strict=0, preload_content=True, decode_content=True,81 original_response=None, pool=None, connection=None):
25 unmodified lines
107 :returns: Truthy redirect location string if we got a redirect status108 code and valid location. ``None`` if redirect status and no109 location. ``False`` if not a redirect status code.110 """110 if self.status in [301, 302, 303, 307]:111 if self.status in self.REDIRECT_STATUSES:112 return self.headers.get('location')113114 return False115
186 unmodified lines
modified:requests/packages/urllib3/util.py+230 added-3 removed
4 unmodified lines
5# the MIT License: http://www.opensource.org/licenses/mit-license.php678from base64 import b64encode9from binascii import hexlify, unhexlify10from collections import namedtuple10from socket import error as SocketError11from hashlib import md5, sha112from binascii import hexlify, unhexlify12from socket import error as SocketError, _GLOBAL_DEFAULT_TIMEOUT13import time1415try:16 from select import poll, POLLIN17except ImportError: # `poll` doesn't exist on OSX and other platforms
14 unmodified lines
32except ImportError:33 pass3435from .packages import six35from .exceptions import LocationParseError, SSLError36from .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 The maximum amount of time to wait for an HTTP request to connect and84 return. This combines the connect and read timeouts into one. 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.899091 :type total: integer, float, or None9293 .. note::9495 Many factors can affect the total amount of time for urllib3 to return96 an HTTP response. Specifically, Python's DNS resolver does not obey the97 timeout specified on the socket. Other factors that can affect total98 request time include high CPU load, high swap, the program running at a99 low priority level, or other behaviors. The observed running time for100 urllib3 to return a response may be greater than the value passed to101 `total`.102103 In addition, the read and total timeouts only measure the time between104 read operations on the socket connecting the client and the server, not105 the total amount of time for the request to return a complete response.106 As an example, you may want a request to return within 7 seconds or107 fail, so you set the ``total`` timeout to 7 seconds. If the server108 sends one byte to you every 5 seconds, the request will **not** trigger109 time out. This case is admittedly rare.110 """111112 #: A sentinel object representing the default timeout value113 DEFAULT_TIMEOUT = _GLOBAL_DEFAULT_TIMEOUT114115 def __init__(self, connect=_Default, read=_Default, total=None):116 self._connect = self._validate_timeout(connect, 'connect')117 self._read = self._validate_timeout(read, 'read')118 self.total = self._validate_timeout(total, 'total')119 self._start_connect = None120121 def __str__(self):122 return '%s(connect=%r, read=%r, total=%r)' % (123 type(self).__name__, self._connect, self._read, self.total)124125126 @classmethod127 def _validate_timeout(cls, value, name):128 """ Check that a timeout attribute is valid129130 :param value: The timeout value to validate131 :param name: The name of the timeout attribute to validate. This is used132 for clear error messages133 :return: the value134 :raises ValueError: if the type is not an integer or a float, or if it135 is a numeric value less than zero136 """137 if value is _Default:138 return cls.DEFAULT_TIMEOUT139140 if value is None or value is cls.DEFAULT_TIMEOUT:141 return value142143 try:144 float(value)145 except (TypeError, ValueError):146 raise ValueError("Timeout value %s was %s, but it must be an "147 "int or float." % (name, value))148149 try:150 if value < 0:151 raise ValueError("Attempted to set %s timeout to %s, but the "152 "timeout cannot be set to a value less "153 "than 0." % (name, value))154 except TypeError: # Python 3155 raise ValueError("Timeout value %s was %s, but it must be an "156 "int or float." % (name, value))157158 return value159160 @classmethod161 def from_float(cls, timeout):162 """ Create a new Timeout from a legacy timeout value.163164 The timeout value used by httplib.py sets the same timeout on the165 connect(), and recv() socket requests. This creates a :class:`Timeout`166 object that sets the individual timeouts to the ``timeout`` value passed167 to this function.168169 :param timeout: The legacy timeout value170 :type timeout: integer, float, sentinel default object, or None171 :return: a Timeout object172 :rtype: :class:`Timeout`173 """174 return Timeout(read=timeout, connect=timeout)175176 def clone(self):177 """ Create a copy of the timeout object178179 Timeout properties are stored per-pool but each request needs a fresh180 Timeout object to ensure each one has its own start/stop configured.181182 :return: a copy of the timeout object183 :rtype: :class:`Timeout`184 """185 # We can't use copy.deepcopy because that will also create a new object186 # for _GLOBAL_DEFAULT_TIMEOUT, which socket.py uses as a sentinel to187 # detect the user default.188 return Timeout(connect=self._connect, read=self._read,189 total=self.total)190191 def start_connect(self):192 """ Start the timeout clock, used during a connect() attempt193194 :raises urllib3.exceptions.TimeoutStateError: if you attempt195 to start a timer that has been started already.196 """197 if self._start_connect is not None:198 raise TimeoutStateError("Timeout timer has already been started.")199 self._start_connect = current_time()200 return self._start_connect201202 def get_connect_duration(self):203 """ Gets the time elapsed since the call to :meth:`start_connect`.204205 :return: the elapsed time206 :rtype: float207 :raises urllib3.exceptions.TimeoutStateError: if you attempt208 to get duration for a timer that hasn't been started.209 """210 if self._start_connect is None:211 raise TimeoutStateError("Can't get connect duration for timer "212 "that has not started.")213 return current_time() - self._start_connect214215 @property216 def connect_timeout(self):217 """ Get the value to use when setting a connection timeout.218219 This will be a positive float or integer, the value None220 (never timeout), or the default system timeout.221222 :return: the connect timeout223 :rtype: int, float, :attr:`Timeout.DEFAULT_TIMEOUT` or None224 """225 if self.total is None:226 return self._connect227228 if self._connect is None or self._connect is self.DEFAULT_TIMEOUT:229 return self.total230231 return min(self._connect, self.total)232233 @property234 def read_timeout(self):235 """ Get the value for the read timeout.236237 This assumes some time has elapsed in the connection timeout and238 computes the read timeout appropriately.239240 If self.total is set, the read timeout is dependent on the amount of241 time taken by the connect timeout. If the connection time has not been242 established, a :exc:`~urllib3.exceptions.TimeoutStateError` will be243 raised.244245 :return: the value to use for the read timeout246 :rtype: int, float, :attr:`Timeout.DEFAULT_TIMEOUT` or None247 :raises urllib3.exceptions.TimeoutStateError: If :meth:`start_connect`248 has not yet been called on this object.249 """250 if (self.total is not None and251 self.total is not self.DEFAULT_TIMEOUT and252 self._read is not None and253 self._read is not self.DEFAULT_TIMEOUT):254 # in case the connect timeout has not yet been established.255 if self._start_connect is None:256 return self._read257 return max(0, min(self.total - self.get_connect_duration(),258 self._read))259 elif self.total is not None and self.total is not self.DEFAULT_TIMEOUT:260 return max(0, self.total - self.get_connect_duration())261 else:262 return self._read263264265class Url(namedtuple('Url', ['scheme', 'auth', 'host', 'port', 'path', 'query', 'fragment'])):266 """267 Datastructure for representing an HTTP URL. Used as a return value for268 :func:`parse_url`.
358 unmodified lines