| 1 |
#!/usr/bin/env python3 |
| 2 |
""" |
| 3 |
A deliberately "buggy" HTTP server that sends early responses before |
| 4 |
reading the full client request. This is used to test rspamd's HTTP |
| 5 |
client handling of edge cases that are allowed by HTTP/1.1 spec. |
| 6 |
|
| 7 |
Scenarios implemented: |
| 8 |
1. /early-reply - Send response immediately after reading headers, before body |
| 9 |
2. /early-error-413 - Send 413 error and close after reading just the request line |
| 10 |
3. /early-error-close - Send error and immediately close connection (no keep-alive) |
| 11 |
4. /keepalive-early - Send response early but keep connection alive |
| 12 |
5. /slow-read-fast-reply - Read request very slowly but reply quickly |
| 13 |
""" |
| 14 |
|
| 15 |
import asyncio |
| 16 |
import argparse |
| 17 |
import sys |
| 18 |
import os |
| 19 |
|
| 20 |
# Add parent directory to path for dummy_killer |
| 21 |
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) |
| 22 |
import dummy_killer |
| 23 |
|
| 24 |
|
| 25 |
class EarlyResponseServer: |
| 26 |
def __init__(self, host: str, port: int): |
| 27 |
self.host = host |
| 28 |
self.port = port |
| 29 |
self.server = None |
| 30 |
|
| 31 |
async def handle_client(self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter): |
| 32 |
"""Handle a single client connection.""" |
| 33 |
addr = writer.get_extra_info('peername') |
| 34 |
print(f"Connection from {addr}", file=sys.stderr) |
| 35 |
|
| 36 |
try: |
| 37 |
# Read just the request line first |
| 38 |
request_line = await asyncio.wait_for(reader.readline(), timeout=10.0) |
| 39 |
if not request_line: |
| 40 |
return |
| 41 |
|
| 42 |
request_line = request_line.decode('utf-8', errors='replace').strip() |
| 43 |
print(f"Request line: {request_line}", file=sys.stderr) |
| 44 |
|
| 45 |
parts = request_line.split(' ') |
| 46 |
if len(parts) < 2: |
| 47 |
return |
| 48 |
|
| 49 |
method = parts[0] |
| 50 |
path = parts[1] |
| 51 |
|
| 52 |
# For /instant-reply, send response BEFORE even reading headers |
| 53 |
# This is the most aggressive early response - client is still sending headers+body |
| 54 |
if path == '/instant-reply': |
| 55 |
print(f"instant-reply: sending 413 BEFORE reading headers!", file=sys.stderr) |
| 56 |
await self._send_response(writer, 413, "Request Entity Too Large", |
| 57 |
{"Content-Type": "text/plain", "Connection": "close"}, |
| 58 |
b"Instant 413 - rejected at request line") |
| 59 |
await writer.drain() |
| 60 |
print(f"instant-reply: response sent, closing", file=sys.stderr) |
| 61 |
return # Close without reading anything else |
| 62 |
|
| 63 |
# Read headers (but we might not read body depending on path) |
| 64 |
headers = {} |
| 65 |
content_length = 0 |
| 66 |
while True: |
| 67 |
line = await asyncio.wait_for(reader.readline(), timeout=10.0) |
| 68 |
if not line or line == b'\r\n' or line == b'\n': |
| 69 |
break |
| 70 |
line = line.decode('utf-8', errors='replace').strip() |
| 71 |
if ':' in line: |
| 72 |
key, value = line.split(':', 1) |
| 73 |
headers[key.strip().lower()] = value.strip() |
| 74 |
if key.strip().lower() == 'content-length': |
| 75 |
content_length = int(value.strip()) |
| 76 |
|
| 77 |
print(f"Headers received, Content-Length: {content_length}", file=sys.stderr) |
| 78 |
|
| 79 |
# Handle different test scenarios based on path |
| 80 |
if path == '/early-reply': |
| 81 |
# Send response immediately WITHOUT reading body |
| 82 |
# This tests client handling when server replies before body is fully sent |
| 83 |
await self._send_response(writer, 200, "OK", |
| 84 |
{"Content-Type": "text/plain", "Connection": "close"}, |
| 85 |
b"early reply - body not read") |
| 86 |
# Now try to drain remaining data |
| 87 |
if content_length > 0: |
| 88 |
try: |
| 89 |
remaining = await asyncio.wait_for(reader.read(content_length), timeout=1.0) |
| 90 |
print(f"Drained {len(remaining)} bytes of body", file=sys.stderr) |
| 91 |
except asyncio.TimeoutError: |
| 92 |
print("Timeout draining body", file=sys.stderr) |
| 93 |
|
| 94 |
elif path == '/early-error-413': |
| 95 |
# Send 413 immediately and close - simulates "request too large" |
| 96 |
# Don't even try to read the body |
| 97 |
await self._send_response(writer, 413, "Request Entity Too Large", |
| 98 |
{"Content-Type": "text/plain", "Connection": "close"}, |
| 99 |
b"Request body too large") |
| 100 |
# Close immediately without reading body |
| 101 |
|
| 102 |
elif path == '/early-error-close': |
| 103 |
# Send error and close connection abruptly |
| 104 |
await self._send_response(writer, 500, "Internal Server Error", |
| 105 |
{"Content-Type": "text/plain", "Connection": "close"}, |
| 106 |
b"Server error - closing") |
| 107 |
|
| 108 |
elif path == '/keepalive-early': |
| 109 |
# Send response early but indicate keep-alive |
| 110 |
# This tests if client can handle early response + continue with keepalive |
| 111 |
await self._send_response(writer, 200, "OK", |
| 112 |
{"Content-Type": "text/plain", |
| 113 |
"Connection": "keep-alive", |
| 114 |
"Keep-Alive": "timeout=30"}, |
| 115 |
b"early keepalive response") |
| 116 |
# Read the body to properly maintain connection state |
| 117 |
if content_length > 0: |
| 118 |
body = await asyncio.wait_for(reader.read(content_length), timeout=5.0) |
| 119 |
print(f"Read body: {len(body)} bytes", file=sys.stderr) |
| 120 |
|
| 121 |
# Wait for potential next request on keep-alive connection |
| 122 |
try: |
| 123 |
next_line = await asyncio.wait_for(reader.readline(), timeout=5.0) |
| 124 |
if next_line: |
| 125 |
print(f"Keep-alive follow-up: {next_line}", file=sys.stderr) |
| 126 |
# Handle second request simply |
| 127 |
while True: |
| 128 |
line = await asyncio.wait_for(reader.readline(), timeout=5.0) |
| 129 |
if not line or line == b'\r\n': |
| 130 |
break |
| 131 |
await self._send_response(writer, 200, "OK", |
| 132 |
{"Content-Type": "text/plain", "Connection": "close"}, |
| 133 |
b"second response on keepalive") |
| 134 |
except asyncio.TimeoutError: |
| 135 |
print("No follow-up request on keepalive", file=sys.stderr) |
| 136 |
|
| 137 |
elif path == '/slow-read-fast-reply': |
| 138 |
# Start reading body very slowly, but send reply quickly |
| 139 |
# This creates a race condition |
| 140 |
await self._send_response(writer, 200, "OK", |
| 141 |
{"Content-Type": "text/plain", "Connection": "close"}, |
| 142 |
b"fast reply while slowly reading") |
| 143 |
# Now slowly read |
| 144 |
if content_length > 0: |
| 145 |
read_so_far = 0 |
| 146 |
while read_so_far < content_length: |
| 147 |
chunk = await reader.read(min(100, content_length - read_so_far)) |
| 148 |
if not chunk: |
| 149 |
break |
| 150 |
read_so_far += len(chunk) |
| 151 |
await asyncio.sleep(0.1) # Slow down |
| 152 |
|
| 153 |
elif path == '/partial-read-then-reply': |
| 154 |
# Read only part of the body, then send response |
| 155 |
if content_length > 0: |
| 156 |
# Read only first 100 bytes |
| 157 |
partial = await reader.read(min(100, content_length)) |
| 158 |
print(f"Read partial body: {len(partial)} bytes", file=sys.stderr) |
| 159 |
|
| 160 |
await self._send_response(writer, 200, "OK", |
| 161 |
{"Content-Type": "text/plain", "Connection": "close"}, |
| 162 |
b"response after partial body read") |
| 163 |
|
| 164 |
elif path == '/immediate-close-413': |
| 165 |
# Send 413 and close socket IMMEDIATELY without reading anything else |
| 166 |
# This is the most aggressive case - RST may be sent if client is still writing |
| 167 |
await self._send_response(writer, 413, "Request Entity Too Large", |
| 168 |
{"Content-Type": "text/plain", "Connection": "close"}, |
| 169 |
b"Too large - closing immediately") |
| 170 |
# Force close without draining - this should cause client write to fail |
| 171 |
writer.transport.abort() # Forceful close |
| 172 |
return # Skip normal close |
| 173 |
|
| 174 |
elif path == '/block-and-reply': |
| 175 |
# TRUE early response test: |
| 176 |
# Send response IMMEDIATELY after headers, before body starts. |
| 177 |
# The client should receive this while still preparing/sending body. |
| 178 |
print(f"block-and-reply: sending 413 IMMEDIATELY (content-length={content_length})", file=sys.stderr) |
| 179 |
# Send response right away - no waiting |
| 180 |
await self._send_response(writer, 413, "Request Entity Too Large", |
| 181 |
{"Content-Type": "text/plain", "Connection": "close"}, |
| 182 |
b"Early 413 - body was never read") |
| 183 |
# Flush immediately |
| 184 |
await writer.drain() |
| 185 |
print(f"block-and-reply: response sent, closing without reading body", file=sys.stderr) |
| 186 |
# Don't read body, just close |
| 187 |
|
| 188 |
elif path == '/block-and-reply-slow': |
| 189 |
# Even more aggressive: wait longer to let more data queue up |
| 190 |
print(f"block-and-reply-slow: waiting for client to fill buffers", file=sys.stderr) |
| 191 |
await asyncio.sleep(1.0) # Wait for client to really fill up buffers |
| 192 |
await self._send_response(writer, 503, "Service Unavailable", |
| 193 |
{"Content-Type": "text/plain", "Connection": "close"}, |
| 194 |
b"Server busy - your data was ignored") |
| 195 |
await asyncio.sleep(0.1) |
| 196 |
|
| 197 |
elif path == '/slow-response-no-drain': |
| 198 |
# Wait a bit (let client send more data), then respond without reading |
| 199 |
await asyncio.sleep(0.5) # Let client start/continue sending |
| 200 |
await self._send_response(writer, 200, "OK", |
| 201 |
{"Content-Type": "text/plain", "Connection": "close"}, |
| 202 |
b"slow response - body not read") |
| 203 |
# Don't drain - close with data potentially still in flight |
| 204 |
|
| 205 |
elif path == '/request': |
| 206 |
# Normal request handling for comparison |
| 207 |
if content_length > 0: |
| 208 |
body = await asyncio.wait_for(reader.read(content_length), timeout=10.0) |
| 209 |
print(f"Read full body: {len(body)} bytes", file=sys.stderr) |
| 210 |
await self._send_response(writer, 200, "OK", |
| 211 |
{"Content-Type": "text/plain", "Connection": "close"}, |
| 212 |
b"normal response") |
| 213 |
|
| 214 |
elif path == '/keepalive-normal': |
| 215 |
# Normal keep-alive handling for comparison |
| 216 |
if content_length > 0: |
| 217 |
body = await asyncio.wait_for(reader.read(content_length), timeout=10.0) |
| 218 |
await self._send_response(writer, 200, "OK", |
| 219 |
{"Content-Type": "text/plain", |
| 220 |
"Connection": "keep-alive", |
| 221 |
"Keep-Alive": "timeout=30"}, |
| 222 |
b"normal keepalive response") |
| 223 |
|
| 224 |
else: |
| 225 |
await self._send_response(writer, 404, "Not Found", |
| 226 |
{"Content-Type": "text/plain", "Connection": "close"}, |
| 227 |
b"Not found") |
| 228 |
|
| 229 |
except asyncio.TimeoutError: |
| 230 |
print(f"Timeout handling {addr}", file=sys.stderr) |
| 231 |
except ConnectionResetError: |
| 232 |
print(f"Connection reset by {addr}", file=sys.stderr) |
| 233 |
except Exception as e: |
| 234 |
print(f"Error handling {addr}: {type(e).__name__}: {e}", file=sys.stderr) |
| 235 |
finally: |
| 236 |
try: |
| 237 |
writer.close() |
| 238 |
await writer.wait_closed() |
| 239 |
except Exception: |
| 240 |
pass |
| 241 |
print(f"Connection closed for {addr}", file=sys.stderr) |
| 242 |
|
| 243 |
async def _send_response(self, writer: asyncio.StreamWriter, status: int, status_text: str, |
| 244 |
headers: dict, body: bytes): |
| 245 |
"""Send an HTTP response.""" |
| 246 |
response_lines = [f"HTTP/1.1 {status} {status_text}"] |
| 247 |
headers["Content-Length"] = str(len(body)) |
| 248 |
for key, value in headers.items(): |
| 249 |
response_lines.append(f"{key}: {value}") |
| 250 |
response_lines.append("") |
| 251 |
response_lines.append("") |
| 252 |
|
| 253 |
response_header = "\r\n".join(response_lines).encode('utf-8') |
| 254 |
writer.write(response_header) |
| 255 |
writer.write(body) |
| 256 |
await writer.drain() |
| 257 |
print(f"Sent response: {status} {status_text}, {len(body)} bytes body", file=sys.stderr) |
| 258 |
|
| 259 |
async def start(self): |
| 260 |
"""Start the server.""" |
| 261 |
self.server = await asyncio.start_server( |
| 262 |
self.handle_client, self.host, self.port |
| 263 |
) |
| 264 |
print(f"Early response server listening on {self.host}:{self.port}", file=sys.stderr) |
| 265 |
|
| 266 |
async def serve_forever(self): |
| 267 |
"""Serve until cancelled.""" |
| 268 |
# Python 3.7+ has serve_forever(), but 3.6 doesn't |
| 269 |
if hasattr(self.server, 'serve_forever'): |
| 270 |
async with self.server: |
| 271 |
await self.server.serve_forever() |
| 272 |
else: |
| 273 |
# For Python 3.6 compatibility, use async context manager |
| 274 |
await asyncio.Event().wait() |
| 275 |
|
| 276 |
|
| 277 |
async def main(): |
| 278 |
parser = argparse.ArgumentParser(description="HTTP server for testing early response scenarios") |
| 279 |
parser.add_argument("--bind", "-b", default="127.0.0.1", help="bind address") |
| 280 |
parser.add_argument("--port", "-p", type=int, default=18083, help="bind port") |
| 281 |
parser.add_argument("--pidfile", "-pf", help="path to the PID file") |
| 282 |
args = parser.parse_args() |
| 283 |
|
| 284 |
print(f"dummy_http_early_response.py: Starting on {args.bind}:{args.port}", file=sys.stderr) |
| 285 |
|
| 286 |
server = EarlyResponseServer(args.host if hasattr(args, 'host') else args.bind, args.port) |
| 287 |
await server.start() |
| 288 |
|
| 289 |
if args.pidfile: |
| 290 |
dummy_killer.write_pid(args.pidfile) |
| 291 |
print(f"PID file written to {args.pidfile}", file=sys.stderr) |
| 292 |
|
| 293 |
await server.serve_forever() |
| 294 |
|
| 295 |
|
| 296 |
if __name__ == "__main__": |
| 297 |
try: |
| 298 |
if hasattr(asyncio, 'run') and callable(getattr(asyncio, 'run')): |
| 299 |
asyncio.run(main()) |
| 300 |
else: |
| 301 |
loop = asyncio.get_event_loop() |
| 302 |
loop.run_until_complete(main()) |
| 303 |
except KeyboardInterrupt: |
| 304 |
print("Shutting down...", file=sys.stderr) |
| 305 |
except Exception as e: |
| 306 |
print(f"FATAL ERROR: {type(e).__name__}: {e}", file=sys.stderr) |
| 307 |
import traceback |
| 308 |
traceback.print_exc(file=sys.stderr) |
| 309 |
sys.exit(1) |