Merge pull request #3979 from schlamar/bypass-proxy
Before adoption: this commit came in with the history the project adopted, so no landing records it.
improve proxy bypass on Windows
authored by Cory Benfield · committed by GitHub · parents 26ab951, 5c389cf · Browse files · 6 files·+113 added−177 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
6 files+113 added−177 removed
- tests:+54 added−73 removed
- other:+59 added−104 removed
Provenance
- Commit
216aee4- Tree
de8bf4b- Author
Cory Benfield <lukasaoz@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
26ab951- Parent 2
5c389cf
6 files changed+113 added−177 removed
modified:requests/compat.py+4 added-2 removed
35 unmodified lines36 # Specifics37 # ---------38 39 if is_py2:40- from urllib import quote, unquote, quote_plus, unquote_plus, urlencode, getproxies, proxy_bypass40+ from urllib import (41+ quote, unquote, quote_plus, unquote_plus, urlencode, getproxies,42+ proxy_bypass, proxy_bypass_environment, getproxies_environment)43 from urlparse import urlparse, urlunparse, urljoin, urlsplit, urldefrag44 from urllib2 import parse_http_list45 import cookielib46 from Cookie import Morsel8 unmodified lines55 integer_types = (int, long)56 57 elif is_py3:58 from urllib.parse import urlparse, urlunparse, urljoin, urlsplit, urlencode, quote, unquote, quote_plus, unquote_plus, urldefrag57- from urllib.request import parse_http_list, getproxies, proxy_bypass59+ from urllib.request import parse_http_list, getproxies, proxy_bypass, proxy_bypass_environment, getproxies_environment60 from http import cookiejar as cookielib61 from http.cookies import Morsel62 from io import StringIO63 from collections import OrderedDict7 unmodified linesmodified:requests/structures.py-89 removed
6 unmodified lines7 Data structures that power Requests.8 """9 10 import collections11-import time11 12 from .compat import OrderedDict13 15-current_time = getattr(time, 'monotonic', time.time)14 17-15 class CaseInsensitiveDict(collections.MutableMapping):16 """A case-insensitive ``dict``-like object.17 18 Implements all methods and operations of83 unmodified lines102 return self.__dict__.get(key, None)103 104 def get(self, key, default=None):105 return self.__dict__.get(key, default)109-110-111-class TimedCacheManaged(object):112- """113- Wrap a function call in a timed cache114- """115- def __init__(self, fnc):116- self.fnc = fnc117- self.cache = TimedCache()118-119- def __call__(self, *args, **kwargs):120- key = args[0]121- found = None122- try:123- found = self.cache[key]124- except KeyError:125- found = self.fnc(key, **kwargs)126- self.cache[key] = found127-128- return found129-130-131-class TimedCache(collections.MutableMapping):132- """133- Evicts entries after expiration_secs. If none are expired and maxlen is hit,134- will evict the oldest cached entry135- """136- def __init__(self, maxlen=32, expiration_secs=60):137- """138- :param maxlen: most number of entries to hold on to139- :param expiration_secs: the number of seconds to hold on140- to entries141- """142- self.maxlen = maxlen143- self.expiration_secs = expiration_secs144- self._dict = OrderedDict()145-146- def __repr__(self):147- return '<TimedCache maxlen:%d len:%d expiration_secs:%d>' % \148- (self.maxlen, len(self._dict), self.expiration_secs)149-150- def __iter__(self):151- return ((key, value[1]) for key, value in self._dict.items())152-153- def __delitem__(self, item):154- del self._dict[item]155-156- def __getitem__(self, key):157- """158- Look up an item in the cache. If the item159- has already expired, it will be invalidated and not returned160-161- :param key: which entry to look up162- :return: the value in the cache, or None163- """164- occurred, value = self._dict[key]165- now = int(current_time())166-167- if now - occurred > self.expiration_secs:168- del self._dict[key]169- raise KeyError(key)170- else:171- return value172-173- def __setitem__(self, key, value):174- """175- Locates the value at lookup key, if cache is full, will evict the176- oldest entry177-178- :param key: the key to search the cache for179- :param value: the value to be added to the cache180- """181- now = int(current_time())182-183- while len(self._dict) >= self.maxlen:184- self._dict.popitem(last=False)185-186- self._dict[key] = (now, value)187-188- def __len__(self):189- """:return: the length of the cache"""190- return len(self._dict)191-192- def clear(self):193- """Clears the cache"""194- return self._dict.clear()modified:requests/utils.py+53 added-13 removed
12 unmodified lines13 import collections14 import contextlib15 import io16 import os17+import platform18 import re19 import socket20 import struct21 import warnings4 unmodified lines26 from ._internal_utils import to_native_string27 from .compat import parse_http_list as _parse_list_header28 from .compat import (29 quote, urlparse, bytes, str, OrderedDict, unquote, getproxies,29- proxy_bypass, urlunparse, basestring, integer_types)30+ proxy_bypass, urlunparse, basestring, integer_types, is_py3,31+ proxy_bypass_environment, getproxies_environment)32 from .cookies import cookiejar_from_dict31-from .structures import CaseInsensitiveDict, TimedCacheManaged33+from .structures import CaseInsensitiveDict34 from .exceptions import (35 InvalidURL, InvalidHeader, FileModeWarning, UnrewindableBodyError)36 37 NETRC_FILES = ('.netrc', '_netrc')38 39 DEFAULT_CA_BUNDLE_PATH = certs.where()40 41 42+if platform.system() == 'Windows':43+ # provide a proxy_bypass version on Windows without DNS lookups44+45+ def proxy_bypass_registry(host):46+ if is_py3:47+ import winreg48+ else:49+ import _winreg as winreg50+ try:51+ internetSettings = winreg.OpenKey(winreg.HKEY_CURRENT_USER,52+ r'Software\Microsoft\Windows\CurrentVersion\Internet Settings')53+ proxyEnable = winreg.QueryValueEx(internetSettings,54+ 'ProxyEnable')[0]55+ proxyOverride = winreg.QueryValueEx(internetSettings,56+ 'ProxyOverride')[0]57+ except OSError:58+ return False59+ if not proxyEnable or not proxyOverride:60+ return False61+62+ # make a check value list from the registry entry: replace the63+ # '<local>' string by the localhost entry and the corresponding64+ # canonical entry.65+ proxyOverride = proxyOverride.split(';')66+ # now check if we match one of the registry values.67+ for test in proxyOverride:68+ if test == '<local>':69+ if '.' not in host:70+ return True71+ test = test.replace(".", r"\.") # mask dots72+ test = test.replace("*", r".*") # change glob sequence73+ test = test.replace("?", r".") # change glob char74+ if re.match(test, host, re.I):75+ return True76+ return False77+78+ def proxy_bypass(host): # noqa79+ """Return True, if the host should be bypassed.80+81+ Checks proxy settings gathered from the environment, if specified,82+ or the registry.83+ """84+ if getproxies_environment():85+ return proxy_bypass_environment(host)86+ else:87+ return proxy_bypass_registry(host)88+89+90 def dict_to_sequence(d):91 """Returns an internal sequence dictionary update."""92 93 if hasattr(d, 'items'):532 unmodified lines626 else:627 os.environ[env_name] = old_value628 629 580-@TimedCacheManaged581-def _proxy_bypass_cached(netloc):582- """583- Looks for netloc in the cache, if not found, will call proxy_bypass584- for the netloc and store its result in the cache585-586- :rtype: bool587- """588- return proxy_bypass(netloc)589-630 def should_bypass_proxies(url, no_proxy):631 """632 Returns whether we should bypass proxies or not.633 39 unmodified lines673 # exceptions we've seen, though: this call failing in other ways can reveal674 # legitimate problems.675 with set_environ('no_proxy', no_proxy_arg):676 try:637- bypass = _proxy_bypass_cached(netloc)677+ bypass = proxy_bypass(netloc)678 except (TypeError, socket.gaierror):679 bypass = False680 681 if bypass:222 unmodified linesmodified:tests/test_structures.py+1 added-73 removed
1 # -*- coding: utf-8 -*-2 3 import pytest4 5-from requests.structures import CaseInsensitiveDict, LookupDict, TimedCache, TimedCacheManaged5+from requests.structures import CaseInsensitiveDict, LookupDict6 7 8 class TestCaseInsensitiveDict:9 63 unmodified lines73 74 @get_item_parameters75 def test_get(self, key, value):76 assert self.lookup_dict.get(key) == value77-78-79-class TestTimedCache(object):80- @pytest.fixture(autouse=True)81- def setup(self):82- self.any_value = 'some value'83- self.expiration_secs = 6084- self.cache = TimedCache(expiration_secs=self.expiration_secs)85- yield86- self.cache.clear()87-88- def test_get(self):89- self.cache['a'] = self.any_value90- assert self.cache['a'] is self.any_value91-92- def test_repr(self):93- repr = str(self.cache)94- assert repr == '<TimedCache maxlen:32 len:0 expiration_secs:60>'95-96- def test_get_expired_item(self, mocker):97- self.cache = TimedCache(maxlen=1, expiration_secs=self.expiration_secs)98-99- mocker.patch('requests.structures.current_time', lambda: 0)100- self.cache['a'] = self.any_value101- mocker.patch('requests.structures.current_time', lambda: self.expiration_secs + 1)102- assert self.cache.get('a') is None103-104- def test_evict_first_entry_when_full(self, mocker):105- self.cache = TimedCache(maxlen=2, expiration_secs=2)106- mocker.patch('requests.structures.current_time', lambda: 0)107- self.cache['a'] = self.any_value108- mocker.patch('requests.structures.current_time', lambda: 1)109- self.cache['b'] = self.any_value110- mocker.patch('requests.structures.current_time', lambda: 3)111- self.cache['c'] = self.any_value112- assert len(self.cache) is 2113- with pytest.raises(KeyError, message='Expected key not found'):114- self.cache['a']115- assert self.cache['b'] is self.any_value116- assert self.cache['c'] is self.any_value117-118- def test_delete_item_removes_item(self):119- self.cache['a'] = self.any_value120- del self.cache['a']121- with pytest.raises(KeyError, message='Expected key not found'):122- self.cache['a']123-124- def test_iterating_hides_timestamps(self):125- self.cache['a'] = 1126- self.cache['b'] = 2127- expected = [('a', 1), ('b', 2)]128- actual = [(key, val) for key, val in self.cache]129- assert expected == actual130-131-132-class TestTimedCacheManagedDecorator(object):133- def test_caches_repeated_calls(self, mocker):134- mocker.patch('requests.structures.current_time', lambda: 0)135-136- nonlocals = {'value': 0}137-138- @TimedCacheManaged139- def some_method(x):140- nonlocals['value'] = nonlocals['value'] + x141- return nonlocals['value']142-143- first_result = some_method(1)144- assert first_result is 1145- second_result = some_method(1)146- assert second_result is 1147- third_result = some_method(2)148- assert third_result is 3modified:tests/test_utils.py+53 added
1 # -*- coding: utf-8 -*-2 3+import os4 from io import BytesIO5 6 import pytest7 from requests import compat591 unmodified lines599 """600 no_proxy = '192.168.0.0/24,127.0.0.1,localhost.localdomain,172.16.1.1'601 # Test 'no_proxy' argument602 assert should_bypass_proxies(url, no_proxy=no_proxy) == expected603+604+605+@pytest.mark.skipif(os.name != 'nt', reason='Test only on Windows')606+@pytest.mark.parametrize(607+ 'url, expected, override', (608+ ('http://192.168.0.1:5000/', True, None),609+ ('http://192.168.0.1/', True, None),610+ ('http://172.16.1.1/', True, None),611+ ('http://172.16.1.1:5000/', True, None),612+ ('http://localhost.localdomain:5000/v1.0/', True, None),613+ ('http://172.16.1.22/', False, None),614+ ('http://172.16.1.22:5000/', False, None),615+ ('http://google.com:5000/v1.0/', False, None),616+ ('http://mylocalhostname:5000/v1.0/', True, '<local>'),617+ ('http://192.168.0.1/', False, ''),618+ ))619+def test_should_bypass_proxies_win_registry(url, expected, override,620+ monkeypatch):621+ """Tests for function should_bypass_proxies to check if proxy622+ can be bypassed or not with Windows registry settings623+ """624+ if override is None:625+ override = '192.168.*;127.0.0.1;localhost.localdomain;172.16.1.1'626+ if compat.is_py3:627+ import winreg628+ else:629+ import _winreg as winreg630+631+ class RegHandle:632+ def Close(self):633+ pass634+635+ ie_settings = RegHandle()636+637+ def OpenKey(key, subkey):638+ return ie_settings639+640+ def QueryValueEx(key, value_name):641+ if key is ie_settings:642+ if value_name == 'ProxyEnable':643+ return [1]644+ elif value_name == 'ProxyOverride':645+ return [override]646+647+ monkeypatch.setenv('http_proxy', '')648+ monkeypatch.setenv('https_proxy', '')649+ monkeypatch.setenv('ftp_proxy', '')650+ monkeypatch.setenv('no_proxy', '')651+ monkeypatch.setenv('NO_PROXY', '')652+ monkeypatch.setattr(winreg, 'OpenKey', OpenKey)653+ monkeypatch.setattr(winreg, 'QueryValueEx', QueryValueEx)654+ assert should_bypass_proxies(url, no_proxy=None) == expectedmodified:HISTORY.rst+2 added
13 unmodified lines14 - Changed the internal calculation of elapsed request time to have higher15 resolution on Windows.16 - Added ``win_inet_pton`` as conditional dependency for the ``[socks]`` extra17 on Windows with Python 2.7.18+- Changed the proxy bypass implementation on Windows: the proxy bypass19+ check doesn't use forward and reverse DNS requests anymore20 21 2.13.0 (2017-01-24)22 +++++++++++++++++++23 1300 unmodified lines