aboutsummaryrefslogtreecommitdiffstats
path: root/ttun_server/websockets.py
diff options
context:
space:
mode:
Diffstat (limited to 'ttun_server/websockets.py')
-rw-r--r--ttun_server/websockets.py60
1 files changed, 32 insertions, 28 deletions
diff --git a/ttun_server/websockets.py b/ttun_server/websockets.py
index 88d6cac..a3cbc5f 100644
--- a/ttun_server/websockets.py
+++ b/ttun_server/websockets.py
@@ -16,24 +16,25 @@ from ttun_server.types import (
16) 16)
17 17
18logger = logging.getLogger(__name__) 18logger = logging.getLogger(__name__)
19logger.setLevel('DEBUG') 19logger.setLevel("DEBUG")
20
20 21
21async def assert_compatible_version(websocket: WebSocket, config: Config) -> None: 22async def assert_compatible_version(websocket: WebSocket, config: Config) -> None:
22 client_version = config.get('version', '1.0.0') 23 client_version = config.get("version", "1.0.0")
23 logger.debug('client_version %s', client_version) 24 logger.debug("client_version %s", client_version)
24 25
25 if 'git' not in client_version and ttun_server.__version__ != 'development': 26 if "git" not in client_version and ttun_server.__version__ != "development":
26 [client_major, *_] = [int(i) for i in client_version.split('.')[:3]] 27 [client_major, *_] = [int(i) for i in client_version.split(".")[:3]]
27 [server_major, *_] = [int(i) for i in ttun_server.__version__.split('.')] 28 [server_major, *_] = [int(i) for i in ttun_server.__version__.split(".")]
28 29
29 if client_major < server_major: 30 if client_major < server_major:
30 await websocket.close(4000, 'Your client is too old') 31 await websocket.close(4000, "Your client is too old")
31 32
32 if client_major > server_major: 33 if client_major > server_major:
33 await websocket.close(4001, 'Your client is too new') 34 await websocket.close(4001, "Your client is too new")
34 35
35 36
36@requires(['authenticated', 'token'] if conf.ENABLE_AUTH else []) 37@requires(["authenticated", "token"] if conf.ENABLE_AUTH else [])
37async def tunnel(websocket: WebSocket) -> None: 38async def tunnel(websocket: WebSocket) -> None:
38 request_tasks: dict[str, asyncio.Task] = {} 39 request_tasks: dict[str, asyncio.Task] = {}
39 proxy_queues: dict[str, ProxyQueue] = {} 40 proxy_queues: dict[str, ProxyQueue] = {}
@@ -43,36 +44,39 @@ async def tunnel(websocket: WebSocket) -> None:
43 44
44 await assert_compatible_version(websocket, config) 45 await assert_compatible_version(websocket, config)
45 46
46 if 'subdomains' not in config: 47 if "subdomains" not in config:
47 config['subdomains'] = [config['subdomain']] 48 config["subdomains"] = [config["subdomain"]]
48 elif config['subdomains'] is None: 49 elif config["subdomains"] is None:
49 config['subdomains'] = [None] 50 config["subdomains"] = [None]
50 51
51 for i, subdomain in enumerate(config['subdomains']): 52 for i, subdomain in enumerate(config["subdomains"]):
52 if subdomain is None or await ProxyQueue.has_connection(subdomain): 53 if subdomain is None or await ProxyQueue.has_connection(subdomain):
53 config['subdomains'][i] = uuid4().hex 54 config["subdomains"][i] = uuid4().hex
54 55
55 for subdomain in config['subdomains']: 56 for subdomain in config["subdomains"]:
56 proxy_queues[subdomain] = await ProxyQueue.create_for_identifier(subdomain) 57 proxy_queues[subdomain] = await ProxyQueue.create_for_identifier(subdomain)
57 58
58 hostname = os.environ.get('TUNNEL_DOMAIN') 59 hostname = os.environ.get("TUNNEL_DOMAIN")
59 protocol = 'https' if os.environ.get('SECURE', False) else 'http' 60 protocol = "https" if os.environ.get("SECURE") else "http"
60 61
61 urls = [ 62 urls = [
62 f'{protocol}://{subdomain}.{hostname}' 63 f"{protocol}://{subdomain}.{hostname}" for subdomain in config["subdomains"]
63 for subdomain in config['subdomains']
64 ] 64 ]
65 65
66 await websocket.send_json({ 66 await websocket.send_json(
67 'url': urls[0], 67 {
68 'urls': urls, 68 "url": urls[0],
69 }) 69 "urls": urls,
70 }
71 )
70 72
71 async def handle_requests(subdomain: str) -> None: 73 async def handle_requests(subdomain: str) -> None:
72 while request := await proxy_queues[subdomain].dequeue(): 74 while request := await proxy_queues[subdomain].dequeue():
73 asyncio.create_task(websocket.send_json(request), name=request['identifier']) 75 asyncio.create_task(
76 websocket.send_json(request), name=request["identifier"]
77 )
74 78
75 for subdomain in config['subdomains']: 79 for subdomain in config["subdomains"]:
76 request_tasks[subdomain] = asyncio.create_task( 80 request_tasks[subdomain] = asyncio.create_task(
77 handle_requests(subdomain), name=subdomain 81 handle_requests(subdomain), name=subdomain
78 ) 82 )
@@ -81,8 +85,8 @@ async def tunnel(websocket: WebSocket) -> None:
81 while True: 85 while True:
82 data: Message = await websocket.receive_json() 86 data: Message = await websocket.receive_json()
83 try: 87 try:
84 data['type'] = MessageType(data['type']).value 88 data["type"] = MessageType(data["type"]).value
85 response_queue = await ProxyQueue.get_for_identifier(data['identifier']) 89 response_queue = await ProxyQueue.get_for_identifier(data["identifier"])
86 await response_queue.enqueue(data) 90 await response_queue.enqueue(data)
87 except AssertionError: 91 except AssertionError:
88 pass 92 pass