Skip to content
Myr

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

15 files+742 added−66 removed

modified:requests/packages/urllib3/contrib/pyopenssl.py+29 added-10 removed
41 unmodified lines
42.. _crime attack: https://en.wikipedia.org/wiki/CRIME_(security_exploit)43"""44from __future__ import absolute_import4546import idna46import OpenSSL.SSL47from cryptography import x50948from cryptography.hazmat.backends.openssl import backend as openssl_backend49from cryptography.hazmat.backends.openssl.x509 import _Certificate
8 unmodified lines
58 from ..packages.backports.makefile import backport_makefile5960import logging61import ssl63import select62import six63import sys6465from .. import util
42 unmodified lines
108109def inject_into_urllib3():110 'Monkey-patch urllib3 with PyOpenSSL-backed SSL-support.'111112 _validate_dependencies_met()113114 util.ssl_.SSLContext = PyOpenSSLContext115 util.HAS_SNI = HAS_SNI116 util.ssl_.HAS_SNI = HAS_SNI117 util.IS_PYOPENSSL = True
9 unmodified lines
127 util.IS_PYOPENSSL = False128 util.ssl_.IS_PYOPENSSL = False129130131def _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.")141142 # 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.")149150151def _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 lines
163 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 idna168169 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 lines
263 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 lines
285 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 lines
299 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 continue307308 def sendall(self, data):
125 unmodified lines
434 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 lines
modified:requests/packages/urllib3/contrib/socks.py+10 added
81 unmodified lines
82 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 lines
153 parsed = parse_url(proxy_url)154155 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 lines
176 '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_options183184 super(SOCKSProxyManager, self).__init__(
4 unmodified lines
modified:requests/packages/urllib3/util/__init__.py+6 added
22 unmodified lines
23 parse_url,24 split_first,25 Url,26)27from .wait import (28 wait_for_read,29 wait_for_write30)3132__all__ = (33 'HAS_SNI',34 'IS_PYOPENSSL',
11 unmodified lines
46 '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
1from __future__ import absolute_import2import socket3try:4 from select import poll, POLLIN5except 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 = False3from .wait import wait_for_read4from .selectors import HAS_SELECT, SelectorError567def is_connection_dropped(conn): # Platform-specific8 """
10 unmodified lines
19 return False20 if sock is None: # Connection already closed (such as by httplib).21 return True2229 if not poll:30 if not select: # Platform-specific: AppEngine31 return False23 if not HAS_SELECT:24 return False2533 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 True3038 # 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 True314632# 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 lines
modified:requests/packages/urllib3/util/request.py+47 added-1 removed
1from __future__ import absolute_import2from base64 import b64encode34from ..packages.six import b4from ..packages.six import b, integer_types5from ..exceptions import UnrewindableBodyError67ACCEPT_ENCODING = 'gzip,deflate'8_FAILEDTELL = object()91011def make_headers(keep_alive=None, accept_encoding=None, user_agent=None,12 basic_auth=None, proxy_basic_auth=None, disable_cache=None):
58 unmodified lines
71 if disable_cache:72 headers['cache-control'] = 'no-cache'7374 return headers757677def 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 = _FAILEDTELL9192 return pos939495def rewind_body(body, body_pos):96 """97 Attempt to rewind body to a certain position.98 Primarily used for request redirects and retries.99100 :param body:101 File-like object that supports seek.102103 :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 lines
272 assume that the server began processing it.273 """274 return isinstance(err, (ReadTimeoutError, ProtocolError))275276 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 False282283 return True284285 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 False294295 if self.status_forcelist and status_code in self.status_forcelist:296 return True297298 return (self.total and self.respect_retry_after_header and
43 unmodified lines
342 connect -= 1343344 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 lines
added: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.78import errno9import math10import select11from collections import namedtuple, Mapping1213import time14try:15 monotonic = time.monotonic16except (AttributeError, ImportError): # Python 3.3<17 monotonic = time.time1819EVENT_READ = (1 << 0)20EVENT_WRITE = (1 << 1)2122HAS_SELECT = True # Variable that shows whether the platform has a selector.23_SYSCALL_SENTINEL = object() # Sentinel in case a system call returns None.242526class SelectorError(Exception):27 def __init__(self, errcode):28 super(SelectorError, self).__init__()29 self.errno = errcode3031 def __repr__(self):32 return "<SelectorError errno={0}>".format(self.errno)3334 def __str__(self):35 return self.__repr__()363738def _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 fd515253def _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() + timeout6768 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")7273 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]8889 # Also test for the Windows equivalent of EINTR.90 is_interrupt = (errcode == errno.EINTR or (hasattr(errno, "WSAEINTR") and91 errcode == errno.WSAEINTR))9293 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 result107108109SelectorKey = namedtuple('SelectorKey', ['fileobj', 'fd', 'events', 'data'])110111112class _SelectorMapping(Mapping):113 """ Mapping of file objects to selector keys """114115 def __init__(self, selector):116 self._selector = selector117118 def __len__(self):119 return len(self._selector._fd_to_key)120121 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))127128 def __iter__(self):129 return iter(self._selector._fd_to_key)130131132class BaseSelector(object):133 """ Abstract Selector class134135 A selector supports registering file objects to be monitored136 for specific I/O events.137138 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.142143 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 = {}150151 # Read-only mapping returned by get_map()152 self._map = _SelectorMapping(self)153154 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:165166 # Search through all our mapped keys.167 for key in self._fd_to_key.values():168 if key.fileobj is fileobj:169 return key.fd170171 # Raise ValueError after all.172 raise173174 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))178179 key = SelectorKey(fileobj, self._fileobj_lookup(fileobj), events, data)180181 if key.fd in self._fd_to_key:182 raise KeyError("{0!r} (FD {1}) is already registered"183 .format(fileobj, key.fd))184185 self._fd_to_key[key.fd] = key186 return key187188 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 key195196 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))203204 if events != key.events:205 self.unregister(fileobj)206 key = self.register(fileobj, events, data)207208 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] = key212213 return key214215 def select(self, timeout=None):216 """ Perform the actual selection until some monitored file objects217 are ready or the timeout expires. """218 raise NotImplementedError()219220 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 = None225226 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))235236 def get_map(self):237 """ Return a mapping of file objects to selector keys """238 return self._map239240 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 None247248 def __enter__(self):249 return self250251 def __exit__(self, *args):252 self.close()253254255# Almost all platforms have select.select()256if 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()263264 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 key271272 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 key277278 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)281282 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 []286287 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_WRITE299300 key = self._key_from_fd(fd)301 if key:302 ready.append((key, events & key.events))303 return ready304305306if 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()312313 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 key322323 def unregister(self, fileobj):324 key = super(PollSelector, self).unregister(fileobj)325 self._poll.unregister(key.fd)326 return key327328 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)338339 result = self._poll.poll(timeout)340 return result341342 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_READ351352 key = self._key_from_fd(fd)353 if key:354 ready.append((key, events & key.events))355356 return ready357358359if 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()365366 def fileno(self):367 return self._epoll.fileno()368369 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 key378379 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 key387388 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.400401 # 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)404405 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_READ415416 key = self._key_from_fd(fd)417 if key:418 ready.append((key, events & key.events))419 return ready420421 def close(self):422 self._epoll.close()423 super(EpollSelector, self).close()424425426if 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()432433 def fileno(self):434 return self._kqueue.fileno()435436 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)442443 _syscall_wrapper(self._kqueue.control, False, [kevent], 0, 0)444445 if events & EVENT_WRITE:446 kevent = select.kevent(key.fd,447 select.KQ_FILTER_WRITE,448 select.KQ_EV_ADD)449450 _syscall_wrapper(self._kqueue.control, False, [kevent], 0, 0)451452 return key453454 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 pass472473 return key474475 def select(self, timeout=None):476 if timeout is not None:477 timeout = max(timeout, 0)478479 max_events = len(self._fd_to_key) * 2480 ready_fds = {}481482 kevent_list = _syscall_wrapper(self._kqueue.control, True,483 None, max_events, timeout)484485 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_WRITE493494 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)501502 return list(ready_fds.values())503504 def close(self):505 self._kqueue.close()506 super(KqueueSelector, self).close()507508509# 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)512if 'KqueueSelector' in globals(): # Platform-specific: Mac OS and BSD513 DefaultSelector = KqueueSelector514elif 'EpollSelector' in globals(): # Platform-specific: Linux515 DefaultSelector = EpollSelector516elif 'PollSelector' in globals(): # Platform-specific: Linux517 DefaultSelector = PollSelector518elif 'SelectSelector' in globals(): # Platform-specific: Windows519 DefaultSelector = SelectSelector520else: # Platform-specific: AppEngine521 def no_selector(_):522 raise ValueError("Platform does not have a selector")523 DefaultSelector = no_selector524 HAS_SELECT = False
modified:requests/packages/urllib3/util/timeout.py+2 added-5 removed
9 unmodified lines
10# urllib311_Default = object()121314def 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.15current_time = getattr(time, "monotonic", time.time)161718class Timeout(object):19 """ Timeout configuration.
223 unmodified lines
added:requests/packages/urllib3/util/wait.py+40 added
1from .selectors import (2 HAS_SELECT,3 DefaultSelector,4 EVENT_READ,5 EVENT_WRITE6)789def _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]272829def 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)343536def 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 lines
31 pass3233__author__ = 'Andrey Petrov (andrey.petrov@shazow.net)'34__license__ = 'MIT'35__version__ = '1.19.1'35__version__ = '1.20'3637__all__ = (38 'HTTPConnectionPool',39 'HTTPSConnectionPool',
58 unmodified lines
modified:requests/packages/urllib3/connection.py+4 added-1 removed
54 unmodified lines
55 'http': 80,56 'https': 443,57}5859# When updating RECENT_DATE, move it to60# within two years of the current date, and no61# earlier than 6 months ago.59RECENT_DATE = datetime.date(2014, 1, 1)62RECENT_DATE = datetime.date(2016, 1, 1)636465class DummyConnection(object):66 """Used to detect a failed ConnectionCls import."""
303 unmodified lines
modified:requests/packages/urllib3/connectionpool.py+48 added-20 removed
23 unmodified lines
24 NewConnectionError,25)26from .packages.ssl_match_hostname import CertificateError27from .packages import six28from .packages.six.moves.queue import LifoQueue, Empty, Full28from .packages.six.moves import queue29from .connection import (30 port_by_scheme,31 DummyConnection,32 HTTPConnection, HTTPSConnection, VerifiedHTTPSConnection,
2 unmodified lines
35from .request import RequestMethods36from .response import HTTPResponse3738from .util.connection import is_connection_dropped39from .util.request import set_file_position40from .util.response import assert_header_parsing41from .util.retry import Retry42from .util.timeout import Timeout43from .util.url import get_host, Url
17 unmodified lines
61 :class:`.HTTPConnectionPool` and :class:`.HTTPSConnectionPool`.62 """6364 scheme = None64 QueueCls = LifoQueue65 QueueCls = queue.LifoQueue6667 def __init__(self, host, port=None):68 if not host:69 raise LocationValueError("No host specified.")7070 # 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 = port7374 def __str__(self):75 return '%s(host=%r, port=%r)' % (type(self).__name__,
72 unmodified lines
148 :param _proxy_headers:149 A dictionary with proxy headers, should not be used directly,150 instead, see :class:`urllib3.connectionpool.ProxyManager`"151157 :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 lines
229230 except AttributeError: # self.pool is None231 raise ClosedPoolError(self, "Pool is closed.")232238 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 lines
268 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 lines
418 conn = old_pool.get(block=False)419 if conn:420 conn.close()421427 except Empty:422 except queue.Empty:423 pass # Done.424425 def is_same_host(self, url):426 """
5 unmodified lines
432433 # TODO: Add optional support for socket.gethostbyname checking.434 scheme, host, port = get_host(url)435436 host = _ipv6_host(host).lower()437438 # 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 lines
445446 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 lines
527 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.530531 :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.535534 :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 lines
577 # Keep track of whether we cleanly exited the except block. This578 # ensures we do proper cleanup in finally.579 clean_exit = False580581 # 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)584585 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 lines
617618 # Everything went great!619 clean_exit = True620615 except Empty:621 except queue.Empty:622 # Timed out by queue.623 raise EmptyPoolError(self, "No pool connections are available.")624625 except (BaseSSLError, CertificateError) as e:
47 unmodified lines
673 "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)679680 # Handle redirect?681 redirect_location = redirect and response.get_redirect_location()682 if redirect_location:
16 unmodified lines
699 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)705706 # 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 lines
721 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)727728 return response729730
130 unmodified lines
861862 :param url:863 Absolute URL string that must include the scheme. Port is optional.864856 :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 lines
877 if scheme == 'https':878 return HTTPSConnectionPool(host, port=port, **kw)879 else:880 return HTTPConnectionPool(host, port=port, **kw)881882883def _ipv6_host(host):884 """885 Process IPv6 address literals886 """887888 # 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 host
modified:requests/packages/urllib3/exceptions.py+5 added
237 unmodified lines
238 "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)242243244class UnrewindableBodyError(HTTPError):245 "urllib3 encountered an error when trying to rewind a body"246 pass
modified:requests/packages/urllib3/poolmanager.py+1 added-1 removed
91 unmodified lines
92 :param headers:93 Headers to include with all requests, unless other headers are given94 explicitly.9596 :param \**connection_pool_kw:96 :param \\**connection_pool_kw:97 Additional parameters are used to create fresh98 :class:`urllib3.connectionpool.ConnectionPool` instances.99100 Example::
263 unmodified lines
modified:Makefile+1 added-1 removed
16 unmodified lines
1718deps: urllib3 chardet idna1920urllib3: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