Update urllib3 to 1.20.0
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Further, fix the Makefile to pull urllib3 from the release branch. git-describe works based on the most recent commit but all of the nearest commits in the graph for urllib3 are on the release branch (since the release branch is never merged back to master).
authored by Ian Cordasco · committed by Ian Cordasco · parent df56f38 · Browse files · 15 files·+742 added−66 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
15 files+742 added−66 removed
- other:+742 added−66 removed
Provenance
- Commit
b5704a6- Tree
08a7114- Author
Ian Cordasco <graffatcolmingov@gmail.com>- Committer
Ian Cordasco <graffatcolmingov@gmail.com>- Parent
df56f38
15 files changed+742 added−66 removed
modified:requests/packages/urllib3/contrib/pyopenssl.py+29 added-10 removed
41 unmodified lines42 .. _crime attack: https://en.wikipedia.org/wiki/CRIME_(security_exploit)43 """44 from __future__ import absolute_import45 46-import idna46 import OpenSSL.SSL47 from cryptography import x50948 from cryptography.hazmat.backends.openssl import backend as openssl_backend49 from cryptography.hazmat.backends.openssl.x509 import _Certificate8 unmodified lines58 from ..packages.backports.makefile import backport_makefile59 60 import logging61 import ssl63-import select62 import six63 import sys64 65 from .. import util42 unmodified lines108 109 def inject_into_urllib3():110 'Monkey-patch urllib3 with PyOpenSSL-backed SSL-support.'111 112+ _validate_dependencies_met()113+114 util.ssl_.SSLContext = PyOpenSSLContext115 util.HAS_SNI = HAS_SNI116 util.ssl_.HAS_SNI = HAS_SNI117 util.IS_PYOPENSSL = True9 unmodified lines127 util.IS_PYOPENSSL = False128 util.ssl_.IS_PYOPENSSL = False129 130 131+def _validate_dependencies_met():132+ """133+ Verifies that PyOpenSSL's package-level dependencies have been met.134+ Throws `ImportError` if they are not met.135+ """136+ # Method added in `cryptography==1.1`; not available in older versions137+ from cryptography.x509.extensions import Extensions138+ if getattr(Extensions, "get_extension_for_class", None) is None:139+ raise ImportError("'cryptography' module missing required functionality. "140+ "Try upgrading to v1.3.4 or newer.")141+142+ # pyOpenSSL 0.14 and above use cryptography for OpenSSL bindings. The _x509143+ # attribute is only present on those versions.144+ from OpenSSL.crypto import X509145+ x509 = X509()146+ if getattr(x509, "_x509", None) is None:147+ raise ImportError("'pyOpenSSL' module missing required functionality. "148+ "Try upgrading to v0.14 or newer.")149+150+151 def _dnsname_to_stdlib(name):152 """153 Converts a dNSName SubjectAlternativeName field to the form used by the154 standard library on the given Python version.8 unmodified lines163 Borrowed wholesale from the Python Cryptography Project. It turns out164 that we can't just safely call `idna.encode`: it can explode for165 wildcard names. This avoids that problem.166 """167+ import idna168+169 for prefix in [u'*.', u'.']:170 if name.startswith(prefix):171 name = name[len(prefix):]172 return prefix.encode('ascii') + idna.encode(name)90 unmodified lines263 return b''264 else:265 raise266 except OpenSSL.SSL.WantReadError:245- rd, wd, ed = select.select(246- [self.socket], [], [], self.socket.gettimeout())267+ rd = util.wait_for_read(self.socket, self.socket.gettimeout())268 if not rd:269 raise timeout('The read operation timed out')270 else:271 return self.recv(*args, **kwargs)13 unmodified lines285 return 0286 else:287 raise288 except OpenSSL.SSL.WantReadError:268- rd, wd, ed = select.select(269- [self.socket], [], [], self.socket.gettimeout())289+ rd = util.wait_for_read(self.socket, self.socket.gettimeout())290 if not rd:291 raise timeout('The read operation timed out')292 else:293 return self.recv_into(*args, **kwargs)5 unmodified lines299 while True:300 try:301 return self.connection.send(data)302 except OpenSSL.SSL.WantWriteError:283- _, wlist, _ = select.select([], [self.socket], [],284- self.socket.gettimeout())285- if not wlist:303+ wr = util.wait_for_write(self.socket, self.socket.gettimeout())304+ if not wr:305 raise timeout()306 continue307 308 def sendall(self, data):125 unmodified lines434 while True:435 try:436 cnx.do_handshake()437 except OpenSSL.SSL.WantReadError:419- rd, _, _ = select.select([sock], [], [], sock.gettimeout())438+ rd = util.wait_for_read(sock, sock.gettimeout())439 if not rd:440 raise timeout('select timed out')441 continue442 except OpenSSL.SSL.Error as e:8 unmodified linesmodified:requests/packages/urllib3/contrib/socks.py+10 added
81 unmodified lines82 proxy_addr=self._socks_options['proxy_host'],83 proxy_port=self._socks_options['proxy_port'],84 proxy_username=self._socks_options['username'],85 proxy_password=self._socks_options['password'],86+ proxy_rdns=self._socks_options['rdns'],87 timeout=self.timeout,88 **extra_kw89 )90 62 unmodified lines153 parsed = parse_url(proxy_url)154 155 if parsed.scheme == 'socks5':156 socks_version = socks.PROXY_TYPE_SOCKS5157+ rdns = False158+ elif parsed.scheme == 'socks5h':159+ socks_version = socks.PROXY_TYPE_SOCKS5160+ rdns = True161 elif parsed.scheme == 'socks4':162 socks_version = socks.PROXY_TYPE_SOCKS4163+ rdns = False164+ elif parsed.scheme == 'socks4a':165+ socks_version = socks.PROXY_TYPE_SOCKS4166+ rdns = True167 else:168 raise ValueError(169 "Unable to determine SOCKS version from %s" % proxy_url170 )5 unmodified lines176 'proxy_host': parsed.host,177 'proxy_port': parsed.port,178 'username': username,179 'password': password,180+ 'rdns': rdns181 }182 connection_pool_kw['_socks_options'] = socks_options183 184 super(SOCKSProxyManager, self).__init__(4 unmodified linesmodified:requests/packages/urllib3/util/__init__.py+6 added
22 unmodified lines23 parse_url,24 split_first,25 Url,26 )27+from .wait import (28+ wait_for_read,29+ wait_for_write30+)31 32 __all__ = (33 'HAS_SNI',34 'IS_PYOPENSSL',11 unmodified lines46 'resolve_cert_reqs',47 'resolve_ssl_version',48 'split_first',49 'ssl_wrap_socket',50+ 'wait_for_read',51+ 'wait_for_write'52 )modified:requests/packages/urllib3/util/connection.py+8 added-23 removed
1 from __future__ import absolute_import2 import socket3-try:4- from select import poll, POLLIN5-except ImportError: # `poll` doesn't exist on OSX and other platforms6- poll = False7- try:8- from select import select9- except ImportError: # `select` doesn't exist on AppEngine.10- select = False3+from .wait import wait_for_read4+from .selectors import HAS_SELECT, SelectorError5 6 7 def is_connection_dropped(conn): # Platform-specific8 """10 unmodified lines19 return False20 if sock is None: # Connection already closed (such as by httplib).21 return True22 29- if not poll:30- if not select: # Platform-specific: AppEngine31- return False23+ if not HAS_SELECT:24+ return False25 33- try:34- return select([sock], [], [], 0.0)[0]35- except socket.error:36- return True26+ try:27+ return bool(wait_for_read(sock, timeout=0.0))28+ except SelectorError:29+ return True30 38- # This version is better on platforms that support it.39- p = poll()40- p.register(sock, POLLIN)41- for (fno, ev) in p.poll(0.0):42- if fno == sock.fileno():43- # Either data is buffered (bad), or the connection is dropped.44- return True31 46-32 # This function is copied from socket.py in the Python 2.7 standard33 # library test suite. Added to its signature is only `socket_options`.34 # One additional modification is that we avoid binding to IPv6 servers35 # discovered in DNS if the system doesn't have IPv6 functionality.95 unmodified linesmodified:requests/packages/urllib3/util/request.py+47 added-1 removed
1 from __future__ import absolute_import2 from base64 import b64encode3 4-from ..packages.six import b4+from ..packages.six import b, integer_types5+from ..exceptions import UnrewindableBodyError6 7 ACCEPT_ENCODING = 'gzip,deflate'8+_FAILEDTELL = object()9 10 11 def make_headers(keep_alive=None, accept_encoding=None, user_agent=None,12 basic_auth=None, proxy_basic_auth=None, disable_cache=None):58 unmodified lines71 if disable_cache:72 headers['cache-control'] = 'no-cache'73 74 return headers75+76+77+def set_file_position(body, pos):78+ """79+ If a position is provided, move file to that point.80+ Otherwise, we'll attempt to record a position for future use.81+ """82+ if pos is not None:83+ rewind_body(body, pos)84+ elif getattr(body, 'tell', None) is not None:85+ try:86+ pos = body.tell()87+ except (IOError, OSError):88+ # This differentiates from None, allowing us to catch89+ # a failed `tell()` later when trying to rewind the body.90+ pos = _FAILEDTELL91+92+ return pos93+94+95+def rewind_body(body, body_pos):96+ """97+ Attempt to rewind body to a certain position.98+ Primarily used for request redirects and retries.99+100+ :param body:101+ File-like object that supports seek.102+103+ :param int pos:104+ Position to seek to in file.105+ """106+ body_seek = getattr(body, 'seek', None)107+ if body_seek is not None and isinstance(body_pos, integer_types):108+ try:109+ body_seek(body_pos)110+ except (IOError, OSError):111+ raise UnrewindableBodyError("An error occured when rewinding request "112+ "body for redirect/retry.")113+ elif body_pos is _FAILEDTELL:114+ raise UnrewindableBodyError("Unable to record file position for rewinding "115+ "request body during a redirect/retry.")116+ else:117+ raise ValueError("body_pos must be of type integer, "118+ "instead it was %s." % type(body_pos))modified:requests/packages/urllib3/util/retry.py+16 added-3 removed
271 unmodified lines272 assume that the server began processing it.273 """274 return isinstance(err, (ReadTimeoutError, ProtocolError))275 276- def is_retry(self, method, status_code, has_retry_after=False):277- """ Is this method/status code retryable? (Based on method/codes whitelists)276+ def _is_method_retryable(self, method):277+ """ Checks if a given HTTP method should be retried upon, depending if278+ it is included on the method whitelist.279 """280 if self.method_whitelist and method.upper() not in self.method_whitelist:281 return False282 283+ return True284+285+ def is_retry(self, method, status_code, has_retry_after=False):286+ """ Is this method/status code retryable? (Based on whitelists and control287+ variables such as the number of total retries to allow, whether to288+ respect the Retry-After header, whether this header is present, and289+ whether the returned status code is on the list of status codes to290+ be retried upon on the presence of the aforementioned header)291+ """292+ if not self._is_method_retryable(method):293+ return False294+295 if self.status_forcelist and status_code in self.status_forcelist:296 return True297 298 return (self.total and self.respect_retry_after_header and43 unmodified lines342 connect -= 1343 344 elif error and self._is_read_error(error):345 # Read retry?333- if read is False:346+ if read is False or not self._is_method_retryable(method):347 raise six.reraise(type(error), error, _stacktrace)348 elif read is not None:349 read -= 1350 39 unmodified linesadded:requests/packages/urllib3/util/selectors.py+524 added
1+# Backport of selectors.py from Python 3.5+ to support Python < 3.42+# Also has the behavior specified in PEP 475 which is to retry syscalls3+# in the case of an EINTR error. This module is required because selectors344+# does not follow this behavior and instead returns that no dile descriptor5+# events have occurred rather than retry the syscall. The decision to drop6+# support for select.devpoll is made to maintain 100% test coverage.7+8+import errno9+import math10+import select11+from collections import namedtuple, Mapping12+13+import time14+try:15+ monotonic = time.monotonic16+except (AttributeError, ImportError): # Python 3.3<17+ monotonic = time.time18+19+EVENT_READ = (1 << 0)20+EVENT_WRITE = (1 << 1)21+22+HAS_SELECT = True # Variable that shows whether the platform has a selector.23+_SYSCALL_SENTINEL = object() # Sentinel in case a system call returns None.24+25+26+class SelectorError(Exception):27+ def __init__(self, errcode):28+ super(SelectorError, self).__init__()29+ self.errno = errcode30+31+ def __repr__(self):32+ return "<SelectorError errno={0}>".format(self.errno)33+34+ def __str__(self):35+ return self.__repr__()36+37+38+def _fileobj_to_fd(fileobj):39+ """ Return a file descriptor from a file object. If40+ given an integer will simply return that integer back. """41+ if isinstance(fileobj, int):42+ fd = fileobj43+ else:44+ try:45+ fd = int(fileobj.fileno())46+ except (AttributeError, TypeError, ValueError):47+ raise ValueError("Invalid file object: {0!r}".format(fileobj))48+ if fd < 0:49+ raise ValueError("Invalid file descriptor: {0}".format(fd))50+ return fd51+52+53+def _syscall_wrapper(func, recalc_timeout, *args, **kwargs):54+ """ Wrapper function for syscalls that could fail due to EINTR.55+ All functions should be retried if there is time left in the timeout56+ in accordance with PEP 475. """57+ timeout = kwargs.get("timeout", None)58+ if timeout is None:59+ expires = None60+ recalc_timeout = False61+ else:62+ timeout = float(timeout)63+ if timeout < 0.0: # Timeout less than 0 treated as no timeout.64+ expires = None65+ else:66+ expires = monotonic() + timeout67+68+ args = list(args)69+ if recalc_timeout and "timeout" not in kwargs:70+ raise ValueError(71+ "Timeout must be in args or kwargs to be recalculated")72+73+ result = _SYSCALL_SENTINEL74+ while result is _SYSCALL_SENTINEL:75+ try:76+ result = func(*args, **kwargs)77+ # OSError is thrown by select.select78+ # IOError is thrown by select.epoll.poll79+ # select.error is thrown by select.poll.poll80+ # Aren't we thankful for Python 3.x rework for exceptions?81+ except (OSError, IOError, select.error) as e:82+ # select.error wasn't a subclass of OSError in the past.83+ errcode = None84+ if hasattr(e, "errno"):85+ errcode = e.errno86+ elif hasattr(e, "args"):87+ errcode = e.args[0]88+89+ # Also test for the Windows equivalent of EINTR.90+ is_interrupt = (errcode == errno.EINTR or (hasattr(errno, "WSAEINTR") and91+ errcode == errno.WSAEINTR))92+93+ if is_interrupt:94+ if expires is not None:95+ current_time = monotonic()96+ if current_time > expires:97+ raise OSError(errno=errno.ETIMEDOUT)98+ if recalc_timeout:99+ if "timeout" in kwargs:100+ kwargs["timeout"] = expires - current_time101+ continue102+ if errcode:103+ raise SelectorError(errcode)104+ else:105+ raise106+ return result107+108+109+SelectorKey = namedtuple('SelectorKey', ['fileobj', 'fd', 'events', 'data'])110+111+112+class _SelectorMapping(Mapping):113+ """ Mapping of file objects to selector keys """114+115+ def __init__(self, selector):116+ self._selector = selector117+118+ def __len__(self):119+ return len(self._selector._fd_to_key)120+121+ def __getitem__(self, fileobj):122+ try:123+ fd = self._selector._fileobj_lookup(fileobj)124+ return self._selector._fd_to_key[fd]125+ except KeyError:126+ raise KeyError("{0!r} is not registered.".format(fileobj))127+128+ def __iter__(self):129+ return iter(self._selector._fd_to_key)130+131+132+class BaseSelector(object):133+ """ Abstract Selector class134+135+ A selector supports registering file objects to be monitored136+ for specific I/O events.137+138+ A file object is a file descriptor or any object with a139+ `fileno()` method. An arbitrary object can be attached to the140+ file object which can be used for example to store context info,141+ a callback, etc.142+143+ A selector can use various implementations (select(), poll(), epoll(),144+ and kqueue()) depending on the platform. The 'DefaultSelector' class uses145+ the most efficient implementation for the current platform.146+ """147+ def __init__(self):148+ # Maps file descriptors to keys.149+ self._fd_to_key = {}150+151+ # Read-only mapping returned by get_map()152+ self._map = _SelectorMapping(self)153+154+ def _fileobj_lookup(self, fileobj):155+ """ Return a file descriptor from a file object.156+ This wraps _fileobj_to_fd() to do an exhaustive157+ search in case the object is invalid but we still158+ have it in our map. Used by unregister() so we can159+ unregister an object that was previously registered160+ even if it is closed. It is also used by _SelectorMapping161+ """162+ try:163+ return _fileobj_to_fd(fileobj)164+ except ValueError:165+166+ # Search through all our mapped keys.167+ for key in self._fd_to_key.values():168+ if key.fileobj is fileobj:169+ return key.fd170+171+ # Raise ValueError after all.172+ raise173+174+ def register(self, fileobj, events, data=None):175+ """ Register a file object for a set of events to monitor. """176+ if (not events) or (events & ~(EVENT_READ | EVENT_WRITE)):177+ raise ValueError("Invalid events: {0!r}".format(events))178+179+ key = SelectorKey(fileobj, self._fileobj_lookup(fileobj), events, data)180+181+ if key.fd in self._fd_to_key:182+ raise KeyError("{0!r} (FD {1}) is already registered"183+ .format(fileobj, key.fd))184+185+ self._fd_to_key[key.fd] = key186+ return key187+188+ def unregister(self, fileobj):189+ """ Unregister a file object from being monitored. """190+ try:191+ key = self._fd_to_key.pop(self._fileobj_lookup(fileobj))192+ except KeyError:193+ raise KeyError("{0!r} is not registered".format(fileobj))194+ return key195+196+ def modify(self, fileobj, events, data=None):197+ """ Change a registered file object monitored events and data. """198+ # NOTE: Some subclasses optimize this operation even further.199+ try:200+ key = self._fd_to_key[self._fileobj_lookup(fileobj)]201+ except KeyError:202+ raise KeyError("{0!r} is not registered".format(fileobj))203+204+ if events != key.events:205+ self.unregister(fileobj)206+ key = self.register(fileobj, events, data)207+208+ elif data != key.data:209+ # Use a shortcut to update the data.210+ key = key._replace(data=data)211+ self._fd_to_key[key.fd] = key212+213+ return key214+215+ def select(self, timeout=None):216+ """ Perform the actual selection until some monitored file objects217+ are ready or the timeout expires. """218+ raise NotImplementedError()219+220+ def close(self):221+ """ Close the selector. This must be called to ensure that all222+ underlying resources are freed. """223+ self._fd_to_key.clear()224+ self._map = None225+226+ def get_key(self, fileobj):227+ """ Return the key associated with a registered file object. """228+ mapping = self.get_map()229+ if mapping is None:230+ raise RuntimeError("Selector is closed")231+ try:232+ return mapping[fileobj]233+ except KeyError:234+ raise KeyError("{0!r} is not registered".format(fileobj))235+236+ def get_map(self):237+ """ Return a mapping of file objects to selector keys """238+ return self._map239+240+ def _key_from_fd(self, fd):241+ """ Return the key associated to a given file descriptor242+ Return None if it is not found. """243+ try:244+ return self._fd_to_key[fd]245+ except KeyError:246+ return None247+248+ def __enter__(self):249+ return self250+251+ def __exit__(self, *args):252+ self.close()253+254+255+# Almost all platforms have select.select()256+if hasattr(select, "select"):257+ class SelectSelector(BaseSelector):258+ """ Select-based selector. """259+ def __init__(self):260+ super(SelectSelector, self).__init__()261+ self._readers = set()262+ self._writers = set()263+264+ def register(self, fileobj, events, data=None):265+ key = super(SelectSelector, self).register(fileobj, events, data)266+ if events & EVENT_READ:267+ self._readers.add(key.fd)268+ if events & EVENT_WRITE:269+ self._writers.add(key.fd)270+ return key271+272+ def unregister(self, fileobj):273+ key = super(SelectSelector, self).unregister(fileobj)274+ self._readers.discard(key.fd)275+ self._writers.discard(key.fd)276+ return key277+278+ def _select(self, r, w, timeout=None):279+ """ Wrapper for select.select because timeout is a positional arg """280+ return select.select(r, w, [], timeout)281+282+ def select(self, timeout=None):283+ # Selecting on empty lists on Windows errors out.284+ if not len(self._readers) and not len(self._writers):285+ return []286+287+ timeout = None if timeout is None else max(timeout, 0.0)288+ ready = []289+ r, w, _ = _syscall_wrapper(self._select, True, self._readers,290+ self._writers, timeout)291+ r = set(r)292+ w = set(w)293+ for fd in r | w:294+ events = 0295+ if fd in r:296+ events |= EVENT_READ297+ if fd in w:298+ events |= EVENT_WRITE299+300+ key = self._key_from_fd(fd)301+ if key:302+ ready.append((key, events & key.events))303+ return ready304+305+306+if hasattr(select, "poll"):307+ class PollSelector(BaseSelector):308+ """ Poll-based selector """309+ def __init__(self):310+ super(PollSelector, self).__init__()311+ self._poll = select.poll()312+313+ def register(self, fileobj, events, data=None):314+ key = super(PollSelector, self).register(fileobj, events, data)315+ event_mask = 0316+ if events & EVENT_READ:317+ event_mask |= select.POLLIN318+ if events & EVENT_WRITE:319+ event_mask |= select.POLLOUT320+ self._poll.register(key.fd, event_mask)321+ return key322+323+ def unregister(self, fileobj):324+ key = super(PollSelector, self).unregister(fileobj)325+ self._poll.unregister(key.fd)326+ return key327+328+ def _wrap_poll(self, timeout=None):329+ """ Wrapper function for select.poll.poll() so that330+ _syscall_wrapper can work with only seconds. """331+ if timeout is not None:332+ if timeout <= 0:333+ timeout = 0334+ else:335+ # select.poll.poll() has a resolution of 1 millisecond,336+ # round away from zero to wait *at least* timeout seconds.337+ timeout = math.ceil(timeout * 1e3)338+339+ result = self._poll.poll(timeout)340+ return result341+342+ def select(self, timeout=None):343+ ready = []344+ fd_events = _syscall_wrapper(self._wrap_poll, True, timeout=timeout)345+ for fd, event_mask in fd_events:346+ events = 0347+ if event_mask & ~select.POLLIN:348+ events |= EVENT_WRITE349+ if event_mask & ~select.POLLOUT:350+ events |= EVENT_READ351+352+ key = self._key_from_fd(fd)353+ if key:354+ ready.append((key, events & key.events))355+356+ return ready357+358+359+if hasattr(select, "epoll"):360+ class EpollSelector(BaseSelector):361+ """ Epoll-based selector """362+ def __init__(self):363+ super(EpollSelector, self).__init__()364+ self._epoll = select.epoll()365+366+ def fileno(self):367+ return self._epoll.fileno()368+369+ def register(self, fileobj, events, data=None):370+ key = super(EpollSelector, self).register(fileobj, events, data)371+ events_mask = 0372+ if events & EVENT_READ:373+ events_mask |= select.EPOLLIN374+ if events & EVENT_WRITE:375+ events_mask |= select.EPOLLOUT376+ _syscall_wrapper(self._epoll.register, False, key.fd, events_mask)377+ return key378+379+ def unregister(self, fileobj):380+ key = super(EpollSelector, self).unregister(fileobj)381+ try:382+ _syscall_wrapper(self._epoll.unregister, False, key.fd)383+ except SelectorError:384+ # This can occur when the fd was closed since registry.385+ pass386+ return key387+388+ def select(self, timeout=None):389+ if timeout is not None:390+ if timeout <= 0:391+ timeout = 0.0392+ else:393+ # select.epoll.poll() has a resolution of 1 millisecond394+ # but luckily takes seconds so we don't need a wrapper395+ # like PollSelector. Just for better rounding.396+ timeout = math.ceil(timeout * 1e3) * 1e-3397+ timeout = float(timeout)398+ else:399+ timeout = -1.0 # epoll.poll() must have a float.400+401+ # We always want at least 1 to ensure that select can be called402+ # with no file descriptors registered. Otherwise will fail.403+ max_events = max(len(self._fd_to_key), 1)404+405+ ready = []406+ fd_events = _syscall_wrapper(self._epoll.poll, True,407+ timeout=timeout,408+ maxevents=max_events)409+ for fd, event_mask in fd_events:410+ events = 0411+ if event_mask & ~select.EPOLLIN:412+ events |= EVENT_WRITE413+ if event_mask & ~select.EPOLLOUT:414+ events |= EVENT_READ415+416+ key = self._key_from_fd(fd)417+ if key:418+ ready.append((key, events & key.events))419+ return ready420+421+ def close(self):422+ self._epoll.close()423+ super(EpollSelector, self).close()424+425+426+if hasattr(select, "kqueue"):427+ class KqueueSelector(BaseSelector):428+ """ Kqueue / Kevent-based selector """429+ def __init__(self):430+ super(KqueueSelector, self).__init__()431+ self._kqueue = select.kqueue()432+433+ def fileno(self):434+ return self._kqueue.fileno()435+436+ def register(self, fileobj, events, data=None):437+ key = super(KqueueSelector, self).register(fileobj, events, data)438+ if events & EVENT_READ:439+ kevent = select.kevent(key.fd,440+ select.KQ_FILTER_READ,441+ select.KQ_EV_ADD)442+443+ _syscall_wrapper(self._kqueue.control, False, [kevent], 0, 0)444+445+ if events & EVENT_WRITE:446+ kevent = select.kevent(key.fd,447+ select.KQ_FILTER_WRITE,448+ select.KQ_EV_ADD)449+450+ _syscall_wrapper(self._kqueue.control, False, [kevent], 0, 0)451+452+ return key453+454+ def unregister(self, fileobj):455+ key = super(KqueueSelector, self).unregister(fileobj)456+ if key.events & EVENT_READ:457+ kevent = select.kevent(key.fd,458+ select.KQ_FILTER_READ,459+ select.KQ_EV_DELETE)460+ try:461+ _syscall_wrapper(self._kqueue.control, False, [kevent], 0, 0)462+ except SelectorError:463+ pass464+ if key.events & EVENT_WRITE:465+ kevent = select.kevent(key.fd,466+ select.KQ_FILTER_WRITE,467+ select.KQ_EV_DELETE)468+ try:469+ _syscall_wrapper(self._kqueue.control, False, [kevent], 0, 0)470+ except SelectorError:471+ pass472+473+ return key474+475+ def select(self, timeout=None):476+ if timeout is not None:477+ timeout = max(timeout, 0)478+479+ max_events = len(self._fd_to_key) * 2480+ ready_fds = {}481+482+ kevent_list = _syscall_wrapper(self._kqueue.control, True,483+ None, max_events, timeout)484+485+ for kevent in kevent_list:486+ fd = kevent.ident487+ event_mask = kevent.filter488+ events = 0489+ if event_mask == select.KQ_FILTER_READ:490+ events |= EVENT_READ491+ if event_mask == select.KQ_FILTER_WRITE:492+ events |= EVENT_WRITE493+494+ key = self._key_from_fd(fd)495+ if key:496+ if key.fd not in ready_fds:497+ ready_fds[key.fd] = (key, events & key.events)498+ else:499+ old_events = ready_fds[key.fd][1]500+ ready_fds[key.fd] = (key, (events | old_events) & key.events)501+502+ return list(ready_fds.values())503+504+ def close(self):505+ self._kqueue.close()506+ super(KqueueSelector, self).close()507+508+509+# Choose the best implementation, roughly:510+# kqueue == epoll > poll > select. Devpoll not supported. (See above)511+# select() also can't accept a FD > FD_SETSIZE (usually around 1024)512+if 'KqueueSelector' in globals(): # Platform-specific: Mac OS and BSD513+ DefaultSelector = KqueueSelector514+elif 'EpollSelector' in globals(): # Platform-specific: Linux515+ DefaultSelector = EpollSelector516+elif 'PollSelector' in globals(): # Platform-specific: Linux517+ DefaultSelector = PollSelector518+elif 'SelectSelector' in globals(): # Platform-specific: Windows519+ DefaultSelector = SelectSelector520+else: # Platform-specific: AppEngine521+ def no_selector(_):522+ raise ValueError("Platform does not have a selector")523+ DefaultSelector = no_selector524+ HAS_SELECT = Falsemodified:requests/packages/urllib3/util/timeout.py+2 added-5 removed
9 unmodified lines10 # urllib311 _Default = object()12 13 14-def current_time():15- """16- Retrieve the current time. This function is mocked out in unit testing.17- """18- return time.time()14+# Use time.monotonic if available.15+current_time = getattr(time, "monotonic", time.time)16 17 18 class Timeout(object):19 """ Timeout configuration.223 unmodified linesadded:requests/packages/urllib3/util/wait.py+40 added
1+from .selectors import (2+ HAS_SELECT,3+ DefaultSelector,4+ EVENT_READ,5+ EVENT_WRITE6+)7+8+9+def _wait_for_io_events(socks, events, timeout=None):10+ """ Waits for IO events to be available from a list of sockets11+ or optionally a single socket if passed in. Returns a list of12+ sockets that can be interacted with immediately. """13+ if not HAS_SELECT:14+ raise ValueError('Platform does not have a selector')15+ if not isinstance(socks, list):16+ # Probably just a single socket.17+ if hasattr(socks, "fileno"):18+ socks = [socks]19+ # Otherwise it might be a non-list iterable.20+ else:21+ socks = list(socks)22+ with DefaultSelector() as selector:23+ for sock in socks:24+ selector.register(sock, events)25+ return [key[0].fileobj for key in26+ selector.select(timeout) if key[1] & events]27+28+29+def wait_for_read(socks, timeout=None):30+ """ Waits for reading to be available from a list of sockets31+ or optionally a single socket if passed in. Returns a list of32+ sockets that can be read from immediately. """33+ return _wait_for_io_events(socks, EVENT_READ, timeout)34+35+36+def wait_for_write(socks, timeout=None):37+ """ Waits for writing to be available from a list of sockets38+ or optionally a single socket if passed in. Returns a list of39+ sockets that can be written to immediately. """40+ return _wait_for_io_events(socks, EVENT_WRITE, timeout)modified:requests/packages/urllib3/__init__.py+1 added-1 removed
30 unmodified lines31 pass32 33 __author__ = 'Andrey Petrov (andrey.petrov@shazow.net)'34 __license__ = 'MIT'35-__version__ = '1.19.1'35+__version__ = '1.20'36 37 __all__ = (38 'HTTPConnectionPool',39 'HTTPSConnectionPool',58 unmodified linesmodified:requests/packages/urllib3/connection.py+4 added-1 removed
54 unmodified lines55 'http': 80,56 'https': 443,57 }58 59+# When updating RECENT_DATE, move it to60+# within two years of the current date, and no61+# earlier than 6 months ago.59-RECENT_DATE = datetime.date(2014, 1, 1)62+RECENT_DATE = datetime.date(2016, 1, 1)63 64 65 class DummyConnection(object):66 """Used to detect a failed ConnectionCls import."""303 unmodified linesmodified:requests/packages/urllib3/connectionpool.py+48 added-20 removed
23 unmodified lines24 NewConnectionError,25 )26 from .packages.ssl_match_hostname import CertificateError27 from .packages import six28-from .packages.six.moves.queue import LifoQueue, Empty, Full28+from .packages.six.moves import queue29 from .connection import (30 port_by_scheme,31 DummyConnection,32 HTTPConnection, HTTPSConnection, VerifiedHTTPSConnection,2 unmodified lines35 from .request import RequestMethods36 from .response import HTTPResponse37 38 from .util.connection import is_connection_dropped39+from .util.request import set_file_position40 from .util.response import assert_header_parsing41 from .util.retry import Retry42 from .util.timeout import Timeout43 from .util.url import get_host, Url17 unmodified lines61 :class:`.HTTPConnectionPool` and :class:`.HTTPSConnectionPool`.62 """63 64 scheme = None64- QueueCls = LifoQueue65+ QueueCls = queue.LifoQueue66 67 def __init__(self, host, port=None):68 if not host:69 raise LocationValueError("No host specified.")70 70- # httplib doesn't like it when we include brackets in ipv6 addresses71- # Specifically, if we include brackets but also pass the port then72- # httplib crazily doubles up the square brackets on the Host header.73- # Instead, we need to make sure we never pass ``None`` as the port.74- # However, for backward compatibility reasons we can't actually75- # *assert* that.76- self.host = host.strip('[]')71+ self.host = _ipv6_host(host).lower()72 self.port = port73 74 def __str__(self):75 return '%s(host=%r, port=%r)' % (type(self).__name__,72 unmodified lines148 :param _proxy_headers:149 A dictionary with proxy headers, should not be used directly,150 instead, see :class:`urllib3.connectionpool.ProxyManager`"151 157- :param \**conn_kw:152+ :param \\**conn_kw:153 Additional parameters are used to create fresh :class:`urllib3.connection.HTTPConnection`,154 :class:`urllib3.connection.HTTPSConnection` instances.155 """156 72 unmodified lines229 230 except AttributeError: # self.pool is None231 raise ClosedPoolError(self, "Pool is closed.")232 238- except Empty:233+ except queue.Empty:234 if self.block:235 raise EmptyPoolError(self,236 "Pool reached maximum size and no more "237 "connections are allowed.")30 unmodified lines268 return # Everything is dandy, done.269 except AttributeError:270 # self.pool is None.271 pass277- except Full:272+ except queue.Full:273 # This should never happen if self.block == True274 log.warning(275 "Connection pool is full, discarding connection: %s",276 self.host)141 unmodified lines418 conn = old_pool.get(block=False)419 if conn:420 conn.close()421 427- except Empty:422+ except queue.Empty:423 pass # Done.424 425 def is_same_host(self, url):426 """5 unmodified lines432 433 # TODO: Add optional support for socket.gethostbyname checking.434 scheme, host, port = get_host(url)435 436+ host = _ipv6_host(host).lower()437+438 # Use explicit default port for comparison when none is given439 if self.port and not port:440 port = port_by_scheme.get(scheme)441 elif not self.port and port == port_by_scheme.get(scheme):3 unmodified lines445 446 def urlopen(self, method, url, body=None, headers=None, retries=None,447 redirect=True, assert_same_host=True, timeout=_Default,448 pool_timeout=None, release_conn=None, chunked=False,452- **response_kw):449+ body_pos=None, **response_kw):450 """451 Get a connection from the pool and perform an HTTP request. This is the452 lowest level call for making a request, so you'll need to specify all453 the raw details.73 unmodified lines527 If True, urllib3 will send the body using chunked transfer528 encoding. Otherwise, urllib3 will send the body using the standard529 content-length form. Defaults to False.530 531+ :param int body_pos:532+ Position to seek to in file-like body in the event of a retry or533+ redirect. Typically this won't need to be set because urllib3 will534+ auto-populate the value when needed.535+534- :param \**response_kw:536+ :param \\**response_kw:537 Additional parameters are passed to538 :meth:`urllib3.response.HTTPResponse.from_httplib`539 """540 if headers is None:36 unmodified lines577 # Keep track of whether we cleanly exited the except block. This578 # ensures we do proper cleanup in finally.579 clean_exit = False580 581+ # Rewind body position, if needed. Record current position582+ # for future rewinds in the event of a redirect/retry.583+ body_pos = set_file_position(body, body_pos)584+585 try:586 # Request a connection from the queue.587 timeout_obj = self._get_timeout(timeout)588 conn = self._get_conn(timeout=pool_timeout)28 unmodified lines617 618 # Everything went great!619 clean_exit = True620 615- except Empty:621+ except queue.Empty:622 # Timed out by queue.623 raise EmptyPoolError(self, "No pool connections are available.")624 625 except (BaseSSLError, CertificateError) as e:47 unmodified lines673 "broken by '%r': %s", retries, err, url)674 return self.urlopen(method, url, body, headers, retries,675 redirect, assert_same_host,676 timeout=timeout, pool_timeout=pool_timeout,671- release_conn=release_conn, **response_kw)677+ release_conn=release_conn, body_pos=body_pos,678+ **response_kw)679 680 # Handle redirect?681 redirect_location = redirect and response.get_redirect_location()682 if redirect_location:16 unmodified lines699 method, redirect_location, body, headers,700 retries=retries, redirect=redirect,701 assert_same_host=assert_same_host,702 timeout=timeout, pool_timeout=pool_timeout,696- release_conn=release_conn, **response_kw)703+ release_conn=release_conn, body_pos=body_pos,704+ **response_kw)705 706 # Check if we should retry the HTTP response.707 has_retry_after = bool(response.getheader('Retry-After'))708 if retries.is_retry(method, response.status, has_retry_after):12 unmodified lines721 method, url, body, headers,722 retries=retries, redirect=redirect,723 assert_same_host=assert_same_host,724 timeout=timeout, pool_timeout=pool_timeout,717- release_conn=release_conn, **response_kw)725+ release_conn=release_conn,726+ body_pos=body_pos, **response_kw)727 728 return response729 730 130 unmodified lines861 862 :param url:863 Absolute URL string that must include the scheme. Port is optional.864 856- :param \**kw:865+ :param \\**kw:866 Passes additional parameters to the constructor of the appropriate867 :class:`.ConnectionPool`. Useful for specifying things like868 timeout, maxsize, headers, etc.869 7 unmodified lines877 if scheme == 'https':878 return HTTPSConnectionPool(host, port=port, **kw)879 else:880 return HTTPConnectionPool(host, port=port, **kw)881+882+883+def _ipv6_host(host):884+ """885+ Process IPv6 address literals886+ """887+888+ # httplib doesn't like it when we include brackets in IPv6 addresses889+ # Specifically, if we include brackets but also pass the port then890+ # httplib crazily doubles up the square brackets on the Host header.891+ # Instead, we need to make sure we never pass ``None`` as the port.892+ # However, for backward compatibility reasons we can't actually893+ # *assert* that. See http://bugs.python.org/issue28539894+ #895+ # Also if an IPv6 address literal has a zone identifier, the896+ # percent sign might be URIencoded, convert it back into ASCII897+ if host.startswith('[') and host.endswith(']'):898+ host = host.replace('%25', '%').strip('[]')899+ return hostmodified:requests/packages/urllib3/exceptions.py+5 added
237 unmodified lines238 "Raised by assert_header_parsing, but we convert it to a log.warning statement."239 def __init__(self, defects, unparsed_data):240 message = '%s, unparsed data: %r' % (defects or 'Unknown', unparsed_data)241 super(HeaderParsingError, self).__init__(message)242+243+244+class UnrewindableBodyError(HTTPError):245+ "urllib3 encountered an error when trying to rewind a body"246+ passmodified:requests/packages/urllib3/poolmanager.py+1 added-1 removed
91 unmodified lines92 :param headers:93 Headers to include with all requests, unless other headers are given94 explicitly.95 96- :param \**connection_pool_kw:96+ :param \\**connection_pool_kw:97 Additional parameters are used to create fresh98 :class:`urllib3.connectionpool.ConnectionPool` instances.99 100 Example::263 unmodified linesmodified:Makefile+1 added-1 removed
16 unmodified lines17 18 deps: urllib3 chardet idna19 20 urllib3:21- git clone https://github.com/shazow/urllib3.git && \21+ git clone -b release https://github.com/shazow/urllib3.git && \22 rm -fr requests/packages/urllib3 && \23 cd urllib3 && \24 git checkout `git describe --abbrev=0 --tags` && \25 cd .. && \34 unmodified lines