Skip to content
Myr

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

13 files+268 added−46 removed

modified:requests/packages/urllib3/contrib/appengine.py+10 added-2 removed
142 unmodified lines
143 # 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 lines
163164 if content_encoding == 'deflate':165 del urlfetch_resp.headers['content-encoding']166167 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)174175 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 lines
184 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.total
39 unmodified lines
modified:requests/packages/urllib3/contrib/ntlmpool.py+10 added-10 removed
41 unmodified lines
42 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)4849 headers = {}50 headers['Connection'] = 'Keep-Alive'51 req_header = 'Authorization'
3 unmodified lines
5556 # 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))6667 # 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 = None
16 unmodified lines
86 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 lines
added:requests/packages/urllib3/contrib/socks.py+172 added
1# -*- coding: utf-8 -*-2"""3SOCKS support for urllib34~~~~~~~~~~~~~~~~~~~~~~~~~56This contrib module contains provisional support for SOCKS proxies from within7urllib3. This module supports SOCKS4 (specifically the SOCKS4A variant) and8SOCKS5. To enable its functionality, either install PySocks or install this9module with the ``socks`` extra.1011Known Limitations:1213- 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"""18from __future__ import absolute_import1920try:21 import socks22except ImportError:23 import warnings24 from ..exceptions import DependencyWarning2526 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 raise3435from socket import error as SocketError, timeout as SocketTimeout3637from ..connection import (38 HTTPConnection, HTTPSConnection39)40from ..connectionpool import (41 HTTPConnectionPool, HTTPSConnectionPool42)43from ..exceptions import ConnectTimeoutError, NewConnectionError44from ..poolmanager import PoolManager45from ..util.url import parse_url4647try:48 import ssl49except ImportError:50 ssl = None515253class 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)6061 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_address6869 if self.socket_options:70 extra_kw['socket_options'] = self.socket_options7172 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 )8384 except SocketTimeout as e:85 raise ConnectTimeoutError(86 self, "Connection to %s timed out. (connect timeout=%s)" %87 (self.host, self.timeout))8889 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 )110111 except SocketError as e: # Defensive: PySocks should catch all these.112 raise NewConnectionError(113 self, "Failed to establish a new connection: %s" % e)114115 return conn116117118# 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.122class SOCKSHTTPSConnection(SOCKSConnection, HTTPSConnection):123 pass124125126class SOCKSHTTPConnectionPool(HTTPConnectionPool):127 ConnectionCls = SOCKSConnection128129130class SOCKSHTTPSConnectionPool(HTTPSConnectionPool):131 ConnectionCls = SOCKSHTTPSConnection132133134class 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 }143144 def __init__(self, proxy_url, username=None, password=None,145 num_pools=10, headers=None, **connection_pool_kw):146 parsed = parse_url(proxy_url)147148 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 )156157 self.proxy_url = proxy_url158159 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_options167168 super(SOCKSProxyManager, self).__init__(169 num_pools, headers, **connection_pool_kw170 )171172 self.pool_classes_by_scheme = SOCKSProxyManager.pool_classes_by_scheme
modified:requests/packages/urllib3/util/response.py+1 added-1 removed
59 unmodified lines
606162def 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.6667 :param conn:68 :type conn: :class:`httplib.HTTPResponse`
6 unmodified lines
modified:requests/packages/urllib3/util/retry.py+2 added-2 removed
151 unmodified lines
152 return retries153154 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_retries158159 def get_backoff_time(self):160 """ Formula for computing the current backoff
110 unmodified lines
271272 if new_retry.is_exhausted():273 raise MaxRetryError(_pool, url, error or ResponseError(cause))274275 log.debug("Incremented Retry for (url='%s'): %r" % (url, new_retry))275 log.debug("Incremented Retry for (url='%s'): %r", url, new_retry)276277 return new_retry278279 def __repr__(self):
7 unmodified lines
modified:requests/packages/urllib3/util/ssl_.py+2 added-1 removed
108 unmodified lines
109 '2.7, 3.2, or later if you need this functionality.'110 )111 self.ciphers = cipher_suite112113 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 lines
124 '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.6
186 unmodified lines
modified:requests/packages/urllib3/__init__.py+2 added-3 removed
1"""2urllib3 - Thread-safe connection pooling and re-using.3"""44from __future__ import absolute_import5import warnings67from .connectionpool import (
22 unmodified lines
30 pass3132__author__ = 'Andrey Petrov (andrey.petrov@shazow.net)'33__license__ = 'MIT'35__version__ = '1.13.1'34__version__ = 'dev'3536__all__ = (37 'HTTPConnectionPool',38 'HTTPSConnectionPool',
27 unmodified lines
66 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 handler7273# ... Clean up.74del NullHandler
18 unmodified lines
modified:requests/packages/urllib3/connectionpool.py+11 added-12 removed
201 unmodified lines
202 """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)208209 conn = self.ConnectionCls(host=self.host, port=self.port,210 timeout=self.timeout.connect_timeout,211 strict=self.strict, **self.conn_kw)
26 unmodified lines
238 pass # Oh well, we'll create a new connection then239240 # 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 would
24 unmodified lines
271 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)277278 # Connection never got put back into the pool, close it.279 if conn:
101 unmodified lines
381 raise382383 # 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)387388 try:389 assert_header_parsing(httplib_response.msg)390 except HeaderParsingError as hpe: # Platform-specific: Python 3
229 unmodified lines
620621 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 lines
642 response.release_conn()643 raise644 return response645647 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 lines
654 # 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 lines
752 """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)758759 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 lines
modified:requests/packages/urllib3/exceptions.py+8 added
178 unmodified lines
179 "Warned when making a HTTPS request without SNI available."180 pass181182183class DependencyWarning(HTTPWarning):184 """185 Warned when an attempt is made to import a module with missing optional186 dependencies.187 """188 pass189190191class ResponseNotChunked(ProtocolError, ValueError):192 "Response needs to be chunked in order to read it as chunks."193 pass194
15 unmodified lines
modified:requests/packages/urllib3/poolmanager.py+10 added-7 removed
16 unmodified lines
1718__all__ = ['PoolManager', 'ProxyManager', 'proxy_from_url']192021pool_classes_by_scheme = {22 'http': HTTPConnectionPool,23 'https': HTTPSConnectionPool,24}2521log = logging.getLogger(__name__)2223SSL_KEYWORDS = ('key_file', 'cert_file', 'cert_reqs', 'ca_certs',24 'ssl_version', 'ca_cert_dir')2526pool_classes_by_scheme = {27 'http': HTTPConnectionPool,28 'https': HTTPSConnectionPool,29}303132class PoolManager(RequestMethods):33 """34 Allows for arbitrary requests while transparently keeping track of35 necessary connection pools for you.
28 unmodified lines
64 self.connection_pool_kw = connection_pool_kw65 self.pools = RecentlyUsedContainer(num_pools,66 dispose_func=lambda p: p.close())6768 # Locally set the pool classes so other PoolManagers can override them.69 self.pool_classes_by_scheme = pool_classes_by_scheme7071 def __enter__(self):72 return self7374 def __exit__(self, exc_type, exc_val, exc_tb):
8 unmodified lines
83 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 lines
188189 kw['retries'] = retries190 kw['redirect'] = redirect191189 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)194195196class ProxyManager(PoolManager):
88 unmodified lines
modified:requests/__init__.py+6 added
53 unmodified lines
54 pyopenssl.inject_into_urllib3()55except ImportError:56 pass5758import warnings5960# urllib3's DependencyWarnings should be silenced.61from .packages.urllib3.exceptions import DependencyWarning62warnings.simplefilter('ignore', DependencyWarning)6364from . import utils65from .models import Request, Response, PreparedRequest66from .api import request, get, head, post, patch, put, delete, options67from .sessions import session, Session
22 unmodified lines
modified:requests/adapters.py+33 added-8 removed
17 unmodified lines
18from .packages.urllib3.util.retry import Retry19from .compat import urlparse, basestring20from .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)23from .structures import CaseInsensitiveDict24from .packages.urllib3.exceptions import ClosedPoolError25from .packages.urllib3.exceptions import ConnectTimeoutError26from .packages.urllib3.exceptions import HTTPError as _HTTPError
5 unmodified lines
32from .packages.urllib3.exceptions import SSLError as _SSLError33from .packages.urllib3.exceptions import ResponseError34from .cookies import extract_cookies_to_jar35from .exceptions import (ConnectionError, ConnectTimeout, ReadTimeout, SSLError,36 ProxyError, RetryError)36 ProxyError, RetryError, InvalidSchema)37from .auth import _basic_auth_str3839try:40 from .packages.urllib3.contrib.socks import SOCKSProxyManager41except ImportError:42 def SOCKSProxyManager(*args, **kwargs):43 raise InvalidSchema("Missing dependencies for SOCKS support.")4445DEFAULT_POOLBLOCK = False46DEFAULT_POOLSIZE = 1047DEFAULT_RETRIES = 048DEFAULT_POOL_TIMEOUT = None
105 unmodified lines
154 :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)180162 return self.proxy_manager[proxy]181 return manager182183 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 the
118 unmodified lines
304 :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':308309 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')314315 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_url318319 return url320321 def add_headers(self, request, **kwargs):
162 unmodified lines
modified:setup.py+1 added
91 unmodified lines
92 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)