| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
""" |
| 6 |
asyncio-server.py |
| 7 |
~~~~~~~~~~~~~~~~~ |
| 8 |
|
| 9 |
A fully-functional HTTP/2 server using asyncio. Requires Python 3.5+. |
| 10 |
|
| 11 |
Supported endpoints: |
| 12 |
|
| 13 |
1. GET /echo (default) |
| 14 |
- Echoes back request headers and body as JSON |
| 15 |
|
| 16 |
2. GET /echo with x-repeat-data header |
| 17 |
- x-repeat-data: <bytes> - Sends repeated test pattern of specified size |
| 18 |
- Example: x-repeat-data: 1000000 (sends 1MB) |
| 19 |
|
| 20 |
3. GET /echo with x-repeat-data + x-slow-response headers |
| 21 |
- x-slow-response: true - Throttles response to ~900 bytes/sec (for timeout testing) |
| 22 |
- x-throughput-bps: <number> - Optional: Override throughput (default 900) |
| 23 |
- Example: x-repeat-data: 5000000, x-slow-response: true, x-throughput-bps: 500 |
| 24 |
|
| 25 |
4. Any other path |
| 26 |
- Returns 404 Not Found |
| 27 |
""" |
| 28 |
import asyncio |
| 29 |
import io |
| 30 |
import json |
| 31 |
import ssl |
| 32 |
import time |
| 33 |
import os |
| 34 |
import collections |
| 35 |
from typing import List, Tuple |
| 36 |
|
| 37 |
from h2.config import H2Configuration |
| 38 |
from h2.connection import H2Connection |
| 39 |
from h2.events import ( |
| 40 |
ConnectionTerminated, DataReceived, RemoteSettingsChanged, |
| 41 |
RequestReceived, StreamEnded, StreamReset, WindowUpdated |
| 42 |
) |
| 43 |
from h2.errors import ErrorCodes |
| 44 |
from h2.exceptions import ProtocolError, StreamClosedError |
| 45 |
from h2.settings import SettingCodes |
| 46 |
|
| 47 |
|
| 48 |
RequestData = collections.namedtuple('RequestData', ['headers', 'data']) |
| 49 |
|
| 50 |
|
| 51 |
class H2Protocol(asyncio.Protocol): |
| 52 |
def __init__(self): |
| 53 |
config = H2Configuration(client_side=False, header_encoding='utf-8') |
| 54 |
self.conn = H2Connection(config=config) |
| 55 |
self.transport = None |
| 56 |
self.stream_data = {} |
| 57 |
self.flow_control_futures = {} |
| 58 |
self.file_path = None |
| 59 |
self.num_sentence_received = {} |
| 60 |
self.raw_headers = None |
| 61 |
self.download_test_length = 2500000000 |
| 62 |
self.out_bytes_per_second = 900 |
| 63 |
|
| 64 |
def connection_made(self, transport: asyncio.Transport): |
| 65 |
self.transport = transport |
| 66 |
self.conn.initiate_connection() |
| 67 |
|
| 68 |
self.conn.increment_flow_control_window(int(2147483647/2)) |
| 69 |
self.transport.write(self.conn.data_to_send()) |
| 70 |
|
| 71 |
def connection_lost(self, exc): |
| 72 |
for future in self.flow_control_futures.values(): |
| 73 |
future.cancel() |
| 74 |
self.flow_control_futures = {} |
| 75 |
|
| 76 |
def data_received(self, data: bytes): |
| 77 |
try: |
| 78 |
events = self.conn.receive_data(data) |
| 79 |
except ProtocolError as e: |
| 80 |
self.transport.write(self.conn.data_to_send()) |
| 81 |
self.transport.close() |
| 82 |
else: |
| 83 |
self.transport.write(self.conn.data_to_send()) |
| 84 |
for event in events: |
| 85 |
if isinstance(event, RequestReceived): |
| 86 |
self.request_received(event.headers, event.stream_id) |
| 87 |
elif isinstance(event, DataReceived): |
| 88 |
self.receive_data(event.data, event.stream_id, |
| 89 |
event.flow_controlled_length) |
| 90 |
elif isinstance(event, StreamEnded): |
| 91 |
self.stream_complete(event.stream_id) |
| 92 |
elif isinstance(event, ConnectionTerminated): |
| 93 |
self.transport.close() |
| 94 |
elif isinstance(event, StreamReset): |
| 95 |
self.stream_reset(event.stream_id) |
| 96 |
elif isinstance(event, WindowUpdated): |
| 97 |
self.window_updated(event.stream_id, event.delta) |
| 98 |
elif isinstance(event, RemoteSettingsChanged): |
| 99 |
if SettingCodes.INITIAL_WINDOW_SIZE in event.changed_settings: |
| 100 |
self.window_updated(None, 0) |
| 101 |
|
| 102 |
self.transport.write(self.conn.data_to_send()) |
| 103 |
|
| 104 |
def request_received(self, headers: List[Tuple[str, str]], stream_id: int): |
| 105 |
|
| 106 |
self.conn.increment_flow_control_window( |
| 107 |
int(2147483647/2), stream_id) |
| 108 |
self.raw_headers = headers |
| 109 |
headers = collections.OrderedDict(headers) |
| 110 |
|
| 111 |
|
| 112 |
request_data = RequestData(headers, io.BytesIO()) |
| 113 |
self.stream_data[stream_id] = request_data |
| 114 |
|
| 115 |
def handle_request_echo(self, stream_id: int, request_data: RequestData): |
| 116 |
""" |
| 117 |
Handle /echo endpoint with optional special headers: |
| 118 |
- x-repeat-data: <bytes> - Triggers send_repeat_data() with specified length |
| 119 |
- x-slow-response: true - Triggers send_slow_repeat_data() instead (requires x-repeat-data) |
| 120 |
- x-throughput-bps: <number> - Override throughput for slow response (default 900) |
| 121 |
|
| 122 |
Without special headers, echoes request headers and body as JSON. |
| 123 |
""" |
| 124 |
headers_dict = dict(self.raw_headers) |
| 125 |
|
| 126 |
expect_status = headers_dict.get('x-expect-status') |
| 127 |
if expect_status: |
| 128 |
response_headers = [(':status', expect_status)] |
| 129 |
self.conn.send_headers(stream_id, response_headers, end_stream=True) |
| 130 |
return |
| 131 |
|
| 132 |
|
| 133 |
repeat_data_header = headers_dict.get('x-repeat-data') |
| 134 |
if repeat_data_header: |
| 135 |
try: |
| 136 |
length = int(repeat_data_header) |
| 137 |
response_headers = [(':status', '200')] |
| 138 |
self.conn.send_headers(stream_id, response_headers, end_stream=False) |
| 139 |
|
| 140 |
|
| 141 |
if headers_dict.get('x-slow-response') == 'true': |
| 142 |
|
| 143 |
throughput_header = headers_dict.get('x-throughput-bps') |
| 144 |
if throughput_header: |
| 145 |
self.out_bytes_per_second = int(throughput_header) |
| 146 |
asyncio.ensure_future(self.send_slow_repeat_data(length, stream_id)) |
| 147 |
else: |
| 148 |
asyncio.ensure_future(self.send_repeat_data(length, stream_id)) |
| 149 |
return |
| 150 |
except ValueError: |
| 151 |
pass |
| 152 |
|
| 153 |
|
| 154 |
if headers_dict.get('x-upload-test') == 'true': |
| 155 |
body_bytes = request_data.data.getvalue() |
| 156 |
data = json.dumps({"bytes": len(body_bytes)}, indent=4).encode("utf8") |
| 157 |
response_headers = [(':status', '200'), ('content-length', str(len(data)))] |
| 158 |
self.conn.send_headers(stream_id, response_headers, end_stream=False) |
| 159 |
asyncio.ensure_future(self.send_data(data, stream_id)) |
| 160 |
return |
| 161 |
|
| 162 |
|
| 163 |
response_headers = [(':status', '200')] |
| 164 |
|
| 165 |
skip_headers = {'content-length', 'content-encoding', 'transfer-encoding'} |
| 166 |
for i in self.raw_headers: |
| 167 |
|
| 168 |
if i[0][0] != ':' and i[0].lower() not in skip_headers: |
| 169 |
response_headers.append(i) |
| 170 |
|
| 171 |
body_bytes = request_data.data.getvalue() |
| 172 |
|
| 173 |
body = body_bytes.decode('utf-8') |
| 174 |
|
| 175 |
data = json.dumps( |
| 176 |
{"body": body, "bytes": len(body_bytes)}, indent=4, |
| 177 |
).encode("utf8") |
| 178 |
|
| 179 |
|
| 180 |
response_headers.append(('content-length', str(len(data)))) |
| 181 |
|
| 182 |
self.conn.send_headers(stream_id, response_headers, end_stream=False) |
| 183 |
asyncio.ensure_future(self.send_data(data, stream_id)) |
| 184 |
|
| 185 |
def stream_complete(self, stream_id: int): |
| 186 |
""" |
| 187 |
When a stream is complete, we can send our response. |
| 188 |
""" |
| 189 |
try: |
| 190 |
request_data = self.stream_data[stream_id] |
| 191 |
except KeyError: |
| 192 |
|
| 193 |
return |
| 194 |
|
| 195 |
path = request_data.headers[':path'] |
| 196 |
if path == '/echo': |
| 197 |
self.handle_request_echo(stream_id, request_data) |
| 198 |
else: |
| 199 |
self.conn.send_headers(stream_id, [(':status', '404')], end_stream=False) |
| 200 |
asyncio.ensure_future(self.send_data(b"Not Found", stream_id)) |
| 201 |
|
| 202 |
def receive_data(self, data: bytes, stream_id: int, flow_controlled_length: int): |
| 203 |
""" |
| 204 |
We've received some data on a stream. If that stream is one we're |
| 205 |
expecting data on, save it off. Otherwise, reset the stream. |
| 206 |
""" |
| 207 |
try: |
| 208 |
if flow_controlled_length > 0: |
| 209 |
|
| 210 |
|
| 211 |
self.conn.increment_flow_control_window( |
| 212 |
flow_controlled_length) |
| 213 |
self.conn.increment_flow_control_window( |
| 214 |
flow_controlled_length, stream_id) |
| 215 |
stream_data = self.stream_data[stream_id] |
| 216 |
except KeyError: |
| 217 |
self.conn.reset_stream( |
| 218 |
stream_id, error_code=ErrorCodes.PROTOCOL_ERROR |
| 219 |
) |
| 220 |
else: |
| 221 |
stream_data.data.write(data) |
| 222 |
|
| 223 |
def stream_reset(self, stream_id): |
| 224 |
""" |
| 225 |
A stream reset was sent. Stop sending data. |
| 226 |
""" |
| 227 |
if stream_id in self.flow_control_futures: |
| 228 |
future = self.flow_control_futures.pop(stream_id) |
| 229 |
future.cancel() |
| 230 |
|
| 231 |
async def send_data(self, data, stream_id): |
| 232 |
""" |
| 233 |
Send data according to the flow control rules. |
| 234 |
""" |
| 235 |
while data: |
| 236 |
while self.conn.local_flow_control_window(stream_id) < 1: |
| 237 |
try: |
| 238 |
await self.wait_for_flow_control(stream_id) |
| 239 |
except asyncio.CancelledError: |
| 240 |
return |
| 241 |
|
| 242 |
chunk_size = min( |
| 243 |
self.conn.local_flow_control_window(stream_id), |
| 244 |
len(data), |
| 245 |
self.conn.max_outbound_frame_size, |
| 246 |
) |
| 247 |
|
| 248 |
try: |
| 249 |
self.conn.send_data( |
| 250 |
stream_id, |
| 251 |
data[:chunk_size], |
| 252 |
end_stream=(chunk_size == len(data)) |
| 253 |
) |
| 254 |
except (StreamClosedError, ProtocolError): |
| 255 |
|
| 256 |
|
| 257 |
break |
| 258 |
|
| 259 |
self.transport.write(self.conn.data_to_send()) |
| 260 |
data = data[chunk_size:] |
| 261 |
|
| 262 |
async def send_repeat_data(self, length, stream_id): |
| 263 |
""" |
| 264 |
Send repeated test pattern data of specified length. |
| 265 |
Respects HTTP/2 flow control rules. |
| 266 |
Triggered by x-repeat-data header on /echo endpoint. |
| 267 |
""" |
| 268 |
while length > 0: |
| 269 |
while self.conn.local_flow_control_window(stream_id) < 1: |
| 270 |
try: |
| 271 |
await self.wait_for_flow_control(stream_id) |
| 272 |
except asyncio.CancelledError: |
| 273 |
return |
| 274 |
|
| 275 |
chunk_size = min( |
| 276 |
self.conn.local_flow_control_window(stream_id), |
| 277 |
length, |
| 278 |
self.conn.max_outbound_frame_size, |
| 279 |
) |
| 280 |
repeated = b"This is CRT HTTP test." |
| 281 |
data = int(chunk_size/len(repeated)) * repeated + \ |
| 282 |
repeated[:chunk_size % len(repeated)] |
| 283 |
|
| 284 |
try: |
| 285 |
self.conn.send_data( |
| 286 |
stream_id, |
| 287 |
data, |
| 288 |
end_stream=(chunk_size == length) |
| 289 |
) |
| 290 |
except (StreamClosedError, ProtocolError): |
| 291 |
|
| 292 |
|
| 293 |
break |
| 294 |
|
| 295 |
self.transport.write(self.conn.data_to_send()) |
| 296 |
length = length - chunk_size |
| 297 |
|
| 298 |
async def send_slow_repeat_data(self, length, stream_id): |
| 299 |
""" |
| 300 |
Send repeated test pattern data slowly (throttled to out_bytes_per_second, default 900). |
| 301 |
Used for timeout and slow connection testing. |
| 302 |
Triggered by x-repeat-data + x-slow-response headers on /echo endpoint. |
| 303 |
""" |
| 304 |
while length > 0: |
| 305 |
while self.conn.local_flow_control_window(stream_id) < 1: |
| 306 |
try: |
| 307 |
await self.wait_for_flow_control(stream_id) |
| 308 |
except asyncio.CancelledError: |
| 309 |
return |
| 310 |
|
| 311 |
chunk_size = min( |
| 312 |
self.conn.local_flow_control_window(stream_id), |
| 313 |
length, |
| 314 |
self.conn.max_outbound_frame_size, |
| 315 |
self.out_bytes_per_second |
| 316 |
) |
| 317 |
repeated = b"This is CRT HTTP test." |
| 318 |
data = int(chunk_size/len(repeated)) * repeated + \ |
| 319 |
repeated[:chunk_size % len(repeated)] |
| 320 |
|
| 321 |
try: |
| 322 |
|
| 323 |
time.sleep(1) |
| 324 |
self.conn.send_data( |
| 325 |
stream_id, |
| 326 |
data, |
| 327 |
end_stream=(chunk_size == length) |
| 328 |
) |
| 329 |
except (StreamClosedError, ProtocolError): |
| 330 |
|
| 331 |
|
| 332 |
break |
| 333 |
|
| 334 |
self.transport.write(self.conn.data_to_send()) |
| 335 |
length = length - chunk_size |
| 336 |
|
| 337 |
async def wait_for_flow_control(self, stream_id): |
| 338 |
""" |
| 339 |
Waits for a Future that fires when the flow control window is opened. |
| 340 |
""" |
| 341 |
f = asyncio.Future() |
| 342 |
self.flow_control_futures[stream_id] = f |
| 343 |
await f |
| 344 |
|
| 345 |
def window_updated(self, stream_id, delta): |
| 346 |
""" |
| 347 |
A window update frame was received. Unblock some number of flow control |
| 348 |
Futures. |
| 349 |
""" |
| 350 |
if stream_id and stream_id in self.flow_control_futures: |
| 351 |
f = self.flow_control_futures.pop(stream_id) |
| 352 |
f.set_result(delta) |
| 353 |
elif not stream_id: |
| 354 |
for f in self.flow_control_futures.values(): |
| 355 |
f.set_result(delta) |
| 356 |
|
| 357 |
self.flow_control_futures = {} |
| 358 |
|
| 359 |
|
| 360 |
ssl_context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH) |
| 361 |
ssl_context.options |= (ssl.OP_NO_COMPRESSION) |
| 362 |
ssl_context.load_cert_chain( |
| 363 |
certfile=os.path.join(os.path.dirname(__file__), |
| 364 |
"../resources/unittests.crt"), |
| 365 |
keyfile=os.path.join(os.path.dirname(__file__), "../resources/unittests.key")) |
| 366 |
ssl_context.set_alpn_protocols(["h2"]) |
| 367 |
|
| 368 |
loop = asyncio.new_event_loop() |
| 369 |
|
| 370 |
coro = loop.create_server(H2Protocol, '127.0.0.1', 3443, ssl=ssl_context) |
| 371 |
server = loop.run_until_complete(coro) |
| 372 |
|
| 373 |
|
| 374 |
print('Serving on {}'.format(server.sockets[0].getsockname())) |
| 375 |
try: |
| 376 |
loop.run_forever() |
| 377 |
except KeyboardInterrupt: |
| 378 |
pass |
| 379 |
|
| 380 |
|
| 381 |
server.close() |
| 382 |
loop.run_until_complete(server.wait_closed()) |
| 383 |
loop.close() |