diff options
Diffstat (limited to 'ttun_server/websockets.py')
| -rw-r--r-- | ttun_server/websockets.py | 217 |
1 files changed, 59 insertions, 158 deletions
diff --git a/ttun_server/websockets.py b/ttun_server/websockets.py index e828b8d..ea9ae94 100644 --- a/ttun_server/websockets.py +++ b/ttun_server/websockets.py | |||
| @@ -1,189 +1,90 @@ | |||
| 1 | import asyncio | 1 | import asyncio |
| 2 | import json | ||
| 3 | import logging | 2 | import logging |
| 4 | import os | 3 | import os |
| 5 | import typing | ||
| 6 | from asyncio import create_task | ||
| 7 | from base64 import b64encode, b64decode | ||
| 8 | from contextlib import asynccontextmanager | ||
| 9 | from typing import Optional | ||
| 10 | from uuid import uuid4 | 4 | from uuid import uuid4 |
| 11 | 5 | ||
| 12 | from starlette.endpoints import WebSocketEndpoint | 6 | from fastapi import WebSocket, WebSocketDisconnect |
| 13 | from starlette.types import Scope, Receive, Send | ||
| 14 | from starlette.websockets import WebSocket | ||
| 15 | 7 | ||
| 16 | import ttun_server | 8 | import ttun_server |
| 17 | from ttun_server.proxy_queue import ProxyQueue | 9 | from ttun_server.proxy_queue import ProxyQueue |
| 18 | from ttun_server.types import Config, Message, WebsocketMessageType, \ | 10 | from ttun_server.types import ( |
| 19 | WebsocketConnectData, WebsocketMessage, WebsocketMessageData, WebsocketDisconnectData, MessageType | 11 | Config, |
| 12 | Message, | ||
| 13 | MessageType, | ||
| 14 | ) | ||
| 20 | 15 | ||
| 21 | logger = logging.getLogger(__name__) | 16 | logger = logging.getLogger(__name__) |
| 22 | logger.setLevel('DEBUG') | 17 | logger.setLevel('DEBUG') |
| 23 | 18 | ||
| 24 | class WebsocketProxy(WebSocketEndpoint): | 19 | async def assert_compatible_version(websocket: WebSocket, config: Config) -> None: |
| 25 | encoding = 'json' | 20 | client_version = config.get('version', '1.0.0') |
| 26 | websocket_listen_task = None | 21 | logger.debug('client_version %s', client_version) |
| 27 | 22 | ||
| 28 | def __init__(self, *args, **kwargs): | 23 | if 'git' not in client_version and ttun_server.__version__ != 'development': |
| 29 | super().__init__(*args, **kwargs) | 24 | [client_major, *_] = [int(i) for i in client_version.split('.')[:3]] |
| 30 | self.id = str(uuid4()) | 25 | [server_major, *_] = [int(i) for i in ttun_server.__version__.split('.')] |
| 31 | 26 | ||
| 32 | @asynccontextmanager | 27 | if client_major < server_major: |
| 33 | async def proxy(self, websocket: WebSocket, message: WebsocketMessage): | 28 | await websocket.close(4000, 'Your client is too old') |
| 34 | [subdomain, *_] = websocket.url.hostname.split('.') | ||
| 35 | 29 | ||
| 36 | expect_ack = WebsocketMessageType(message['type']) == WebsocketMessageType.connect | 30 | if client_major > server_major: |
| 31 | await websocket.close(4001, 'Your client is too new') | ||
| 37 | 32 | ||
| 38 | try: | ||
| 39 | request_queue = await ProxyQueue.get_for_identifier(subdomain) | ||
| 40 | await request_queue.enqueue(message) | ||
| 41 | 33 | ||
| 42 | if expect_ack: | 34 | async def tunnel(websocket: WebSocket) -> None: |
| 43 | response_queue = await ProxyQueue.create_for_identifier(message["identifier"]) | 35 | request_tasks: dict[str, asyncio.Task] = {} |
| 44 | yield await response_queue.dequeue() | 36 | proxy_queues: dict[str, ProxyQueue] = {} |
| 45 | await response_queue.delete() | ||
| 46 | else: | ||
| 47 | yield | ||
| 48 | except AssertionError: | ||
| 49 | yield None | ||
| 50 | 37 | ||
| 51 | async def listen_for_messages(self, websocket: WebSocket): | 38 | await websocket.accept() |
| 52 | response_queue = await ProxyQueue.create_for_identifier(self.id) | 39 | config: Config = await websocket.receive_json() |
| 53 | 40 | ||
| 54 | while True: | 41 | await assert_compatible_version(websocket, config) |
| 55 | message: WebsocketMessage = await response_queue.dequeue() | ||
| 56 | logger.debug(message) | ||
| 57 | await websocket.send_text(b64decode(message['payload']['body'].encode()).decode()) | ||
| 58 | |||
| 59 | async def on_connect(self, websocket: WebSocket) -> None: | ||
| 60 | message = WebsocketMessage( | ||
| 61 | type=WebsocketMessageType.connect.value, | ||
| 62 | identifier=self.id, | ||
| 63 | payload=WebsocketConnectData( | ||
| 64 | path=websocket.path_params['path'], | ||
| 65 | headers=[ | ||
| 66 | (k.decode(), v.decode()) | ||
| 67 | for k, v | ||
| 68 | in websocket.scope['headers'] | ||
| 69 | ], | ||
| 70 | ) | ||
| 71 | ) | ||
| 72 | 42 | ||
| 73 | async with self.proxy(websocket, message) as m: | 43 | if 'subdomains' not in config: |
| 74 | if m is not None and WebsocketMessageType(m['type']) == WebsocketMessageType.ack: | 44 | config['subdomains'] = [config['subdomain']] |
| 75 | await super().on_connect(websocket) | 45 | elif config['subdomains'] is None: |
| 46 | config['subdomains'] = [None] | ||
| 76 | 47 | ||
| 77 | self.websocket_listen_task = asyncio.create_task(self.listen_for_messages(websocket)) | 48 | for i, subdomain in enumerate(config['subdomains']): |
| 49 | if subdomain is None or await ProxyQueue.has_connection(subdomain): | ||
| 50 | config['subdomains'][i] = uuid4().hex | ||
| 78 | 51 | ||
| 79 | def callback(*args, **kwargs): | 52 | for subdomain in config['subdomains']: |
| 80 | self.websocket_listen_task = None | 53 | proxy_queues[subdomain] = await ProxyQueue.create_for_identifier(subdomain) |
| 81 | 54 | ||
| 82 | self.websocket_listen_task.add_done_callback(callback) | 55 | hostname = os.environ.get('TUNNEL_DOMAIN') |
| 56 | protocol = 'https' if os.environ.get('SECURE', False) else 'http' | ||
| 83 | 57 | ||
| 84 | async def on_receive(self, websocket: WebSocket, data: typing.Any) -> None: | 58 | urls = [ |
| 85 | match data: | 59 | f'{protocol}://{subdomain}.{hostname}' |
| 86 | case dict(): | 60 | for subdomain in config['subdomains'] |
| 87 | data_bytes = json.dumps(data).encode() | 61 | ] |
| 88 | case bytes(): | ||
| 89 | data_bytes = data | ||
| 90 | case _: | ||
| 91 | data_bytes = data.encode() | ||
| 92 | 62 | ||
| 93 | message = WebsocketMessage( | 63 | await websocket.send_json({ |
| 94 | type=WebsocketMessageType.message.value, | 64 | 'url': urls[0], |
| 95 | identifier=self.id, | 65 | 'urls': urls, |
| 96 | payload=WebsocketMessageData( | 66 | }) |
| 97 | body=b64encode(data_bytes).decode(), | ||
| 98 | ) | ||
| 99 | ) | ||
| 100 | 67 | ||
| 101 | async with self.proxy(websocket, message): | 68 | async def handle_requests(subdomain: str) -> None: |
| 102 | pass | 69 | while request := await proxy_queues[subdomain].dequeue(): |
| 70 | asyncio.create_task(websocket.send_json(request), name=request['identifier']) | ||
| 103 | 71 | ||
| 104 | async def on_disconnect(self, websocket: WebSocket, close_code: int) -> None: | 72 | for subdomain in config['subdomains']: |
| 105 | message = WebsocketMessage( | 73 | request_tasks[subdomain] = asyncio.create_task( |
| 106 | type=WebsocketMessageType.disconnect.value, | 74 | handle_requests(subdomain), name=subdomain |
| 107 | identifier=self.id, | ||
| 108 | payload=WebsocketDisconnectData( | ||
| 109 | close_code=close_code, | ||
| 110 | ) | ||
| 111 | ) | 75 | ) |
| 112 | 76 | ||
| 113 | async with self.proxy(websocket, message): | 77 | try: |
| 114 | if self.websocket_listen_task is not None: | 78 | while True: |
| 115 | self.websocket_listen_task.cancel() | 79 | data: Message = await websocket.receive_json() |
| 116 | 80 | try: | |
| 117 | class Tunnel(WebSocketEndpoint): | 81 | data['type'] = MessageType(data['type']).value |
| 118 | encoding = 'json' | 82 | response_queue = await ProxyQueue.get_for_identifier(data['identifier']) |
| 119 | 83 | await response_queue.enqueue(data) | |
| 120 | def __init__(self, scope: Scope, receive: Receive, send: Send): | 84 | except AssertionError: |
| 121 | super().__init__(scope, receive, send) | 85 | pass |
| 122 | self.request_tasks: dict[str, asyncio.Task] = {} | 86 | except WebSocketDisconnect: |
| 123 | self.config: Optional[Config] = None | 87 | for proxy_queue in proxy_queues.values(): |
| 124 | self.proxy_queues: dict[str, ProxyQueue] = {} | ||
| 125 | |||
| 126 | async def handle_requests(self, websocket: WebSocket, subdomain: str): | ||
| 127 | while request := await self.proxy_queues[subdomain].dequeue(): | ||
| 128 | task = asyncio.create_task(websocket.send_json(request), name=request['identifier']) | ||
| 129 | |||
| 130 | |||
| 131 | async def on_connect(self, websocket: WebSocket) -> None: | ||
| 132 | await websocket.accept() | ||
| 133 | self.config = await websocket.receive_json() | ||
| 134 | |||
| 135 | client_version = self.config.get('version', '1.0.0') | ||
| 136 | logger.debug('client_version %s', client_version) | ||
| 137 | |||
| 138 | if 'git' not in client_version and ttun_server.__version__ != 'development': | ||
| 139 | [client_major, *_] = [int(i) for i in client_version.split('.')[:3]] | ||
| 140 | [server_major, *_] = [int(i) for i in ttun_server.__version__.split('.')] | ||
| 141 | |||
| 142 | if client_major < server_major: | ||
| 143 | await websocket.close(4000, 'Your client is too old') | ||
| 144 | |||
| 145 | if client_major > server_major: | ||
| 146 | await websocket.close(4001, 'Your client is too new') | ||
| 147 | |||
| 148 | if 'subdomains' not in self.config: | ||
| 149 | self.config['subdomains'] = [self.config['subdomain']] | ||
| 150 | elif self.config['subdomains'] is None: | ||
| 151 | self.config['subdomains'] = [None] | ||
| 152 | |||
| 153 | for i, subdomain in enumerate(self.config['subdomains']): | ||
| 154 | if subdomain is None or await ProxyQueue.has_connection(subdomain): | ||
| 155 | self.config['subdomains'][i] = uuid4().hex | ||
| 156 | |||
| 157 | for subdomain in self.config['subdomains']: | ||
| 158 | self.proxy_queues[subdomain] = await ProxyQueue.create_for_identifier(subdomain) | ||
| 159 | |||
| 160 | hostname = os.environ.get("TUNNEL_DOMAIN") | ||
| 161 | protocol = "https" if os.environ.get("SECURE", False) else "http" | ||
| 162 | |||
| 163 | urls = [ | ||
| 164 | f'{protocol}://{subdomain}.{hostname}' | ||
| 165 | for subdomain in self.config['subdomains'] | ||
| 166 | ] | ||
