Debian Codegraph @

examples/interop.py

raw symbols SCIP
1 #
2 # !!! WARNING !!!
3 #
4 # This example uses some private APIs.
5 #
6
7 import argparse
8 import asyncio
9 import logging
10 import ssl
11 import time
12 from dataclasses import dataclass, field
13 from enum import Flag
14 from typing import Optional, cast
15
16 import httpx
17 from aioquic.asyncio import connect
18 from aioquic.h0.connection import H0_ALPN
19 from aioquic.h3.connection import H3_ALPN, H3Connection
20 from aioquic.h3.events import DataReceived, HeadersReceived, PushPromiseReceived
21 from aioquic.quic.configuration import QuicConfiguration
22 from aioquic.quic.logger import QuicFileLogger, QuicLogger
23 from http3_client import HttpClient
24
25
26 class Result(Flag):
27 V = 0x000001
28 H = 0x000002
29 D = 0x000004
30 C = 0x000008
31 R = 0x000010
32 Z = 0x000020
33 S = 0x000040
34 Q = 0x000080
35
36 M = 0x000100
37 B = 0x000200
38 A = 0x000400
39 U = 0x000800
40 P = 0x001000
41 E = 0x002000
42 L = 0x004000
43 T = 0x008000
44
45 three = 0x010000
46 d = 0x020000
47 p = 0x040000
48
49 def __str__(self):
50 flags = sorted(
51 map(
52 lambda x: getattr(Result, x),
53 filter(lambda x: not x.startswith("_"), dir(Result)),
54 ),
55 key=lambda x: x.value,
56 )
57 result_str = ""
58 for flag in flags:
59 if self & flag:
60 result_str += flag.name
61 else:
62 result_str += "-"
63 return result_str
64
65
66 @dataclass
67 class Server:
68 name: str
69 host: str
70 port: int = 4433
71 http3: bool = True
72 http3_port: Optional[int] = None
73 retry_port: Optional[int] = 4434
74 path: str = "/"
75 push_path: Optional[str] = None
76 result: Result = field(default_factory=lambda: Result(0))
77 session_resumption_port: Optional[int] = None
78 structured_logging: bool = False
79 throughput_path: Optional[str] = "/%(size)d"
80 verify_mode: Optional[int] = None
81
82
83 SERVERS = [
84 Server("akamaiquic", "ietf.akaquic.com", port=443, verify_mode=ssl.CERT_NONE),
85 Server(
86 "aioquic", "quic.aiortc.org", port=443, push_path="/", structured_logging=True
87 ),
88 Server("ats", "quic.ogre.com"),
89 Server("f5", "f5quic.com", retry_port=4433, throughput_path=None),
90 Server(
91 "haskell", "mew.org", structured_logging=True, throughput_path="/num/%(size)s"
92 ),
93 Server("gquic", "quic.rocks", retry_port=None),
94 Server("lsquic", "http3-test.litespeedtech.com", push_path="/200?push=/100"),
95 Server(
96 "msquic",
97 "quic.westus.cloudapp.azure.com",
98 structured_logging=True,
99 throughput_path=None, # "/%(size)d.txt",
100 verify_mode=ssl.CERT_NONE,
101 ),
102 Server(
103 "mvfst",
104 "fb.mvfst.net",
105 port=443,
106 push_path="/push",
107 retry_port=None,
108 structured_logging=True,
109 ),
110 Server(
111 "ngtcp2",
112 "nghttp2.org",
113 push_path="/?push=/100",
114 structured_logging=True,
115 throughput_path=None,
116 ),
117 Server("ngx_quic", "cloudflare-quic.com", port=443, retry_port=None),
118 Server("pandora", "pandora.cm.in.tum.de", verify_mode=ssl.CERT_NONE),
119 Server("picoquic", "test.privateoctopus.com", structured_logging=True),
120 Server("quant", "quant.eggert.org", http3=False, structured_logging=True),
121 Server("quic-go", "interop.seemann.io", port=443, retry_port=443),
122 Server("quiche", "quic.tech", port=8443, retry_port=8444),
123 Server("quicly", "quic.examp1e.net", http3_port=443),
124 Server("quinn", "h3.stammw.eu", port=443),
125 ]
126
127
128 async def test_version_negotiation(server: Server, configuration: QuicConfiguration):
129 # force version negotiation
130 configuration.supported_versions.insert(0, 0x1A2A3A4A)
131
132 async with connect(
133 server.host, server.port, configuration=configuration
134 ) as protocol:
135 await protocol.ping()
136
137 # check log
138 for event in configuration.quic_logger.to_dict()["traces"][0]["events"]:
139 if (
140 event["name"] == "transport:packet_received"
141 and event["data"]["header"]["packet_type"] == "version_negotiation"
142 ):
143 server.result |= Result.V
144
145
146 async def test_handshake_and_close(server: Server, configuration: QuicConfiguration):
147 async with connect(
148 server.host, server.port, configuration=configuration
149 ) as protocol:
150 await protocol.ping()
151 server.result |= Result.H
152 server.result |= Result.C
153
154
155 async def test_retry(server: Server, configuration: QuicConfiguration):
156 # skip test if there is not retry port
157 if server.retry_port is None:
158 return
159
160 async with connect(
161 server.host, server.retry_port, configuration=configuration
162 ) as protocol:
163 await protocol.ping()
164
165 # check log
166 for event in configuration.quic_logger.to_dict()["traces"][0]["events"]:
167 if (
168 event["name"] == "transport:packet_received"
169 and event["data"]["header"]["packet_type"] == "retry"
170 ):
171 server.result |= Result.S
172
173
174 async def test_quantum_readiness(server: Server, configuration: QuicConfiguration):
175 configuration.quantum_readiness_test = True
176 async with connect(
177 server.host, server.port, configuration=configuration
178 ) as protocol:
179 await protocol.ping()
180 server.result |= Result.Q
181
182
183 async def test_http_0(server: Server, configuration: QuicConfiguration):
184 if server.path is None:
185 return
186
187 configuration.alpn_protocols = H0_ALPN
188 async with connect(
189 server.host,
190 server.port,
191 configuration=configuration,
192 create_protocol=HttpClient,
193 ) as protocol:
194 protocol = cast(HttpClient, protocol)
195
196 # perform HTTP request
197 events = await protocol.get(
198 "https://{}:{}{}".format(server.host, server.port, server.path)
199 )
200 if events and isinstance(events[0], HeadersReceived):
201 server.result |= Result.D
202
203
204 async def test_http_3(server: Server, configuration: QuicConfiguration):
205 port = server.http3_port or server.port
206 if server.path is None:
207 return
208
209 configuration.alpn_protocols = H3_ALPN
210 async with connect(
211 server.host,
212 port,
213 configuration=configuration,
214 create_protocol=HttpClient,
215 ) as protocol:
216 protocol = cast(HttpClient, protocol)
217
218 # perform HTTP request
219 events = await protocol.get(
220 "https://{}:{}{}".format(server.host, server.port, server.path)
221 )
222 if events and isinstance(events[0], HeadersReceived):
223 server.result |= Result.D
224 server.result |= Result.three
225
226 # perform more HTTP requests to use QPACK dynamic tables
227 for i in range(2):
228 events = await protocol.get(
229 "https://{}:{}{}".format(server.host, server.port, server.path)
230 )
231 if events and isinstance(events[0], HeadersReceived):
232 http = cast(H3Connection, protocol._http)
233 protocol._quic._logger.info(
234 "QPACK decoder bytes RX %d TX %d",
235 http._decoder_bytes_received,
236 http._decoder_bytes_sent,
237 )
238 protocol._quic._logger.info(
239 "QPACK encoder bytes RX %d TX %d",
240 http._encoder_bytes_received,
241 http._encoder_bytes_sent,
242 )
243 if (
244 http._decoder_bytes_received
245 and http._decoder_bytes_sent
246 and http._encoder_bytes_received
247 and http._encoder_bytes_sent
248 ):
249 server.result |= Result.d
250
251 # check push support
252 if server.push_path is not None:
253 protocol.pushes.clear()
254 await protocol.get(
255 "https://{}:{}{}".format(server.host, server.port, server.push_path)
256 )
257 await asyncio.sleep(0.5)
258 for push_id, events in protocol.pushes.items():
259 if (
260 len(events) >= 3
261 and isinstance(events[0], PushPromiseReceived)
262 and isinstance(events[1], HeadersReceived)
263 and isinstance(events[2], DataReceived)
264 ):
265 protocol._quic._logger.info(
266 "Push promise %d for %s received (status %s)",
267 push_id,
268 dict(events[0].headers)[b":path"].decode("ascii"),
269 int(dict(events[1].headers)[b":status"]),
270 )
271
272 server.result |= Result.p
273
274
275 async def test_session_resumption(server: Server, configuration: QuicConfiguration):
276 port = server.session_resumption_port or server.port
277 saved_ticket = None
278
279 def session_ticket_handler(ticket):
280 nonlocal saved_ticket
281 saved_ticket = ticket
282
283 # connect a first time, receive a ticket
284 async with connect(
285 server.host,
286 port,
287 configuration=configuration,
288 session_ticket_handler=session_ticket_handler,
289 ) as protocol:
290 await protocol.ping()
291
292 # some servers don't send the ticket immediately
293 await asyncio.sleep(1)
294
295 # connect a second time, with the ticket
296 if saved_ticket is not None:
297 configuration.session_ticket = saved_ticket
298 async with connect(server.host, port, configuration=configuration) as protocol:
299 await protocol.ping()
300
301 # check session was resumed
302 if protocol._quic.tls.session_resumed:
303 server.result |= Result.R
304
305 # check early data was accepted
306 if protocol._quic.tls.early_data_accepted:
307 server.result |= Result.Z
308
309
310 async def test_key_update(server: Server, configuration: QuicConfiguration):
311 async with connect(
312 server.host, server.port, configuration=configuration
313 ) as protocol:
314 # cause some traffic
315 await protocol.ping()
316
317 # request key update
318 protocol.request_key_update()
319
320 # cause more traffic
321 await protocol.ping()
322
323 server.result |= Result.U
324
325
326 async def test_server_cid_change(server: Server, configuration: QuicConfiguration):
327 async with connect(
328 server.host, server.port, configuration=configuration
329 ) as protocol:
330 # cause some traffic
331 await protocol.ping()
332
333 # change connection ID
334 protocol.change_connection_id()
335
336 # cause more traffic
337 await protocol.ping()
338
339 server.result |= Result.M
340
341
342 async def test_nat_rebinding(server: Server, configuration: QuicConfiguration):
343 async with connect(
344 server.host, server.port, configuration=configuration
345 ) as protocol:
346 # cause some traffic
347 await protocol.ping()
348
349 # replace transport
350 protocol._transport.close()
351 loop = asyncio.get_running_loop()
352 await loop.create_datagram_endpoint(lambda: protocol, local_addr=("::", 0))
353
354 # cause more traffic
355 await protocol.ping()
356
357 # check log
358 path_challenges = 0
359 for event in configuration.quic_logger.to_dict()["traces"][0]["events"]:
360 if (
361 event["name"] == "transport:packet_received"
362 and event["data"]["header"]["packet_type"] == "1RTT"
363 ):
364 for frame in event["data"]["frames"]:
365 if frame["frame_type"] == "path_challenge":
366 path_challenges += 1
367 if not path_challenges:
368 protocol._quic._logger.warning("No PATH_CHALLENGE received")
369 else:
370 server.result |= Result.B
371
372
373 async def test_address_mobility(server: Server, configuration: QuicConfiguration):
374 async with connect(
375 server.host, server.port, configuration=configuration
376 ) as protocol:
377 # cause some traffic
378 await protocol.ping()
379
380 # replace transport
381 protocol._transport.close()
382 loop = asyncio.get_running_loop()
383 await loop.create_datagram_endpoint(lambda: protocol, local_addr=("::", 0))
384
385 # change connection ID
386 protocol.change_connection_id()
387
388 # cause more traffic
389 await protocol.ping()
390
391 # check log
392 path_challenges = 0
393 for event in configuration.quic_logger.to_dict()["traces"][0]["events"]:
394 if (
395 event["name"] == "transport:packet_received"
396 and event["data"]["header"]["packet_type"] == "1RTT"
397 ):
398 for frame in event["data"]["frames"]:
399 if frame["frame_type"] == "path_challenge":
400 path_challenges += 1
401 if not path_challenges:
402 protocol._quic._logger.warning("No PATH_CHALLENGE received")
403 else:
404 server.result |= Result.A
405
406
407 async def test_spin_bit(server: Server, configuration: QuicConfiguration):
408 async with connect(
409 server.host, server.port, configuration=configuration
410 ) as protocol:
411 for i in range(5):
412 await protocol.ping()
413
414 # check log
415 spin_bits = set()
416 for event in configuration.quic_logger.to_dict()["traces"][0]["events"]:
417 if event["name"] == "connectivity:spin_bit_updated":
418 spin_bits.add(event["data"]["state"])
419 if len(spin_bits) == 2:
420 server.result |= Result.P
421
422
423 async def test_throughput(server: Server, configuration: QuicConfiguration):
424 failures = 0
425 if server.throughput_path is None:
426 return
427
428 for size in [5000000, 10000000]:
429 path = server.throughput_path % {"size": size}
430 print("Testing %d bytes download: %s" % (size, path))
431
432 # perform HTTP request over TCP
433 start = time.time()
434 response = httpx.get("https://" + server.host + path, verify=False)
435 tcp_octets = len(response.content)
436 tcp_elapsed = time.time() - start
437 assert tcp_octets == size, "HTTP/TCP response size mismatch"
438
439 # perform HTTP request over QUIC
440 if server.http3:
441 configuration.alpn_protocols = H3_ALPN
442 port = server.http3_port or server.port
443 else:
444 configuration.alpn_protocols = H0_ALPN
445 port = server.port
446 start = time.time()
447 async with connect(
448 server.host,
449 port,
450 configuration=configuration,
451 create_protocol=HttpClient,
452 ) as protocol:
453 protocol = cast(HttpClient, protocol)
454
455 http_events = await protocol.get(
456 "https://{}:{}{}".format(server.host, server.port, path)
457 )
458 quic_elapsed = time.time() - start
459 quic_octets = 0
460 for http_event in http_events:
461 if isinstance(http_event, DataReceived):
462 quic_octets += len(http_event.data)
463 assert quic_octets == size, "HTTP/QUIC response size mismatch"
464
465 print(" - HTTP/TCP completed in %.3f s" % tcp_elapsed)
466 print(" - HTTP/QUIC completed in %.3f s" % quic_elapsed)
467
468 if quic_elapsed > 1.1 * tcp_elapsed:
469 failures += 1
470 print(" => FAIL")
471 else:
472 print(" => PASS")
473
474 if failures == 0:
475 server.result |= Result.T
476
477
478 def print_result(server: Server) -> None:
479 result = str(server.result).replace("three", "3")
480 result = result[0:8] + " " + result[8:16] + " " + result[16:]
481 print("%s%s%s" % (server.name, " " * (20 - len(server.name)), result))
482
483
484 async def main(servers, tests, quic_log=False, secrets_log_file=None) -> None:
485 for server in servers:
486 if server.structured_logging:
487 server.result |= Result.L
488 for test_name, test_func in tests:
489 print("\n=== %s %s ===\n" % (server.name, test_name))
490 configuration = QuicConfiguration(
491 alpn_protocols=H3_ALPN + H0_ALPN,
492 is_client=True,
493 quic_logger=QuicFileLogger(quic_log) if quic_log else QuicLogger(),
494 secrets_log_file=secrets_log_file,
495 verify_mode=server.verify_mode,
496 )
497 if test_name == "test_throughput":
498 timeout = 120
499 else:
500 timeout = 10
501 try:
502 await asyncio.wait_for(
503 test_func(server, configuration), timeout=timeout
504 )
505 except Exception as exc:
506 print(exc)
507
508 print("")
509 print_result(server)
510
511 # print summary
512 if len(servers) > 1:
513 print("SUMMARY")
514 for server in servers:
515 print_result(server)
516
517
518 if __name__ == "__main__":
519 parser = argparse.ArgumentParser(description="QUIC interop client")
520 parser.add_argument(
521 "-q",
522 "--quic-log",
523 type=str,
524 help="log QUIC events to QLOG files in the specified directory",
525 )
526 parser.add_argument(
527 "--server", type=str, help="only run against the specified server."
528 )
529 parser.add_argument("--test", type=str, help="only run the specified test.")
530 parser.add_argument(
531 "-l",
532 "--secrets-log",
533 type=str,
534 help="log secrets to a file, for use with Wireshark",
535 )
536 parser.add_argument(
537 "-v", "--verbose", action="store_true", help="increase logging verbosity"
538 )
539
540 args = parser.parse_args()
541
542 logging.basicConfig(
543 format="%(asctime)s %(levelname)s %(name)s %(message)s",
544 level=logging.DEBUG if args.verbose else logging.INFO,
545 )
546
547 # open SSL log file
548 if args.secrets_log:
549 secrets_log_file = open(args.secrets_log, "a")
550 else:
551 secrets_log_file = None
552
553 # determine what to run
554 servers = SERVERS
555 tests = list(filter(lambda x: x[0].startswith("test_"), globals().items()))
556 if args.server:
557 servers = list(filter(lambda x: x.name == args.server, servers))
558 if args.test:
559 tests = list(filter(lambda x: x[0] == args.test, tests))
560
561 asyncio.run(
562 main(
563 servers=servers,
564 tests=tests,
565 quic_log=args.quic_log,
566 secrets_log_file=secrets_log_file,
567 )
568 )