Skip to content

Qwen3.8-Flash-Next on any consumer hardware: one-click install for Windows / Linux. Strata inference engine, OpenAI/Anthropic API on localhost, optional image input.

C++

serve: read the request body an answer left unread, so the close is not a reset

Guillaume PUTIER612a4d450c9b
diff --git a/serve/server.py b/serve/server.py
index 496f6f805..2c11de079 100644
--- a/serve/server.py
+++ b/serve/server.py
@@ -2989,10 +2989,40 @@ def make_handler(svc: Service):
record = None # #332: this request's monitor record, if kept
watch_done = None # #430 #431: stops this request's disconnect watcher
+ body_read = False # whether a handler took this request's body
+ DRAIN_LIMIT = 1 << 20 # the most an unread body is read and dropped
def log_message(self, fmt, *args):
pass
+ def handle_one_request(self):
+ super().handle_one_request()
+ self._drain_body()
+
+ def _body(self) -> bytes:
+ self.body_read = True
+ return self.rfile.read(int(self.headers.get("Content-Length", 0)))
+
+ def _drain_body(self):
+ """An answer sent before the body was read (a 401, a 403, /load, a method with no handler) must not close
+ the connection on unread bytes: the close then sends a reset, and a client that sends its body after the
+ headers (http.client, urllib, requests) gets a connection error instead of the answer. So the body is
+ read and dropped here, once, after an answer. A body over DRAIN_LIMIT is left unread."""
+ headers = getattr(self, "headers", None)
+ if self.body_read or headers is None:
+ return
+ try:
+ left = int(headers.get("Content-Length", 0))
+ except ValueError:
+ return
+ if not 0 < left <= self.DRAIN_LIMIT:
+ return
+ self.connection.settimeout(5) # a client that never sends what it announced
+ try:
+ self.rfile.read(left)
+ except OSError:
+ pass
+
def parse_request(self):
"""Without an API key, every request (any method) first passes the Host check: DNS rebinding protection
(host_allowed). With a key a rebinding page cannot authenticate, so the check is skipped: tunnels and
@@ -3269,7 +3299,7 @@ def make_handler(svc: Service):
self._json(503, {"error": {"type": "server_error", "message": str(e)}})
return
try:
- req = json.loads(self.rfile.read(int(self.headers.get("Content-Length", 0))) or b"{}")
+ req = json.loads(self._body() or b"{}")
if not isinstance(req, dict):
raise ValueError("send a JSON object")
if path.startswith("/v1/responses/"): # retrieve/delete/cancel/compact: nothing is stored
@@ -3474,7 +3504,7 @@ def make_handler(svc: Service):
def _settings(self):
# They change what every client gets, so only the app's own page may set them
- body = self.rfile.read(int(self.headers.get("Content-Length", 0)))
+ body = self._body()
if not self._own_page("settings can be changed"):
return
try:
diff --git a/serve/test_server.py b/serve/test_server.py
index 77b1df996..6efa48d8a 100644
--- a/serve/test_server.py
+++ b/serve/test_server.py
@@ -8,6 +8,7 @@ import contextlib
import io
import json
import os
+import socket
import sys
import tempfile
import threading
@@ -3008,5 +3009,62 @@ class StopStrings(unittest.TestCase):
self.assertEqual(m.push("more"), "")
+class AnswerBeforeTheBody(unittest.TestCase):
+ """An answer sent before the request body was read must still reach a client that sends the body after the headers
+ (http.client, urllib and requests do): closing the connection on unread bytes sends a reset that eats the answer."""
+
+ def setUp(self):
+ tok = ByteTokenizer()
+ self.engine = UnloadableEngine(tok, "</think>\n\nok", max_context=CTX)
+ self.svc = Service(self.engine, tok, ChatTemplate(ROOT / "serve/chat_template.jinja"))
+ self.httpd = serve(self.svc, port=0)
+ self.port = self.httpd.server_address[1]
+
+ def tearDown(self):
+ self.httpd.shutdown()
+ self.httpd.server_close()
+
+ def status(self, method, path, headers=None, body=b'{"x": 1}'):
+ """The status line of the answer to a request whose body follows the headers after a pause."""
+ head = {"Host": f"127.0.0.1:{self.port}", "Content-Type": "application/json", "Content-Length": str(len(body)),
+ **(headers or {})}
+ with socket.create_connection(("127.0.0.1", self.port), timeout=10) as s:
+ s.sendall((f"{method} {path} HTTP/1.1\r\n" + "".join(f"{k}: {v}\r\n" for k, v in head.items()) +
+ "\r\n").encode())
+ time.sleep(0.3) # the server answers (and, unfixed, closes) meanwhile
+ try:
+ s.sendall(body)
+ except OSError:
+ pass
+ answer = b""
+ while chunk := s.recv(65536): # Windows raises a reset here, where Linux keeps the answer
+ answer += chunk
+ time.sleep(0.2)
+ # Linux shows the reset only as a pending socket error, after the answer and the end of the stream
+ self.assertEqual(s.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR), 0, "the connection was reset")
+ return answer.split(b"\r\n", 1)[0].decode()
+
+ def test_a_wrong_key(self):
+ self.svc.api_key = "secret"
+ try:
+ self.assertEqual(self.status("POST", "/v1/chat/completions"), "HTTP/1.0 401 Unauthorized")
+ finally:
+ self.svc.api_key = ""
+
+ def test_load_and_unload(self):
+ self.assertEqual(self.status("POST", "/unload"), "HTTP/1.0 200 OK")
+ self.assertEqual(self.status("POST", "/load"), "HTTP/1.0 200 OK")
+
+ def test_not_the_apps_own_page(self):
+ self.assertEqual(self.status("POST", "/load", {"Origin": "https://example.com"}), "HTTP/1.0 403 Forbidden")
+
+ def test_a_host_the_server_does_not_answer_to(self):
+ self.assertEqual(self.status("POST", "/v1/chat/completions", {"Host": "rebind.example.com"}),
+ "HTTP/1.0 403 Forbidden")
+
+ def test_a_method_with_no_handler(self):
+ self.assertEqual(self.status("PUT", "/v1/chat/completions"), "HTTP/1.0 501 Unsupported method ('PUT')")
+
+
if __name__ == "__main__":
unittest.main()