Debian Codegraph @

examples/http3_server.py

raw symbols SCIP
1 import argparse
2 import asyncio
3 import importlib
4 import logging
5 import time
6 from collections import deque
7 from email.utils import formatdate
8 from typing import Callable, Deque, Optional, Union, cast
9
10 import aioquic
11 import wsproto
12 import wsproto.events
13 from aioquic.asyncio import QuicConnectionProtocol, serve
14 from aioquic.h0.connection import H0_ALPN, H0Connection
15 from aioquic.h3.connection import H3_ALPN, H3Connection
16 from aioquic.h3.events import (
17 DatagramReceived,
18 DataReceived,
19 H3Event,
20 HeadersReceived,
21 WebTransportStreamDataReceived,
22 )
23 from aioquic.h3.exceptions import NoAvailablePushIDError
24 from aioquic.quic.configuration import QuicConfiguration
25 from aioquic.quic.events import DatagramFrameReceived, ProtocolNegotiated, QuicEvent
26 from aioquic.quic.logger import QuicFileLogger
27 from aioquic.tls import SessionTicket
28
29 try:
30 import uvloop
31 except ImportError:
32 uvloop = None
33
34 AsgiApplication = Callable
35 HttpConnection = Union[H0Connection, H3Connection]
36
37 SERVER_NAME = "aioquic/" + aioquic.__version__
38
39
40 class HttpRequestHandler:
41 def __init__(
42 self,
43 *,
44 authority: bytes,
45 connection: HttpConnection,
46 protocol: QuicConnectionProtocol,
47 scope: dict,
48 stream_ended: bool,
49 stream_id: int,
50 transmit: Callable[[], None],
51 ) -> None:
52 self.authority = authority
53 self.connection = connection
54 self.protocol = protocol
55 self.queue: asyncio.Queue[dict] = asyncio.Queue()
56 self.scope = scope
57 self.stream_id = stream_id
58 self.transmit = transmit
59
60 if stream_ended:
61 self.queue.put_nowait({"type": "http.request"})
62
63 def http_event_received(self, event: H3Event) -> None:
64 if isinstance(event, DataReceived):
65 self.queue.put_nowait(
66 {
67 "type": "http.request",
68 "body": event.data,
69 "more_body": not event.stream_ended,
70 }
71 )
72 elif isinstance(event, HeadersReceived) and event.stream_ended:
73 self.queue.put_nowait(
74 {"type": "http.request", "body": b"", "more_body": False}
75 )
76
77 async def run_asgi(self, app: AsgiApplication) -> None:
78 await app(self.scope, self.receive, self.send)
79
80 async def receive(self) -> dict:
81 return await self.queue.get()
82
83 async def send(self, message: dict) -> None:
84 if message["type"] == "http.response.start":
85 self.connection.send_headers(
86 stream_id=self.stream_id,
87 headers=[
88 (b":status", str(message["status"]).encode()),
89 (b"server", SERVER_NAME.encode()),
90 (b"date", formatdate(time.time(), usegmt=True).encode()),
91 ]
92 + [(k, v) for k, v in message["headers"]],
93 )
94 elif message["type"] == "http.response.body":
95 self.connection.send_data(
96 stream_id=self.stream_id,
97 data=message.get("body", b""),
98 end_stream=not message.get("more_body", False),
99 )
100 elif message["type"] == "http.response.push" and isinstance(
101 self.connection, H3Connection
102 ):
103 request_headers = [
104 (b":method", b"GET"),
105 (b":scheme", b"https"),
106 (b":authority", self.authority),
107 (b":path", message["path"].encode()),
108 ] + [(k, v) for k, v in message["headers"]]
109
110 # send push promise
111 try:
112 push_stream_id = self.connection.send_push_promise(
113 stream_id=self.stream_id, headers=request_headers
114 )
115 except NoAvailablePushIDError:
116 return
117
118 # fake request
119 cast(HttpServerProtocol, self.protocol).http_event_received(
120 HeadersReceived(
121 headers=request_headers, stream_ended=True, stream_id=push_stream_id
122 )
123 )
124 self.transmit()
125
126
127 class WebSocketHandler:
128 def __init__(
129 self,
130 *,
131 connection: HttpConnection,
132 scope: dict,
133 stream_id: int,
134 transmit: Callable[[], None],
135 ) -> None:
136 self.closed = False
137 self.connection = connection
138 self.http_event_queue: Deque[DataReceived] = deque()
139 self.queue: asyncio.Queue[dict] = asyncio.Queue()
140 self.scope = scope
141 self.stream_id = stream_id
142 self.transmit = transmit
143 self.websocket: Optional[wsproto.Connection] = None
144
145 def http_event_received(self, event: H3Event) -> None:
146 if isinstance(event, DataReceived) and not self.closed:
147 if self.websocket is not None:
148 self.websocket.receive_data(event.data)
149
150 for ws_event in self.websocket.events():
151 self.websocket_event_received(ws_event)
152 else:
153 # delay event processing until we get `websocket.accept`
154 # from the ASGI application
155 self.http_event_queue.append(event)
156
157 def websocket_event_received(self, event: wsproto.events.Event) -> None:
158 if isinstance(event, wsproto.events.TextMessage):
159 self.queue.put_nowait({"type": "websocket.receive", "text": event.data})
160 elif isinstance(event, wsproto.events.Message):
161 self.queue.put_nowait({"type": "websocket.receive", "bytes": event.data})
162 elif isinstance(event, wsproto.events.CloseConnection):
163 self.queue.put_nowait({"type": "websocket.disconnect", "code": event.code})
164
165 async def run_asgi(self, app: AsgiApplication) -> None:
166 self.queue.put_nowait({"type": "websocket.connect"})
167
168 try:
169 await app(self.scope, self.receive, self.send)
170 finally:
171 if not self.closed:
172 await self.send({"type": "websocket.close", "code": 1000})
173
174 async def receive(self) -> dict:
175 return await self.queue.get()
176
177 async def send(self, message: dict) -> None:
178 data = b""
179 end_stream = False
180 if message["type"] == "websocket.accept":
181 subprotocol = message.get("subprotocol")
182
183 self.websocket = wsproto.Connection(wsproto.ConnectionType.SERVER)
184
185 headers = [
186 (b":status", b"200"),
187 (b"server", SERVER_NAME.encode()),
188 (b"date", formatdate(time.time(), usegmt=True).encode()),
189 ]
190 if subprotocol is not None:
191 headers.append((b"sec-websocket-protocol", subprotocol.encode()))
192 self.connection.send_headers(stream_id=self.stream_id, headers=headers)
193
194 # consume backlog
195 while self.http_event_queue:
196 self.http_event_received(self.http_event_queue.popleft())
197
198 elif message["type"] == "websocket.close":
199 if self.websocket is not None:
200 data = self.websocket.send(
201 wsproto.events.CloseConnection(code=message["code"])
202 )
203 else:
204 self.connection.send_headers(
205 stream_id=self.stream_id, headers=[(b":status", b"403")]
206 )
207 end_stream = True
208 elif message["type"] == "websocket.send":
209 if message.get("text") is not None:
210 data = self.websocket.send(
211 wsproto.events.TextMessage(data=message["text"])
212 )
213 elif message.get("bytes") is not None:
214 data = self.websocket.send(
215 wsproto.events.Message(data=message["bytes"])
216 )
217
218 if data:
219 self.connection.send_data(
220 stream_id=self.stream_id, data=data, end_stream=end_stream
221 )
222 if end_stream:
223 self.closed = True
224 self.transmit()
225
226
227 class WebTransportHandler:
228 def __init__(
229 self,
230 *,
231 connection: H3Connection,
232 scope: dict,
233 stream_id: int,
234 transmit: Callable[[], None],
235 ) -> None:
236 self.accepted = False
237 self.closed = False
238 self.connection = connection
239 self.http_event_queue: Deque[H3Event] = deque()
240 self.queue: asyncio.Queue[dict] = asyncio.Queue()
241 self.scope = scope
242 self.stream_id = stream_id
243 self.transmit = transmit
244
245 def http_event_received(self, event: H3Event) -> None:
246 if not self.closed:
247 if self.accepted:
248 if isinstance(event, DatagramReceived):
249 self.queue.put_nowait(
250 {
251 "data": event.data,
252 "type": "webtransport.datagram.receive",
253 }
254 )
255 elif isinstance(event, WebTransportStreamDataReceived):
256 self.queue.put_nowait(
257 {
258 "data": event.data,
259 "stream": event.stream_id,
260 "type": "webtransport.stream.receive",
261 }
262 )
263 else:
264 # delay event processing until we get `webtransport.accept`
265 # from the ASGI application
266 self.http_event_queue.append(event)
267
268 async def run_asgi(self, app: AsgiApplication) -> None:
269 self.queue.put_nowait({"type": "webtransport.connect"})
270
271 try:
272 await app(self.scope, self.receive, self.send)
273 finally:
274 if not self.closed:
275 await self.send({"type": "webtransport.close"})
276
277 async def receive(self) -> dict:
278 return await self.queue.get()
279
280 async def send(self, message: dict) -> None:
281 data = b""
282 end_stream = False
283
284 if message["type"] == "webtransport.accept":
285 self.accepted = True
286
287 headers = [
288 (b":status", b"200"),
289 (b"server", SERVER_NAME.encode()),
290 (b"date", formatdate(time.time(), usegmt=True).encode()),
291 (b"sec-webtransport-http3-draft", b"draft02"),
292 ]
293 self.connection.send_headers(stream_id=self.stream_id, headers=headers)
294
295 # consume backlog
296 while self.http_event_queue:
297 self.http_event_received(self.http_event_queue.popleft())
298 elif message["type"] == "webtransport.close":
299 if not self.accepted:
300 self.connection.send_headers(
301 stream_id=self.stream_id, headers=[(b":status", b"403")]
302 )
303 end_stream = True
304 elif message["type"] == "webtransport.datagram.send":
305 self.connection.send_datagram(
306 stream_id=self.stream_id, data=message["data"]
307 )
308 elif message["type"] == "webtransport.stream.send":
309 self.connection._quic.send_stream_data(
310 stream_id=message["stream"], data=message["data"]
311 )
312
313 if data or end_stream:
314 self.connection.send_data(
315 stream_id=self.stream_id, data=data, end_stream=end_stream
316 )
317 if end_stream:
318 self.closed = True
319 self.transmit()
320
321
322 Handler = Union[HttpRequestHandler, WebSocketHandler, WebTransportHandler]
323
324
325 class HttpServerProtocol(QuicConnectionProtocol):
326 def __init__(self, *args, **kwargs) -> None:
327 super().__init__(*args, **kwargs)
328 self._handlers: dict[int, Handler] = {}
329 self._http: Optional[HttpConnection] = None
330
331 def http_event_received(self, event: H3Event) -> None:
332 if isinstance(event, HeadersReceived) and event.stream_id not in self._handlers:
333 authority = None
334 headers = []
335 http_version = "0.9" if isinstance(self._http, H0Connection) else "3"
336 raw_path = b""
337 method = ""
338 protocol = None
339 for header, value in event.headers:
340 if header == b":authority":
341 authority = value
342 headers.append((b"host", value))
343 elif header == b":method":
344 method = value.decode()
345 elif header == b":path":
346 raw_path = value
347 elif header == b":protocol":
348 protocol = value.decode()
349 elif header and not header.startswith(b":"):
350 headers.append((header, value))
351
352 if b"?" in raw_path:
353 path_bytes, query_string = raw_path.split(b"?", maxsplit=1)
354 else:
355 path_bytes, query_string = raw_path, b""
356 path = path_bytes.decode()
357 self._quic._logger.info("HTTP request %s %s", method, path)
358
359 # FIXME: add a public API to retrieve peer address
360 client_addr = self._http._quic._network_paths[0].addr
361 client = (client_addr[0], client_addr[1])
362
363 handler: Handler
364 scope: dict
365 if method == "CONNECT" and protocol == "websocket":
366 subprotocols: list[str] = []
367 for header, value in event.headers:
368 if header == b"sec-websocket-protocol":
369 subprotocols = [x.strip() for x in value.decode().split(",")]
370 scope = {
371 "client": client,
372 "headers": headers,
373 "http_version": http_version,
374 "method": method,
375 "path": path,
376 "query_string": query_string,
377 "raw_path": raw_path,
378 "root_path": "",
379 "scheme": "wss",
380 "subprotocols": subprotocols,
381 "type": "websocket",
382 }
383 handler = WebSocketHandler(
384 connection=self._http,
385 scope=scope,
386 stream_id=event.stream_id,
387 transmit=self.transmit,
388 )
389 elif method == "CONNECT" and protocol == "webtransport":
390 assert isinstance(self._http, H3Connection), (
391 "WebTransport is only supported over HTTP/3"
392 )
393 scope = {
394 "client": client,
395 "headers": headers,
396 "http_version": http_version,
397 "method": method,
398 "path": path,
399 "query_string": query_string,
400 "raw_path": raw_path,
401 "root_path": "",
402 "scheme": "https",
403 "type": "webtransport",
404 }
405 handler = WebTransportHandler(
406 connection=self._http,
407 scope=scope,
408 stream_id=event.stream_id,
409 transmit=self.transmit,
410 )
411 else:
412 extensions: dict[str, dict] = {}
413 if isinstance(self._http, H3Connection):
414 extensions["http.response.push"] = {}
415 scope = {
416 "client": client,
417 "extensions": extensions,
418 "headers": headers,
419 "http_version": http_version,
420 "method": method,
421 "path": path,
422 "query_string": query_string,
423 "raw_path": raw_path,
424 "root_path": "",
425 "scheme": "https",
426 "type": "http",
427 }
428 handler = HttpRequestHandler(
429 authority=authority,
430 connection=self._http,
431 protocol=self,
432 scope=scope,
433 stream_ended=event.stream_ended,
434 stream_id=event.stream_id,
435 transmit=self.transmit,
436 )
437 self._handlers[event.stream_id] = handler
438 asyncio.ensure_future(handler.run_asgi(application))
439 elif (
440 isinstance(event, (DataReceived, HeadersReceived))
441 and event.stream_id in self._handlers
442 ):
443 handler = self._handlers[event.stream_id]
444 handler.http_event_received(event)
445 elif isinstance(event, DatagramReceived):
446 handler = self._handlers[event.stream_id]
447 handler.http_event_received(event)
448 elif isinstance(event, WebTransportStreamDataReceived):
449 handler = self._handlers[event.session_id]
450 handler.http_event_received(event)
451
452 def quic_event_received(self, event: QuicEvent) -> None:
453 if isinstance(event, ProtocolNegotiated):
454 if event.alpn_protocol in H3_ALPN:
455 self._http = H3Connection(self._quic, enable_webtransport=True)
456 elif event.alpn_protocol in H0_ALPN:
457 self._http = H0Connection(self._quic)
458 elif isinstance(event, DatagramFrameReceived):
459 if event.data == b"quack":
460 self._quic.send_datagram_frame(b"quack-ack")
461
462 #  pass event to the HTTP layer
463 if self._http is not None:
464 for http_event in self._http.handle_event(event):
465 self.http_event_received(http_event)
466
467
468 class SessionTicketStore:
469 """
470 Simple in-memory store for session tickets.
471 """
472
473 def __init__(self) -> None:
474 self.tickets: dict[bytes, SessionTicket] = {}
475
476 def add(self, ticket: SessionTicket) -> None:
477 self.tickets[ticket.ticket] = ticket
478
479 def pop(self, label: bytes) -> Optional[SessionTicket]:
480 return self.tickets.pop(label, None)
481
482
483 async def main(
484 host: str,
485 port: int,
486 configuration: QuicConfiguration,
487 session_ticket_store: SessionTicketStore,
488 retry: bool,
489 ) -> None:
490 await serve(
491 host,
492 port,
493 configuration=configuration,
494 create_protocol=HttpServerProtocol,
495 session_ticket_fetcher=session_ticket_store.pop,
496 session_ticket_handler=session_ticket_store.add,
497 retry=retry,
498 )
499 await asyncio.Future()
500
501
502 if __name__ == "__main__":
503 defaults = QuicConfiguration(is_client=False)
504
505 parser = argparse.ArgumentParser(description="QUIC server")
506 parser.add_argument(
507 "app",
508 type=str,
509 nargs="?",
510 default="demo:app",
511 help="the ASGI application as <module>:<attribute>",
512 )
513 parser.add_argument(
514 "-c",
515 "--certificate",
516 type=str,
517 required=True,
518 help="load the TLS certificate from the specified file",
519 )
520 parser.add_argument(
521 "--congestion-control-algorithm",
522 type=str,
523 default="reno",
524 help="use the specified congestion control algorithm",
525 )
526 parser.add_argument(
527 "--host",
528 type=str,
529 default="::",
530 help="listen on the specified address (defaults to ::)",
531 )
532 parser.add_argument(
533 "--port",
534 type=int,
535 default=4433,
536 help="listen on the specified port (defaults to 4433)",
537 )
538 parser.add_argument(
539 "-k",
540 "--private-key",
541 type=str,
542 help="load the TLS private key from the specified file",
543 )
544 parser.add_argument(
545 "-l",
546 "--secrets-log",
547 type=str,
548 help="log secrets to a file, for use with Wireshark",
549 )
550 parser.add_argument(
551 "--max-datagram-size",
552 type=int,
553 default=defaults.max_datagram_size,
554 help="maximum datagram size to send, excluding UDP or IP overhead",
555 )
556 parser.add_argument(
557 "-q",
558 "--quic-log",
559 type=str,
560 help="log QUIC events to QLOG files in the specified directory",
561 )
562 parser.add_argument(
563 "--retry",
564 action="store_true",
565 help="send a retry for new connections",
566 )
567 parser.add_argument(
568 "-v", "--verbose", action="store_true", help="increase logging verbosity"
569 )
570 args = parser.parse_args()
571
572 logging.basicConfig(
573 format="%(asctime)s %(levelname)s %(name)s %(message)s",
574 level=logging.DEBUG if args.verbose else logging.INFO,
575 )
576
577 # import ASGI application
578 module_str, attr_str = args.app.split(":", maxsplit=1)
579 module = importlib.import_module(module_str)
580 application = getattr(module, attr_str)
581
582 # create QUIC logger
583 if args.quic_log:
584 quic_logger = QuicFileLogger(args.quic_log)
585 else:
586 quic_logger = None
587
588 # open SSL log file
589 if args.secrets_log:
590 secrets_log_file = open(args.secrets_log, "a")
591 else:
592 secrets_log_file = None
593
594 configuration = QuicConfiguration(
595 alpn_protocols=H3_ALPN + H0_ALPN + ["siduck"],
596 congestion_control_algorithm=args.congestion_control_algorithm,
597 is_client=False,
598 max_datagram_frame_size=65536,
599 max_datagram_size=args.max_datagram_size,
600 quic_logger=quic_logger,
601 secrets_log_file=secrets_log_file,
602 )
603
604 # load SSL certificate and key
605 configuration.load_cert_chain(args.certificate, args.private_key)
606
607 if uvloop is not None:
608 uvloop.install()
609
610 try:
611 asyncio.run(
612 main(
613 host=args.host,
614 port=args.port,
615 configuration=configuration,
616 session_ticket_store=SessionTicketStore(),
617 retry=args.retry,
618 )
619 )
620 except KeyboardInterrupt:
621 pass