2023-07-21 03:02:50 +00:00
|
|
|
# Asgiproxify - An ASGI middleware for dynamic reverse proxy
|
|
|
|
# Copyright (C) 2023 William Goodspeed (龚志乐)
|
|
|
|
#
|
|
|
|
# This library is free software: you can redistribute it and/or modify
|
|
|
|
# it under the terms of the GNU General Public License as published by
|
|
|
|
# the Free Software Foundation, either version 3 of the License, or
|
|
|
|
# (at your option) any later version.
|
|
|
|
#
|
|
|
|
# This library is distributed in the hope that it will be useful,
|
|
|
|
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
|
|
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
|
|
# GNU General Public License for more details.
|
|
|
|
#
|
|
|
|
# You should have received a copy of the GNU General Public License
|
|
|
|
# along with this library. If not, see <https://www.gnu.org/licenses/>.
|
|
|
|
|
|
|
|
"""An ASGI middleware for dynamic reverse proxy."""
|
|
|
|
|
2023-07-15 12:01:35 +00:00
|
|
|
import asyncio
|
|
|
|
import aiohttp
|
|
|
|
|
2023-07-21 03:02:50 +00:00
|
|
|
|
2023-07-15 12:01:35 +00:00
|
|
|
class AsgiproxifyHandler():
|
2023-07-21 03:02:50 +00:00
|
|
|
"""Handle the proxy request from the AsgiProxify middleware."""
|
|
|
|
|
2023-07-15 12:01:35 +00:00
|
|
|
def __init__(self, scope):
|
|
|
|
self.scope = scope
|
2023-07-21 03:02:50 +00:00
|
|
|
|
2023-07-15 12:01:35 +00:00
|
|
|
def make_request_url(self):
|
2023-07-21 03:02:50 +00:00
|
|
|
"""Specify which URL will be requested from aiohttp client."""
|
2023-07-15 12:01:35 +00:00
|
|
|
return 'http://example.org/'
|
|
|
|
|
|
|
|
def make_request_cookies(self):
|
2023-07-21 03:02:50 +00:00
|
|
|
"""Specify which cookies will be used from aiohttp client."""
|
2023-07-15 12:01:35 +00:00
|
|
|
return {}
|
|
|
|
|
|
|
|
def make_request_headers(self):
|
2023-07-21 03:02:50 +00:00
|
|
|
"""Specify which headers will be used from aiohttp client."""
|
|
|
|
req_headers = {k.decode(): v.decode()
|
|
|
|
for k, v in self.scope['headers']}
|
2023-07-15 12:01:35 +00:00
|
|
|
req_headers.pop('host', None)
|
|
|
|
return req_headers
|
|
|
|
|
|
|
|
def make_response_headers(self, upstream_headers):
|
2023-07-21 03:02:50 +00:00
|
|
|
"""Specify which headers will be returned to the actual client."""
|
2023-07-15 12:01:35 +00:00
|
|
|
headers = dict(upstream_headers)
|
|
|
|
headers.pop('Server', None)
|
|
|
|
headers.pop('Date', None)
|
2023-07-21 03:02:50 +00:00
|
|
|
|
2023-10-04 02:11:46 +00:00
|
|
|
bheaders = {}
|
|
|
|
for k, v in headers.items():
|
|
|
|
bheaders[k.encode()] = v.encode()
|
|
|
|
|
|
|
|
resp_headers = list(bheaders.items())
|
2023-07-15 12:01:35 +00:00
|
|
|
return resp_headers
|
2023-07-21 03:02:50 +00:00
|
|
|
|
2023-07-15 12:01:35 +00:00
|
|
|
def make_request(self, session):
|
2023-07-21 03:02:50 +00:00
|
|
|
"""Generate a aiohttp request for streaming contents."""
|
2023-07-15 12:01:35 +00:00
|
|
|
return session.request('GET', self.make_request_url(),
|
|
|
|
cookies=self.make_request_cookies(),
|
|
|
|
headers=self.make_request_headers(),)
|
|
|
|
|
2023-07-21 03:02:50 +00:00
|
|
|
|
2023-07-15 12:01:35 +00:00
|
|
|
class Asgiproxify():
|
2023-07-21 03:02:50 +00:00
|
|
|
"""An ASGI middleware for dynamic reverse proxy."""
|
2023-07-15 12:01:35 +00:00
|
|
|
app = None
|
|
|
|
reg = {}
|
|
|
|
|
|
|
|
def __init__(self, app=None):
|
2023-07-21 03:02:50 +00:00
|
|
|
"""Initialize an Asgiproxify app with optional fallback app."""
|
2023-07-15 12:01:35 +00:00
|
|
|
self.to(app)
|
2023-07-21 03:02:50 +00:00
|
|
|
|
2023-07-15 12:01:35 +00:00
|
|
|
def to(self, app):
|
2023-07-21 03:02:50 +00:00
|
|
|
"""Set the ASGI app which will be forwarded to if no proxy."""
|
2023-07-15 12:01:35 +00:00
|
|
|
self.app = app
|
|
|
|
|
|
|
|
def install(self, leading_path, handler):
|
2023-07-21 03:02:50 +00:00
|
|
|
"""Install a proxy handler for handling `leading_path'."""
|
2023-07-15 12:01:35 +00:00
|
|
|
self.reg[leading_path] = handler
|
|
|
|
|
|
|
|
def register(self, leading_path):
|
2023-07-21 03:02:50 +00:00
|
|
|
"""Register the current class as a porxy handler for `leading_path'."""
|
2023-07-15 12:01:35 +00:00
|
|
|
def decorator(c):
|
|
|
|
self.install(leading_path, c)
|
|
|
|
return decorator
|
2023-07-21 03:02:50 +00:00
|
|
|
|
|
|
|
async def _handle_proxy(self, scope, receive, send, handler):
|
2023-07-15 12:01:35 +00:00
|
|
|
handler_i = handler(scope)
|
2023-07-21 03:02:50 +00:00
|
|
|
await receive()
|
2023-07-15 12:01:35 +00:00
|
|
|
|
|
|
|
async def reverse_proxy_task():
|
|
|
|
async with aiohttp.ClientSession(auto_decompress=False) as session:
|
|
|
|
async with handler_i.make_request(session) as resp:
|
|
|
|
await send({
|
|
|
|
'type': 'http.response.start',
|
|
|
|
'status': resp.status,
|
2023-07-21 03:02:50 +00:00
|
|
|
'headers': handler_i
|
|
|
|
.make_response_headers(resp.headers),
|
2023-07-15 12:01:35 +00:00
|
|
|
})
|
2023-07-21 03:02:50 +00:00
|
|
|
async for chunk, _ in resp.content.iter_chunks():
|
|
|
|
try:
|
2024-02-19 14:18:00 +00:00
|
|
|
await asyncio.wait_for(send({
|
|
|
|
'type': 'http.response.body',
|
|
|
|
'body': chunk,
|
|
|
|
'more_body': True,
|
|
|
|
}), timeout=10)
|
|
|
|
except asyncio.TimeoutError:
|
2023-07-21 03:02:50 +00:00
|
|
|
return
|
|
|
|
await send({'type': 'http.response.body'})
|
|
|
|
|
2023-07-15 12:01:35 +00:00
|
|
|
task = asyncio.create_task(reverse_proxy_task())
|
2023-07-21 03:02:50 +00:00
|
|
|
|
|
|
|
ev = await receive()
|
2023-07-24 07:00:19 +00:00
|
|
|
task.cancel()
|
|
|
|
return
|
2023-07-15 12:01:35 +00:00
|
|
|
|
|
|
|
async def __call__(self, scope, receive, send):
|
|
|
|
if scope['type'] != 'http':
|
|
|
|
return await self.app(scope, receive, send)
|
2023-07-21 03:02:50 +00:00
|
|
|
|
2023-07-15 12:01:35 +00:00
|
|
|
handler = None
|
|
|
|
|
|
|
|
for leading_path, proxy_handler in self.reg.items():
|
|
|
|
if scope['path'].startswith(leading_path):
|
|
|
|
handler = proxy_handler
|
|
|
|
|
|
|
|
if not handler:
|
|
|
|
return await self.app(scope, receive, send)
|
2023-07-21 03:02:50 +00:00
|
|
|
return await self._handle_proxy(scope, receive, send, handler)
|