-
Notifications
You must be signed in to change notification settings - Fork 12
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
add proxy, fix smart contract refactor bug
- Loading branch information
Showing
5 changed files
with
208 additions
and
6 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,189 @@ | ||
#!/usr/bin/env python | ||
# | ||
# Simple asynchronous HTTP proxy with tunnelling (CONNECT). | ||
# | ||
# GET/POST proxying based on | ||
# http://groups.google.com/group/python-tornado/msg/7bea08e7a049cf26 | ||
# | ||
# Copyright (C) 2012 Senko Rasic <senko.rasic@dobarkod.hr> | ||
# | ||
# Permission is hereby granted, free of charge, to any person obtaining a copy | ||
# of this software and associated documentation files (the "Software"), to deal | ||
# in the Software without restriction, including without limitation the rights | ||
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | ||
# copies of the Software, and to permit persons to whom the Software is | ||
# furnished to do so, subject to the following conditions: | ||
# | ||
# The above copyright notice and this permission notice shall be included in | ||
# all copies or substantial portions of the Software. | ||
# | ||
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | ||
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | ||
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | ||
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | ||
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | ||
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN | ||
# THE SOFTWARE. | ||
|
||
import asyncio | ||
import os | ||
import sys | ||
import socket | ||
if sys.version_info[0] == 2: | ||
from urlparse import urlparse | ||
else: | ||
from urllib.parse import urlparse | ||
|
||
import tornado.httpserver | ||
import tornado.ioloop | ||
import tornado.iostream | ||
import tornado.web | ||
import tornado.httpclient | ||
import tornado.httputil | ||
from yadacoin.core.config import get_config | ||
|
||
|
||
__all__ = ['ProxyHandler'] | ||
|
||
|
||
def get_proxy(url): | ||
url_parsed = urlparse(url, scheme='http') | ||
proxy_key = '%s_proxy' % url_parsed.scheme | ||
return os.environ.get(proxy_key) | ||
|
||
|
||
def parse_proxy(proxy): | ||
proxy_parsed = urlparse(proxy, scheme='http') | ||
return proxy_parsed.hostname, proxy_parsed.port | ||
|
||
|
||
def fetch_request(url, **kwargs): | ||
proxy = get_proxy(url) | ||
if proxy: | ||
get_config().app_log.debug('Forward request via upstream proxy %s', proxy) | ||
tornado.httpclient.AsyncHTTPClient.configure( | ||
'tornado.curl_httpclient.CurlAsyncHTTPClient') | ||
host, port = parse_proxy(proxy) | ||
kwargs['proxy_host'] = host | ||
kwargs['proxy_port'] = port | ||
|
||
req = tornado.httpclient.HTTPRequest(url, **kwargs) | ||
client = tornado.httpclient.AsyncHTTPClient() | ||
return client.fetch(req, raise_error=False) | ||
|
||
|
||
class ProxyHandler(tornado.web.RequestHandler): | ||
SUPPORTED_METHODS = ['GET', 'POST', 'CONNECT'] | ||
|
||
def compute_etag(self): | ||
return None # disable tornado Etag | ||
|
||
async def get(self): | ||
get_config().app_log.debug('Handle %s request to %s', self.request.method, | ||
self.request.uri) | ||
|
||
def handle_response(response): | ||
if (response.error and not | ||
isinstance(response.error, tornado.httpclient.HTTPError)): | ||
self.set_status(500) | ||
self.write('Internal server error:\n' + str(response.error)) | ||
else: | ||
self.set_status(response.code, response.reason) | ||
self._headers = tornado.httputil.HTTPHeaders() # clear tornado default header | ||
|
||
for header, v in response.headers.get_all(): | ||
if header not in ('Content-Length', 'Transfer-Encoding', 'Content-Encoding', 'Connection'): | ||
self.add_header(header, v) # some header appear multiple times, eg 'Set-Cookie' | ||
|
||
if response.body: | ||
self.set_header('Content-Length', len(response.body)) | ||
self.write(response.body) | ||
self.finish() | ||
|
||
body = self.request.body | ||
if not body: | ||
body = None | ||
try: | ||
if 'Proxy-Connection' in self.request.headers: | ||
del self.request.headers['Proxy-Connection'] | ||
resp = await fetch_request( | ||
self.request.uri, | ||
method=self.request.method, body=body, | ||
headers=self.request.headers, follow_redirects=False, | ||
allow_nonstandard_methods=True) | ||
handle_response(resp) | ||
except tornado.httpclient.HTTPError as e: | ||
if hasattr(e, 'response') and e.response: | ||
handle_response(e.response) | ||
else: | ||
self.set_status(500) | ||
self.write('Internal server error:\n' + str(e)) | ||
self.finish() | ||
|
||
async def post(self): | ||
return await self.get() | ||
|
||
async def connect(self): | ||
config = get_config() | ||
config.app_log.debug('Start CONNECT to %s', self.request.uri) | ||
host, port = self.request.uri.split(':') | ||
client = self.request.connection.stream | ||
|
||
async def relay(reader, writer): | ||
try: | ||
alldata = b'' | ||
while True: | ||
data = await reader.read_bytes(1024*64, partial=True) | ||
if writer.closed(): | ||
get_config().app_log.debug(alldata) | ||
return | ||
if data: | ||
alldata += data | ||
writer.write(data) | ||
else: | ||
break | ||
get_config().app_log.debug(alldata) | ||
except tornado.iostream.StreamClosedError: | ||
pass | ||
|
||
async def start_tunnel(): | ||
get_config().app_log.debug('CONNECT tunnel established to %s', self.request.uri) | ||
client.write(b'HTTP/1.0 407 Proxy Authentication Required\r\n') | ||
client.write(b'Proxy-Authenticate: Basic realm="Access to internal site"\r\n\r\n') | ||
await asyncio.gather( | ||
relay(client, upstream), | ||
relay(upstream, client) | ||
) | ||
client.close() | ||
upstream.close() | ||
|
||
async def on_proxy_response(data=None): | ||
if data: | ||
first_line = data.splitlines()[0] | ||
http_v, status, text = first_line.split(None, 2) | ||
if int(status) == 200: | ||
get_config().app_log.debug('Connected to upstream proxy %s', proxy) | ||
await start_tunnel() | ||
return | ||
|
||
self.set_status(500) | ||
self.finish() | ||
|
||
async def start_proxy_tunnel(): | ||
upstream.write('CONNECT %s HTTP/1.1\r\n' % self.request.uri) | ||
upstream.write('Host: %s\r\n' % self.request.uri) | ||
upstream.write('Proxy-Connection: Keep-Alive\r\n\r\n') | ||
data = await upstream.read_until('\r\n\r\n') | ||
on_proxy_response(data) | ||
|
||
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0) | ||
upstream = tornado.iostream.IOStream(s) | ||
|
||
proxy = get_proxy(self.request.uri) | ||
if proxy: | ||
proxy_host, proxy_port = parse_proxy(proxy) | ||
await upstream.connect((proxy_host, proxy_port)) | ||
await start_proxy_tunnel() | ||
else: | ||
await upstream.connect((host, int(port))) | ||
await start_tunnel() |