Merge pull request #2953 from Lukasa/socks_proxy_support
Before adoption: this commit came in with the history the project adopted, so no landing records it.
SOCKS Proxy Support
authored by Kenneth Reitz · committed by Kenneth Reitz · parents c9ef565, a3acd30 · Browse files · 13 files·+268 added−46 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
13 files+268 added−46 removed
- other:+268 added−46 removed
Provenance
- Commit
39d6935- Tree
d75fae8- Author
Kenneth Reitz <me@kennethreitz.org>- Committer
Kenneth Reitz <me@kennethreitz.org>- Parent 1
c9ef565- Parent 2
a3acd30
13 files changed+268 added−46 removed
modified:requests/packages/urllib3/contrib/appengine.py+10 added-2 removed
142 unmodified lines143 # Check if we should retry the HTTP response.144 if retries.is_forced_retry(method, status_code=http_response.status):145 retries = retries.increment(146 method, url, response=http_response, _pool=self)147- log.info("Forced retry: %s" % url)147+ log.info("Forced retry: %s", url)148 retries.sleep()149 return self.urlopen(150 method, url,151 body=body, headers=headers,11 unmodified lines163 164 if content_encoding == 'deflate':165 del urlfetch_resp.headers['content-encoding']166 167+ transfer_encoding = urlfetch_resp.headers.get('transfer-encoding')168+ # We have a full response's content,169+ # so let's make sure we don't report ourselves as chunked data.170+ if transfer_encoding == 'chunked':171+ encodings = transfer_encoding.split(",")172+ encodings.remove('chunked')173+ urlfetch_resp.headers['transfer-encoding'] = ','.join(encodings)174+175 return HTTPResponse(176 # In order for decoding to work, we must present the content as177 # a file-like object.178 body=BytesIO(urlfetch_resp.content),5 unmodified lines184 def _get_absolute_timeout(self, timeout):185 if timeout is Timeout.DEFAULT_TIMEOUT:186 return 5 # 5s is the default timeout for URLFetch.187 if isinstance(timeout, Timeout):180- if timeout.read is not timeout.connect:188+ if timeout._read is not timeout._connect:189 warnings.warn(190 "URLFetch does not support granular timeout settings, "191 "reverting to total timeout.", AppEnginePlatformWarning)192 return timeout.total39 unmodified linesmodified:requests/packages/urllib3/contrib/ntlmpool.py+10 added-10 removed
41 unmodified lines42 def _new_conn(self):43 # Performs the NTLM handshake that secures the connection. The socket44 # must be kept open while requests are performed.45 self.num_connections += 146- log.debug('Starting NTLM HTTPS connection no. %d: https://%s%s' %47- (self.num_connections, self.host, self.authurl))46+ log.debug('Starting NTLM HTTPS connection no. %d: https://%s%s',47+ self.num_connections, self.host, self.authurl)48 49 headers = {}50 headers['Connection'] = 'Keep-Alive'51 req_header = 'Authorization'3 unmodified lines55 56 # Send negotiation message57 headers[req_header] = (58 'NTLM %s' % ntlm.create_NTLM_NEGOTIATE_MESSAGE(self.rawuser))59- log.debug('Request headers: %s' % headers)59+ log.debug('Request headers: %s', headers)60 conn.request('GET', self.authurl, None, headers)61 res = conn.getresponse()62 reshdr = dict(res.getheaders())63- log.debug('Response status: %s %s' % (res.status, res.reason))64- log.debug('Response headers: %s' % reshdr)65- log.debug('Response data: %s [...]' % res.read(100))63+ log.debug('Response status: %s %s', res.status, res.reason)64+ log.debug('Response headers: %s', reshdr)65+ log.debug('Response data: %s [...]', res.read(100))66 67 # Remove the reference to the socket, so that it can not be closed by68 # the response object (we want to keep the socket open)69 res.fp = None16 unmodified lines86 self.domain,87 self.pw,88 NegotiateFlags)89 headers[req_header] = 'NTLM %s' % auth_msg90- log.debug('Request headers: %s' % headers)90+ log.debug('Request headers: %s', headers)91 conn.request('GET', self.authurl, None, headers)92 res = conn.getresponse()93- log.debug('Response status: %s %s' % (res.status, res.reason))94- log.debug('Response headers: %s' % dict(res.getheaders()))95- log.debug('Response data: %s [...]' % res.read()[:100])93+ log.debug('Response status: %s %s', res.status, res.reason)94+ log.debug('Response headers: %s', dict(res.getheaders()))95+ log.debug('Response data: %s [...]', res.read()[:100])96 if res.status != 200:97 if res.status == 401:98 raise Exception('Server rejected request: wrong '99 'username or password')16 unmodified linesadded:requests/packages/urllib3/contrib/socks.py+172 added
1+# -*- coding: utf-8 -*-2+"""3+SOCKS support for urllib34+~~~~~~~~~~~~~~~~~~~~~~~~~5+6+This contrib module contains provisional support for SOCKS proxies from within7+urllib3. This module supports SOCKS4 (specifically the SOCKS4A variant) and8+SOCKS5. To enable its functionality, either install PySocks or install this9+module with the ``socks`` extra.10+11+Known Limitations:12+13+- Currently PySocks does not support contacting remote websites via literal14+ IPv6 addresses. Any such connection attempt will fail.15+- Currently PySocks does not support IPv6 connections to the SOCKS proxy. Any16+ such connection attempt will fail.17+"""18+from __future__ import absolute_import19+20+try:21+ import socks22+except ImportError:23+ import warnings24+ from ..exceptions import DependencyWarning25+26+ warnings.warn((27+ 'SOCKS support in urllib3 requires the installation of optional '28+ 'dependencies: specifically, PySocks. For more information, see '29+ 'https://urllib3.readthedocs.org/en/latest/contrib.html#socks-proxies'30+ ),31+ DependencyWarning32+ )33+ raise34+35+from socket import error as SocketError, timeout as SocketTimeout36+37+from ..connection import (38+ HTTPConnection, HTTPSConnection39+)40+from ..connectionpool import (41+ HTTPConnectionPool, HTTPSConnectionPool42+)43+from ..exceptions import ConnectTimeoutError, NewConnectionError44+from ..poolmanager import PoolManager45+from ..util.url import parse_url46+47+try:48+ import ssl49+except ImportError:50+ ssl = None51+52+53+class SOCKSConnection(HTTPConnection):54+ """55+ A plain-text HTTP connection that connects via a SOCKS proxy.56+ """57+ def __init__(self, *args, **kwargs):58+ self._socks_options = kwargs.pop('_socks_options')59+ super(SOCKSConnection, self).__init__(*args, **kwargs)60+61+ def _new_conn(self):62+ """63+ Establish a new connection via the SOCKS proxy.64+ """65+ extra_kw = {}66+ if self.source_address:67+ extra_kw['source_address'] = self.source_address68+69+ if self.socket_options:70+ extra_kw['socket_options'] = self.socket_options71+72+ try:73+ conn = socks.create_connection(74+ (self.host, self.port),75+ proxy_type=self._socks_options['socks_version'],76+ proxy_addr=self._socks_options['proxy_host'],77+ proxy_port=self._socks_options['proxy_port'],78+ proxy_username=self._socks_options['username'],79+ proxy_password=self._socks_options['password'],80+ timeout=self.timeout,81+ **extra_kw82+ )83+84+ except SocketTimeout as e:85+ raise ConnectTimeoutError(86+ self, "Connection to %s timed out. (connect timeout=%s)" %87+ (self.host, self.timeout))88+89+ except socks.ProxyError as e:90+ # This is fragile as hell, but it seems to be the only way to raise91+ # useful errors here.92+ if e.socket_err:93+ error = e.socket_err94+ if isinstance(error, SocketTimeout):95+ raise ConnectTimeoutError(96+ self,97+ "Connection to %s timed out. (connect timeout=%s)" %98+ (self.host, self.timeout)99+ )100+ else:101+ raise NewConnectionError(102+ self,103+ "Failed to establish a new connection: %s" % error104+ )105+ else:106+ raise NewConnectionError(107+ self,108+ "Failed to establish a new connection: %s" % e109+ )110+111+ except SocketError as e: # Defensive: PySocks should catch all these.112+ raise NewConnectionError(113+ self, "Failed to establish a new connection: %s" % e)114+115+ return conn116+117+118+# We don't need to duplicate the Verified/Unverified distinction from119+# urllib3/connection.py here because the HTTPSConnection will already have been120+# correctly set to either the Verified or Unverified form by that module. This121+# means the SOCKSHTTPSConnection will automatically be the correct type.122+class SOCKSHTTPSConnection(SOCKSConnection, HTTPSConnection):123+ pass124+125+126+class SOCKSHTTPConnectionPool(HTTPConnectionPool):127+ ConnectionCls = SOCKSConnection128+129+130+class SOCKSHTTPSConnectionPool(HTTPSConnectionPool):131+ ConnectionCls = SOCKSHTTPSConnection132+133+134+class SOCKSProxyManager(PoolManager):135+ """136+ A version of the urllib3 ProxyManager that routes connections via the137+ defined SOCKS proxy.138+ """139+ pool_classes_by_scheme = {140+ 'http': SOCKSHTTPConnectionPool,141+ 'https': SOCKSHTTPSConnectionPool,142+ }143+144+ def __init__(self, proxy_url, username=None, password=None,145+ num_pools=10, headers=None, **connection_pool_kw):146+ parsed = parse_url(proxy_url)147+148+ if parsed.scheme == 'socks5':149+ socks_version = socks.PROXY_TYPE_SOCKS5150+ elif parsed.scheme == 'socks4':151+ socks_version = socks.PROXY_TYPE_SOCKS4152+ else:153+ raise ValueError(154+ "Unable to determine SOCKS version from %s" % proxy_url155+ )156+157+ self.proxy_url = proxy_url158+159+ socks_options = {160+ 'socks_version': socks_version,161+ 'proxy_host': parsed.host,162+ 'proxy_port': parsed.port,163+ 'username': username,164+ 'password': password,165+ }166+ connection_pool_kw['_socks_options'] = socks_options167+168+ super(SOCKSProxyManager, self).__init__(169+ num_pools, headers, **connection_pool_kw170+ )171+172+ self.pool_classes_by_scheme = SOCKSProxyManager.pool_classes_by_schememodified:requests/packages/urllib3/util/response.py+1 added-1 removed
59 unmodified lines60 61 62 def is_response_to_head(response):63 """64- Checks, wether a the request of a response has been a HEAD-request.64+ Checks whether the request of a response has been a HEAD-request.65 Handles the quirks of AppEngine.66 67 :param conn:68 :type conn: :class:`httplib.HTTPResponse`6 unmodified linesmodified:requests/packages/urllib3/util/retry.py+2 added-2 removed
151 unmodified lines152 return retries153 154 redirect = bool(redirect) and None155 new_retries = cls(retries, redirect=redirect)156- log.debug("Converted retries value: %r -> %r" % (retries, new_retries))156+ log.debug("Converted retries value: %r -> %r", retries, new_retries)157 return new_retries158 159 def get_backoff_time(self):160 """ Formula for computing the current backoff110 unmodified lines271 272 if new_retry.is_exhausted():273 raise MaxRetryError(_pool, url, error or ResponseError(cause))274 275- log.debug("Incremented Retry for (url='%s'): %r" % (url, new_retry))275+ log.debug("Incremented Retry for (url='%s'): %r", url, new_retry)276 277 return new_retry278 279 def __repr__(self):7 unmodified linesmodified:requests/packages/urllib3/util/ssl_.py+2 added-1 removed
108 unmodified lines109 '2.7, 3.2, or later if you need this functionality.'110 )111 self.ciphers = cipher_suite112 113- def wrap_socket(self, socket, server_hostname=None):113+ def wrap_socket(self, socket, server_hostname=None, server_side=False):114 warnings.warn(115 'A true SSLContext object is not available. This prevents '116 'urllib3 from configuring SSL appropriately and may cause '117 'certain SSL connections to fail. For more information, see '6 unmodified lines124 'certfile': self.certfile,125 'ca_certs': self.ca_certs,126 'cert_reqs': self.verify_mode,127 'ssl_version': self.protocol,128+ 'server_side': server_side,129 }130 if self.supports_set_ciphers: # Platform-specific: Python 2.7+131 return wrap_socket(socket, ciphers=self.ciphers, **kwargs)132 else: # Platform-specific: Python 2.6186 unmodified linesmodified:requests/packages/urllib3/__init__.py+2 added-3 removed
1 """2 urllib3 - Thread-safe connection pooling and re-using.3 """4-4 from __future__ import absolute_import5 import warnings6 7 from .connectionpool import (22 unmodified lines30 pass31 32 __author__ = 'Andrey Petrov (andrey.petrov@shazow.net)'33 __license__ = 'MIT'35-__version__ = '1.13.1'34+__version__ = 'dev'35 36 __all__ = (37 'HTTPConnectionPool',38 'HTTPSConnectionPool',27 unmodified lines66 handler = logging.StreamHandler()67 handler.setFormatter(logging.Formatter('%(asctime)s %(levelname)s %(message)s'))68 logger.addHandler(handler)69 logger.setLevel(level)71- logger.debug('Added a stderr logging handler to logger: %s' % __name__)70+ logger.debug('Added a stderr logging handler to logger: %s', __name__)71 return handler72 73 # ... Clean up.74 del NullHandler18 unmodified linesmodified:requests/packages/urllib3/connectionpool.py+11 added-12 removed
201 unmodified lines202 """203 Return a fresh :class:`HTTPConnection`.204 """205 self.num_connections += 1206- log.info("Starting new HTTP connection (%d): %s" %207- (self.num_connections, self.host))206+ log.info("Starting new HTTP connection (%d): %s",207+ self.num_connections, self.host)208 209 conn = self.ConnectionCls(host=self.host, port=self.port,210 timeout=self.timeout.connect_timeout,211 strict=self.strict, **self.conn_kw)26 unmodified lines238 pass # Oh well, we'll create a new connection then239 240 # If this is a persistent connection, check if it got disconnected241 if conn and is_connection_dropped(conn):242- log.info("Resetting dropped connection: %s" % self.host)242+ log.info("Resetting dropped connection: %s", self.host)243 conn.close()244 if getattr(conn, 'auto_open', 1) == 0:245 # This is a proxied connection that has been mutated by246 # httplib._tunnel() and cannot be reused (since it would24 unmodified lines271 pass272 except Full:273 # This should never happen if self.block == True274 log.warning(275- "Connection pool is full, discarding connection: %s" %275+ "Connection pool is full, discarding connection: %s",276 self.host)277 278 # Connection never got put back into the pool, close it.279 if conn:101 unmodified lines381 raise382 383 # AppEngine doesn't have a version attr.384 http_version = getattr(conn, '_http_vsn_str', 'HTTP/?')385- log.debug("\"%s %s %s\" %s %s" % (method, url, http_version,386- httplib_response.status,387- httplib_response.length))385+ log.debug("\"%s %s %s\" %s %s", method, url, http_version,386+ httplib_response.status, httplib_response.length)387 388 try:389 assert_header_parsing(httplib_response.msg)390 except HeaderParsingError as hpe: # Platform-specific: Python 3229 unmodified lines620 621 if not conn:622 # Try again623 log.warning("Retrying (%r) after connection "625- "broken by '%r': %s" % (retries, err, url))624+ "broken by '%r': %s", retries, err, url)625 return self.urlopen(method, url, body, headers, retries,626 redirect, assert_same_host,627 timeout=timeout, pool_timeout=pool_timeout,628 release_conn=release_conn, **response_kw)13 unmodified lines642 response.release_conn()643 raise644 return response645 647- log.info("Redirecting %s -> %s" % (url, redirect_location))646+ log.info("Redirecting %s -> %s", url, redirect_location)647 return self.urlopen(648 method, redirect_location, body, headers,649 retries=retries, redirect=redirect,650 assert_same_host=assert_same_host,3 unmodified lines654 # Check if we should retry the HTTP response.655 if retries.is_forced_retry(method, status_code=response.status):656 retries = retries.increment(method, url, response=response, _pool=self)657 retries.sleep()659- log.info("Forced retry: %s" % url)658+ log.info("Forced retry: %s", url)659 return self.urlopen(660 method, url, body, headers,661 retries=retries, redirect=redirect,662 assert_same_host=assert_same_host,89 unmodified lines752 """753 Return a fresh :class:`httplib.HTTPSConnection`.754 """755 self.num_connections += 1757- log.info("Starting new HTTPS connection (%d): %s"758- % (self.num_connections, self.host))756+ log.info("Starting new HTTPS connection (%d): %s",757+ self.num_connections, self.host)758 759 if not self.ConnectionCls or self.ConnectionCls is DummyConnection:760 raise SSLError("Can't connect to HTTPS URL because the SSL "761 "module is not available.")56 unmodified linesmodified:requests/packages/urllib3/exceptions.py+8 added
178 unmodified lines179 "Warned when making a HTTPS request without SNI available."180 pass181 182 183+class DependencyWarning(HTTPWarning):184+ """185+ Warned when an attempt is made to import a module with missing optional186+ dependencies.187+ """188+ pass189+190+191 class ResponseNotChunked(ProtocolError, ValueError):192 "Response needs to be chunked in order to read it as chunks."193 pass194 15 unmodified linesmodified:requests/packages/urllib3/poolmanager.py+10 added-7 removed
16 unmodified lines17 18 __all__ = ['PoolManager', 'ProxyManager', 'proxy_from_url']19 20 21-pool_classes_by_scheme = {22- 'http': HTTPConnectionPool,23- 'https': HTTPSConnectionPool,24-}25-21 log = logging.getLogger(__name__)22 23 SSL_KEYWORDS = ('key_file', 'cert_file', 'cert_reqs', 'ca_certs',24 'ssl_version', 'ca_cert_dir')25 26+pool_classes_by_scheme = {27+ 'http': HTTPConnectionPool,28+ 'https': HTTPSConnectionPool,29+}30 31+32 class PoolManager(RequestMethods):33 """34 Allows for arbitrary requests while transparently keeping track of35 necessary connection pools for you.28 unmodified lines64 self.connection_pool_kw = connection_pool_kw65 self.pools = RecentlyUsedContainer(num_pools,66 dispose_func=lambda p: p.close())67 68+ # Locally set the pool classes so other PoolManagers can override them.69+ self.pool_classes_by_scheme = pool_classes_by_scheme70+71 def __enter__(self):72 return self73 74 def __exit__(self, exc_type, exc_val, exc_tb):8 unmodified lines83 This method is used to actually create the connection pools handed out84 by :meth:`connection_from_url` and companion methods. It is intended85 to be overridden for customization.86 """84- pool_cls = pool_classes_by_scheme[scheme]87+ pool_cls = self.pool_classes_by_scheme[scheme]88 kwargs = self.connection_pool_kw89 if scheme == 'http':90 kwargs = self.connection_pool_kw.copy()91 for kw in SSL_KEYWORDS:96 unmodified lines188 189 kw['retries'] = retries190 kw['redirect'] = redirect191 189- log.info("Redirecting %s -> %s" % (url, redirect_location))192+ log.info("Redirecting %s -> %s", url, redirect_location)193 return self.urlopen(method, redirect_location, **kw)194 195 196 class ProxyManager(PoolManager):88 unmodified linesmodified:requests/__init__.py+6 added
53 unmodified lines54 pyopenssl.inject_into_urllib3()55 except ImportError:56 pass57 58+import warnings59+60+# urllib3's DependencyWarnings should be silenced.61+from .packages.urllib3.exceptions import DependencyWarning62+warnings.simplefilter('ignore', DependencyWarning)63+64 from . import utils65 from .models import Request, Response, PreparedRequest66 from .api import request, get, head, post, patch, put, delete, options67 from .sessions import session, Session22 unmodified linesmodified:requests/adapters.py+33 added-8 removed
17 unmodified lines18 from .packages.urllib3.util.retry import Retry19 from .compat import urlparse, basestring20 from .utils import (DEFAULT_CA_BUNDLE_PATH, get_encoding_from_headers,21 prepend_scheme_if_needed, get_auth_from_url, urldefragauth,22- select_proxy)22+ select_proxy, to_native_string)23 from .structures import CaseInsensitiveDict24 from .packages.urllib3.exceptions import ClosedPoolError25 from .packages.urllib3.exceptions import ConnectTimeoutError26 from .packages.urllib3.exceptions import HTTPError as _HTTPError5 unmodified lines32 from .packages.urllib3.exceptions import SSLError as _SSLError33 from .packages.urllib3.exceptions import ResponseError34 from .cookies import extract_cookies_to_jar35 from .exceptions import (ConnectionError, ConnectTimeout, ReadTimeout, SSLError,36- ProxyError, RetryError)36+ ProxyError, RetryError, InvalidSchema)37 from .auth import _basic_auth_str38 39+try:40+ from .packages.urllib3.contrib.socks import SOCKSProxyManager41+except ImportError:42+ def SOCKSProxyManager(*args, **kwargs):43+ raise InvalidSchema("Missing dependencies for SOCKS support.")44+45 DEFAULT_POOLBLOCK = False46 DEFAULT_POOLSIZE = 1047 DEFAULT_RETRIES = 048 DEFAULT_POOL_TIMEOUT = None105 unmodified lines154 :param proxy: The proxy to return a urllib3 ProxyManager for.155 :param proxy_kwargs: Extra keyword arguments used to configure the Proxy Manager.156 :returns: ProxyManager157 """152- if not proxy in self.proxy_manager:158+ if proxy in self.proxy_manager:159+ manager = self.proxy_manager[proxy]160+ elif proxy.lower().startswith('socks'):161+ username, password = get_auth_from_url(proxy)162+ manager = self.proxy_manager[proxy] = SOCKSProxyManager(163+ proxy,164+ username=username,165+ password=password,166+ num_pools=self._pool_connections,167+ maxsize=self._pool_maxsize,168+ block=self._pool_block,169+ **proxy_kwargs170+ )171+ else:172 proxy_headers = self.proxy_headers(proxy)154- self.proxy_manager[proxy] = proxy_from_url(173+ manager = self.proxy_manager[proxy] = proxy_from_url(174 proxy,175 proxy_headers=proxy_headers,176 num_pools=self._pool_connections,177 maxsize=self._pool_maxsize,178 block=self._pool_block,179 **proxy_kwargs)180 162- return self.proxy_manager[proxy]181+ return manager182 183 def cert_verify(self, conn, url, verify, cert):184 """Verify a SSL certificate. This method should not be called from user185 code, and is only exposed for use when subclassing the118 unmodified lines304 :param proxies: A dictionary of schemes or schemes and hosts to proxy URLs.305 """306 proxy = select_proxy(request.url, proxies)307 scheme = urlparse(request.url).scheme289- if proxy and scheme != 'https':308+309+ is_proxied_http_request = (proxy and scheme != 'https')310+ using_socks_proxy = False311+ if proxy:312+ proxy_scheme = urlparse(proxy).scheme.lower()313+ using_socks_proxy = proxy_scheme.startswith('socks')314+315+ url = request.path_url316+ if is_proxied_http_request and not using_socks_proxy:317 url = urldefragauth(request.url)291- else:292- url = request.path_url318 319 return url320 321 def add_headers(self, request, **kwargs):162 unmodified linesmodified:setup.py+1 added
91 unmodified lines92 cmdclass={'test': PyTest},93 tests_require=test_requirements,94 extras_require={95 'security': ['pyOpenSSL>=0.13', 'ndg-httpsclient', 'pyasn1'],96+ 'socks': ['PySocks>=1.5.6'],97 },98 )