| 1 |
import argparse |
| 2 |
import asyncio |
| 3 |
import logging |
| 4 |
import os |
| 5 |
import pickle |
| 6 |
import ssl |
| 7 |
import time |
| 8 |
from collections import deque |
| 9 |
from typing import AsyncIterator, Deque, Optional, cast |
| 10 |
from urllib.parse import urlparse |
| 11 |
|
| 12 |
import httpx |
| 13 |
from aioquic.asyncio.client import connect |
| 14 |
from aioquic.asyncio.protocol import QuicConnectionProtocol |
| 15 |
from aioquic.h3.connection import H3_ALPN, H3Connection |
| 16 |
from aioquic.h3.events import DataReceived, H3Event, Headers, HeadersReceived |
| 17 |
from aioquic.quic.configuration import QuicConfiguration |
| 18 |
from aioquic.quic.events import QuicEvent |
| 19 |
from aioquic.quic.logger import QuicFileLogger |
| 20 |
|
| 21 |
logger = logging.getLogger("client") |
| 22 |
|
| 23 |
|
| 24 |
class H3ResponseStream(httpx.AsyncByteStream): |
| 25 |
def __init__(self, aiterator: AsyncIterator[bytes]): |
| 26 |
self._aiterator = aiterator |
| 27 |
|
| 28 |
async def __aiter__(self) -> AsyncIterator[bytes]: |
| 29 |
async for part in self._aiterator: |
| 30 |
yield part |
| 31 |
|
| 32 |
|
| 33 |
class H3Transport(QuicConnectionProtocol, httpx.AsyncBaseTransport): |
| 34 |
def __init__(self, *args, **kwargs) -> None: |
| 35 |
super().__init__(*args, **kwargs) |
| 36 |
|
| 37 |
self._http = H3Connection(self._quic) |
| 38 |
self._read_queue: dict[int, Deque[H3Event]] = {} |
| 39 |
self._read_ready: dict[int, asyncio.Event] = {} |
| 40 |
|
| 41 |
async def handle_async_request(self, request: httpx.Request) -> httpx.Response: |
| 42 |
assert isinstance(request.stream, httpx.AsyncByteStream) |
| 43 |
|
| 44 |
stream_id = self._quic.get_next_available_stream_id() |
| 45 |
self._read_queue[stream_id] = deque() |
| 46 |
self._read_ready[stream_id] = asyncio.Event() |
| 47 |
|
| 48 |
|
| 49 |
self._http.send_headers( |
| 50 |
stream_id=stream_id, |
| 51 |
headers=[ |
| 52 |
(b":method", request.method.encode()), |
| 53 |
(b":scheme", request.url.raw_scheme), |
| 54 |
(b":authority", request.url.netloc), |
| 55 |
(b":path", request.url.raw_path), |
| 56 |
] |
| 57 |
+ [ |
| 58 |
(k.lower(), v) |
| 59 |
for (k, v) in request.headers.raw |
| 60 |
if k.lower() not in (b"connection", b"host") |
| 61 |
], |
| 62 |
) |
| 63 |
async for data in request.stream: |
| 64 |
self._http.send_data(stream_id=stream_id, data=data, end_stream=False) |
| 65 |
self._http.send_data(stream_id=stream_id, data=b"", end_stream=True) |
| 66 |
|
| 67 |
|
| 68 |
self.transmit() |
| 69 |
|
| 70 |
|
| 71 |
status_code, headers, stream_ended = await self._receive_response(stream_id) |
| 72 |
|
| 73 |
return httpx.Response( |
| 74 |
status_code=status_code, |
| 75 |
headers=headers, |
| 76 |
stream=H3ResponseStream( |
| 77 |
self._receive_response_data(stream_id, stream_ended) |
| 78 |
), |
| 79 |
extensions={ |
| 80 |
"http_version": b"HTTP/3", |
| 81 |
}, |
| 82 |
) |
| 83 |
|
| 84 |
def http_event_received(self, event: H3Event): |
| 85 |
if isinstance(event, (HeadersReceived, DataReceived)): |
| 86 |
stream_id = event.stream_id |
| 87 |
if stream_id in self._read_queue: |
| 88 |
self._read_queue[event.stream_id].append(event) |
| 89 |
self._read_ready[event.stream_id].set() |
| 90 |
|
| 91 |
def quic_event_received(self, event: QuicEvent): |
| 92 |
r |
| 93 |
if self._http is not None: |
| 94 |
for http_event in self._http.handle_event(event): |
| 95 |
self.http_event_received(http_event) |
| 96 |
|
| 97 |
async def _receive_response(self, stream_id: int) -> tuple[int, Headers, bool]: |
| 98 |
""" |
| 99 |
Read the response status and headers. |
| 100 |
""" |
| 101 |
stream_ended = False |
| 102 |
while True: |
| 103 |
event = await self._wait_for_http_event(stream_id) |
| 104 |
if isinstance(event, HeadersReceived): |
| 105 |
stream_ended = event.stream_ended |
| 106 |
break |
| 107 |
|
| 108 |
headers = [] |
| 109 |
status_code = 0 |
| 110 |
for header, value in event.headers: |
| 111 |
if header == b":status": |
| 112 |
status_code = int(value.decode()) |
| 113 |
else: |
| 114 |
headers.append((header, value)) |
| 115 |
return status_code, headers, stream_ended |
| 116 |
|
| 117 |
async def _receive_response_data( |
| 118 |
self, stream_id: int, stream_ended: bool |
| 119 |
) -> AsyncIterator[bytes]: |
| 120 |
""" |
| 121 |
Read the response data. |
| 122 |
""" |
| 123 |
while not stream_ended: |
| 124 |
event = await self._wait_for_http_event(stream_id) |
| 125 |
if isinstance(event, DataReceived): |
| 126 |
stream_ended = event.stream_ended |
| 127 |
yield event.data |
| 128 |
elif isinstance(event, HeadersReceived): |
| 129 |
stream_ended = event.stream_ended |
| 130 |
|
| 131 |
async def _wait_for_http_event(self, stream_id: int) -> H3Event: |
| 132 |
""" |
| 133 |
Returns the next HTTP/3 event for the given stream. |
| 134 |
""" |
| 135 |
if not self._read_queue[stream_id]: |
| 136 |
await self._read_ready[stream_id].wait() |
| 137 |
event = self._read_queue[stream_id].popleft() |
| 138 |
if not self._read_queue[stream_id]: |
| 139 |
self._read_ready[stream_id].clear() |
| 140 |
return event |
| 141 |
|
| 142 |
|
| 143 |
def save_session_ticket(ticket): |
| 144 |
""" |
| 145 |
Callback which is invoked by the TLS engine when a new session ticket |
| 146 |
is received. |
| 147 |
""" |
| 148 |
logger.info("New session ticket received") |
| 149 |
if args.session_ticket: |
| 150 |
with open(args.session_ticket, "wb") as fp: |
| 151 |
pickle.dump(ticket, fp) |
| 152 |
|
| 153 |
|
| 154 |
async def main( |
| 155 |
configuration: QuicConfiguration, |
| 156 |
url: str, |
| 157 |
data: Optional[str], |
| 158 |
include: bool, |
| 159 |
output_dir: Optional[str], |
| 160 |
) -> None: |
| 161 |
|
| 162 |
parsed = urlparse(url) |
| 163 |
assert parsed.scheme == "https", "Only https:// URLs are supported." |
| 164 |
host = parsed.hostname |
| 165 |
if parsed.port is not None: |
| 166 |
port = parsed.port |
| 167 |
else: |
| 168 |
port = 443 |
| 169 |
|
| 170 |
async with connect( |
| 171 |
host, |
| 172 |
port, |
| 173 |
configuration=configuration, |
| 174 |
create_protocol=H3Transport, |
| 175 |
session_ticket_handler=save_session_ticket, |
| 176 |
) as transport: |
| 177 |
async with httpx.AsyncClient( |
| 178 |
transport=cast(httpx.AsyncBaseTransport, transport) |
| 179 |
) as client: |
| 180 |
|
| 181 |
start = time.time() |
| 182 |
if data is not None: |
| 183 |
response = await client.post( |
| 184 |
url, |
| 185 |
content=data.encode(), |
| 186 |
headers={"content-type": "application/x-www-form-urlencoded"}, |
| 187 |
) |
| 188 |
else: |
| 189 |
response = await client.get(url) |
| 190 |
|
| 191 |
elapsed = time.time() - start |
| 192 |
|
| 193 |
|
| 194 |
octets = len(response.content) |
| 195 |
logger.info( |
| 196 |
"Received %d bytes in %.1f s (%.3f Mbps)" |
| 197 |
% (octets, elapsed, octets * 8 / elapsed / 1000000) |
| 198 |
) |
| 199 |
|
| 200 |
|
| 201 |
if output_dir is not None: |
| 202 |
output_path = os.path.join( |
| 203 |
output_dir, os.path.basename(urlparse(url).path) or "index.html" |
| 204 |
) |
| 205 |
with open(output_path, "wb") as output_file: |
| 206 |
if include: |
| 207 |
headers = "" |
| 208 |
for header, value in response.headers.items(): |
| 209 |
headers += header + ": " + value + "\r\n" |
| 210 |
if headers: |
| 211 |
output_file.write(headers.encode() + b"\r\n") |
| 212 |
|
| 213 |
output_file.write(response.content) |
| 214 |
|
| 215 |
|
| 216 |
if __name__ == "__main__": |
| 217 |
parser = argparse.ArgumentParser(description="HTTP/3 client") |
| 218 |
parser.add_argument("url", type=str, help="the URL to query (must be HTTPS)") |
| 219 |
parser.add_argument( |
| 220 |
"--ca-certs", type=str, help="load CA certificates from the specified file" |
| 221 |
) |
| 222 |
parser.add_argument( |
| 223 |
"-d", "--data", type=str, help="send the specified data in a POST request" |
| 224 |
) |
| 225 |
parser.add_argument( |
| 226 |
"-i", |
| 227 |
"--include", |
| 228 |
action="store_true", |
| 229 |
help="include the HTTP response headers in the output", |
| 230 |
) |
| 231 |
parser.add_argument( |
| 232 |
"-k", |
| 233 |
"--insecure", |
| 234 |
action="store_true", |
| 235 |
help="do not validate server certificate", |
| 236 |
) |
| 237 |
parser.add_argument( |
| 238 |
"--output-dir", |
| 239 |
type=str, |
| 240 |
help="write downloaded files to this directory", |
| 241 |
) |
| 242 |
parser.add_argument( |
| 243 |
"-q", |
| 244 |
"--quic-log", |
| 245 |
type=str, |
| 246 |
help="log QUIC events to QLOG files in the specified directory", |
| 247 |
) |
| 248 |
parser.add_argument( |
| 249 |
"-l", |
| 250 |
"--secrets-log", |
| 251 |
type=str, |
| 252 |
help="log secrets to a file, for use with Wireshark", |
| 253 |
) |
| 254 |
parser.add_argument( |
| 255 |
"-s", |
| 256 |
"--session-ticket", |
| 257 |
type=str, |
| 258 |
help="read and write session ticket from the specified file", |
| 259 |
) |
| 260 |
parser.add_argument( |
| 261 |
"-v", "--verbose", action="store_true", help="increase logging verbosity" |
| 262 |
) |
| 263 |
|
| 264 |
args = parser.parse_args() |
| 265 |
|
| 266 |
logging.basicConfig( |
| 267 |
format="%(asctime)s %(levelname)s %(name)s %(message)s", |
| 268 |
level=logging.DEBUG if args.verbose else logging.INFO, |
| 269 |
) |
| 270 |
|
| 271 |
if args.output_dir is not None and not os.path.isdir(args.output_dir): |
| 272 |
raise Exception("%s is not a directory" % args.output_dir) |
| 273 |
|
| 274 |
|
| 275 |
configuration = QuicConfiguration(is_client=True, alpn_protocols=H3_ALPN) |
| 276 |
if args.ca_certs: |
| 277 |
configuration.load_verify_locations(args.ca_certs) |
| 278 |
if args.insecure: |
| 279 |
configuration.verify_mode = ssl.CERT_NONE |
| 280 |
if args.quic_log: |
| 281 |
configuration.quic_logger = QuicFileLogger(args.quic_log) |
| 282 |
if args.secrets_log: |
| 283 |
configuration.secrets_log_file = open(args.secrets_log, "a") |
| 284 |
if args.session_ticket: |
| 285 |
try: |
| 286 |
with open(args.session_ticket, "rb") as fp: |
| 287 |
configuration.session_ticket = pickle.load(fp) |
| 288 |
except FileNotFoundError: |
| 289 |
pass |
| 290 |
|
| 291 |
asyncio.run( |
| 292 |
main( |
| 293 |
configuration=configuration, |
| 294 |
url=args.url, |
| 295 |
data=args.data, |
| 296 |
include=args.include, |
| 297 |
output_dir=args.output_dir, |
| 298 |
) |
| 299 |
) |