devdoor 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- devdoor/__init__.py +6 -0
- devdoor/__main__.py +8 -0
- devdoor/cli/__init__.py +1 -0
- devdoor/cli/app.py +99 -0
- devdoor/cli/auth.py +178 -0
- devdoor/cli/domains.py +214 -0
- devdoor/cli/inspector.py +209 -0
- devdoor/cli/local.py +790 -0
- devdoor/cli/share.py +443 -0
- devdoor/cli/validators.py +40 -0
- devdoor/core/__init__.py +1 -0
- devdoor/core/config.py +482 -0
- devdoor/core/engine.py +495 -0
- devdoor/core/events.py +287 -0
- devdoor/core/protocol.py +462 -0
- devdoor/core/router.py +163 -0
- devdoor/inspector/__init__.py +14 -0
- devdoor/inspector/curl.py +68 -0
- devdoor/inspector/daemon_hook.py +147 -0
- devdoor/inspector/replay.py +122 -0
- devdoor/inspector/store.py +291 -0
- devdoor/platform/__init__.py +36 -0
- devdoor/platform/base.py +209 -0
- devdoor/platform/darwin.py +194 -0
- devdoor/platform/linux.py +185 -0
- devdoor/platform/windows.py +143 -0
- devdoor/proxy/__init__.py +7 -0
- devdoor/proxy/certs.py +311 -0
- devdoor/proxy/forwarder.py +457 -0
- devdoor/proxy/https_server.py +122 -0
- devdoor/tui/__init__.py +17 -0
- devdoor/tui/inspector_app.py +667 -0
- devdoor/tunnel/__init__.py +1 -0
- devdoor/tunnel/auth_client.py +287 -0
- devdoor/tunnel/client.py +309 -0
- devdoor/tunnel/httperr.py +168 -0
- devdoor/tunnel/mux.py +566 -0
- devdoor/tunnel/relay_api.py +245 -0
- devdoor-0.1.0.dist-info/METADATA +227 -0
- devdoor-0.1.0.dist-info/RECORD +43 -0
- devdoor-0.1.0.dist-info/WHEEL +4 -0
- devdoor-0.1.0.dist-info/entry_points.txt +3 -0
- devdoor-0.1.0.dist-info/licenses/LICENSE +21 -0
devdoor/tunnel/mux.py
ADDED
|
@@ -0,0 +1,566 @@
|
|
|
1
|
+
"""Client-side multiplexed stream manager with window backpressure."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
import contextlib
|
|
7
|
+
import struct
|
|
8
|
+
import time
|
|
9
|
+
from collections.abc import AsyncIterator, Awaitable, Callable
|
|
10
|
+
from dataclasses import dataclass, field
|
|
11
|
+
|
|
12
|
+
import aiohttp
|
|
13
|
+
|
|
14
|
+
from devdoor.core.events import BodyTapBuffer, TrafficEventBus
|
|
15
|
+
from devdoor.core.protocol import (
|
|
16
|
+
INITIAL_STREAM_WINDOW,
|
|
17
|
+
MAX_FRAME_PAYLOAD,
|
|
18
|
+
WINDOW_UPDATE_THRESHOLD,
|
|
19
|
+
BinaryFrame,
|
|
20
|
+
FrameType,
|
|
21
|
+
ProtocolError,
|
|
22
|
+
StreamOpenRequest,
|
|
23
|
+
StreamOpenResponse,
|
|
24
|
+
WsOpcode,
|
|
25
|
+
WsOpenOk,
|
|
26
|
+
decode_stream_open,
|
|
27
|
+
decode_window_update,
|
|
28
|
+
encode_frame,
|
|
29
|
+
encode_rst,
|
|
30
|
+
encode_stream_open_response,
|
|
31
|
+
encode_window_update,
|
|
32
|
+
encode_ws_open_ok,
|
|
33
|
+
)
|
|
34
|
+
from devdoor.core.router import RouteMatch, Router
|
|
35
|
+
from devdoor.proxy.forwarder import (
|
|
36
|
+
Forwarder,
|
|
37
|
+
build_downstream_headers,
|
|
38
|
+
build_upstream_headers,
|
|
39
|
+
)
|
|
40
|
+
|
|
41
|
+
SendBytesFn = Callable[[bytes], Awaitable[None]]
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
class StreamWindow:
|
|
45
|
+
"""Sliding byte-credit flow control window for a single multiplexed stream."""
|
|
46
|
+
|
|
47
|
+
def __init__(self, initial_credits: int = INITIAL_STREAM_WINDOW) -> None:
|
|
48
|
+
self._credits = initial_credits
|
|
49
|
+
self._closed = False
|
|
50
|
+
self._event = asyncio.Event()
|
|
51
|
+
if self._credits > 0:
|
|
52
|
+
self._event.set()
|
|
53
|
+
|
|
54
|
+
def replenish(self, delta: int) -> None:
|
|
55
|
+
"""Add ``delta`` bytes of send credit and wake waiting senders."""
|
|
56
|
+
if delta <= 0 or self._closed:
|
|
57
|
+
return
|
|
58
|
+
self._credits += delta
|
|
59
|
+
self._event.set()
|
|
60
|
+
|
|
61
|
+
def close(self) -> None:
|
|
62
|
+
"""Close the window and unblock any waiting writers."""
|
|
63
|
+
self._closed = True
|
|
64
|
+
self._event.set()
|
|
65
|
+
|
|
66
|
+
async def consume(self, requested: int) -> int:
|
|
67
|
+
"""Wait for send credit and reserve up to ``requested`` bytes."""
|
|
68
|
+
while self._credits <= 0 and not self._closed:
|
|
69
|
+
self._event.clear()
|
|
70
|
+
if self._credits <= 0 and not self._closed:
|
|
71
|
+
await self._event.wait()
|
|
72
|
+
if self._closed or requested <= 0:
|
|
73
|
+
return 0
|
|
74
|
+
granted = min(requested, self._credits)
|
|
75
|
+
self._credits -= granted
|
|
76
|
+
if self._credits <= 0:
|
|
77
|
+
self._event.clear()
|
|
78
|
+
return granted
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def _new_inbound_queue() -> asyncio.Queue[BinaryFrame | None]:
|
|
82
|
+
return asyncio.Queue()
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
@dataclass(slots=True)
|
|
86
|
+
class StreamContext:
|
|
87
|
+
"""Active per-stream queues, flow-control state, and background task handle."""
|
|
88
|
+
|
|
89
|
+
stream_id: int
|
|
90
|
+
kind: str
|
|
91
|
+
inbound_queue: asyncio.Queue[BinaryFrame | None] = field(default_factory=_new_inbound_queue)
|
|
92
|
+
send_window: StreamWindow = field(default_factory=StreamWindow)
|
|
93
|
+
unacked_recv: int = 0
|
|
94
|
+
task: asyncio.Task[None] | None = None
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def _extract_header(headers: tuple[tuple[str, str], ...], name: str) -> str | None:
|
|
98
|
+
target = name.lower()
|
|
99
|
+
for key, value in headers:
|
|
100
|
+
if key.lower() == target:
|
|
101
|
+
return value
|
|
102
|
+
return None
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def _request_has_body(method: str, headers: tuple[tuple[str, str], ...]) -> bool:
|
|
106
|
+
if method.upper() not in {"GET", "HEAD", "OPTIONS", "TRACE"}:
|
|
107
|
+
return True
|
|
108
|
+
if _extract_header(headers, "transfer-encoding") is not None:
|
|
109
|
+
return True
|
|
110
|
+
raw_len = _extract_header(headers, "content-length")
|
|
111
|
+
return raw_len is not None and raw_len.strip().isdigit() and int(raw_len.strip()) > 0
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
async def _iter_inbound_body(
|
|
115
|
+
ctx: StreamContext,
|
|
116
|
+
tap: BodyTapBuffer,
|
|
117
|
+
) -> AsyncIterator[bytes]:
|
|
118
|
+
while True:
|
|
119
|
+
frame = await ctx.inbound_queue.get()
|
|
120
|
+
if frame is None or frame.frame_type == FrameType.END:
|
|
121
|
+
return
|
|
122
|
+
if frame.frame_type == FrameType.DATA and frame.payload:
|
|
123
|
+
tap.write(frame.payload)
|
|
124
|
+
yield frame.payload
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
class StreamMux:
|
|
128
|
+
"""Multiplexes tunneled HTTP/WebSocket streams across ``proxy-core``."""
|
|
129
|
+
|
|
130
|
+
def __init__(
|
|
131
|
+
self,
|
|
132
|
+
*,
|
|
133
|
+
send_bytes: SendBytesFn,
|
|
134
|
+
router: Router,
|
|
135
|
+
forwarder: Forwarder,
|
|
136
|
+
event_bus: TrafficEventBus,
|
|
137
|
+
public_domain: str,
|
|
138
|
+
target_domain: str | None = None,
|
|
139
|
+
preserve_host: bool = False,
|
|
140
|
+
) -> None:
|
|
141
|
+
self._send_bytes = send_bytes
|
|
142
|
+
self._router = router
|
|
143
|
+
self._forwarder = forwarder
|
|
144
|
+
self._event_bus = event_bus
|
|
145
|
+
self._public_domain = public_domain
|
|
146
|
+
self._target_domain = target_domain
|
|
147
|
+
self._preserve_host = preserve_host
|
|
148
|
+
self._send_lock = asyncio.Lock()
|
|
149
|
+
self._streams: dict[int, StreamContext] = {}
|
|
150
|
+
|
|
151
|
+
def _match_route(self, incoming_host: str, raw_path: str) -> RouteMatch | None:
|
|
152
|
+
lookup_host = (
|
|
153
|
+
incoming_host
|
|
154
|
+
if self._router.has_domain(incoming_host)
|
|
155
|
+
else (self._target_domain or incoming_host)
|
|
156
|
+
)
|
|
157
|
+
return self._router.match(lookup_host, raw_path)
|
|
158
|
+
|
|
159
|
+
@property
|
|
160
|
+
def active_stream_ids(self) -> tuple[int, ...]:
|
|
161
|
+
"""Return stream IDs currently running inside the multiplexer."""
|
|
162
|
+
return tuple(self._streams.keys())
|
|
163
|
+
|
|
164
|
+
async def _send_frame(self, frame: BinaryFrame) -> None:
|
|
165
|
+
raw = encode_frame(frame)
|
|
166
|
+
async with self._send_lock:
|
|
167
|
+
await self._send_bytes(raw)
|
|
168
|
+
|
|
169
|
+
async def close_all(self) -> None:
|
|
170
|
+
"""Cancel and await all active stream tasks (called on tunnel disconnect)."""
|
|
171
|
+
contexts = list(self._streams.values())
|
|
172
|
+
self._streams.clear()
|
|
173
|
+
tasks: list[asyncio.Task[None]] = []
|
|
174
|
+
for ctx in contexts:
|
|
175
|
+
ctx.send_window.close()
|
|
176
|
+
ctx.inbound_queue.put_nowait(None)
|
|
177
|
+
if ctx.task is not None and not ctx.task.done():
|
|
178
|
+
ctx.task.cancel()
|
|
179
|
+
tasks.append(ctx.task)
|
|
180
|
+
if tasks:
|
|
181
|
+
await asyncio.gather(*tasks, return_exceptions=True)
|
|
182
|
+
|
|
183
|
+
async def handle_frame(self, frame: BinaryFrame) -> None:
|
|
184
|
+
"""Dispatch a decoded inbound frame from ``devdoor-relay``."""
|
|
185
|
+
if frame.frame_type == FrameType.STREAM_OPEN:
|
|
186
|
+
opened = decode_stream_open(frame)
|
|
187
|
+
if not isinstance(opened, StreamOpenRequest):
|
|
188
|
+
raise ProtocolError("Relay sent response metadata on STREAM_OPEN")
|
|
189
|
+
ctx = StreamContext(stream_id=frame.stream_id, kind=opened.kind)
|
|
190
|
+
self._streams[frame.stream_id] = ctx
|
|
191
|
+
ctx.task = asyncio.create_task(self._run_stream_safe(ctx, opened))
|
|
192
|
+
return
|
|
193
|
+
|
|
194
|
+
ctx = self._streams.get(frame.stream_id)
|
|
195
|
+
if ctx is None:
|
|
196
|
+
return
|
|
197
|
+
|
|
198
|
+
if frame.frame_type == FrameType.WINDOW_UPDATE:
|
|
199
|
+
ctx.send_window.replenish(decode_window_update(frame))
|
|
200
|
+
return
|
|
201
|
+
|
|
202
|
+
if frame.frame_type == FrameType.RST:
|
|
203
|
+
ctx.send_window.close()
|
|
204
|
+
ctx.inbound_queue.put_nowait(None)
|
|
205
|
+
if ctx.task is not None and not ctx.task.done():
|
|
206
|
+
ctx.task.cancel()
|
|
207
|
+
self._streams.pop(frame.stream_id, None)
|
|
208
|
+
return
|
|
209
|
+
|
|
210
|
+
if frame.frame_type == FrameType.DATA and frame.payload:
|
|
211
|
+
ctx.unacked_recv += len(frame.payload)
|
|
212
|
+
if ctx.unacked_recv >= WINDOW_UPDATE_THRESHOLD:
|
|
213
|
+
credit = ctx.unacked_recv
|
|
214
|
+
ctx.unacked_recv = 0
|
|
215
|
+
await self._send_frame(encode_window_update(frame.stream_id, credit))
|
|
216
|
+
|
|
217
|
+
await ctx.inbound_queue.put(frame)
|
|
218
|
+
|
|
219
|
+
async def _run_stream_safe(self, ctx: StreamContext, req: StreamOpenRequest) -> None:
|
|
220
|
+
try:
|
|
221
|
+
if req.kind == "ws":
|
|
222
|
+
await self._run_ws_stream(ctx, req)
|
|
223
|
+
else:
|
|
224
|
+
await self._run_http_stream(ctx, req)
|
|
225
|
+
except asyncio.CancelledError:
|
|
226
|
+
raise
|
|
227
|
+
except (aiohttp.ClientError, TimeoutError, OSError, ProtocolError) as exc:
|
|
228
|
+
with contextlib.suppress(aiohttp.ClientError, OSError, ProtocolError):
|
|
229
|
+
await self._send_frame(encode_rst(ctx.stream_id, "stream_error", str(exc)))
|
|
230
|
+
finally:
|
|
231
|
+
ctx.send_window.close()
|
|
232
|
+
self._streams.pop(ctx.stream_id, None)
|
|
233
|
+
|
|
234
|
+
async def _send_body_chunked(
|
|
235
|
+
self,
|
|
236
|
+
ctx: StreamContext,
|
|
237
|
+
chunk: bytes,
|
|
238
|
+
tap: BodyTapBuffer,
|
|
239
|
+
) -> bool:
|
|
240
|
+
tap.write(chunk)
|
|
241
|
+
offset = 0
|
|
242
|
+
while offset < len(chunk):
|
|
243
|
+
window = min(MAX_FRAME_PAYLOAD, len(chunk) - offset)
|
|
244
|
+
granted = await ctx.send_window.consume(window)
|
|
245
|
+
if granted <= 0:
|
|
246
|
+
return False
|
|
247
|
+
piece = chunk[offset : offset + granted]
|
|
248
|
+
offset += granted
|
|
249
|
+
await self._send_frame(
|
|
250
|
+
BinaryFrame(stream_id=ctx.stream_id, frame_type=FrameType.DATA, payload=piece)
|
|
251
|
+
)
|
|
252
|
+
return True
|
|
253
|
+
|
|
254
|
+
def _emit_tunnel_exchange(
|
|
255
|
+
self,
|
|
256
|
+
*,
|
|
257
|
+
req: StreamOpenRequest,
|
|
258
|
+
host: str,
|
|
259
|
+
target_port: int,
|
|
260
|
+
status: int,
|
|
261
|
+
started: float,
|
|
262
|
+
resp_headers: tuple[tuple[str, str], ...],
|
|
263
|
+
req_tap: BodyTapBuffer,
|
|
264
|
+
resp_tap: BodyTapBuffer,
|
|
265
|
+
match: RouteMatch | None,
|
|
266
|
+
) -> None:
|
|
267
|
+
req_preview, req_truncated = req_tap.snapshot()
|
|
268
|
+
resp_preview, resp_truncated = resp_tap.snapshot()
|
|
269
|
+
self._event_bus.emit_exchange(
|
|
270
|
+
source="tunnel",
|
|
271
|
+
host=host,
|
|
272
|
+
method=req.method,
|
|
273
|
+
path=req.raw_path or "/",
|
|
274
|
+
target_port=target_port,
|
|
275
|
+
status=status,
|
|
276
|
+
duration_ms=(time.perf_counter() - started) * 1000.0,
|
|
277
|
+
req_headers=req.headers,
|
|
278
|
+
resp_headers=resp_headers,
|
|
279
|
+
req_body_preview=req_preview,
|
|
280
|
+
resp_body_preview=resp_preview,
|
|
281
|
+
req_body_truncated=req_truncated,
|
|
282
|
+
resp_body_truncated=resp_truncated,
|
|
283
|
+
log_mode=match.log_mode if match is not None else "full",
|
|
284
|
+
)
|
|
285
|
+
|
|
286
|
+
async def _send_simple_http_error(
|
|
287
|
+
self,
|
|
288
|
+
ctx: StreamContext,
|
|
289
|
+
req: StreamOpenRequest,
|
|
290
|
+
*,
|
|
291
|
+
host: str,
|
|
292
|
+
target_port: int,
|
|
293
|
+
status: int,
|
|
294
|
+
reason: str,
|
|
295
|
+
body: bytes,
|
|
296
|
+
started: float,
|
|
297
|
+
match: RouteMatch | None,
|
|
298
|
+
extra_headers: tuple[tuple[str, str], ...] = (),
|
|
299
|
+
) -> None:
|
|
300
|
+
headers = (("Content-Type", "text/plain; charset=utf-8"), *extra_headers)
|
|
301
|
+
await self._send_frame(
|
|
302
|
+
encode_stream_open_response(
|
|
303
|
+
ctx.stream_id,
|
|
304
|
+
StreamOpenResponse(status=status, reason=reason, headers=headers),
|
|
305
|
+
)
|
|
306
|
+
)
|
|
307
|
+
tap_in = BodyTapBuffer()
|
|
308
|
+
tap_out = BodyTapBuffer()
|
|
309
|
+
if body:
|
|
310
|
+
await self._send_body_chunked(ctx, body, tap_out)
|
|
311
|
+
await self._send_frame(BinaryFrame(stream_id=ctx.stream_id, frame_type=FrameType.END))
|
|
312
|
+
self._emit_tunnel_exchange(
|
|
313
|
+
req=req,
|
|
314
|
+
host=host,
|
|
315
|
+
target_port=target_port,
|
|
316
|
+
status=status,
|
|
317
|
+
started=started,
|
|
318
|
+
resp_headers=headers,
|
|
319
|
+
req_tap=tap_in,
|
|
320
|
+
resp_tap=tap_out,
|
|
321
|
+
match=match,
|
|
322
|
+
)
|
|
323
|
+
|
|
324
|
+
async def _run_http_stream(self, ctx: StreamContext, req: StreamOpenRequest) -> None:
|
|
325
|
+
started = time.perf_counter()
|
|
326
|
+
incoming_host = _extract_header(req.headers, "host") or self._public_domain
|
|
327
|
+
match = self._match_route(incoming_host, req.raw_path)
|
|
328
|
+
if match is None:
|
|
329
|
+
await self._send_simple_http_error(
|
|
330
|
+
ctx,
|
|
331
|
+
req,
|
|
332
|
+
host=incoming_host,
|
|
333
|
+
target_port=0,
|
|
334
|
+
status=404,
|
|
335
|
+
reason="Not Found",
|
|
336
|
+
body=b"No local route matches this host.",
|
|
337
|
+
started=started,
|
|
338
|
+
match=None,
|
|
339
|
+
)
|
|
340
|
+
return
|
|
341
|
+
|
|
342
|
+
origin = _extract_header(req.headers, "origin")
|
|
343
|
+
if req.method.upper() == "OPTIONS" and match.cors and origin:
|
|
344
|
+
cors_headers = tuple(
|
|
345
|
+
build_downstream_headers(
|
|
346
|
+
(),
|
|
347
|
+
cors_enabled=True,
|
|
348
|
+
request_origin=origin,
|
|
349
|
+
request_headers=_extract_header(req.headers, "access-control-request-headers"),
|
|
350
|
+
).items()
|
|
351
|
+
)
|
|
352
|
+
await self._send_frame(
|
|
353
|
+
encode_stream_open_response(
|
|
354
|
+
ctx.stream_id,
|
|
355
|
+
StreamOpenResponse(status=204, reason="No Content", headers=cors_headers),
|
|
356
|
+
)
|
|
357
|
+
)
|
|
358
|
+
await self._send_frame(BinaryFrame(stream_id=ctx.stream_id, frame_type=FrameType.END))
|
|
359
|
+
self._emit_tunnel_exchange(
|
|
360
|
+
req=req,
|
|
361
|
+
host=incoming_host,
|
|
362
|
+
target_port=match.port,
|
|
363
|
+
status=204,
|
|
364
|
+
started=started,
|
|
365
|
+
resp_headers=cors_headers,
|
|
366
|
+
req_tap=BodyTapBuffer(),
|
|
367
|
+
resp_tap=BodyTapBuffer(),
|
|
368
|
+
match=match,
|
|
369
|
+
)
|
|
370
|
+
return
|
|
371
|
+
|
|
372
|
+
req_tap = BodyTapBuffer()
|
|
373
|
+
resp_tap = BodyTapBuffer()
|
|
374
|
+
has_body = _request_has_body(req.method, req.headers)
|
|
375
|
+
host_override = None if self._preserve_host else f"localhost:{match.port}"
|
|
376
|
+
upstream_headers = build_upstream_headers(
|
|
377
|
+
req.headers,
|
|
378
|
+
client_ip=req.client_ip or None,
|
|
379
|
+
proto="https",
|
|
380
|
+
original_host=incoming_host,
|
|
381
|
+
host_override=host_override,
|
|
382
|
+
drop_content_length=has_body,
|
|
383
|
+
)
|
|
384
|
+
upstream_url = f"http://127.0.0.1:{match.port}{match.target_path}"
|
|
385
|
+
request_data = _iter_inbound_body(ctx, req_tap) if has_body else None
|
|
386
|
+
|
|
387
|
+
try:
|
|
388
|
+
async with self._forwarder.get_session().request(
|
|
389
|
+
req.method,
|
|
390
|
+
upstream_url,
|
|
391
|
+
headers=upstream_headers,
|
|
392
|
+
data=request_data,
|
|
393
|
+
allow_redirects=False,
|
|
394
|
+
) as upstream_resp:
|
|
395
|
+
resp_headers = tuple(
|
|
396
|
+
build_downstream_headers(
|
|
397
|
+
upstream_resp.headers.items(),
|
|
398
|
+
cors_enabled=match.cors,
|
|
399
|
+
request_origin=origin,
|
|
400
|
+
request_headers=_extract_header(
|
|
401
|
+
req.headers, "access-control-request-headers"
|
|
402
|
+
),
|
|
403
|
+
).items()
|
|
404
|
+
)
|
|
405
|
+
await self._send_frame(
|
|
406
|
+
encode_stream_open_response(
|
|
407
|
+
ctx.stream_id,
|
|
408
|
+
StreamOpenResponse(
|
|
409
|
+
status=upstream_resp.status,
|
|
410
|
+
reason=upstream_resp.reason or "",
|
|
411
|
+
headers=resp_headers,
|
|
412
|
+
),
|
|
413
|
+
)
|
|
414
|
+
)
|
|
415
|
+
async for chunk in upstream_resp.content.iter_any():
|
|
416
|
+
if chunk:
|
|
417
|
+
ok = await self._send_body_chunked(ctx, chunk, resp_tap)
|
|
418
|
+
if not ok:
|
|
419
|
+
return
|
|
420
|
+
await self._send_frame(
|
|
421
|
+
BinaryFrame(stream_id=ctx.stream_id, frame_type=FrameType.END)
|
|
422
|
+
)
|
|
423
|
+
self._emit_tunnel_exchange(
|
|
424
|
+
req=req,
|
|
425
|
+
host=incoming_host,
|
|
426
|
+
target_port=match.port,
|
|
427
|
+
status=upstream_resp.status,
|
|
428
|
+
started=started,
|
|
429
|
+
resp_headers=resp_headers,
|
|
430
|
+
req_tap=req_tap,
|
|
431
|
+
resp_tap=resp_tap,
|
|
432
|
+
match=match,
|
|
433
|
+
)
|
|
434
|
+
except aiohttp.ClientError, TimeoutError, OSError:
|
|
435
|
+
await self._send_simple_http_error(
|
|
436
|
+
ctx,
|
|
437
|
+
req,
|
|
438
|
+
host=incoming_host,
|
|
439
|
+
target_port=match.port,
|
|
440
|
+
status=502,
|
|
441
|
+
reason="Bad Gateway",
|
|
442
|
+
body=f"Upstream 127.0.0.1:{match.port} is unreachable.".encode(),
|
|
443
|
+
started=started,
|
|
444
|
+
match=match,
|
|
445
|
+
extra_headers=(("X-DevDoor-Error", "upstream-down"),),
|
|
446
|
+
)
|
|
447
|
+
|
|
448
|
+
async def _run_ws_stream(self, ctx: StreamContext, req: StreamOpenRequest) -> None:
|
|
449
|
+
started = time.perf_counter()
|
|
450
|
+
incoming_host = _extract_header(req.headers, "host") or self._public_domain
|
|
451
|
+
match = self._match_route(incoming_host, req.raw_path)
|
|
452
|
+
if match is None:
|
|
453
|
+
await self._send_frame(encode_rst(ctx.stream_id, "not_found", "Unknown host"))
|
|
454
|
+
return
|
|
455
|
+
|
|
456
|
+
host_override = None if self._preserve_host else f"localhost:{match.port}"
|
|
457
|
+
upstream_headers = build_upstream_headers(
|
|
458
|
+
req.headers,
|
|
459
|
+
client_ip=req.client_ip or None,
|
|
460
|
+
proto="https",
|
|
461
|
+
original_host=incoming_host,
|
|
462
|
+
host_override=host_override,
|
|
463
|
+
for_websocket=True,
|
|
464
|
+
)
|
|
465
|
+
raw_proto = _extract_header(req.headers, "sec-websocket-protocol") or ""
|
|
466
|
+
protocols = [item.strip() for item in raw_proto.split(",") if item.strip()]
|
|
467
|
+
ws_url = f"ws://127.0.0.1:{match.port}{match.target_path}"
|
|
468
|
+
|
|
469
|
+
try:
|
|
470
|
+
async with self._forwarder.get_session().ws_connect(
|
|
471
|
+
ws_url,
|
|
472
|
+
headers=upstream_headers,
|
|
473
|
+
protocols=protocols,
|
|
474
|
+
autoclose=False,
|
|
475
|
+
) as upstream_ws:
|
|
476
|
+
ok_headers = (
|
|
477
|
+
(("Sec-WebSocket-Protocol", upstream_ws.protocol),)
|
|
478
|
+
if upstream_ws.protocol
|
|
479
|
+
else ()
|
|
480
|
+
)
|
|
481
|
+
await self._send_frame(
|
|
482
|
+
encode_ws_open_ok(ctx.stream_id, WsOpenOk(headers=ok_headers))
|
|
483
|
+
)
|
|
484
|
+
self._emit_tunnel_exchange(
|
|
485
|
+
req=req,
|
|
486
|
+
host=incoming_host,
|
|
487
|
+
target_port=match.port,
|
|
488
|
+
status=101,
|
|
489
|
+
started=started,
|
|
490
|
+
resp_headers=ok_headers,
|
|
491
|
+
req_tap=BodyTapBuffer(),
|
|
492
|
+
resp_tap=BodyTapBuffer(),
|
|
493
|
+
match=match,
|
|
494
|
+
)
|
|
495
|
+
|
|
496
|
+
async def _relay_to_upstream() -> None:
|
|
497
|
+
while True:
|
|
498
|
+
frame = await ctx.inbound_queue.get()
|
|
499
|
+
if frame is None:
|
|
500
|
+
return
|
|
501
|
+
if frame.frame_type != FrameType.WS_FRAME:
|
|
502
|
+
continue
|
|
503
|
+
if frame.flags == WsOpcode.TEXT:
|
|
504
|
+
await upstream_ws.send_str(frame.payload.decode("utf-8"))
|
|
505
|
+
elif frame.flags == WsOpcode.BINARY:
|
|
506
|
+
await upstream_ws.send_bytes(frame.payload)
|
|
507
|
+
elif frame.flags == WsOpcode.CLOSE:
|
|
508
|
+
code = (
|
|
509
|
+
struct.unpack("!H", frame.payload[:2])[0]
|
|
510
|
+
if len(frame.payload) >= 2
|
|
511
|
+
else aiohttp.WSCloseCode.OK
|
|
512
|
+
)
|
|
513
|
+
await upstream_ws.close(code=code)
|
|
514
|
+
return
|
|
515
|
+
|
|
516
|
+
async def _upstream_to_relay() -> None:
|
|
517
|
+
async for msg in upstream_ws:
|
|
518
|
+
if msg.type == aiohttp.WSMsgType.TEXT:
|
|
519
|
+
data = msg.data.encode("utf-8")
|
|
520
|
+
await self._send_frame(
|
|
521
|
+
BinaryFrame(
|
|
522
|
+
stream_id=ctx.stream_id,
|
|
523
|
+
frame_type=FrameType.WS_FRAME,
|
|
524
|
+
flags=WsOpcode.TEXT,
|
|
525
|
+
payload=data,
|
|
526
|
+
)
|
|
527
|
+
)
|
|
528
|
+
elif msg.type == aiohttp.WSMsgType.BINARY:
|
|
529
|
+
await self._send_frame(
|
|
530
|
+
BinaryFrame(
|
|
531
|
+
stream_id=ctx.stream_id,
|
|
532
|
+
frame_type=FrameType.WS_FRAME,
|
|
533
|
+
flags=WsOpcode.BINARY,
|
|
534
|
+
payload=bytes(msg.data),
|
|
535
|
+
)
|
|
536
|
+
)
|
|
537
|
+
elif msg.type == aiohttp.WSMsgType.CLOSE:
|
|
538
|
+
close_code = int(msg.data or aiohttp.WSCloseCode.OK)
|
|
539
|
+
await self._send_frame(
|
|
540
|
+
BinaryFrame(
|
|
541
|
+
stream_id=ctx.stream_id,
|
|
542
|
+
frame_type=FrameType.WS_FRAME,
|
|
543
|
+
flags=WsOpcode.CLOSE,
|
|
544
|
+
payload=struct.pack("!H", close_code),
|
|
545
|
+
)
|
|
546
|
+
)
|
|
547
|
+
return
|
|
548
|
+
|
|
549
|
+
async with asyncio.TaskGroup() as group:
|
|
550
|
+
group.create_task(_relay_to_upstream())
|
|
551
|
+
group.create_task(_upstream_to_relay())
|
|
552
|
+
except aiohttp.ClientError, TimeoutError, OSError:
|
|
553
|
+
await self._send_frame(
|
|
554
|
+
encode_rst(ctx.stream_id, "upstream_down", f"Port {match.port} refused WS")
|
|
555
|
+
)
|
|
556
|
+
self._emit_tunnel_exchange(
|
|
557
|
+
req=req,
|
|
558
|
+
host=incoming_host,
|
|
559
|
+
target_port=match.port,
|
|
560
|
+
status=502,
|
|
561
|
+
started=started,
|
|
562
|
+
resp_headers=(("X-DevDoor-Error", "upstream-down"),),
|
|
563
|
+
req_tap=BodyTapBuffer(),
|
|
564
|
+
resp_tap=BodyTapBuffer(),
|
|
565
|
+
match=match,
|
|
566
|
+
)
|