Merge pull request #1515 from schlamar/https-proxy-2.0
Before adoption: this commit came in with the history the project adopted, so no landing records it.
[2.0] Https proxy support
authored by Kenneth Reitz · committed by Kenneth Reitz · parents d3b7863, 2e5a674 · Browse files · 6 files·+176 added−52 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+176 added−52 removed
- other:+176 added−52 removed
Provenance
- Commit
d8268fb- Tree
ca8063a- Author
Kenneth Reitz <me@kennethreitz.com>- Committer
Kenneth Reitz <me@kennethreitz.com>- Parent 1
d3b7863- Parent 2
2e5a674
6 files changed+176 added−52 removed
modified:requests/packages/urllib3/connectionpool.py+60 added-16 removed
99 unmodified lines100 101 resolved_cert_reqs = resolve_cert_reqs(self.cert_reqs)102 resolved_ssl_version = resolve_ssl_version(self.ssl_version)103 104+ if self._tunnel_host:105+ self.sock = sock106+ # Calls self._set_hostport(), so self.host is107+ # self._tunnel_host below.108+ self._tunnel()109+110 # Wrap socket using verification with the root certs in111 # trusted_root_certs112 self.sock = ssl_wrap_socket(sock, self.key_file, self.cert_file,113 cert_reqs=resolved_cert_reqs,65 unmodified lines179 180 :param headers:181 Headers to include with all requests, unless other headers are given182 explicitly.183+184+ :param _proxy:185+ Parsed proxy URL, should not be used directly, instead, see186+ :class:`urllib3.connectionpool.ProxyManager`"187+188+ :param _proxy_headers:189+ A dictionary with proxy headers, should not be used directly,190+ instead, see :class:`urllib3.connectionpool.ProxyManager`"191 """192 193 scheme = 'http'194 195 def __init__(self, host, port=None, strict=False, timeout=None, maxsize=1,182- block=False, headers=None):196+ block=False, headers=None, _proxy=None, _proxy_headers=None):197 ConnectionPool.__init__(self, host, port)198 RequestMethods.__init__(self, headers)199 200 self.strict = strict201 self.timeout = timeout202 self.pool = self.QueueCls(maxsize)203 self.block = block204 205+ self.proxy = _proxy206+ self.proxy_headers = _proxy_headers or {}207+208 # Fill the queue up so that doing get() on it will block properly209 for _ in xrange(maxsize):210 self.pool.put(None)211 330 unmodified lines542 543 def __init__(self, host, port=None,544 strict=False, timeout=None, maxsize=1,545 block=False, headers=None,546+ _proxy=None, _proxy_headers=None,547 key_file=None, cert_file=None, cert_reqs=None,548 ca_certs=None, ssl_version=None,549 assert_hostname=None, assert_fingerprint=None):550 551 HTTPConnectionPool.__init__(self, host, port,552 strict, timeout, maxsize,535- block, headers)553+ block, headers, _proxy, _proxy_headers)554 self.key_file = key_file555 self.cert_file = cert_file556 self.cert_reqs = cert_reqs557 self.ca_certs = ca_certs558 self.ssl_version = ssl_version559 self.assert_hostname = assert_hostname560 self.assert_fingerprint = assert_fingerprint561 562+ def _prepare_conn(self, connection):563+ """564+ Prepare the ``connection`` for :meth:`urllib3.util.ssl_wrap_socket`565+ and establish the tunnel if proxy is used.566+ """567+568+ if isinstance(connection, VerifiedHTTPSConnection):569+ connection.set_cert(key_file=self.key_file,570+ cert_file=self.cert_file,571+ cert_reqs=self.cert_reqs,572+ ca_certs=self.ca_certs,573+ assert_hostname=self.assert_hostname,574+ assert_fingerprint=self.assert_fingerprint)575+ connection.ssl_version = self.ssl_version576+577+ if self.proxy is not None:578+ # Python 2.7+579+ try:580+ set_tunnel = connection.set_tunnel581+ except AttributeError: # Platform-specific: Python 2.6582+ set_tunnel = connection._set_tunnel583+ set_tunnel(self.host, self.port, self.proxy_headers)584+ # Establish tunnel connection early, because otherwise httplib585+ # would improperly set Host: header to proxy's IP:port.586+ connection.connect()587+588+ return connection589+590 def _new_conn(self):591 """592 Return a fresh :class:`httplib.HTTPSConnection`.593 """594 self.num_connections += 1595 log.info("Starting new HTTPS connection (%d): %s"596 % (self.num_connections, self.host))597 598+ actual_host = self.host599+ actual_port = self.port600+ if self.proxy is not None:601+ actual_host = self.proxy.host602+ actual_port = self.proxy.port603+604 if not ssl: # Platform-specific: Python compiled without +ssl605 if not HTTPSConnection or HTTPSConnection is object:606 raise SSLError("Can't connect to HTTPS URL because the SSL "607 "module is not available.")608+ connection_class = HTTPSConnection609+ else:610+ connection_class = VerifiedHTTPSConnection611 557- return HTTPSConnection(host=self.host,558- port=self.port,559- strict=self.strict)612+ connection = connection_class(host=actual_host, port=actual_port,613+ strict=self.strict)614 561- connection = VerifiedHTTPSConnection(host=self.host,562- port=self.port,563- strict=self.strict)564- connection.set_cert(key_file=self.key_file, cert_file=self.cert_file,565- cert_reqs=self.cert_reqs, ca_certs=self.ca_certs,566- assert_hostname=self.assert_hostname,567- assert_fingerprint=self.assert_fingerprint)615+ return self._prepare_conn(connection)616 569- connection.ssl_version = self.ssl_version617 571- return connection572-573-618 def connection_from_url(url, **kw):619 """620 Given a url, return an :class:`.ConnectionPool` instance of its host.621 21 unmodified linesmodified:requests/packages/urllib3/poolmanager.py+81 added-24 removed
11 unmodified lines12 from urlparse import urljoin13 14 from ._collections import RecentlyUsedContainer15 from .connectionpool import HTTPConnectionPool, HTTPSConnectionPool16-from .connectionpool import connection_from_url, port_by_scheme16+from .connectionpool import port_by_scheme17 from .request import RequestMethods18 from .util import parse_url19 20 38 unmodified lines59 260 61 """62 63+ proxy = None64+65 def __init__(self, num_pools=10, headers=None, **connection_pool_kw):66 RequestMethods.__init__(self, headers)67 self.connection_pool_kw = connection_pool_kw68 self.pools = RecentlyUsedContainer(num_pools,31 unmodified lines100 101 If ``port`` isn't given, it will be derived from the ``scheme`` using102 ``urllib3.connectionpool.port_by_scheme``.103 """104+105 scheme = scheme or 'http'106+107 port = port or port_by_scheme.get(scheme, 80)108 109 pool_key = (scheme, host, port)110 111 with self.pools.lock:108- # If the scheme, host, or port doesn't match existing open connections,109- # open a new ConnectionPool.110- pool = self.pools.get(pool_key)111- if pool:112- return pool112+ # If the scheme, host, or port doesn't match existing open113+ # connections, open a new ConnectionPool.114+ pool = self.pools.get(pool_key)115+ if pool:116+ return pool117 114- # Make a fresh ConnectionPool of the desired type115- pool = self._new_pool(scheme, host, port)116- self.pools[pool_key] = pool118+ # Make a fresh ConnectionPool of the desired type119+ pool = self._new_pool(scheme, host, port)120+ self.pools[pool_key] = pool121 return pool122 123 def connection_from_url(self, url):124 """23 unmodified lines148 kw['redirect'] = False149 if 'headers' not in kw:150 kw['headers'] = self.headers151 152+ if self.proxy is not None and u.scheme == "http":153+ response = conn.urlopen(method, url, **kw)154+ else:148- response = conn.urlopen(method, u.request_uri, **kw)155+ response = conn.urlopen(method, u.request_uri, **kw)156 157 redirect_location = redirect and response.get_redirect_location()158 if not redirect_location:159 return response10 unmodified lines170 kw['redirect'] = redirect171 return self.urlopen(method, redirect_location, **kw)172 173 167-class ProxyManager(RequestMethods):174+class ProxyManager(PoolManager):175 """169- Given a ConnectionPool to a proxy, the ProxyManager's ``urlopen`` method170- will make requests to any url through the defined proxy. The ProxyManager171- class will automatically set the 'Host' header if it is not provided.176+ Behaves just like :class:`PoolManager`, but sends all requests through177+ the defined proxy, using the CONNECT method for HTTPS URLs.178+179+ :param poxy_url:180+ The URL of the proxy to be used.181+182+ :param proxy_headers:183+ A dictionary contaning headers that will be sent to the proxy. In case184+ of HTTP they are being sent with each request, while in the185+ HTTPS/CONNECT case they are sent only once. Could be used for proxy186+ authentication.187+188+ Example:189+ >>> proxy = urllib3.ProxyManager('http://localhost:3128/')190+ >>> r1 = proxy.request('GET', 'http://google.com/')191+ >>> r2 = proxy.request('GET', 'http://httpbin.org/')192+ >>> len(proxy.pools)193+ 1194+ >>> r3 = proxy.request('GET', 'https://httpbin.org/')195+ >>> r4 = proxy.request('GET', 'https://twitter.com/')196+ >>> len(proxy.pools)197+ 3198+199 """200 174- def __init__(self, proxy_pool):175- self.proxy_pool = proxy_pool201+ def __init__(self, proxy_url, num_pools=10, headers=None,202+ proxy_headers=None, **connection_pool_kw):203 204+ if isinstance(proxy_url, HTTPConnectionPool):205+ proxy_url = '%s://%s:%i' % (proxy_url.scheme, proxy_url.host,206+ proxy_url.port)207+ proxy = parse_url(proxy_url)208+ if not proxy.port:209+ port = port_by_scheme.get(proxy.scheme, 80)210+ proxy = proxy._replace(port=port)211+ self.proxy = proxy212+ self.proxy_headers = proxy_headers or {}213+ assert self.proxy.scheme in ("http", "https"), \214+ 'Not supported proxy scheme %s' % self.proxy.scheme215+ connection_pool_kw['_proxy'] = self.proxy216+ connection_pool_kw['_proxy_headers'] = self.proxy_headers217+ super(ProxyManager, self).__init__(218+ num_pools, headers, **connection_pool_kw)219+220+ def connection_from_host(self, host, port=None, scheme='http'):221+ if scheme == "https":222+ return super(ProxyManager, self).connection_from_host(223+ host, port, scheme)224+225+ return super(ProxyManager, self).connection_from_host(226+ self.proxy.host, self.proxy.port, self.proxy.scheme)227+228 def _set_proxy_headers(self, url, headers=None):229 """230 Sets headers needed by proxies: specifically, the Accept and Host231 headers. Only sets headers not provided by the user.5 unmodified lines237 headers_['Host'] = netloc238 239 if headers:240 headers_.update(headers)190-241 return headers_242 193- def urlopen(self, method, url, **kw):243+ def urlopen(self, method, url, redirect=True, **kw):244 "Same as HTTP(S)ConnectionPool.urlopen, ``url`` must be absolute."195- kw['assert_same_host'] = False196- kw['headers'] = self._set_proxy_headers(url, headers=kw.get('headers'))197- return self.proxy_pool.urlopen(method, url, **kw)245+ u = parse_url(url)246 247+ if u.scheme == "http":248+ # It's too late to set proxy headers on per-request basis for249+ # tunnelled HTTPS connections, should use250+ # constructor's proxy_headers instead.251+ kw['headers'] = self._set_proxy_headers(url, kw.get('headers',252+ self.headers))253+ kw['headers'].update(self.proxy_headers)254 200-def proxy_from_url(url, **pool_kw):201- proxy_pool = connection_from_url(url, **pool_kw)202- return ProxyManager(proxy_pool)255+ return super(ProxyManager, self).urlopen(method, url, redirect, **kw)256+257+258+def proxy_from_url(url, **kw):259+ return ProxyManager(proxy_url=url, **kw)modified:requests/packages/urllib3/response.py+1 added-1 removed
189 unmodified lines190 "Received response with content-encoding: %s, but "191 "failed to decode it." % content_encoding,192 e)193 194- if flush_decoder and self._decoder:194+ if flush_decoder and decode_content and self._decoder:195 buf = self._decoder.decompress(binary_type())196 data += buf + self._decoder.flush()197 198 if cache_content:102 unmodified linesmodified:requests/adapters.py+32 added-11 removed
9 unmodified lines10 11 import socket12 13 from .models import Response14-from .packages.urllib3.poolmanager import PoolManager, ProxyManager14+from .packages.urllib3.poolmanager import PoolManager, proxy_from_url15 from .packages.urllib3.response import HTTPResponse16 from .compat import urlparse, basestring, urldefrag, unquote17 from .utils import (DEFAULT_CA_BUNDLE_PATH, get_encoding_from_headers,18 except_on_missing_scheme, get_auth_from_url)51 unmodified lines70 pool_maxsize=DEFAULT_POOLSIZE, max_retries=DEFAULT_RETRIES,71 pool_block=DEFAULT_POOLBLOCK):72 self.max_retries = max_retries73 self.config = {}74+ self.proxy_manager = {}75 76 super(HTTPAdapter, self).__init__()77 78 self._pool_connections = pool_connections115 unmodified lines194 proxy = proxies.get(urlparse(url.lower()).scheme)195 196 if proxy:197 except_on_missing_scheme(proxy)197- conn = ProxyManager(self.poolmanager.connection_from_url(proxy))198+ proxy_headers = self.proxy_headers(proxy)199+200+ if not proxy in self.proxy_manager:201+ self.proxy_manager[proxy] = proxy_from_url(202+ proxy,203+ proxy_headers=proxy_headers)204+205+ conn = self.proxy_manager[proxy].connection_from_url(url)206 else:207 conn = self.poolmanager.connection_from_url(url.lower())208 209 return conn29 unmodified lines239 240 return url241 242 def add_headers(self, request, **kwargs):235- """Add any headers needed by the connection. Currently this adds a236- Proxy-Authorization header.243+ """Add any headers needed by the connection. As of v2.0 this does244+ nothing by default, but is left for overriding by users that subclass245+ the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.246 247 This should not be called from user code, and is only exposed for use248 when subclassing the249 :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.250 251 :param request: The :class:`PreparedRequest <PreparedRequest>` to add headers to.252 :param kwargs: The keyword arguments from the call to send().253 """245- proxies = kwargs.get('proxies', {})254+ pass255 247- if proxies is None:248- proxies = {}256+ def proxy_headers(self, proxy):257+ """Returns a dictionary of the headers to add to any request sent258+ through a proxy. This works with urllib3 magic to ensure that they are259+ correctly sent to the proxy, rather than in a tunnelled request if260+ CONNECT is being used.261 250- proxy = proxies.get(urlparse(request.url).scheme)262+ This should not be called from user code, and is only exposed for use263+ when subclassing the264+ :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.265+266+ :param proxies: The url of the proxy being used for this request.267+ :param kwargs: Optional additional keyword arguments.268+ """269+ headers = {}270 username, password = get_auth_from_url(proxy)271 272 if username and password:273 # Proxy auth usernames and passwords will be urlencoded, we need274 # to decode them.275 username = unquote(username)276 password = unquote(password)258- request.headers['Proxy-Authorization'] = _basic_auth_str(username,259- password)277+ headers['Proxy-Authorization'] = _basic_auth_str(username,278+ password)279 280+ return headers281+282 def send(self, request, stream=False, timeout=None, verify=True, cert=None, proxies=None):283 """Sends PreparedRequest object. Returns Response object.284 285 :param request: The :class:`PreparedRequest <PreparedRequest>` being sent.7 unmodified lines293 conn = self.get_connection(request.url, proxies)294 295 self.cert_verify(conn, request.url, verify, cert)296 url = self.request_url(request, proxies)276- self.add_headers(request, proxies=proxies)297+ self.add_headers(request)298 299 chunked = not (request.body is None or 'Content-Length' in request.headers)300 301 try:62 unmodified linesmodified:AUTHORS.rst+1 added
131 unmodified lines132 - James Clarke (jam)133 - Kevin Burke <kev@inburke.com>134 - Flavio Curella135 - David Pursehouse <david.pursehouse@gmail.com> @dpursehouse136+- Marc Schlaich @schlamarmodified:README.rst+1 added
52 unmodified lines53 - Unicode Response Bodies54 - Multipart File Uploads55 - Connection Timeouts56 - Thread-safety57+- HTTP(S) proxy support58 59 60 Installation61 ------------32 unmodified lines