From 93e466ba682a7544506f68d7636dc3f6f231d34b Mon Sep 17 00:00:00 2001 From: Lachlan Grose Date: Wed, 25 Nov 2026 16:21:11 +1030 Subject: [PATCH 1/3] fix(loop-link): read large frames in linear time and close the link after an interrupted send The receive buffer was bytes, so each chunk copied the full buffer: a 64 MB frame took 40 s. The buffer is now a bytearray. A Ctrl-C in the middle of a frame left half a frame on the socket, and the next send wrote into it. Now any exception during a frame write closes the client, and the next Viewer send opens a new connection. Co-Authored-By: Claude Opus 5.5 --- .../loop_link/src/loop_link/_websocket.py | 17 +++++- packages/loop_link/src/loop_link/viewer.py | 7 ++- packages/loop_link/tests/test_viewer.py | 32 ++++++++++ packages/loop_link/tests/test_websocket.py | 58 +++++++++++++++++++ 4 files changed, 108 insertions(+), 6 deletions(-) create mode 100644 packages/loop_link/tests/test_websocket.py diff --git a/packages/loop_link/src/loop_link/_websocket.py b/packages/loop_link/src/loop_link/_websocket.py index 888a56c01..9c65fc68e 100644 --- a/packages/loop_link/src/loop_link/_websocket.py +++ b/packages/loop_link/src/loop_link/_websocket.py @@ -101,7 +101,7 @@ class WebSocketClient: def __init__(self, sock: socket.socket) -> None: self._sock = sock - self._buffer = b"" + self._buffer = bytearray() self._partial = False self._fragmenting = False self._fragment_opcode = OP_BINARY @@ -198,7 +198,7 @@ def _handshake(self, host: str, port: int, token: str, path: str) -> None: except OSError as error: raise WebSocketError(f"The handshake failed: {error}") from error head, _, rest = data.partition(b"\r\n\r\n") - self._buffer = rest + self._buffer = bytearray(rest) status_line, *header_lines = head.decode("latin-1").split("\r\n") parts = status_line.split(" ", 2) status = parts[1] if len(parts) > 1 else "" @@ -245,6 +245,10 @@ def _send_frame(self, opcode: int, payload: bytes) -> None: # This includes a timeout: part of the frame can be sent, so the stream is broken. self._abort() raise WebSocketError(f"Cannot send to the viewer: {error}") from error + except BaseException: + # For example Ctrl-C: part of the frame can be sent, so the stream is broken. + self._abort() + raise def send_binary(self, data: bytes) -> None: """Send one binary message. @@ -284,8 +288,10 @@ def _read_exactly(self, count: int) -> bytes: if not chunk: self.closed = True raise WebSocketClosed("The viewer closed the connection.") + # A bytearray grows in place: bytes concatenation made large frames quadratic. self._buffer += chunk - data, self._buffer = self._buffer[:count], self._buffer[count:] + data = bytes(self._buffer[:count]) + del self._buffer[:count] return data def _read_frame(self, wait: float | None) -> tuple[bool, int, bytes]: @@ -401,6 +407,11 @@ def receive(self, timeout: float) -> bytes | None: except OSError as error: self._abort() raise WebSocketError(f"Cannot read from the viewer: {error}") from error + except BaseException: + # For example Ctrl-C in the middle of a frame: the next read would be misaligned. + if self._partial: + self._abort() + raise def _check_open(self) -> None: """Raise ``WebSocketClosed`` if the connection is closed.""" diff --git a/packages/loop_link/src/loop_link/viewer.py b/packages/loop_link/src/loop_link/viewer.py index 008a5a3ce..3fbfd982e 100644 --- a/packages/loop_link/src/loop_link/viewer.py +++ b/packages/loop_link/src/loop_link/viewer.py @@ -157,7 +157,8 @@ def scene_crs(self) -> str: @property def connected(self) -> bool: """True while the connection is open.""" - return self._client is not None and not self._dead + client = self._client + return client is not None and not client.closed and not self._dead @property def tool_connected(self) -> bool: @@ -1252,8 +1253,8 @@ def _ensure_connected(self) -> None: raise ViewerClosedError if self._client is None: self.connect() - elif self._dead: - # The last connection failed: open a new one. If the viewer is gone, give + elif self._dead or self._client.closed: + # The last connection failed (a client closes itself after a broken send): open a new one. If the viewer is gone, give # the error of a closed viewer, as the failed send did. try: self.connect() diff --git a/packages/loop_link/tests/test_viewer.py b/packages/loop_link/tests/test_viewer.py index 397c58e3d..05909f86e 100644 --- a/packages/loop_link/tests/test_viewer.py +++ b/packages/loop_link/tests/test_viewer.py @@ -625,3 +625,35 @@ def test_send_after_heartbeat_failure_reconnects(fake_viewer: Any, viewer_factor viewer.send(small_points(), id="after") assert viewer.connected assert viewer.flush() == [] + + +def test_send_after_interrupted_send_reconnects( + fake_viewer: Any, viewer_factory: FACTORY, monkeypatch: pytest.MonkeyPatch +) -> None: + """A Ctrl-C in the middle of a frame closes the client, so the next send opens a new one.""" + viewer = viewer_factory() + viewer.connect() + first = viewer._client + real = first._sock + + class Interrupted: + # The second sendall of a frame is the body: stop there, after the head went out. + calls = 0 + + def __getattr__(self, name: str) -> Any: + return getattr(real, name) + + def sendall(self, data: bytes) -> None: + Interrupted.calls += 1 + if Interrupted.calls == 2: + raise KeyboardInterrupt + real.sendall(data) + + monkeypatch.setattr(first, "_sock", Interrupted()) + with pytest.raises(KeyboardInterrupt): + viewer.send(small_points(), id="before") + assert not viewer.connected + viewer.send(small_points(), id="after") + assert viewer._client is not first + assert viewer.connected + assert viewer.flush() == [] diff --git a/packages/loop_link/tests/test_websocket.py b/packages/loop_link/tests/test_websocket.py new file mode 100644 index 000000000..04ceb0453 --- /dev/null +++ b/packages/loop_link/tests/test_websocket.py @@ -0,0 +1,58 @@ +"""Tests for the small WebSocket client in ``loop_link._websocket``.""" + +from __future__ import annotations + +import socket +import struct +import threading +import time + +import pytest + +from loop_link._websocket import OP_BINARY, WebSocketClient + + +def test_large_frame_is_read_in_linear_time() -> None: + # Reads of a growing bytes buffer were quadratic: 16 MB took seconds. + size = 32 * 1024 * 1024 + ours, theirs = socket.socketpair() + head = bytes([0x80 | OP_BINARY, 127]) + struct.pack(">Q", size) + writer = threading.Thread(target=theirs.sendall, args=(head + bytes(size),)) + writer.start() + try: + start = time.monotonic() + data = WebSocketClient(ours).receive(10.0) + elapsed = time.monotonic() - start + finally: + writer.join() + ours.close() + theirs.close() + assert data is not None and len(data) == size + assert elapsed < 2.0 + + +class _InterruptedSocket: + """A socket whose second sendall is interrupted, after part of the frame went out.""" + + def __init__(self) -> None: + self.calls = 0 + self.closed = False + + def settimeout(self, value: float | None) -> None: + pass + + def sendall(self, data: bytes) -> None: + self.calls += 1 + if self.calls == 2: + raise KeyboardInterrupt + + def close(self) -> None: + self.closed = True + + +def test_interrupt_during_send_closes_the_client() -> None: + sock = _InterruptedSocket() + client = WebSocketClient(sock) # type: ignore[arg-type] + with pytest.raises(KeyboardInterrupt): + client.send_binary(b"x" * 1000) + assert client.closed and sock.closed From e0957d69b934d22fa30de7b17dcbc8d756dff178 Mon Sep 17 00:00:00 2001 From: Lachlan Grose Date: Wed, 25 Nov 2026 16:21:11 +1030 Subject: [PATCH 2/3] fix(loop-link): do not send the saved local token to a remote host For a host that is not loopback, find_viewer now uses only an explicit token or GEOVIEWER_TOKEN. It does not read link.json or the instance files, and it gives a warning because the link is not encrypted. The repr of ViewerAddress does not show the token. Co-Authored-By: Claude Opus 5.5 --- packages/loop_link/README.md | 6 +++ packages/loop_link/src/loop_link/discovery.py | 39 +++++++++++++---- packages/loop_link/tests/test_discovery.py | 43 +++++++++++++++++++ 3 files changed, 80 insertions(+), 8 deletions(-) diff --git a/packages/loop_link/README.md b/packages/loop_link/README.md index 9a4e5d2a2..7efe629be 100644 --- a/packages/loop_link/README.md +++ b/packages/loop_link/README.md @@ -16,6 +16,12 @@ The package needs a token. It reads the `GEOVIEWER_TOKEN` environment variable. If this variable is not set, it uses the token that the viewer saved. +The link is not encrypted. For a host that is not on this computer +(`Viewer(host=...)` with an address that is not loopback), the package does +not use the saved token and does not read the instance files of the local +viewer. Give the token with `token=` or `GEOVIEWER_TOKEN`. The package gives +a warning, because the token and the data go over the network as plain text. + ## Example ```python diff --git a/packages/loop_link/src/loop_link/discovery.py b/packages/loop_link/src/loop_link/discovery.py index 46515d06c..b40ca1cce 100644 --- a/packages/loop_link/src/loop_link/discovery.py +++ b/packages/loop_link/src/loop_link/discovery.py @@ -6,12 +6,14 @@ from __future__ import annotations +import ipaddress import json import math import os import socket import sys -from dataclasses import dataclass +import warnings +from dataclasses import dataclass, field from pathlib import Path from loop_link.errors import NoViewerError, TokenError @@ -40,7 +42,16 @@ class ViewerAddress: host: str port: int - token: str + token: str = field(repr=False) + + +def _is_loopback(host: str) -> bool: + if host.lower() == "localhost": + return True + try: + return ipaddress.ip_address(host).is_loopback + except ValueError: + return False def settings_dir() -> Path: @@ -75,13 +86,14 @@ def _file_token(settings: Path) -> str: return "" -def _resolve_token(token: str | None, settings: Path) -> str: +def _resolve_token(token: str | None, settings: Path, local: bool) -> str: if token: return token env_token = os.environ.get("GEOVIEWER_TOKEN") if env_token: return env_token - file_token = _file_token(settings) + # The saved token belongs to the viewer on this computer: never send it to another host. + file_token = _file_token(settings) if local else "" if file_token: return file_token raise TokenError(_TOKEN_TEXT) @@ -100,7 +112,8 @@ def _find_port(settings: Path, host: str, timeout: float) -> int: live: list[tuple[tuple[bool, int], int]] = [] folder = settings / "instances" try: - files = sorted(folder.glob("*.json")) + # The instance files list the ports of the viewers on this computer only. + files = sorted(folder.glob("*.json")) if _is_loopback(host) else [] except OSError: files = [] for path in files: @@ -143,9 +156,12 @@ def find_viewer( function does not check it and does not read the instance files. token : str, optional The access token. If not given, the function reads the - ``GEOVIEWER_TOKEN`` environment variable, then ``link.json``. + ``GEOVIEWER_TOKEN`` environment variable, then ``link.json``. For a + host that is not loopback, it does not read ``link.json``. host : str - The host of the viewer. + The host of the viewer. For a host that is not loopback, the function + does not read the instance files and gives a warning, because the link + is not encrypted. settings : pathlib.Path, optional The settings folder. The default is :func:`settings_dir`. timeout : float @@ -164,7 +180,14 @@ def find_viewer( If no viewer is running. """ folder = settings if settings is not None else settings_dir() - resolved = _resolve_token(token, folder) + local = _is_loopback(host) + if not local: + warnings.warn( + f"The link to {host} is not encrypted: the token and the data are sent in plain text.", + UserWarning, + stacklevel=2, + ) + resolved = _resolve_token(token, folder, local) if port is not None: return ViewerAddress(host=host, port=port, token=resolved) return ViewerAddress(host=host, port=_find_port(folder, host, timeout), token=resolved) diff --git a/packages/loop_link/tests/test_discovery.py b/packages/loop_link/tests/test_discovery.py index ee5f71769..87b20c289 100644 --- a/packages/loop_link/tests/test_discovery.py +++ b/packages/loop_link/tests/test_discovery.py @@ -290,3 +290,46 @@ def test_non_finite_focused_counts_as_zero(tmp_path, listeners): (tmp_path / "instances" / "222.json").write_text(text, encoding="utf-8") address = find_viewer(settings=tmp_path) assert address.port == good_port + + +# A host that is not loopback + + +REMOTE = "203.0.113.5" + + +def test_remote_host_does_not_get_the_saved_token(tmp_path): + write_link(tmp_path) + with pytest.warns(UserWarning, match="not encrypted"), pytest.raises(TokenError): + find_viewer(port=4321, host=REMOTE, settings=tmp_path) + + +def test_remote_host_uses_explicit_or_env_token(tmp_path, monkeypatch): + write_link(tmp_path) + with pytest.warns(UserWarning, match="not encrypted"): + assert find_viewer(port=1, token="given", host=REMOTE, settings=tmp_path).token == "given" + monkeypatch.setenv("GEOVIEWER_TOKEN", "env-token") + with pytest.warns(UserWarning, match="not encrypted"): + assert find_viewer(port=1, host=REMOTE, settings=tmp_path).token == "env-token" + + +def test_remote_host_skips_instance_files(tmp_path, monkeypatch): + write_instance(tmp_path, 111, 5555) + probed: list[tuple[str, int]] = [] + monkeypatch.setattr( + discovery, "_is_alive", lambda host, port, timeout: probed.append((host, port)) or False + ) + with pytest.warns(UserWarning), pytest.raises(NoViewerError): + find_viewer(token="given", host=REMOTE, settings=tmp_path) + assert probed == [(REMOTE, DEFAULT_PORT)] + + +@pytest.mark.parametrize("host", ["localhost", "127.0.0.1", "127.1.2.3", "::1"]) +def test_loopback_host_uses_saved_token_without_warning(tmp_path, host, recwarn): + write_link(tmp_path) + assert find_viewer(port=1, host=host, settings=tmp_path).token == "file-token" + assert not recwarn.list + + +def test_viewer_address_repr_hides_the_token(): + assert "secret" not in repr(ViewerAddress(host="h", port=1, token="secret")) From 9b4533905704a15752d6301fe9a1138b967b552f Mon Sep 17 00:00:00 2001 From: Lachlan Grose Date: Wed, 25 Nov 2026 17:54:33 +1030 Subject: [PATCH 3/3] fix(loop-link): open a new tool connection after an interrupted send ToolConnection kept a client that closed itself after a broken send, so the next request failed one time. It now drops a closed client and opens a new one, and connected is False for a closed client. Co-Authored-By: Claude Opus 5.5 --- packages/loop_link/src/loop_link/tool.py | 7 +++-- packages/loop_link/src/loop_link/viewer.py | 5 ++-- packages/loop_link/tests/test_tool.py | 30 ++++++++++++++++++++++ packages/loop_link/tests/test_websocket.py | 29 +++++++++++++++++++++ 4 files changed, 67 insertions(+), 4 deletions(-) diff --git a/packages/loop_link/src/loop_link/tool.py b/packages/loop_link/src/loop_link/tool.py index f066f4cda..4ec4c1354 100644 --- a/packages/loop_link/src/loop_link/tool.py +++ b/packages/loop_link/src/loop_link/tool.py @@ -112,7 +112,8 @@ def __init__( @property def connected(self) -> bool: """True while the connection is open.""" - return self._client is not None + client = self._client + return client is not None and not client.closed def connect(self) -> ToolConnection: """Connect to the ``/tool`` path of the viewer. No ``hello`` is sent. @@ -247,8 +248,10 @@ def post(self, build: Callable[[int], bytes]) -> int: def _connect_locked(self) -> WebSocketClient: """Return the open client, or open one. The caller holds the lock.""" - if self._client is not None: + if self._client is not None and not self._client.closed: return self._client + # A client closes itself after a broken send: drop it and open a new one. + self._drop_locked() if self._resolve is not None: address = self._resolve() else: diff --git a/packages/loop_link/src/loop_link/viewer.py b/packages/loop_link/src/loop_link/viewer.py index 3fbfd982e..34065f1e1 100644 --- a/packages/loop_link/src/loop_link/viewer.py +++ b/packages/loop_link/src/loop_link/viewer.py @@ -1254,8 +1254,9 @@ def _ensure_connected(self) -> None: if self._client is None: self.connect() elif self._dead or self._client.closed: - # The last connection failed (a client closes itself after a broken send): open a new one. If the viewer is gone, give - # the error of a closed viewer, as the failed send did. + # The last connection failed, or the client closed itself after a broken send: + # open a new one. If the viewer is gone, give the error of a closed viewer, as + # the failed send did. try: self.connect() except NoViewerError as error: diff --git a/packages/loop_link/tests/test_tool.py b/packages/loop_link/tests/test_tool.py index f767fae0f..7f66ce76f 100644 --- a/packages/loop_link/tests/test_tool.py +++ b/packages/loop_link/tests/test_tool.py @@ -443,6 +443,36 @@ def test_socket_closed_in_the_middle_of_a_request( assert viewer.tool_connections == 2 +def test_post_after_interrupted_post_reconnects( + connection: ToolConnection, monkeypatch: pytest.MonkeyPatch +) -> None: + """A Ctrl-C in the middle of a frame closes the client, so the next post opens a new one.""" + connection.connect() + first = connection._client + real = first._sock + + class Interrupted: + # The second sendall of a frame is the body: stop there, after the head went out. + calls = 0 + + def __getattr__(self, name: str) -> Any: + return getattr(real, name) + + def sendall(self, data: bytes) -> None: + Interrupted.calls += 1 + if Interrupted.calls == 2: + raise KeyboardInterrupt + real.sendall(data) + + monkeypatch.setattr(first, "_sock", Interrupted()) + with pytest.raises(KeyboardInterrupt): + connection.post(encode.selection_get_frame) + assert not connection.connected + connection.post(encode.selection_get_frame) + assert connection._client is not first + assert connection.connected + + def test_wrong_token_gives_token_error(direct: Callable[..., ToolConnection]) -> None: with FakeViewer() as viewer: tool = direct(viewer, token="wrong") diff --git a/packages/loop_link/tests/test_websocket.py b/packages/loop_link/tests/test_websocket.py index 04ceb0453..8929e2818 100644 --- a/packages/loop_link/tests/test_websocket.py +++ b/packages/loop_link/tests/test_websocket.py @@ -56,3 +56,32 @@ def test_interrupt_during_send_closes_the_client() -> None: with pytest.raises(KeyboardInterrupt): client.send_binary(b"x" * 1000) assert client.closed and sock.closed + + +def test_interrupt_while_waiting_for_a_frame_keeps_the_client() -> None: + # No byte of the frame was read, so the stream is still aligned. + ours, theirs = socket.socketpair() + real = ours + + class InterruptedOnce: + interrupted = False + + def __getattr__(self, name: str) -> object: + return getattr(real, name) + + def recv(self, size: int) -> bytes: + if not InterruptedOnce.interrupted: + InterruptedOnce.interrupted = True + raise KeyboardInterrupt + return real.recv(size) + + client = WebSocketClient(InterruptedOnce()) # type: ignore[arg-type] + try: + with pytest.raises(KeyboardInterrupt): + client.receive(1.0) + assert not client.closed + theirs.sendall(bytes([0x80 | OP_BINARY, 5]) + b"hello") + assert client.receive(1.0) == b"hello" + finally: + ours.close() + theirs.close()