diff --git a/src/roborock_local_server/bundled_backend/mqtt_tls_proxy_server/server.py b/src/roborock_local_server/bundled_backend/mqtt_tls_proxy_server/server.py index 8cc8ef08..907a090f 100644 --- a/src/roborock_local_server/bundled_backend/mqtt_tls_proxy_server/server.py +++ b/src/roborock_local_server/bundled_backend/mqtt_tls_proxy_server/server.py @@ -35,13 +35,19 @@ _CONN_CLOSED = "closed" -def _shutdown_and_close(endpoint: socket.socket) -> None: - """Close a relay endpoint so a thread blocked in recv() on it wakes up. +def _shutdown_endpoint(endpoint: socket.socket) -> None: + """Shut a relay endpoint down so a thread blocked in recv() or send() on it wakes up. close() alone does not interrupt a recv() blocked in another thread on Linux, so the - socket is shut down first. For an SSLSocket the plain socket shutdown is used: + socket is shut down. For an SSLSocket the plain socket shutdown is used: SSLSocket.shutdown() clears the SSL object before shutting down, which would let the other relay thread fall through to a plaintext recv/send on the same socket. + + This does not close the socket. Its file descriptor must stay allocated until every + thread that may still be using the socket has finished: once it is closed the kernel + hands the same number to the next file or socket opened (typically the decode log the + trace worker opens per line), and an SSL write already in flight in the other relay + thread then lands in that file as a raw TLS record. """ try: if isinstance(endpoint, ssl.SSLSocket): @@ -50,6 +56,9 @@ def _shutdown_and_close(endpoint: socket.socket) -> None: endpoint.shutdown(socket.SHUT_RDWR) except OSError: pass + + +def _close_endpoint(endpoint: socket.socket) -> None: try: endpoint.close() except OSError: @@ -145,8 +154,10 @@ def _close_conn_endpoints(self, conn_id: str) -> None: endpoints = self._pop_conn_endpoints(conn_id) if endpoints is None: return + # Only shut down: the relay threads may still be inside recv/send on these sockets. + # _handle_client closes them once both relay threads have exited. for endpoint in endpoints: - _shutdown_and_close(endpoint) + _shutdown_endpoint(endpoint) def _set_pending_onboarding_auth(self, conn_id: str, candidate: dict[str, str]) -> None: with self._lock: @@ -938,13 +949,15 @@ def _relay(self, src: socket.socket, dst: socket.socket, conn_id: str, direction # SSLSocket.recv/sendall checking it and reading or writing. pass finally: + # Wake the other relay thread, but leave closing to _handle_client: closing here + # frees the fd while the other thread may still be about to write to it. for endpoint in (src, dst): - _shutdown_and_close(endpoint) + _shutdown_endpoint(endpoint) def _handle_client(self, tls_conn: socket.socket | ssl.SSLSocket, addr: tuple[str, int]) -> None: conn_id = self._next_conn() backend: socket.socket | None = None - relay_started = False + relay_threads: list[threading.Thread] = [] self.logger.info( "[conn %s] backend connect %s:%d from %s:%d", conn_id, @@ -1006,19 +1019,23 @@ def _handle_client(self, tls_conn: socket.socket | ssl.SSLSocket, addr: tuple[st daemon=True, ) b2c = threading.Thread(target=self._relay, args=(backend, tls_conn, conn_id, "b2c", bytearray()), daemon=True) - relay_started = True - c2b.start() - b2c.start() - c2b.join() - b2c.join() + for thread in (c2b, b2c): + thread.start() + relay_threads.append(thread) + for thread in relay_threads: + thread.join() except Exception as exc: self.logger.error("[conn %s] connection error: %s", conn_id, exc) finally: self._pop_conn_endpoints(conn_id) - if not relay_started: - for endpoint in (tls_conn, backend): - if endpoint is not None: - _shutdown_and_close(endpoint) + endpoints = [endpoint for endpoint in (tls_conn, backend) if endpoint is not None] + for endpoint in endpoints: + _shutdown_endpoint(endpoint) + # Close only after both relay threads are gone, so no thread still holds the fds. + for thread in relay_threads: + thread.join() + for endpoint in endpoints: + _close_endpoint(endpoint) if self.runtime_state is not None: self.runtime_state.record_mqtt_disconnect(conn_id=conn_id) # The trace worker may not have reached this connection's last packets yet, and diff --git a/tests/test_mqtt_tls_proxy.py b/tests/test_mqtt_tls_proxy.py index 3dac6205..3b7f2016 100644 --- a/tests/test_mqtt_tls_proxy.py +++ b/tests/test_mqtt_tls_proxy.py @@ -228,8 +228,9 @@ def slow_trace_packet(conn_id: str, direction: str, packet: bytes) -> None: assert trace_started.wait(0.1) assert elapsed < 0.15 assert trace_finished.wait(1.0) - assert src.closed is True - assert dst.closed is True + # The relay only shuts the sockets down; _handle_client closes them after both relay threads exit. + assert src.closed is False + assert dst.closed is False assert src.shutdown_calls == [socket.SHUT_RDWR] assert dst.shutdown_calls == [socket.SHUT_RDWR] @@ -1173,8 +1174,11 @@ def test_trace_packet_closes_provisional_onboarding_session_when_first_publish_t assert persisted is not None assert persisted["device_mqtt_usr"] == "" assert persisted["device_mqtt_pass"] == "" - assert client_sock.closed is True - assert backend_sock.closed is True + # Shut down to end the relay; _handle_client closes the sockets once the relay threads exit. + assert client_sock.closed is False + assert backend_sock.closed is False + assert client_sock.shutdown_calls == [socket.SHUT_RDWR] + assert backend_sock.shutdown_calls == [socket.SHUT_RDWR] assert proxy._get_pending_onboarding_auth("1") is None @@ -1332,6 +1336,9 @@ def test_handle_client_traces_packets_already_buffered_before_relay(tmp_path, mo ("1", "c2b", connect_packet), ("1", "c2b", b"\xc0\x00"), ] + # The relay threads only shut the sockets down; _handle_client closes both once they exit. + assert tls_conn.closed is True + assert backend.closed is True def test_handle_client_closes_tls_conn_when_client_closes_before_connect(tmp_path) -> None: @@ -1847,8 +1854,9 @@ def test_close_conn_endpoints_shuts_down_sockets(tmp_path) -> None: proxy._register_conn_endpoints("test-conn", s1, s2) proxy._close_conn_endpoints("test-conn") - assert s1.closed is True - assert s2.closed is True + # Only shut down: the relay threads may still be using the sockets, _handle_client closes them. + assert s1.closed is False + assert s2.closed is False assert s1.shutdown_calls == [socket.SHUT_RDWR] assert s2.shutdown_calls == [socket.SHUT_RDWR] @@ -1984,5 +1992,83 @@ def recv(self, _size: int) -> bytes: proxy._relay(src, dst, "1", "c2b", bytearray()) - assert src.closed is True - assert dst.closed is True + # The relay only shuts the sockets down; _handle_client closes them after both relay threads exit. + assert src.closed is False + assert dst.closed is False + assert src.shutdown_calls == [socket.SHUT_RDWR] + assert dst.shutdown_calls == [socket.SHUT_RDWR] + + +class _GatedSslWrites: + """Stand-in for SSLSocket._sslobj that parks the next write until released. + + It holds the b2c relay thread exactly where a preempted thread would be: past + SSLSocket.sendall's checks, holding the SSL object, not yet in SSL_write. + """ + + def __init__(self, sslobj: object) -> None: + self._sslobj = sslobj + self.entered = threading.Event() + self.release = threading.Event() + + def write(self, data: bytes) -> int: + self.entered.set() + assert self.release.wait(5) + return self._sslobj.write(data) + + def __getattr__(self, name: str) -> object: + return getattr(self._sslobj, name) + + +def test_relay_teardown_keeps_the_tls_fd_until_the_other_relay_thread_is_done(tmp_path) -> None: + """A write still in flight on the TLS socket must not land in a file reusing its fd. + + The old teardown closed both sockets in whichever relay thread ended first. The other + thread could still be about to write to the TLS socket; once its fd number was reused + (by the trace worker opening decompiled_mqtt.jsonl per line), that write appended a + raw TLS record to the decode log, which later broke strict UTF-8 readers. + """ + proxy = _teardown_test_proxy(tmp_path) + robot, client_conn = _wrap_tls_socketpair(tmp_path, proxy) + backend_conn, broker = socket.socketpair() + tls_fd = client_conn.fileno() + gate = _GatedSslWrites(client_conn._sslobj) + client_conn._sslobj = gate + errors: list[BaseException] = [] + threads = _start_relay_threads(proxy, client_conn, backend_conn, errors) + log_path = tmp_path / "decompiled_mqtt.jsonl" + opened: list = [] + try: + broker.sendall(b"\xd0\x00") # PINGRESP: the b2c thread parks before encrypting it + assert gate.entered.wait(5) + # The broker drops the session (as it does after a DISCONNECT), so the c2b relay + # thread fails forwarding the client's next packet and tears the connection down. + broker.close() + robot.sendall(b"\xe0\x00") # DISCONNECT + threads[0].join(5) + assert not threads[0].is_alive() + + # Open the log the way the trace worker does, taking the lowest free fds, until one + # reuses the TLS socket's number or it is clear that number is still in use. + for _ in range(16): + handle = open(log_path, "a", encoding="utf-8") + opened.append(handle) + if handle.fileno() == tls_fd: + break + gate.release.set() + threads[1].join(5) + assert not threads[1].is_alive() + for handle in opened: + handle.write('{"ok":true}\n') + handle.close() + + data = log_path.read_bytes() + assert data == b'{"ok":true}\n' * len(opened) + assert errors == [] + finally: + gate.release.set() + for handle in opened: + handle.close() + proxy.stop() + for sock in (robot, client_conn, backend_conn, broker): + sock.close()